sftpfs.go 26 KB

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