sftpfs.go 32 KB

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