sftpfs.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929
  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 validates the config and encrypts credentials 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 fs.config.BufferSize == 0 {
  278. return f, nil, nil, err
  279. }
  280. if offset > 0 {
  281. _, err = f.Seek(offset, io.SeekStart)
  282. if err != nil {
  283. f.Close()
  284. return nil, nil, nil, err
  285. }
  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. if fs.config.BufferSize > 0 {
  470. // we need a local directory for temporary files
  471. osFs := NewOsFs(fs.ConnectionID(), fs.localTempDir, "")
  472. osFs.CheckRootPath(username, uid, gid)
  473. }
  474. if fs.config.Prefix == "/" {
  475. return true
  476. }
  477. if err := fs.checkConnection(); err != nil {
  478. return false
  479. }
  480. if err := fs.sftpClient.MkdirAll(fs.config.Prefix); err != nil {
  481. fsLog(fs, logger.LevelDebug, "error creating root directory %#v for user %#v: %v", fs.config.Prefix, username, err)
  482. return false
  483. }
  484. return true
  485. }
  486. // ScanRootDirContents returns the number of files contained in a directory and
  487. // their size
  488. func (fs *SFTPFs) ScanRootDirContents() (int, int64, error) {
  489. return fs.GetDirSize(fs.config.Prefix)
  490. }
  491. // CheckMetadata checks the metadata consistency
  492. func (*SFTPFs) CheckMetadata() error {
  493. return nil
  494. }
  495. // GetAtomicUploadPath returns the path to use for an atomic upload
  496. func (*SFTPFs) GetAtomicUploadPath(name string) string {
  497. dir := path.Dir(name)
  498. guid := xid.New().String()
  499. return path.Join(dir, ".sftpgo-upload."+guid+"."+path.Base(name))
  500. }
  501. // GetRelativePath returns the path for a file relative to the sftp prefix if any.
  502. // This is the path as seen by SFTPGo users
  503. func (fs *SFTPFs) GetRelativePath(name string) string {
  504. rel := path.Clean(name)
  505. if rel == "." {
  506. rel = ""
  507. }
  508. if !path.IsAbs(rel) {
  509. return "/" + rel
  510. }
  511. if fs.config.Prefix != "/" {
  512. if !strings.HasPrefix(rel, fs.config.Prefix) {
  513. rel = "/"
  514. }
  515. rel = path.Clean("/" + strings.TrimPrefix(rel, fs.config.Prefix))
  516. }
  517. if fs.mountPath != "" {
  518. rel = path.Join(fs.mountPath, rel)
  519. }
  520. return rel
  521. }
  522. // Walk walks the file tree rooted at root, calling walkFn for each file or
  523. // directory in the tree, including root
  524. func (fs *SFTPFs) Walk(root string, walkFn filepath.WalkFunc) error {
  525. if err := fs.checkConnection(); err != nil {
  526. return err
  527. }
  528. walker := fs.sftpClient.Walk(root)
  529. for walker.Step() {
  530. err := walker.Err()
  531. if err != nil {
  532. return err
  533. }
  534. err = walkFn(walker.Path(), walker.Stat(), err)
  535. if err != nil {
  536. return err
  537. }
  538. }
  539. return nil
  540. }
  541. // Join joins any number of path elements into a single path
  542. func (*SFTPFs) Join(elem ...string) string {
  543. return path.Join(elem...)
  544. }
  545. // HasVirtualFolders returns true if folders are emulated
  546. func (*SFTPFs) HasVirtualFolders() bool {
  547. return false
  548. }
  549. // ResolvePath returns the matching filesystem path for the specified virtual path
  550. func (fs *SFTPFs) ResolvePath(virtualPath string) (string, error) {
  551. if fs.mountPath != "" {
  552. virtualPath = strings.TrimPrefix(virtualPath, fs.mountPath)
  553. }
  554. if !path.IsAbs(virtualPath) {
  555. virtualPath = path.Clean("/" + virtualPath)
  556. }
  557. fsPath := fs.Join(fs.config.Prefix, virtualPath)
  558. if fs.config.Prefix != "/" && fsPath != "/" {
  559. // we need to check if this path is a symlink outside the given prefix
  560. // or a file/dir inside a dir symlinked outside the prefix
  561. if err := fs.checkConnection(); err != nil {
  562. return "", err
  563. }
  564. var validatedPath string
  565. var err error
  566. validatedPath, err = fs.getRealPath(fsPath)
  567. isNotExist := fs.IsNotExist(err)
  568. if err != nil && !isNotExist {
  569. fsLog(fs, logger.LevelError, "Invalid path resolution, original path %v resolved %#v err: %v",
  570. virtualPath, fsPath, err)
  571. return "", err
  572. } else if isNotExist {
  573. for fs.IsNotExist(err) {
  574. validatedPath = path.Dir(validatedPath)
  575. if validatedPath == "/" {
  576. err = nil
  577. break
  578. }
  579. validatedPath, err = fs.getRealPath(validatedPath)
  580. }
  581. if err != nil {
  582. fsLog(fs, logger.LevelError, "Invalid path resolution, dir %#v original path %#v resolved %#v err: %v",
  583. validatedPath, virtualPath, fsPath, err)
  584. return "", err
  585. }
  586. }
  587. if err := fs.isSubDir(validatedPath); err != nil {
  588. fsLog(fs, logger.LevelError, "Invalid path resolution, dir %#v original path %#v resolved %#v err: %v",
  589. validatedPath, virtualPath, fsPath, err)
  590. return "", err
  591. }
  592. }
  593. return fsPath, nil
  594. }
  595. // RealPath implements the FsRealPather interface
  596. func (fs *SFTPFs) RealPath(p string) (string, error) {
  597. if err := fs.checkConnection(); err != nil {
  598. return "", err
  599. }
  600. resolved, err := fs.sftpClient.RealPath(p)
  601. if err != nil {
  602. return "", err
  603. }
  604. if fs.config.Prefix != "/" {
  605. if err := fs.isSubDir(resolved); err != nil {
  606. fsLog(fs, logger.LevelError, "Invalid real path resolution, original path %q resolved %q err: %v",
  607. p, resolved, err)
  608. return "", err
  609. }
  610. }
  611. return fs.GetRelativePath(resolved), nil
  612. }
  613. // getRealPath returns the real remote path trying to resolve symbolic links if any
  614. func (fs *SFTPFs) getRealPath(name string) (string, error) {
  615. linksWalked := 0
  616. for {
  617. info, err := fs.sftpClient.Lstat(name)
  618. if err != nil {
  619. return name, err
  620. }
  621. if info.Mode()&os.ModeSymlink == 0 {
  622. return name, nil
  623. }
  624. resolvedLink, err := fs.sftpClient.ReadLink(name)
  625. if err != nil {
  626. return name, fmt.Errorf("unable to resolve link to %q: %w", name, err)
  627. }
  628. resolvedLink = path.Clean(resolvedLink)
  629. if path.IsAbs(resolvedLink) {
  630. name = resolvedLink
  631. } else {
  632. name = path.Join(path.Dir(name), resolvedLink)
  633. }
  634. linksWalked++
  635. if linksWalked > 10 {
  636. fsLog(fs, logger.LevelError, "unable to get real path, too many links: %d", linksWalked)
  637. return "", &pathResolutionError{err: "too many links"}
  638. }
  639. }
  640. }
  641. func (fs *SFTPFs) isSubDir(name string) error {
  642. if name == fs.config.Prefix {
  643. return nil
  644. }
  645. if len(name) < len(fs.config.Prefix) {
  646. err := fmt.Errorf("path %q is not inside: %#v", name, fs.config.Prefix)
  647. return &pathResolutionError{err: err.Error()}
  648. }
  649. if !strings.HasPrefix(name, fs.config.Prefix+"/") {
  650. err := fmt.Errorf("path %q is not inside: %#v", name, fs.config.Prefix)
  651. return &pathResolutionError{err: err.Error()}
  652. }
  653. return nil
  654. }
  655. // GetDirSize returns the number of files and the size for a folder
  656. // including any subfolders
  657. func (fs *SFTPFs) GetDirSize(dirname string) (int, int64, error) {
  658. numFiles := 0
  659. size := int64(0)
  660. if err := fs.checkConnection(); err != nil {
  661. return numFiles, size, err
  662. }
  663. isDir, err := IsDirectory(fs, dirname)
  664. if err == nil && isDir {
  665. walker := fs.sftpClient.Walk(dirname)
  666. for walker.Step() {
  667. err := walker.Err()
  668. if err != nil {
  669. return numFiles, size, err
  670. }
  671. if walker.Stat().Mode().IsRegular() {
  672. size += walker.Stat().Size()
  673. numFiles++
  674. }
  675. }
  676. }
  677. return numFiles, size, err
  678. }
  679. // GetMimeType returns the content type
  680. func (fs *SFTPFs) GetMimeType(name string) (string, error) {
  681. if err := fs.checkConnection(); err != nil {
  682. return "", err
  683. }
  684. f, err := fs.sftpClient.OpenFile(name, os.O_RDONLY)
  685. if err != nil {
  686. return "", err
  687. }
  688. defer f.Close()
  689. var buf [512]byte
  690. n, err := io.ReadFull(f, buf[:])
  691. if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF {
  692. return "", err
  693. }
  694. ctype := http.DetectContentType(buf[:n])
  695. // Rewind file.
  696. _, err = f.Seek(0, io.SeekStart)
  697. return ctype, err
  698. }
  699. // GetAvailableDiskSize returns the available size for the specified path
  700. func (fs *SFTPFs) GetAvailableDiskSize(dirName string) (*sftp.StatVFS, error) {
  701. if err := fs.checkConnection(); err != nil {
  702. return nil, err
  703. }
  704. if _, ok := fs.sftpClient.HasExtension("[email protected]"); !ok {
  705. return nil, ErrStorageSizeUnavailable
  706. }
  707. return fs.sftpClient.StatVFS(dirName)
  708. }
  709. // Close the connection
  710. func (fs *SFTPFs) Close() error {
  711. fs.Lock()
  712. defer fs.Unlock()
  713. var sftpErr, sshErr error
  714. if fs.sftpClient != nil {
  715. sftpErr = fs.sftpClient.Close()
  716. }
  717. if fs.sshClient != nil {
  718. sshErr = fs.sshClient.Close()
  719. }
  720. if sftpErr != nil {
  721. return sftpErr
  722. }
  723. return sshErr
  724. }
  725. func (fs *SFTPFs) copy(dst io.Writer, src io.Reader) (written int64, err error) {
  726. buf := make([]byte, 32768)
  727. for {
  728. nr, er := src.Read(buf)
  729. if nr > 0 {
  730. nw, ew := dst.Write(buf[0:nr])
  731. if nw < 0 || nr < nw {
  732. nw = 0
  733. if ew == nil {
  734. ew = errors.New("invalid write")
  735. }
  736. }
  737. written += int64(nw)
  738. if ew != nil {
  739. err = ew
  740. break
  741. }
  742. if nr != nw {
  743. err = io.ErrShortWrite
  744. break
  745. }
  746. }
  747. if er != nil {
  748. if er != io.EOF {
  749. err = er
  750. }
  751. break
  752. }
  753. }
  754. return written, err
  755. }
  756. func (fs *SFTPFs) checkConnection() error {
  757. err := fs.closed()
  758. if err == nil {
  759. return nil
  760. }
  761. return fs.createConnection()
  762. }
  763. func (fs *SFTPFs) createConnection() error {
  764. fs.Lock()
  765. defer fs.Unlock()
  766. var err error
  767. clientConfig := &ssh.ClientConfig{
  768. User: fs.config.Username,
  769. HostKeyCallback: func(_ string, _ net.Addr, key ssh.PublicKey) error {
  770. fp := ssh.FingerprintSHA256(key)
  771. if util.Contains(sftpFingerprints, fp) {
  772. if util.Contains(fs.config.forbiddenSelfUsernames, fs.config.Username) {
  773. fsLog(fs, logger.LevelError, "SFTP loop or nested local SFTP folders detected, mount path %#v, username %#v, forbidden usernames: %+v",
  774. fs.mountPath, fs.config.Username, fs.config.forbiddenSelfUsernames)
  775. return ErrSFTPLoop
  776. }
  777. }
  778. if len(fs.config.Fingerprints) > 0 {
  779. for _, provided := range fs.config.Fingerprints {
  780. if provided == fp {
  781. return nil
  782. }
  783. }
  784. return fmt.Errorf("invalid fingerprint %#v", fp)
  785. }
  786. fsLog(fs, logger.LevelWarn, "login without host key validation, please provide at least a fingerprint!")
  787. return nil
  788. },
  789. Timeout: 10 * time.Second,
  790. ClientVersion: fmt.Sprintf("SSH-2.0-SFTPGo_%v", version.Get().Version),
  791. }
  792. if fs.config.PrivateKey.GetPayload() != "" {
  793. var signer ssh.Signer
  794. if fs.config.KeyPassphrase.GetPayload() != "" {
  795. signer, err = ssh.ParsePrivateKeyWithPassphrase([]byte(fs.config.PrivateKey.GetPayload()),
  796. []byte(fs.config.KeyPassphrase.GetPayload()))
  797. } else {
  798. signer, err = ssh.ParsePrivateKey([]byte(fs.config.PrivateKey.GetPayload()))
  799. }
  800. if err != nil {
  801. fs.err <- err
  802. return fmt.Errorf("sftpfs: unable to parse the private key: %w", err)
  803. }
  804. clientConfig.Auth = append(clientConfig.Auth, ssh.PublicKeys(signer))
  805. }
  806. if fs.config.Password.GetPayload() != "" {
  807. clientConfig.Auth = append(clientConfig.Auth, ssh.Password(fs.config.Password.GetPayload()))
  808. }
  809. // add more ciphers, KEXs and MACs, they are negotiated according to the order
  810. clientConfig.Ciphers = []string{"[email protected]", "[email protected]", "[email protected]",
  811. "aes128-ctr", "aes192-ctr", "aes256-ctr", "aes128-cbc", "aes192-cbc", "aes256-cbc"}
  812. clientConfig.KeyExchanges = []string{"curve25519-sha256", "[email protected]",
  813. "ecdh-sha2-nistp256", "ecdh-sha2-nistp384", "ecdh-sha2-nistp521",
  814. "diffie-hellman-group14-sha256", "diffie-hellman-group16-sha512", "diffie-hellman-group18-sha512",
  815. "diffie-hellman-group-exchange-sha256", "diffie-hellman-group-exchange-sha1",
  816. "diffie-hellman-group14-sha1", "diffie-hellman-group1-sha1"}
  817. clientConfig.MACs = []string{"[email protected]", "hmac-sha2-256",
  818. "[email protected]", "hmac-sha2-512",
  819. "hmac-sha1", "hmac-sha1-96"}
  820. fs.sshClient, err = ssh.Dial("tcp", fs.config.Endpoint, clientConfig)
  821. if err != nil {
  822. fsLog(fs, logger.LevelError, "unable to connect: %v", err)
  823. fs.err <- err
  824. return err
  825. }
  826. fs.sftpClient, err = sftp.NewClient(fs.sshClient)
  827. if err != nil {
  828. fsLog(fs, logger.LevelError, "unable to create SFTP client: %v", err)
  829. fs.sshClient.Close()
  830. fs.err <- err
  831. return err
  832. }
  833. if fs.config.DisableCouncurrentReads {
  834. fsLog(fs, logger.LevelDebug, "disabling concurrent reads")
  835. opt := sftp.UseConcurrentReads(false)
  836. opt(fs.sftpClient) //nolint:errcheck
  837. }
  838. if fs.config.BufferSize > 0 {
  839. fsLog(fs, logger.LevelDebug, "enabling concurrent writes")
  840. opt := sftp.UseConcurrentWrites(true)
  841. opt(fs.sftpClient) //nolint:errcheck
  842. }
  843. go fs.wait()
  844. return nil
  845. }
  846. func (fs *SFTPFs) wait() {
  847. // we wait on the sftp client otherwise if the channel is closed but not the connection
  848. // we don't detect the event.
  849. fs.err <- fs.sftpClient.Wait()
  850. fsLog(fs, logger.LevelDebug, "sftp channel closed")
  851. fs.Lock()
  852. defer fs.Unlock()
  853. if fs.sshClient != nil {
  854. fs.sshClient.Close()
  855. }
  856. }
  857. func (fs *SFTPFs) closed() error {
  858. select {
  859. case err := <-fs.err:
  860. return err
  861. default:
  862. return nil
  863. }
  864. }