sftpfs.go 32 KB

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