sftpfs.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907
  1. // Copyright (C) 2019-2022 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. "errors"
  18. "fmt"
  19. "io"
  20. "io/fs"
  21. "net"
  22. "net/http"
  23. "os"
  24. "path"
  25. "path/filepath"
  26. "strings"
  27. "sync"
  28. "time"
  29. "github.com/eikenb/pipeat"
  30. "github.com/pkg/sftp"
  31. "github.com/rs/xid"
  32. "github.com/sftpgo/sdk"
  33. "golang.org/x/crypto/ssh"
  34. "github.com/drakkan/sftpgo/v2/kms"
  35. "github.com/drakkan/sftpgo/v2/logger"
  36. "github.com/drakkan/sftpgo/v2/util"
  37. "github.com/drakkan/sftpgo/v2/version"
  38. )
  39. const (
  40. // sftpFsName is the name for the SFTP Fs implementation
  41. sftpFsName = "sftpfs"
  42. )
  43. // ErrSFTPLoop defines the error to return if an SFTP loop is detected
  44. var ErrSFTPLoop = errors.New("SFTP loop or nested local SFTP folders detected")
  45. // SFTPFsConfig defines the configuration for SFTP based filesystem
  46. type SFTPFsConfig struct {
  47. sdk.BaseSFTPFsConfig
  48. Password *kms.Secret `json:"password,omitempty"`
  49. PrivateKey *kms.Secret `json:"private_key,omitempty"`
  50. KeyPassphrase *kms.Secret `json:"key_passphrase,omitempty"`
  51. forbiddenSelfUsernames []string `json:"-"`
  52. }
  53. // HideConfidentialData hides confidential data
  54. func (c *SFTPFsConfig) HideConfidentialData() {
  55. if c.Password != nil {
  56. c.Password.Hide()
  57. }
  58. if c.PrivateKey != nil {
  59. c.PrivateKey.Hide()
  60. }
  61. if c.KeyPassphrase != nil {
  62. c.KeyPassphrase.Hide()
  63. }
  64. }
  65. func (c *SFTPFsConfig) setNilSecretsIfEmpty() {
  66. if c.Password != nil && c.Password.IsEmpty() {
  67. c.Password = nil
  68. }
  69. if c.PrivateKey != nil && c.PrivateKey.IsEmpty() {
  70. c.PrivateKey = nil
  71. }
  72. if c.KeyPassphrase != nil && c.KeyPassphrase.IsEmpty() {
  73. c.KeyPassphrase = nil
  74. }
  75. }
  76. func (c *SFTPFsConfig) isEqual(other *SFTPFsConfig) bool {
  77. if c.Endpoint != other.Endpoint {
  78. return false
  79. }
  80. if c.Username != other.Username {
  81. return false
  82. }
  83. if c.Prefix != other.Prefix {
  84. return false
  85. }
  86. if c.DisableCouncurrentReads != other.DisableCouncurrentReads {
  87. return false
  88. }
  89. if c.BufferSize != other.BufferSize {
  90. return false
  91. }
  92. if len(c.Fingerprints) != len(other.Fingerprints) {
  93. return false
  94. }
  95. for _, fp := range c.Fingerprints {
  96. if !util.Contains(other.Fingerprints, fp) {
  97. return false
  98. }
  99. }
  100. c.setEmptyCredentialsIfNil()
  101. other.setEmptyCredentialsIfNil()
  102. if !c.Password.IsEqual(other.Password) {
  103. return false
  104. }
  105. if !c.KeyPassphrase.IsEqual(other.KeyPassphrase) {
  106. return false
  107. }
  108. return c.PrivateKey.IsEqual(other.PrivateKey)
  109. }
  110. func (c *SFTPFsConfig) setEmptyCredentialsIfNil() {
  111. if c.Password == nil {
  112. c.Password = kms.NewEmptySecret()
  113. }
  114. if c.PrivateKey == nil {
  115. c.PrivateKey = kms.NewEmptySecret()
  116. }
  117. if c.KeyPassphrase == nil {
  118. c.KeyPassphrase = kms.NewEmptySecret()
  119. }
  120. }
  121. // validate returns an error if the configuration is not valid
  122. func (c *SFTPFsConfig) validate() error {
  123. c.setEmptyCredentialsIfNil()
  124. if c.Endpoint == "" {
  125. return errors.New("endpoint cannot be empty")
  126. }
  127. _, _, err := net.SplitHostPort(c.Endpoint)
  128. if err != nil {
  129. return fmt.Errorf("invalid endpoint: %v", err)
  130. }
  131. if c.Username == "" {
  132. return errors.New("username cannot be empty")
  133. }
  134. if c.BufferSize < 0 || c.BufferSize > 16 {
  135. return errors.New("invalid buffer_size, valid range is 0-16")
  136. }
  137. if err := c.validateCredentials(); err != nil {
  138. return err
  139. }
  140. if c.Prefix != "" {
  141. c.Prefix = util.CleanPath(c.Prefix)
  142. } else {
  143. c.Prefix = "/"
  144. }
  145. return nil
  146. }
  147. func (c *SFTPFsConfig) validateCredentials() error {
  148. if c.Password.IsEmpty() && c.PrivateKey.IsEmpty() {
  149. return errors.New("credentials cannot be empty")
  150. }
  151. if c.Password.IsEncrypted() && !c.Password.IsValid() {
  152. return errors.New("invalid encrypted password")
  153. }
  154. if !c.Password.IsEmpty() && !c.Password.IsValidInput() {
  155. return errors.New("invalid password")
  156. }
  157. if c.PrivateKey.IsEncrypted() && !c.PrivateKey.IsValid() {
  158. return errors.New("invalid encrypted private key")
  159. }
  160. if !c.PrivateKey.IsEmpty() && !c.PrivateKey.IsValidInput() {
  161. return errors.New("invalid private key")
  162. }
  163. if c.KeyPassphrase.IsEncrypted() && !c.KeyPassphrase.IsValid() {
  164. return errors.New("invalid encrypted private key passphrase")
  165. }
  166. if !c.KeyPassphrase.IsEmpty() && !c.KeyPassphrase.IsValidInput() {
  167. return errors.New("invalid private key passphrase")
  168. }
  169. return nil
  170. }
  171. // ValidateAndEncryptCredentials encrypts password and/or private key if they are in plain text
  172. func (c *SFTPFsConfig) ValidateAndEncryptCredentials(additionalData string) error {
  173. if err := c.validate(); err != nil {
  174. return util.NewValidationError(fmt.Sprintf("could not validate SFTP fs config: %v", err))
  175. }
  176. if c.Password.IsPlain() {
  177. c.Password.SetAdditionalData(additionalData)
  178. if err := c.Password.Encrypt(); err != nil {
  179. return util.NewValidationError(fmt.Sprintf("could not encrypt SFTP fs password: %v", err))
  180. }
  181. }
  182. if c.PrivateKey.IsPlain() {
  183. c.PrivateKey.SetAdditionalData(additionalData)
  184. if err := c.PrivateKey.Encrypt(); err != nil {
  185. return util.NewValidationError(fmt.Sprintf("could not encrypt SFTP fs private key: %v", err))
  186. }
  187. }
  188. if c.KeyPassphrase.IsPlain() {
  189. c.KeyPassphrase.SetAdditionalData(additionalData)
  190. if err := c.KeyPassphrase.Encrypt(); err != nil {
  191. return util.NewValidationError(fmt.Sprintf("could not encrypt SFTP fs private key passphrase: %v", err))
  192. }
  193. }
  194. return nil
  195. }
  196. // SFTPFs is a Fs implementation for SFTP backends
  197. type SFTPFs struct {
  198. sync.Mutex
  199. connectionID string
  200. // if not empty this fs is mouted as virtual folder in the specified path
  201. mountPath string
  202. localTempDir string
  203. config *SFTPFsConfig
  204. sshClient *ssh.Client
  205. sftpClient *sftp.Client
  206. err chan error
  207. }
  208. // NewSFTPFs returns an SFTPFs object that allows to interact with an SFTP server
  209. func NewSFTPFs(connectionID, mountPath, localTempDir string, forbiddenSelfUsernames []string, config SFTPFsConfig) (Fs, error) {
  210. if localTempDir == "" {
  211. if tempPath != "" {
  212. localTempDir = tempPath
  213. } else {
  214. localTempDir = filepath.Clean(os.TempDir())
  215. }
  216. }
  217. if err := config.validate(); err != nil {
  218. return nil, err
  219. }
  220. if !config.Password.IsEmpty() {
  221. if err := config.Password.TryDecrypt(); err != nil {
  222. return nil, err
  223. }
  224. }
  225. if !config.PrivateKey.IsEmpty() {
  226. if err := config.PrivateKey.TryDecrypt(); err != nil {
  227. return nil, err
  228. }
  229. }
  230. if !config.KeyPassphrase.IsEmpty() {
  231. if err := config.KeyPassphrase.TryDecrypt(); err != nil {
  232. return nil, err
  233. }
  234. }
  235. config.forbiddenSelfUsernames = forbiddenSelfUsernames
  236. sftpFs := &SFTPFs{
  237. connectionID: connectionID,
  238. mountPath: getMountPath(mountPath),
  239. localTempDir: localTempDir,
  240. config: &config,
  241. err: make(chan error, 1),
  242. }
  243. err := sftpFs.createConnection()
  244. return sftpFs, err
  245. }
  246. // Name returns the name for the Fs implementation
  247. func (fs *SFTPFs) Name() string {
  248. return fmt.Sprintf("%v %#v", sftpFsName, fs.config.Endpoint)
  249. }
  250. // ConnectionID returns the connection ID associated to this Fs implementation
  251. func (fs *SFTPFs) ConnectionID() string {
  252. return fs.connectionID
  253. }
  254. // Stat returns a FileInfo describing the named file
  255. func (fs *SFTPFs) Stat(name string) (os.FileInfo, error) {
  256. if err := fs.checkConnection(); err != nil {
  257. return nil, err
  258. }
  259. return fs.sftpClient.Stat(name)
  260. }
  261. // Lstat returns a FileInfo describing the named file
  262. func (fs *SFTPFs) Lstat(name string) (os.FileInfo, error) {
  263. if err := fs.checkConnection(); err != nil {
  264. return nil, err
  265. }
  266. return fs.sftpClient.Lstat(name)
  267. }
  268. // Open opens the named file for reading
  269. func (fs *SFTPFs) Open(name string, offset int64) (File, *pipeat.PipeReaderAt, func(), error) {
  270. if err := fs.checkConnection(); err != nil {
  271. return nil, nil, nil, err
  272. }
  273. f, err := fs.sftpClient.Open(name)
  274. if err != nil {
  275. return nil, nil, nil, err
  276. }
  277. if offset > 0 {
  278. _, err = f.Seek(offset, io.SeekStart)
  279. if err != nil {
  280. f.Close()
  281. return nil, nil, nil, err
  282. }
  283. }
  284. if fs.config.BufferSize == 0 {
  285. return f, nil, nil, nil
  286. }
  287. r, w, err := pipeat.PipeInDir(fs.localTempDir)
  288. if err != nil {
  289. f.Close()
  290. return nil, nil, nil, err
  291. }
  292. go func() {
  293. // if we enable buffering the client stalls
  294. //br := bufio.NewReaderSize(f, int(fs.config.BufferSize)*1024*1024)
  295. //n, err := fs.copy(w, br)
  296. n, err := io.Copy(w, f)
  297. w.CloseWithError(err) //nolint:errcheck
  298. f.Close()
  299. fsLog(fs, logger.LevelDebug, "download completed, path: %#v size: %v, err: %v", name, n, err)
  300. }()
  301. return nil, r, nil, nil
  302. }
  303. // Create creates or opens the named file for writing
  304. func (fs *SFTPFs) Create(name string, flag int) (File, *PipeWriter, func(), error) {
  305. err := fs.checkConnection()
  306. if err != nil {
  307. return nil, nil, nil, err
  308. }
  309. if fs.config.BufferSize == 0 {
  310. var f File
  311. if flag == 0 {
  312. f, err = fs.sftpClient.Create(name)
  313. } else {
  314. f, err = fs.sftpClient.OpenFile(name, flag)
  315. }
  316. return f, nil, nil, err
  317. }
  318. // buffering is enabled
  319. f, err := fs.sftpClient.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_TRUNC)
  320. if err != nil {
  321. return nil, nil, nil, err
  322. }
  323. r, w, err := pipeat.PipeInDir(fs.localTempDir)
  324. if err != nil {
  325. f.Close()
  326. return nil, nil, nil, err
  327. }
  328. p := NewPipeWriter(w)
  329. go func() {
  330. bw := bufio.NewWriterSize(f, int(fs.config.BufferSize)*1024*1024)
  331. // we don't use io.Copy since bufio.Writer implements io.WriterTo and
  332. // so it calls the sftp.File WriteTo method without buffering
  333. n, err := fs.copy(bw, r)
  334. errFlush := bw.Flush()
  335. if err == nil && errFlush != nil {
  336. err = errFlush
  337. }
  338. var errTruncate error
  339. if err != nil {
  340. errTruncate = f.Truncate(n)
  341. }
  342. errClose := f.Close()
  343. if err == nil && errClose != nil {
  344. err = errClose
  345. }
  346. r.CloseWithError(err) //nolint:errcheck
  347. p.Done(err)
  348. fsLog(fs, logger.LevelDebug, "upload completed, path: %#v, readed bytes: %v, err: %v err truncate: %v",
  349. name, n, err, errTruncate)
  350. }()
  351. return nil, p, nil, nil
  352. }
  353. // Rename renames (moves) source to target.
  354. func (fs *SFTPFs) Rename(source, target string) error {
  355. if err := fs.checkConnection(); err != nil {
  356. return err
  357. }
  358. if _, ok := fs.sftpClient.HasExtension("[email protected]"); ok {
  359. return fs.sftpClient.PosixRename(source, target)
  360. }
  361. return fs.sftpClient.Rename(source, target)
  362. }
  363. // Remove removes the named file or (empty) directory.
  364. func (fs *SFTPFs) Remove(name string, isDir bool) error {
  365. if err := fs.checkConnection(); err != nil {
  366. return err
  367. }
  368. if isDir {
  369. return fs.sftpClient.RemoveDirectory(name)
  370. }
  371. return fs.sftpClient.Remove(name)
  372. }
  373. // Mkdir creates a new directory with the specified name and default permissions
  374. func (fs *SFTPFs) Mkdir(name string) error {
  375. if err := fs.checkConnection(); err != nil {
  376. return err
  377. }
  378. return fs.sftpClient.Mkdir(name)
  379. }
  380. // Symlink creates source as a symbolic link to target.
  381. func (fs *SFTPFs) Symlink(source, target string) error {
  382. if err := fs.checkConnection(); err != nil {
  383. return err
  384. }
  385. return fs.sftpClient.Symlink(source, target)
  386. }
  387. // Readlink returns the destination of the named symbolic link
  388. func (fs *SFTPFs) Readlink(name string) (string, error) {
  389. if err := fs.checkConnection(); err != nil {
  390. return "", err
  391. }
  392. resolved, err := fs.sftpClient.ReadLink(name)
  393. if err != nil {
  394. return resolved, err
  395. }
  396. resolved = path.Clean(resolved)
  397. if !path.IsAbs(resolved) {
  398. // we assume that multiple links are not followed
  399. resolved = path.Join(path.Dir(name), resolved)
  400. }
  401. return fs.GetRelativePath(resolved), nil
  402. }
  403. // Chown changes the numeric uid and gid of the named file.
  404. func (fs *SFTPFs) Chown(name string, uid int, gid int) error {
  405. if err := fs.checkConnection(); err != nil {
  406. return err
  407. }
  408. return fs.sftpClient.Chown(name, uid, gid)
  409. }
  410. // Chmod changes the mode of the named file to mode.
  411. func (fs *SFTPFs) Chmod(name string, mode os.FileMode) error {
  412. if err := fs.checkConnection(); err != nil {
  413. return err
  414. }
  415. return fs.sftpClient.Chmod(name, mode)
  416. }
  417. // Chtimes changes the access and modification times of the named file.
  418. func (fs *SFTPFs) Chtimes(name string, atime, mtime time.Time, isUploading bool) error {
  419. if err := fs.checkConnection(); err != nil {
  420. return err
  421. }
  422. return fs.sftpClient.Chtimes(name, atime, mtime)
  423. }
  424. // Truncate changes the size of the named file.
  425. func (fs *SFTPFs) Truncate(name string, size int64) error {
  426. if err := fs.checkConnection(); err != nil {
  427. return err
  428. }
  429. return fs.sftpClient.Truncate(name, size)
  430. }
  431. // ReadDir reads the directory named by dirname and returns
  432. // a list of directory entries.
  433. func (fs *SFTPFs) ReadDir(dirname string) ([]os.FileInfo, error) {
  434. if err := fs.checkConnection(); err != nil {
  435. return nil, err
  436. }
  437. return fs.sftpClient.ReadDir(dirname)
  438. }
  439. // IsUploadResumeSupported returns true if resuming uploads is supported.
  440. func (fs *SFTPFs) IsUploadResumeSupported() bool {
  441. return fs.config.BufferSize == 0
  442. }
  443. // IsAtomicUploadSupported returns true if atomic upload is supported.
  444. func (fs *SFTPFs) IsAtomicUploadSupported() bool {
  445. return fs.config.BufferSize == 0
  446. }
  447. // IsNotExist returns a boolean indicating whether the error is known to
  448. // report that a file or directory does not exist
  449. func (*SFTPFs) IsNotExist(err error) bool {
  450. return errors.Is(err, fs.ErrNotExist)
  451. }
  452. // IsPermission returns a boolean indicating whether the error is known to
  453. // report that permission is denied.
  454. func (*SFTPFs) IsPermission(err error) bool {
  455. if _, ok := err.(*pathResolutionError); ok {
  456. return true
  457. }
  458. return errors.Is(err, fs.ErrPermission)
  459. }
  460. // IsNotSupported returns true if the error indicate an unsupported operation
  461. func (*SFTPFs) IsNotSupported(err error) bool {
  462. if err == nil {
  463. return false
  464. }
  465. return err == ErrVfsUnsupported
  466. }
  467. // CheckRootPath creates the specified local root directory if it does not exists
  468. func (fs *SFTPFs) CheckRootPath(username string, uid int, gid int) bool {
  469. // we need a local directory for temporary files
  470. osFs := NewOsFs(fs.ConnectionID(), fs.localTempDir, "")
  471. osFs.CheckRootPath(username, uid, gid)
  472. if fs.config.Prefix == "/" {
  473. return true
  474. }
  475. if err := fs.checkConnection(); err != nil {
  476. return false
  477. }
  478. if err := fs.sftpClient.MkdirAll(fs.config.Prefix); err != nil {
  479. fsLog(fs, logger.LevelDebug, "error creating root directory %#v for user %#v: %v", fs.config.Prefix, username, err)
  480. return false
  481. }
  482. return true
  483. }
  484. // ScanRootDirContents returns the number of files contained in a directory and
  485. // their size
  486. func (fs *SFTPFs) ScanRootDirContents() (int, int64, error) {
  487. return fs.GetDirSize(fs.config.Prefix)
  488. }
  489. // CheckMetadata checks the metadata consistency
  490. func (*SFTPFs) CheckMetadata() error {
  491. return nil
  492. }
  493. // GetAtomicUploadPath returns the path to use for an atomic upload
  494. func (*SFTPFs) GetAtomicUploadPath(name string) string {
  495. dir := path.Dir(name)
  496. guid := xid.New().String()
  497. return path.Join(dir, ".sftpgo-upload."+guid+"."+path.Base(name))
  498. }
  499. // GetRelativePath returns the path for a file relative to the sftp prefix if any.
  500. // This is the path as seen by SFTPGo users
  501. func (fs *SFTPFs) GetRelativePath(name string) string {
  502. rel := path.Clean(name)
  503. if rel == "." {
  504. rel = ""
  505. }
  506. if !path.IsAbs(rel) {
  507. return "/" + rel
  508. }
  509. if fs.config.Prefix != "/" {
  510. if !strings.HasPrefix(rel, fs.config.Prefix) {
  511. rel = "/"
  512. }
  513. rel = path.Clean("/" + strings.TrimPrefix(rel, fs.config.Prefix))
  514. }
  515. if fs.mountPath != "" {
  516. rel = path.Join(fs.mountPath, rel)
  517. }
  518. return rel
  519. }
  520. // Walk walks the file tree rooted at root, calling walkFn for each file or
  521. // directory in the tree, including root
  522. func (fs *SFTPFs) Walk(root string, walkFn filepath.WalkFunc) error {
  523. if err := fs.checkConnection(); err != nil {
  524. return err
  525. }
  526. walker := fs.sftpClient.Walk(root)
  527. for walker.Step() {
  528. err := walker.Err()
  529. if err != nil {
  530. return err
  531. }
  532. err = walkFn(walker.Path(), walker.Stat(), err)
  533. if err != nil {
  534. return err
  535. }
  536. }
  537. return nil
  538. }
  539. // Join joins any number of path elements into a single path
  540. func (*SFTPFs) Join(elem ...string) string {
  541. return path.Join(elem...)
  542. }
  543. // HasVirtualFolders returns true if folders are emulated
  544. func (*SFTPFs) HasVirtualFolders() bool {
  545. return false
  546. }
  547. // ResolvePath returns the matching filesystem path for the specified virtual path
  548. func (fs *SFTPFs) ResolvePath(virtualPath string) (string, error) {
  549. if fs.mountPath != "" {
  550. virtualPath = strings.TrimPrefix(virtualPath, fs.mountPath)
  551. }
  552. if !path.IsAbs(virtualPath) {
  553. virtualPath = path.Clean("/" + virtualPath)
  554. }
  555. fsPath := fs.Join(fs.config.Prefix, virtualPath)
  556. if fs.config.Prefix != "/" && fsPath != "/" {
  557. // we need to check if this path is a symlink outside the given prefix
  558. // or a file/dir inside a dir symlinked outside the prefix
  559. if err := fs.checkConnection(); err != nil {
  560. return "", err
  561. }
  562. var validatedPath string
  563. var err error
  564. validatedPath, err = fs.getRealPath(fsPath)
  565. isNotExist := fs.IsNotExist(err)
  566. if err != nil && !isNotExist {
  567. fsLog(fs, logger.LevelError, "Invalid path resolution, original path %v resolved %#v err: %v",
  568. virtualPath, fsPath, err)
  569. return "", err
  570. } else if isNotExist {
  571. for fs.IsNotExist(err) {
  572. validatedPath = path.Dir(validatedPath)
  573. if validatedPath == "/" {
  574. err = nil
  575. break
  576. }
  577. validatedPath, err = fs.getRealPath(validatedPath)
  578. }
  579. if err != nil {
  580. fsLog(fs, logger.LevelError, "Invalid path resolution, dir %#v original path %#v resolved %#v err: %v",
  581. validatedPath, virtualPath, fsPath, err)
  582. return "", err
  583. }
  584. }
  585. if err := fs.isSubDir(validatedPath); err != nil {
  586. fsLog(fs, logger.LevelError, "Invalid path resolution, dir %#v original path %#v resolved %#v err: %v",
  587. validatedPath, virtualPath, fsPath, err)
  588. return "", err
  589. }
  590. }
  591. return fsPath, nil
  592. }
  593. // getRealPath returns the real remote path trying to resolve symbolic links if any
  594. func (fs *SFTPFs) getRealPath(name string) (string, error) {
  595. linksWalked := 0
  596. for {
  597. info, err := fs.sftpClient.Lstat(name)
  598. if err != nil {
  599. return name, err
  600. }
  601. if info.Mode()&os.ModeSymlink == 0 {
  602. return name, nil
  603. }
  604. resolvedLink, err := fs.sftpClient.ReadLink(name)
  605. if err != nil {
  606. return name, err
  607. }
  608. resolvedLink = path.Clean(resolvedLink)
  609. if path.IsAbs(resolvedLink) {
  610. name = resolvedLink
  611. } else {
  612. name = path.Join(path.Dir(name), resolvedLink)
  613. }
  614. linksWalked++
  615. if linksWalked > 10 {
  616. return "", &pathResolutionError{err: "too many links"}
  617. }
  618. }
  619. }
  620. func (fs *SFTPFs) isSubDir(name string) error {
  621. if name == fs.config.Prefix {
  622. return nil
  623. }
  624. if len(name) < len(fs.config.Prefix) {
  625. err := fmt.Errorf("path %#v is not inside: %#v", name, fs.config.Prefix)
  626. return &pathResolutionError{err: err.Error()}
  627. }
  628. if !strings.HasPrefix(name, fs.config.Prefix+"/") {
  629. err := fmt.Errorf("path %#v is not inside: %#v", name, fs.config.Prefix)
  630. return &pathResolutionError{err: err.Error()}
  631. }
  632. return nil
  633. }
  634. // GetDirSize returns the number of files and the size for a folder
  635. // including any subfolders
  636. func (fs *SFTPFs) GetDirSize(dirname string) (int, int64, error) {
  637. numFiles := 0
  638. size := int64(0)
  639. if err := fs.checkConnection(); err != nil {
  640. return numFiles, size, err
  641. }
  642. isDir, err := IsDirectory(fs, dirname)
  643. if err == nil && isDir {
  644. walker := fs.sftpClient.Walk(dirname)
  645. for walker.Step() {
  646. err := walker.Err()
  647. if err != nil {
  648. return numFiles, size, err
  649. }
  650. if walker.Stat().Mode().IsRegular() {
  651. size += walker.Stat().Size()
  652. numFiles++
  653. }
  654. }
  655. }
  656. return numFiles, size, err
  657. }
  658. // GetMimeType returns the content type
  659. func (fs *SFTPFs) GetMimeType(name string) (string, error) {
  660. if err := fs.checkConnection(); err != nil {
  661. return "", err
  662. }
  663. f, err := fs.sftpClient.OpenFile(name, os.O_RDONLY)
  664. if err != nil {
  665. return "", err
  666. }
  667. defer f.Close()
  668. var buf [512]byte
  669. n, err := io.ReadFull(f, buf[:])
  670. if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF {
  671. return "", err
  672. }
  673. ctype := http.DetectContentType(buf[:n])
  674. // Rewind file.
  675. _, err = f.Seek(0, io.SeekStart)
  676. return ctype, err
  677. }
  678. // GetAvailableDiskSize returns the available size for the specified path
  679. func (fs *SFTPFs) GetAvailableDiskSize(dirName string) (*sftp.StatVFS, error) {
  680. if err := fs.checkConnection(); err != nil {
  681. return nil, err
  682. }
  683. if _, ok := fs.sftpClient.HasExtension("[email protected]"); !ok {
  684. return nil, ErrStorageSizeUnavailable
  685. }
  686. return fs.sftpClient.StatVFS(dirName)
  687. }
  688. // Close the connection
  689. func (fs *SFTPFs) Close() error {
  690. fs.Lock()
  691. defer fs.Unlock()
  692. var sftpErr, sshErr error
  693. if fs.sftpClient != nil {
  694. sftpErr = fs.sftpClient.Close()
  695. }
  696. if fs.sshClient != nil {
  697. sshErr = fs.sshClient.Close()
  698. }
  699. if sftpErr != nil {
  700. return sftpErr
  701. }
  702. return sshErr
  703. }
  704. func (fs *SFTPFs) copy(dst io.Writer, src io.Reader) (written int64, err error) {
  705. buf := make([]byte, 32768)
  706. for {
  707. nr, er := src.Read(buf)
  708. if nr > 0 {
  709. nw, ew := dst.Write(buf[0:nr])
  710. if nw < 0 || nr < nw {
  711. nw = 0
  712. if ew == nil {
  713. ew = errors.New("invalid write")
  714. }
  715. }
  716. written += int64(nw)
  717. if ew != nil {
  718. err = ew
  719. break
  720. }
  721. if nr != nw {
  722. err = io.ErrShortWrite
  723. break
  724. }
  725. }
  726. if er != nil {
  727. if er != io.EOF {
  728. err = er
  729. }
  730. break
  731. }
  732. }
  733. return written, err
  734. }
  735. func (fs *SFTPFs) checkConnection() error {
  736. err := fs.closed()
  737. if err == nil {
  738. return nil
  739. }
  740. return fs.createConnection()
  741. }
  742. func (fs *SFTPFs) createConnection() error {
  743. fs.Lock()
  744. defer fs.Unlock()
  745. var err error
  746. clientConfig := &ssh.ClientConfig{
  747. User: fs.config.Username,
  748. HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
  749. fp := ssh.FingerprintSHA256(key)
  750. if util.Contains(sftpFingerprints, fp) {
  751. if util.Contains(fs.config.forbiddenSelfUsernames, fs.config.Username) {
  752. fsLog(fs, logger.LevelError, "SFTP loop or nested local SFTP folders detected, mount path %#v, username %#v, forbidden usernames: %+v",
  753. fs.mountPath, fs.config.Username, fs.config.forbiddenSelfUsernames)
  754. return ErrSFTPLoop
  755. }
  756. }
  757. if len(fs.config.Fingerprints) > 0 {
  758. for _, provided := range fs.config.Fingerprints {
  759. if provided == fp {
  760. return nil
  761. }
  762. }
  763. return fmt.Errorf("invalid fingerprint %#v", fp)
  764. }
  765. fsLog(fs, logger.LevelWarn, "login without host key validation, please provide at least a fingerprint!")
  766. return nil
  767. },
  768. Timeout: 10 * time.Second,
  769. ClientVersion: fmt.Sprintf("SSH-2.0-SFTPGo_%v", version.Get().Version),
  770. }
  771. if fs.config.PrivateKey.GetPayload() != "" {
  772. var signer ssh.Signer
  773. if fs.config.KeyPassphrase.GetPayload() != "" {
  774. signer, err = ssh.ParsePrivateKeyWithPassphrase([]byte(fs.config.PrivateKey.GetPayload()),
  775. []byte(fs.config.KeyPassphrase.GetPayload()))
  776. } else {
  777. signer, err = ssh.ParsePrivateKey([]byte(fs.config.PrivateKey.GetPayload()))
  778. }
  779. if err != nil {
  780. fs.err <- err
  781. return fmt.Errorf("sftpfs: unable to parse the private key: %w", err)
  782. }
  783. clientConfig.Auth = append(clientConfig.Auth, ssh.PublicKeys(signer))
  784. }
  785. if fs.config.Password.GetPayload() != "" {
  786. clientConfig.Auth = append(clientConfig.Auth, ssh.Password(fs.config.Password.GetPayload()))
  787. }
  788. // add more ciphers, KEXs and MACs, they are negotiated according to the order
  789. clientConfig.Ciphers = []string{"[email protected]", "[email protected]", "[email protected]",
  790. "aes128-ctr", "aes192-ctr", "aes256-ctr", "aes128-cbc", "aes192-cbc", "aes256-cbc"}
  791. clientConfig.KeyExchanges = []string{"curve25519-sha256", "[email protected]",
  792. "ecdh-sha2-nistp256", "ecdh-sha2-nistp384", "ecdh-sha2-nistp521",
  793. "diffie-hellman-group14-sha256", "diffie-hellman-group16-sha512", "diffie-hellman-group18-sha512",
  794. "diffie-hellman-group-exchange-sha256", "diffie-hellman-group-exchange-sha1",
  795. "diffie-hellman-group14-sha1", "diffie-hellman-group1-sha1"}
  796. clientConfig.MACs = []string{"[email protected]", "hmac-sha2-256",
  797. "[email protected]", "hmac-sha2-512",
  798. "hmac-sha1", "hmac-sha1-96"}
  799. fs.sshClient, err = ssh.Dial("tcp", fs.config.Endpoint, clientConfig)
  800. if err != nil {
  801. fsLog(fs, logger.LevelError, "unable to connect: %v", err)
  802. fs.err <- err
  803. return err
  804. }
  805. fs.sftpClient, err = sftp.NewClient(fs.sshClient)
  806. if err != nil {
  807. fsLog(fs, logger.LevelError, "unable to create SFTP client: %v", err)
  808. fs.sshClient.Close()
  809. fs.err <- err
  810. return err
  811. }
  812. if fs.config.DisableCouncurrentReads {
  813. fsLog(fs, logger.LevelDebug, "disabling concurrent reads")
  814. opt := sftp.UseConcurrentReads(false)
  815. opt(fs.sftpClient) //nolint:errcheck
  816. }
  817. if fs.config.BufferSize > 0 {
  818. fsLog(fs, logger.LevelDebug, "enabling concurrent writes")
  819. opt := sftp.UseConcurrentWrites(true)
  820. opt(fs.sftpClient) //nolint:errcheck
  821. }
  822. go fs.wait()
  823. return nil
  824. }
  825. func (fs *SFTPFs) wait() {
  826. // we wait on the sftp client otherwise if the channel is closed but not the connection
  827. // we don't detect the event.
  828. fs.err <- fs.sftpClient.Wait()
  829. fsLog(fs, logger.LevelDebug, "sftp channel closed")
  830. fs.Lock()
  831. defer fs.Unlock()
  832. if fs.sshClient != nil {
  833. fs.sshClient.Close()
  834. }
  835. }
  836. func (fs *SFTPFs) closed() error {
  837. select {
  838. case err := <-fs.err:
  839. return err
  840. default:
  841. return nil
  842. }
  843. }