sftpfs.go 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201
  1. // Copyright (C) 2019-2023 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. package vfs
  15. import (
  16. "bufio"
  17. "bytes"
  18. "errors"
  19. "fmt"
  20. "hash/fnv"
  21. "io"
  22. "io/fs"
  23. "net"
  24. "net/http"
  25. "os"
  26. "path"
  27. "path/filepath"
  28. "strconv"
  29. "strings"
  30. "sync"
  31. "sync/atomic"
  32. "time"
  33. "github.com/eikenb/pipeat"
  34. "github.com/pkg/sftp"
  35. "github.com/robfig/cron/v3"
  36. "github.com/rs/xid"
  37. "github.com/sftpgo/sdk"
  38. "golang.org/x/crypto/ssh"
  39. "github.com/drakkan/sftpgo/v2/internal/kms"
  40. "github.com/drakkan/sftpgo/v2/internal/logger"
  41. "github.com/drakkan/sftpgo/v2/internal/util"
  42. "github.com/drakkan/sftpgo/v2/internal/version"
  43. )
  44. const (
  45. // sftpFsName is the name for the SFTP Fs implementation
  46. sftpFsName = "sftpfs"
  47. logSenderSFTPCache = "sftpCache"
  48. maxSessionsPerConnection = 5
  49. )
  50. var (
  51. // ErrSFTPLoop defines the error to return if an SFTP loop is detected
  52. ErrSFTPLoop = errors.New("SFTP loop or nested local SFTP folders detected")
  53. sftpConnsCache = newSFTPConnectionCache()
  54. )
  55. // SFTPFsConfig defines the configuration for SFTP based filesystem
  56. type SFTPFsConfig struct {
  57. sdk.BaseSFTPFsConfig
  58. Password *kms.Secret `json:"password,omitempty"`
  59. PrivateKey *kms.Secret `json:"private_key,omitempty"`
  60. KeyPassphrase *kms.Secret `json:"key_passphrase,omitempty"`
  61. forbiddenSelfUsernames []string `json:"-"`
  62. }
  63. // HideConfidentialData hides confidential data
  64. func (c *SFTPFsConfig) HideConfidentialData() {
  65. if c.Password != nil {
  66. c.Password.Hide()
  67. }
  68. if c.PrivateKey != nil {
  69. c.PrivateKey.Hide()
  70. }
  71. if c.KeyPassphrase != nil {
  72. c.KeyPassphrase.Hide()
  73. }
  74. }
  75. func (c *SFTPFsConfig) setNilSecretsIfEmpty() {
  76. if c.Password != nil && c.Password.IsEmpty() {
  77. c.Password = nil
  78. }
  79. if c.PrivateKey != nil && c.PrivateKey.IsEmpty() {
  80. c.PrivateKey = nil
  81. }
  82. if c.KeyPassphrase != nil && c.KeyPassphrase.IsEmpty() {
  83. c.KeyPassphrase = nil
  84. }
  85. }
  86. func (c *SFTPFsConfig) isEqual(other SFTPFsConfig) bool {
  87. if c.Endpoint != other.Endpoint {
  88. return false
  89. }
  90. if c.Username != other.Username {
  91. return false
  92. }
  93. if c.Prefix != other.Prefix {
  94. return false
  95. }
  96. if c.DisableCouncurrentReads != other.DisableCouncurrentReads {
  97. return false
  98. }
  99. if c.BufferSize != other.BufferSize {
  100. return false
  101. }
  102. if len(c.Fingerprints) != len(other.Fingerprints) {
  103. return false
  104. }
  105. for _, fp := range c.Fingerprints {
  106. if !util.Contains(other.Fingerprints, fp) {
  107. return false
  108. }
  109. }
  110. c.setEmptyCredentialsIfNil()
  111. other.setEmptyCredentialsIfNil()
  112. if !c.Password.IsEqual(other.Password) {
  113. return false
  114. }
  115. if !c.KeyPassphrase.IsEqual(other.KeyPassphrase) {
  116. return false
  117. }
  118. return c.PrivateKey.IsEqual(other.PrivateKey)
  119. }
  120. func (c *SFTPFsConfig) setEmptyCredentialsIfNil() {
  121. if c.Password == nil {
  122. c.Password = kms.NewEmptySecret()
  123. }
  124. if c.PrivateKey == nil {
  125. c.PrivateKey = kms.NewEmptySecret()
  126. }
  127. if c.KeyPassphrase == nil {
  128. c.KeyPassphrase = kms.NewEmptySecret()
  129. }
  130. }
  131. func (c *SFTPFsConfig) isSameResource(other SFTPFsConfig) bool {
  132. if c.EqualityCheckMode > 0 || other.EqualityCheckMode > 0 {
  133. if c.Username != other.Username {
  134. return false
  135. }
  136. }
  137. return c.Endpoint == other.Endpoint
  138. }
  139. // validate returns an error if the configuration is not valid
  140. func (c *SFTPFsConfig) validate() error {
  141. c.setEmptyCredentialsIfNil()
  142. if c.Endpoint == "" {
  143. return errors.New("endpoint cannot be empty")
  144. }
  145. if !strings.Contains(c.Endpoint, ":") {
  146. c.Endpoint += ":22"
  147. }
  148. _, _, err := net.SplitHostPort(c.Endpoint)
  149. if err != nil {
  150. return fmt.Errorf("invalid endpoint: %v", err)
  151. }
  152. if c.Username == "" {
  153. return errors.New("username cannot be empty")
  154. }
  155. if c.BufferSize < 0 || c.BufferSize > 16 {
  156. return errors.New("invalid buffer_size, valid range is 0-16")
  157. }
  158. if !isEqualityCheckModeValid(c.EqualityCheckMode) {
  159. return errors.New("invalid equality_check_mode")
  160. }
  161. if err := c.validateCredentials(); err != nil {
  162. return err
  163. }
  164. if c.Prefix != "" {
  165. c.Prefix = util.CleanPath(c.Prefix)
  166. } else {
  167. c.Prefix = "/"
  168. }
  169. return nil
  170. }
  171. func (c *SFTPFsConfig) validateCredentials() error {
  172. if c.Password.IsEmpty() && c.PrivateKey.IsEmpty() {
  173. return errors.New("credentials cannot be empty")
  174. }
  175. if c.Password.IsEncrypted() && !c.Password.IsValid() {
  176. return errors.New("invalid encrypted password")
  177. }
  178. if !c.Password.IsEmpty() && !c.Password.IsValidInput() {
  179. return errors.New("invalid password")
  180. }
  181. if c.PrivateKey.IsEncrypted() && !c.PrivateKey.IsValid() {
  182. return errors.New("invalid encrypted private key")
  183. }
  184. if !c.PrivateKey.IsEmpty() && !c.PrivateKey.IsValidInput() {
  185. return errors.New("invalid private key")
  186. }
  187. if c.KeyPassphrase.IsEncrypted() && !c.KeyPassphrase.IsValid() {
  188. return errors.New("invalid encrypted private key passphrase")
  189. }
  190. if !c.KeyPassphrase.IsEmpty() && !c.KeyPassphrase.IsValidInput() {
  191. return errors.New("invalid private key passphrase")
  192. }
  193. return nil
  194. }
  195. // ValidateAndEncryptCredentials validates the config and encrypts credentials if they are in plain text
  196. func (c *SFTPFsConfig) ValidateAndEncryptCredentials(additionalData string) error {
  197. if err := c.validate(); err != nil {
  198. return util.NewValidationError(fmt.Sprintf("could not validate SFTP fs config: %v", err))
  199. }
  200. if c.Password.IsPlain() {
  201. c.Password.SetAdditionalData(additionalData)
  202. if err := c.Password.Encrypt(); err != nil {
  203. return util.NewValidationError(fmt.Sprintf("could not encrypt SFTP fs password: %v", err))
  204. }
  205. }
  206. if c.PrivateKey.IsPlain() {
  207. c.PrivateKey.SetAdditionalData(additionalData)
  208. if err := c.PrivateKey.Encrypt(); err != nil {
  209. return util.NewValidationError(fmt.Sprintf("could not encrypt SFTP fs private key: %v", err))
  210. }
  211. }
  212. if c.KeyPassphrase.IsPlain() {
  213. c.KeyPassphrase.SetAdditionalData(additionalData)
  214. if err := c.KeyPassphrase.Encrypt(); err != nil {
  215. return util.NewValidationError(fmt.Sprintf("could not encrypt SFTP fs private key passphrase: %v", err))
  216. }
  217. }
  218. return nil
  219. }
  220. // getUniqueID returns an hash of the settings used to connect to the SFTP server
  221. func (c *SFTPFsConfig) getUniqueID(partition int) uint64 {
  222. h := fnv.New64a()
  223. var b bytes.Buffer
  224. b.WriteString(c.Endpoint)
  225. b.WriteString(c.Username)
  226. b.WriteString(strings.Join(c.Fingerprints, ""))
  227. b.WriteString(strconv.FormatBool(c.DisableCouncurrentReads))
  228. b.WriteString(strconv.FormatInt(c.BufferSize, 10))
  229. b.WriteString(c.Password.GetPayload())
  230. b.WriteString(c.PrivateKey.GetPayload())
  231. b.WriteString(c.KeyPassphrase.GetPayload())
  232. if allowSelfConnections != 0 {
  233. b.WriteString(strings.Join(c.forbiddenSelfUsernames, ""))
  234. }
  235. b.WriteString(strconv.Itoa(partition))
  236. h.Write(b.Bytes())
  237. return h.Sum64()
  238. }
  239. // SFTPFs is a Fs implementation for SFTP backends
  240. type SFTPFs struct {
  241. connectionID string
  242. // if not empty this fs is mouted as virtual folder in the specified path
  243. mountPath string
  244. localTempDir string
  245. config *SFTPFsConfig
  246. conn *sftpConnection
  247. }
  248. // NewSFTPFs returns an SFTPFs object that allows to interact with an SFTP server
  249. func NewSFTPFs(connectionID, mountPath, localTempDir string, forbiddenSelfUsernames []string, config SFTPFsConfig) (Fs, error) {
  250. if localTempDir == "" {
  251. if tempPath != "" {
  252. localTempDir = tempPath
  253. } else {
  254. localTempDir = filepath.Clean(os.TempDir())
  255. }
  256. }
  257. if err := config.validate(); err != nil {
  258. return nil, err
  259. }
  260. if !config.Password.IsEmpty() {
  261. if err := config.Password.TryDecrypt(); err != nil {
  262. return nil, err
  263. }
  264. }
  265. if !config.PrivateKey.IsEmpty() {
  266. if err := config.PrivateKey.TryDecrypt(); err != nil {
  267. return nil, err
  268. }
  269. }
  270. if !config.KeyPassphrase.IsEmpty() {
  271. if err := config.KeyPassphrase.TryDecrypt(); err != nil {
  272. return nil, err
  273. }
  274. }
  275. config.forbiddenSelfUsernames = forbiddenSelfUsernames
  276. sftpFs := &SFTPFs{
  277. connectionID: connectionID,
  278. mountPath: getMountPath(mountPath),
  279. localTempDir: localTempDir,
  280. config: &config,
  281. conn: sftpConnsCache.Get(&config, connectionID),
  282. }
  283. err := sftpFs.createConnection()
  284. if err != nil {
  285. sftpFs.Close() //nolint:errcheck
  286. }
  287. return sftpFs, err
  288. }
  289. // Name returns the name for the Fs implementation
  290. func (fs *SFTPFs) Name() string {
  291. return fmt.Sprintf(`%s %q@%q`, sftpFsName, fs.config.Username, fs.config.Endpoint)
  292. }
  293. // ConnectionID returns the connection ID associated to this Fs implementation
  294. func (fs *SFTPFs) ConnectionID() string {
  295. return fs.connectionID
  296. }
  297. // Stat returns a FileInfo describing the named file
  298. func (fs *SFTPFs) Stat(name string) (os.FileInfo, error) {
  299. client, err := fs.conn.getClient()
  300. if err != nil {
  301. return nil, err
  302. }
  303. return client.Stat(name)
  304. }
  305. // Lstat returns a FileInfo describing the named file
  306. func (fs *SFTPFs) Lstat(name string) (os.FileInfo, error) {
  307. client, err := fs.conn.getClient()
  308. if err != nil {
  309. return nil, err
  310. }
  311. return client.Lstat(name)
  312. }
  313. // Open opens the named file for reading
  314. func (fs *SFTPFs) Open(name string, offset int64) (File, *pipeat.PipeReaderAt, func(), error) {
  315. client, err := fs.conn.getClient()
  316. if err != nil {
  317. return nil, nil, nil, err
  318. }
  319. f, err := client.Open(name)
  320. if err != nil {
  321. return nil, nil, nil, err
  322. }
  323. if offset > 0 {
  324. _, err = f.Seek(offset, io.SeekStart)
  325. if err != nil {
  326. f.Close()
  327. return nil, nil, nil, err
  328. }
  329. }
  330. if fs.config.BufferSize == 0 {
  331. return f, nil, nil, nil
  332. }
  333. r, w, err := pipeat.PipeInDir(fs.localTempDir)
  334. if err != nil {
  335. f.Close()
  336. return nil, nil, nil, err
  337. }
  338. go func() {
  339. // if we enable buffering the client stalls
  340. //br := bufio.NewReaderSize(f, int(fs.config.BufferSize)*1024*1024)
  341. //n, err := fs.copy(w, br)
  342. n, err := io.Copy(w, f)
  343. w.CloseWithError(err) //nolint:errcheck
  344. f.Close()
  345. fsLog(fs, logger.LevelDebug, "download completed, path: %#v size: %v, err: %v", name, n, err)
  346. }()
  347. return nil, r, nil, nil
  348. }
  349. // Create creates or opens the named file for writing
  350. func (fs *SFTPFs) Create(name string, flag int) (File, *PipeWriter, func(), error) {
  351. client, err := fs.conn.getClient()
  352. if err != nil {
  353. return nil, nil, nil, err
  354. }
  355. if fs.config.BufferSize == 0 {
  356. var f File
  357. if flag == 0 {
  358. f, err = client.Create(name)
  359. } else {
  360. f, err = client.OpenFile(name, flag)
  361. }
  362. return f, nil, nil, err
  363. }
  364. // buffering is enabled
  365. f, err := client.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_TRUNC)
  366. if err != nil {
  367. return nil, nil, nil, err
  368. }
  369. r, w, err := pipeat.PipeInDir(fs.localTempDir)
  370. if err != nil {
  371. f.Close()
  372. return nil, nil, nil, err
  373. }
  374. p := NewPipeWriter(w)
  375. go func() {
  376. bw := bufio.NewWriterSize(f, int(fs.config.BufferSize)*1024*1024)
  377. // we don't use io.Copy since bufio.Writer implements io.WriterTo and
  378. // so it calls the sftp.File WriteTo method without buffering
  379. n, err := fs.copy(bw, r)
  380. errFlush := bw.Flush()
  381. if err == nil && errFlush != nil {
  382. err = errFlush
  383. }
  384. var errTruncate error
  385. if err != nil {
  386. errTruncate = f.Truncate(n)
  387. }
  388. errClose := f.Close()
  389. if err == nil && errClose != nil {
  390. err = errClose
  391. }
  392. r.CloseWithError(err) //nolint:errcheck
  393. p.Done(err)
  394. fsLog(fs, logger.LevelDebug, "upload completed, path: %#v, readed bytes: %v, err: %v err truncate: %v",
  395. name, n, err, errTruncate)
  396. }()
  397. return nil, p, nil, nil
  398. }
  399. // Rename renames (moves) source to target.
  400. func (fs *SFTPFs) Rename(source, target string) (int, int64, error) {
  401. if source == target {
  402. return -1, -1, nil
  403. }
  404. client, err := fs.conn.getClient()
  405. if err != nil {
  406. return -1, -1, err
  407. }
  408. if _, ok := client.HasExtension("[email protected]"); ok {
  409. err := client.PosixRename(source, target)
  410. return -1, -1, err
  411. }
  412. err = client.Rename(source, target)
  413. return -1, -1, err
  414. }
  415. // Remove removes the named file or (empty) directory.
  416. func (fs *SFTPFs) Remove(name string, isDir bool) error {
  417. client, err := fs.conn.getClient()
  418. if err != nil {
  419. return err
  420. }
  421. if isDir {
  422. return client.RemoveDirectory(name)
  423. }
  424. return client.Remove(name)
  425. }
  426. // Mkdir creates a new directory with the specified name and default permissions
  427. func (fs *SFTPFs) Mkdir(name string) error {
  428. client, err := fs.conn.getClient()
  429. if err != nil {
  430. return err
  431. }
  432. return client.Mkdir(name)
  433. }
  434. // Symlink creates source as a symbolic link to target.
  435. func (fs *SFTPFs) Symlink(source, target string) error {
  436. client, err := fs.conn.getClient()
  437. if err != nil {
  438. return err
  439. }
  440. return client.Symlink(source, target)
  441. }
  442. // Readlink returns the destination of the named symbolic link
  443. func (fs *SFTPFs) Readlink(name string) (string, error) {
  444. client, err := fs.conn.getClient()
  445. if err != nil {
  446. return "", err
  447. }
  448. resolved, err := client.ReadLink(name)
  449. if err != nil {
  450. return resolved, err
  451. }
  452. resolved = path.Clean(resolved)
  453. if !path.IsAbs(resolved) {
  454. // we assume that multiple links are not followed
  455. resolved = path.Join(path.Dir(name), resolved)
  456. }
  457. return fs.GetRelativePath(resolved), nil
  458. }
  459. // Chown changes the numeric uid and gid of the named file.
  460. func (fs *SFTPFs) Chown(name string, uid int, gid int) error {
  461. client, err := fs.conn.getClient()
  462. if err != nil {
  463. return err
  464. }
  465. return client.Chown(name, uid, gid)
  466. }
  467. // Chmod changes the mode of the named file to mode.
  468. func (fs *SFTPFs) Chmod(name string, mode os.FileMode) error {
  469. client, err := fs.conn.getClient()
  470. if err != nil {
  471. return err
  472. }
  473. return client.Chmod(name, mode)
  474. }
  475. // Chtimes changes the access and modification times of the named file.
  476. func (fs *SFTPFs) Chtimes(name string, atime, mtime time.Time, isUploading bool) error {
  477. client, err := fs.conn.getClient()
  478. if err != nil {
  479. return err
  480. }
  481. return client.Chtimes(name, atime, mtime)
  482. }
  483. // Truncate changes the size of the named file.
  484. func (fs *SFTPFs) Truncate(name string, size int64) error {
  485. client, err := fs.conn.getClient()
  486. if err != nil {
  487. return err
  488. }
  489. return client.Truncate(name, size)
  490. }
  491. // ReadDir reads the directory named by dirname and returns
  492. // a list of directory entries.
  493. func (fs *SFTPFs) ReadDir(dirname string) ([]os.FileInfo, error) {
  494. client, err := fs.conn.getClient()
  495. if err != nil {
  496. return nil, err
  497. }
  498. return client.ReadDir(dirname)
  499. }
  500. // IsUploadResumeSupported returns true if resuming uploads is supported.
  501. func (fs *SFTPFs) IsUploadResumeSupported() bool {
  502. return fs.config.BufferSize == 0
  503. }
  504. // IsAtomicUploadSupported returns true if atomic upload is supported.
  505. func (fs *SFTPFs) IsAtomicUploadSupported() bool {
  506. return fs.config.BufferSize == 0
  507. }
  508. // IsNotExist returns a boolean indicating whether the error is known to
  509. // report that a file or directory does not exist
  510. func (*SFTPFs) IsNotExist(err error) bool {
  511. return errors.Is(err, fs.ErrNotExist)
  512. }
  513. // IsPermission returns a boolean indicating whether the error is known to
  514. // report that permission is denied.
  515. func (*SFTPFs) IsPermission(err error) bool {
  516. if _, ok := err.(*pathResolutionError); ok {
  517. return true
  518. }
  519. return errors.Is(err, fs.ErrPermission)
  520. }
  521. // IsNotSupported returns true if the error indicate an unsupported operation
  522. func (*SFTPFs) IsNotSupported(err error) bool {
  523. if err == nil {
  524. return false
  525. }
  526. return err == ErrVfsUnsupported
  527. }
  528. // CheckRootPath creates the specified local root directory if it does not exists
  529. func (fs *SFTPFs) CheckRootPath(username string, uid int, gid int) bool {
  530. // local directory for temporary files in buffer mode
  531. osFs := NewOsFs(fs.ConnectionID(), fs.localTempDir, "")
  532. osFs.CheckRootPath(username, uid, gid)
  533. if fs.config.Prefix == "/" {
  534. return true
  535. }
  536. client, err := fs.conn.getClient()
  537. if err != nil {
  538. return false
  539. }
  540. if err := client.MkdirAll(fs.config.Prefix); err != nil {
  541. fsLog(fs, logger.LevelDebug, "error creating root directory %q for user %q: %v", fs.config.Prefix, username, err)
  542. return false
  543. }
  544. return true
  545. }
  546. // ScanRootDirContents returns the number of files contained in a directory and
  547. // their size
  548. func (fs *SFTPFs) ScanRootDirContents() (int, int64, error) {
  549. return fs.GetDirSize(fs.config.Prefix)
  550. }
  551. // CheckMetadata checks the metadata consistency
  552. func (*SFTPFs) CheckMetadata() error {
  553. return nil
  554. }
  555. // GetAtomicUploadPath returns the path to use for an atomic upload
  556. func (*SFTPFs) GetAtomicUploadPath(name string) string {
  557. dir := path.Dir(name)
  558. guid := xid.New().String()
  559. return path.Join(dir, ".sftpgo-upload."+guid+"."+path.Base(name))
  560. }
  561. // GetRelativePath returns the path for a file relative to the sftp prefix if any.
  562. // This is the path as seen by SFTPGo users
  563. func (fs *SFTPFs) GetRelativePath(name string) string {
  564. rel := path.Clean(name)
  565. if rel == "." {
  566. rel = ""
  567. }
  568. if !path.IsAbs(rel) {
  569. return "/" + rel
  570. }
  571. if fs.config.Prefix != "/" {
  572. if !strings.HasPrefix(rel, fs.config.Prefix) {
  573. rel = "/"
  574. }
  575. rel = path.Clean("/" + strings.TrimPrefix(rel, fs.config.Prefix))
  576. }
  577. if fs.mountPath != "" {
  578. rel = path.Join(fs.mountPath, rel)
  579. }
  580. return rel
  581. }
  582. // Walk walks the file tree rooted at root, calling walkFn for each file or
  583. // directory in the tree, including root
  584. func (fs *SFTPFs) Walk(root string, walkFn filepath.WalkFunc) error {
  585. client, err := fs.conn.getClient()
  586. if err != nil {
  587. return err
  588. }
  589. walker := client.Walk(root)
  590. for walker.Step() {
  591. err := walker.Err()
  592. if err != nil {
  593. return err
  594. }
  595. err = walkFn(walker.Path(), walker.Stat(), err)
  596. if err != nil {
  597. return err
  598. }
  599. }
  600. return nil
  601. }
  602. // Join joins any number of path elements into a single path
  603. func (*SFTPFs) Join(elem ...string) string {
  604. return path.Join(elem...)
  605. }
  606. // HasVirtualFolders returns true if folders are emulated
  607. func (*SFTPFs) HasVirtualFolders() bool {
  608. return false
  609. }
  610. // ResolvePath returns the matching filesystem path for the specified virtual path
  611. func (fs *SFTPFs) ResolvePath(virtualPath string) (string, error) {
  612. if fs.mountPath != "" {
  613. virtualPath = strings.TrimPrefix(virtualPath, fs.mountPath)
  614. }
  615. if !path.IsAbs(virtualPath) {
  616. virtualPath = path.Clean("/" + virtualPath)
  617. }
  618. fsPath := fs.Join(fs.config.Prefix, virtualPath)
  619. if fs.config.Prefix != "/" && fsPath != "/" {
  620. // we need to check if this path is a symlink outside the given prefix
  621. // or a file/dir inside a dir symlinked outside the prefix
  622. var validatedPath string
  623. var err error
  624. validatedPath, err = fs.getRealPath(fsPath)
  625. isNotExist := fs.IsNotExist(err)
  626. if err != nil && !isNotExist {
  627. fsLog(fs, logger.LevelError, "Invalid path resolution, original path %v resolved %#v err: %v",
  628. virtualPath, fsPath, err)
  629. return "", err
  630. } else if isNotExist {
  631. for fs.IsNotExist(err) {
  632. validatedPath = path.Dir(validatedPath)
  633. if validatedPath == "/" {
  634. err = nil
  635. break
  636. }
  637. validatedPath, err = fs.getRealPath(validatedPath)
  638. }
  639. if err != nil {
  640. fsLog(fs, logger.LevelError, "Invalid path resolution, dir %#v original path %#v resolved %#v err: %v",
  641. validatedPath, virtualPath, fsPath, err)
  642. return "", err
  643. }
  644. }
  645. if err := fs.isSubDir(validatedPath); err != nil {
  646. fsLog(fs, logger.LevelError, "Invalid path resolution, dir %#v original path %#v resolved %#v err: %v",
  647. validatedPath, virtualPath, fsPath, err)
  648. return "", err
  649. }
  650. }
  651. return fsPath, nil
  652. }
  653. // RealPath implements the FsRealPather interface
  654. func (fs *SFTPFs) RealPath(p string) (string, error) {
  655. client, err := fs.conn.getClient()
  656. if err != nil {
  657. return "", err
  658. }
  659. resolved, err := client.RealPath(p)
  660. if err != nil {
  661. return "", err
  662. }
  663. if fs.config.Prefix != "/" {
  664. if err := fs.isSubDir(resolved); err != nil {
  665. fsLog(fs, logger.LevelError, "Invalid real path resolution, original path %q resolved %q err: %v",
  666. p, resolved, err)
  667. return "", err
  668. }
  669. }
  670. return fs.GetRelativePath(resolved), nil
  671. }
  672. // getRealPath returns the real remote path trying to resolve symbolic links if any
  673. func (fs *SFTPFs) getRealPath(name string) (string, error) {
  674. client, err := fs.conn.getClient()
  675. if err != nil {
  676. return "", err
  677. }
  678. linksWalked := 0
  679. for {
  680. info, err := client.Lstat(name)
  681. if err != nil {
  682. return name, err
  683. }
  684. if info.Mode()&os.ModeSymlink == 0 {
  685. return name, nil
  686. }
  687. resolvedLink, err := client.ReadLink(name)
  688. if err != nil {
  689. return name, fmt.Errorf("unable to resolve link to %q: %w", name, err)
  690. }
  691. resolvedLink = path.Clean(resolvedLink)
  692. if path.IsAbs(resolvedLink) {
  693. name = resolvedLink
  694. } else {
  695. name = path.Join(path.Dir(name), resolvedLink)
  696. }
  697. linksWalked++
  698. if linksWalked > 10 {
  699. fsLog(fs, logger.LevelError, "unable to get real path, too many links: %d", linksWalked)
  700. return "", &pathResolutionError{err: "too many links"}
  701. }
  702. }
  703. }
  704. func (fs *SFTPFs) isSubDir(name string) error {
  705. if name == fs.config.Prefix {
  706. return nil
  707. }
  708. if len(name) < len(fs.config.Prefix) {
  709. err := fmt.Errorf("path %q is not inside: %#v", name, fs.config.Prefix)
  710. return &pathResolutionError{err: err.Error()}
  711. }
  712. if !strings.HasPrefix(name, fs.config.Prefix+"/") {
  713. err := fmt.Errorf("path %q is not inside: %#v", name, fs.config.Prefix)
  714. return &pathResolutionError{err: err.Error()}
  715. }
  716. return nil
  717. }
  718. // GetDirSize returns the number of files and the size for a folder
  719. // including any subfolders
  720. func (fs *SFTPFs) GetDirSize(dirname string) (int, int64, error) {
  721. numFiles := 0
  722. size := int64(0)
  723. client, err := fs.conn.getClient()
  724. if err != nil {
  725. return numFiles, size, err
  726. }
  727. isDir, err := isDirectory(fs, dirname)
  728. if err == nil && isDir {
  729. walker := client.Walk(dirname)
  730. for walker.Step() {
  731. err := walker.Err()
  732. if err != nil {
  733. return numFiles, size, err
  734. }
  735. if walker.Stat().Mode().IsRegular() {
  736. size += walker.Stat().Size()
  737. numFiles++
  738. if numFiles%1000 == 0 {
  739. fsLog(fs, logger.LevelDebug, "dirname %q scan in progress, files: %d, size: %d", dirname, numFiles, size)
  740. }
  741. }
  742. }
  743. }
  744. return numFiles, size, err
  745. }
  746. // GetMimeType returns the content type
  747. func (fs *SFTPFs) GetMimeType(name string) (string, error) {
  748. client, err := fs.conn.getClient()
  749. if err != nil {
  750. return "", err
  751. }
  752. f, err := client.OpenFile(name, os.O_RDONLY)
  753. if err != nil {
  754. return "", err
  755. }
  756. defer f.Close()
  757. var buf [512]byte
  758. n, err := io.ReadFull(f, buf[:])
  759. if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF {
  760. return "", err
  761. }
  762. ctype := http.DetectContentType(buf[:n])
  763. // Rewind file.
  764. _, err = f.Seek(0, io.SeekStart)
  765. return ctype, err
  766. }
  767. // GetAvailableDiskSize returns the available size for the specified path
  768. func (fs *SFTPFs) GetAvailableDiskSize(dirName string) (*sftp.StatVFS, error) {
  769. client, err := fs.conn.getClient()
  770. if err != nil {
  771. return nil, err
  772. }
  773. if _, ok := client.HasExtension("[email protected]"); !ok {
  774. return nil, ErrStorageSizeUnavailable
  775. }
  776. return client.StatVFS(dirName)
  777. }
  778. // Close the connection
  779. func (fs *SFTPFs) Close() error {
  780. fs.conn.RemoveSession(fs.connectionID)
  781. return nil
  782. }
  783. func (fs *SFTPFs) copy(dst io.Writer, src io.Reader) (written int64, err error) {
  784. buf := make([]byte, 32768)
  785. for {
  786. nr, er := src.Read(buf)
  787. if nr > 0 {
  788. nw, ew := dst.Write(buf[0:nr])
  789. if nw < 0 || nr < nw {
  790. nw = 0
  791. if ew == nil {
  792. ew = errors.New("invalid write")
  793. }
  794. }
  795. written += int64(nw)
  796. if ew != nil {
  797. err = ew
  798. break
  799. }
  800. if nr != nw {
  801. err = io.ErrShortWrite
  802. break
  803. }
  804. }
  805. if er != nil {
  806. if er != io.EOF {
  807. err = er
  808. }
  809. break
  810. }
  811. }
  812. return written, err
  813. }
  814. func (fs *SFTPFs) createConnection() error {
  815. err := fs.conn.OpenConnection()
  816. if err != nil {
  817. fsLog(fs, logger.LevelError, "error opening connection: %v", err)
  818. return err
  819. }
  820. return nil
  821. }
  822. type sftpConnection struct {
  823. config *SFTPFsConfig
  824. logSender string
  825. sshClient *ssh.Client
  826. sftpClient *sftp.Client
  827. mu sync.RWMutex
  828. isConnected bool
  829. sessions map[string]bool
  830. lastActivity time.Time
  831. }
  832. func newSFTPConnection(config *SFTPFsConfig, sessionID string) *sftpConnection {
  833. c := &sftpConnection{
  834. config: config,
  835. logSender: fmt.Sprintf(`%s "%s@%s"`, sftpFsName, config.Username, config.Endpoint),
  836. isConnected: false,
  837. sessions: map[string]bool{},
  838. lastActivity: time.Now().UTC(),
  839. }
  840. c.sessions[sessionID] = true
  841. return c
  842. }
  843. func (c *sftpConnection) OpenConnection() error {
  844. c.mu.Lock()
  845. defer c.mu.Unlock()
  846. return c.openConnNoLock()
  847. }
  848. func (c *sftpConnection) openConnNoLock() error {
  849. if c.isConnected {
  850. logger.Debug(c.logSender, "", "reusing connection")
  851. return nil
  852. }
  853. logger.Debug(c.logSender, "", "try to open a new connection")
  854. clientConfig := &ssh.ClientConfig{
  855. User: c.config.Username,
  856. HostKeyCallback: func(_ string, _ net.Addr, key ssh.PublicKey) error {
  857. fp := ssh.FingerprintSHA256(key)
  858. if util.Contains(sftpFingerprints, fp) {
  859. if allowSelfConnections == 0 {
  860. logger.Log(logger.LevelError, c.logSender, "", "SFTP self connections not allowed")
  861. return ErrSFTPLoop
  862. }
  863. if util.Contains(c.config.forbiddenSelfUsernames, c.config.Username) {
  864. logger.Log(logger.LevelError, c.logSender, "",
  865. "SFTP loop or nested local SFTP folders detected, username %q, forbidden usernames: %+v",
  866. c.config.Username, c.config.forbiddenSelfUsernames)
  867. return ErrSFTPLoop
  868. }
  869. }
  870. if len(c.config.Fingerprints) > 0 {
  871. for _, provided := range c.config.Fingerprints {
  872. if provided == fp {
  873. return nil
  874. }
  875. }
  876. return fmt.Errorf("invalid fingerprint %q", fp)
  877. }
  878. logger.Log(logger.LevelWarn, c.logSender, "", "login without host key validation, please provide at least a fingerprint!")
  879. return nil
  880. },
  881. Timeout: 10 * time.Second,
  882. ClientVersion: fmt.Sprintf("SSH-2.0-SFTPGo_%v", version.Get().Version),
  883. }
  884. if c.config.PrivateKey.GetPayload() != "" {
  885. var signer ssh.Signer
  886. var err error
  887. if c.config.KeyPassphrase.GetPayload() != "" {
  888. signer, err = ssh.ParsePrivateKeyWithPassphrase([]byte(c.config.PrivateKey.GetPayload()),
  889. []byte(c.config.KeyPassphrase.GetPayload()))
  890. } else {
  891. signer, err = ssh.ParsePrivateKey([]byte(c.config.PrivateKey.GetPayload()))
  892. }
  893. if err != nil {
  894. return fmt.Errorf("sftpfs: unable to parse the private key: %w", err)
  895. }
  896. clientConfig.Auth = append(clientConfig.Auth, ssh.PublicKeys(signer))
  897. }
  898. if c.config.Password.GetPayload() != "" {
  899. clientConfig.Auth = append(clientConfig.Auth, ssh.Password(c.config.Password.GetPayload()))
  900. }
  901. // add more ciphers, KEXs and MACs, they are negotiated according to the order
  902. clientConfig.Ciphers = []string{"[email protected]", "[email protected]", "[email protected]",
  903. "aes128-ctr", "aes192-ctr", "aes256-ctr", "aes128-cbc", "aes192-cbc", "aes256-cbc"}
  904. clientConfig.KeyExchanges = []string{"curve25519-sha256", "[email protected]",
  905. "ecdh-sha2-nistp256", "ecdh-sha2-nistp384", "ecdh-sha2-nistp521",
  906. "diffie-hellman-group14-sha256", "diffie-hellman-group16-sha512", "diffie-hellman-group18-sha512",
  907. "diffie-hellman-group-exchange-sha256", "diffie-hellman-group-exchange-sha1",
  908. "diffie-hellman-group14-sha1", "diffie-hellman-group1-sha1"}
  909. clientConfig.MACs = []string{"[email protected]", "hmac-sha2-256",
  910. "[email protected]", "hmac-sha2-512",
  911. "hmac-sha1", "hmac-sha1-96"}
  912. sshClient, err := ssh.Dial("tcp", c.config.Endpoint, clientConfig)
  913. if err != nil {
  914. return fmt.Errorf("sftpfs: unable to connect: %w", err)
  915. }
  916. sftpClient, err := sftp.NewClient(sshClient, c.getClientOptions()...)
  917. if err != nil {
  918. sshClient.Close()
  919. return fmt.Errorf("sftpfs: unable to create SFTP client: %w", err)
  920. }
  921. c.sshClient = sshClient
  922. c.sftpClient = sftpClient
  923. c.isConnected = true
  924. go c.Wait()
  925. return nil
  926. }
  927. func (c *sftpConnection) getClientOptions() []sftp.ClientOption {
  928. var options []sftp.ClientOption
  929. if c.config.DisableCouncurrentReads {
  930. options = append(options, sftp.UseConcurrentReads(false))
  931. logger.Debug(c.logSender, "", "disabling concurrent reads")
  932. }
  933. if c.config.BufferSize > 0 {
  934. options = append(options, sftp.UseConcurrentWrites(true))
  935. logger.Debug(c.logSender, "", "enabling concurrent writes")
  936. }
  937. return options
  938. }
  939. func (c *sftpConnection) getClient() (*sftp.Client, error) {
  940. c.mu.Lock()
  941. defer c.mu.Unlock()
  942. if c.isConnected {
  943. return c.sftpClient, nil
  944. }
  945. err := c.openConnNoLock()
  946. return c.sftpClient, err
  947. }
  948. func (c *sftpConnection) Wait() {
  949. done := make(chan struct{})
  950. go func() {
  951. var watchdogInProgress atomic.Bool
  952. ticker := time.NewTicker(30 * time.Second)
  953. defer ticker.Stop()
  954. for {
  955. select {
  956. case <-ticker.C:
  957. if watchdogInProgress.Load() {
  958. logger.Error(c.logSender, "", "watchdog still in progress, closing hanging connection")
  959. c.sshClient.Close()
  960. return
  961. }
  962. go func() {
  963. watchdogInProgress.Store(true)
  964. defer watchdogInProgress.Store(false)
  965. _, err := c.sftpClient.Getwd()
  966. if err != nil {
  967. logger.Error(c.logSender, "", "watchdog error: %v", err)
  968. }
  969. }()
  970. case <-done:
  971. logger.Debug(c.logSender, "", "quitting watchdog")
  972. return
  973. }
  974. }
  975. }()
  976. // we wait on the sftp client otherwise if the channel is closed but not the connection
  977. // we don't detect the event.
  978. err := c.sftpClient.Wait()
  979. logger.Log(logger.LevelDebug, c.logSender, "", "sftp channel closed: %v", err)
  980. close(done)
  981. c.mu.Lock()
  982. defer c.mu.Unlock()
  983. c.isConnected = false
  984. if c.sshClient != nil {
  985. c.sshClient.Close()
  986. }
  987. }
  988. func (c *sftpConnection) Close() error {
  989. c.mu.Lock()
  990. defer c.mu.Unlock()
  991. logger.Debug(c.logSender, "", "closing connection")
  992. var sftpErr, sshErr error
  993. if c.sftpClient != nil {
  994. sftpErr = c.sftpClient.Close()
  995. }
  996. if c.sshClient != nil {
  997. sshErr = c.sshClient.Close()
  998. }
  999. if sftpErr != nil {
  1000. return sftpErr
  1001. }
  1002. c.isConnected = false
  1003. return sshErr
  1004. }
  1005. func (c *sftpConnection) AddSession(sessionID string) {
  1006. c.mu.Lock()
  1007. defer c.mu.Unlock()
  1008. c.sessions[sessionID] = true
  1009. logger.Debug(c.logSender, "", "added session %s, active sessions: %d", sessionID, len(c.sessions))
  1010. }
  1011. func (c *sftpConnection) RemoveSession(sessionID string) {
  1012. c.mu.Lock()
  1013. defer c.mu.Unlock()
  1014. delete(c.sessions, sessionID)
  1015. logger.Debug(c.logSender, "", "removed session %s, active sessions: %d", sessionID, len(c.sessions))
  1016. if len(c.sessions) == 0 {
  1017. c.lastActivity = time.Now().UTC()
  1018. }
  1019. }
  1020. func (c *sftpConnection) ActiveSessions() int {
  1021. c.mu.RLock()
  1022. defer c.mu.RUnlock()
  1023. return len(c.sessions)
  1024. }
  1025. func (c *sftpConnection) GetLastActivity() time.Time {
  1026. c.mu.RLock()
  1027. defer c.mu.RUnlock()
  1028. if len(c.sessions) > 0 {
  1029. return time.Now().UTC()
  1030. }
  1031. logger.Debug(c.logSender, "", "last activity %s", c.lastActivity)
  1032. return c.lastActivity
  1033. }
  1034. type sftpConnectionsCache struct {
  1035. scheduler *cron.Cron
  1036. sync.RWMutex
  1037. items map[uint64]*sftpConnection
  1038. }
  1039. func newSFTPConnectionCache() *sftpConnectionsCache {
  1040. c := &sftpConnectionsCache{
  1041. scheduler: cron.New(),
  1042. items: make(map[uint64]*sftpConnection),
  1043. }
  1044. _, err := c.scheduler.AddFunc("@every 1m", c.Cleanup)
  1045. util.PanicOnError(err)
  1046. c.scheduler.Start()
  1047. return c
  1048. }
  1049. func (c *sftpConnectionsCache) Get(config *SFTPFsConfig, sessionID string) *sftpConnection {
  1050. partition := 0
  1051. key := config.getUniqueID(partition)
  1052. c.Lock()
  1053. defer c.Unlock()
  1054. var oldKey uint64
  1055. for {
  1056. if val, ok := c.items[key]; ok {
  1057. activeSessions := val.ActiveSessions()
  1058. if activeSessions < maxSessionsPerConnection || key == oldKey {
  1059. logger.Debug(logSenderSFTPCache, "",
  1060. "reusing connection for session ID %q, key: %d, active sessions %d, active connections: %d",
  1061. sessionID, key, activeSessions+1, len(c.items))
  1062. val.AddSession(sessionID)
  1063. return val
  1064. }
  1065. partition++
  1066. oldKey = key
  1067. key = config.getUniqueID(partition)
  1068. logger.Debug(logSenderSFTPCache, "",
  1069. "connection full, generated new key for partition: %d, active sessions: %d, key: %d, old key: %d",
  1070. partition, activeSessions, oldKey, key)
  1071. } else {
  1072. conn := newSFTPConnection(config, sessionID)
  1073. c.items[key] = conn
  1074. logger.Debug(logSenderSFTPCache, "",
  1075. "adding new connection for session ID %q, partition: %d, key: %d, active connections: %d",
  1076. sessionID, partition, key, len(c.items))
  1077. return conn
  1078. }
  1079. }
  1080. }
  1081. func (c *sftpConnectionsCache) Remove(key uint64) {
  1082. c.Lock()
  1083. defer c.Unlock()
  1084. if conn, ok := c.items[key]; ok {
  1085. delete(c.items, key)
  1086. logger.Debug(logSenderSFTPCache, "", "removed connection with key %d, active connections: %d", key, len(c.items))
  1087. defer conn.Close()
  1088. }
  1089. }
  1090. func (c *sftpConnectionsCache) Cleanup() {
  1091. c.RLock()
  1092. for k, conn := range c.items {
  1093. if val := conn.GetLastActivity(); val.Before(time.Now().Add(-30 * time.Second)) {
  1094. logger.Debug(conn.logSender, "", "removing inactive connection, last activity %s", val)
  1095. defer func(key uint64) {
  1096. c.Remove(key)
  1097. }(k)
  1098. }
  1099. }
  1100. c.RUnlock()
  1101. }