1
0

sftpfs.go 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199
  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. "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: %#v 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 := fs.copy(bw, r)
  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: %#v, 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) error {
  401. if source == target {
  402. return nil
  403. }
  404. client, err := fs.conn.getClient()
  405. if err != nil {
  406. return err
  407. }
  408. if _, ok := client.HasExtension("[email protected]"); ok {
  409. return client.PosixRename(source, target)
  410. }
  411. return client.Rename(source, target)
  412. }
  413. // Remove removes the named file or (empty) directory.
  414. func (fs *SFTPFs) Remove(name string, isDir bool) error {
  415. client, err := fs.conn.getClient()
  416. if err != nil {
  417. return err
  418. }
  419. if isDir {
  420. return client.RemoveDirectory(name)
  421. }
  422. return client.Remove(name)
  423. }
  424. // Mkdir creates a new directory with the specified name and default permissions
  425. func (fs *SFTPFs) Mkdir(name string) error {
  426. client, err := fs.conn.getClient()
  427. if err != nil {
  428. return err
  429. }
  430. return client.Mkdir(name)
  431. }
  432. // Symlink creates source as a symbolic link to target.
  433. func (fs *SFTPFs) Symlink(source, target string) error {
  434. client, err := fs.conn.getClient()
  435. if err != nil {
  436. return err
  437. }
  438. return client.Symlink(source, target)
  439. }
  440. // Readlink returns the destination of the named symbolic link
  441. func (fs *SFTPFs) Readlink(name string) (string, error) {
  442. client, err := fs.conn.getClient()
  443. if err != nil {
  444. return "", err
  445. }
  446. resolved, err := client.ReadLink(name)
  447. if err != nil {
  448. return resolved, err
  449. }
  450. resolved = path.Clean(resolved)
  451. if !path.IsAbs(resolved) {
  452. // we assume that multiple links are not followed
  453. resolved = path.Join(path.Dir(name), resolved)
  454. }
  455. return fs.GetRelativePath(resolved), nil
  456. }
  457. // Chown changes the numeric uid and gid of the named file.
  458. func (fs *SFTPFs) Chown(name string, uid int, gid int) error {
  459. client, err := fs.conn.getClient()
  460. if err != nil {
  461. return err
  462. }
  463. return client.Chown(name, uid, gid)
  464. }
  465. // Chmod changes the mode of the named file to mode.
  466. func (fs *SFTPFs) Chmod(name string, mode os.FileMode) error {
  467. client, err := fs.conn.getClient()
  468. if err != nil {
  469. return err
  470. }
  471. return client.Chmod(name, mode)
  472. }
  473. // Chtimes changes the access and modification times of the named file.
  474. func (fs *SFTPFs) Chtimes(name string, atime, mtime time.Time, isUploading bool) error {
  475. client, err := fs.conn.getClient()
  476. if err != nil {
  477. return err
  478. }
  479. return client.Chtimes(name, atime, mtime)
  480. }
  481. // Truncate changes the size of the named file.
  482. func (fs *SFTPFs) Truncate(name string, size int64) error {
  483. client, err := fs.conn.getClient()
  484. if err != nil {
  485. return err
  486. }
  487. return client.Truncate(name, size)
  488. }
  489. // ReadDir reads the directory named by dirname and returns
  490. // a list of directory entries.
  491. func (fs *SFTPFs) ReadDir(dirname string) ([]os.FileInfo, error) {
  492. client, err := fs.conn.getClient()
  493. if err != nil {
  494. return nil, err
  495. }
  496. return client.ReadDir(dirname)
  497. }
  498. // IsUploadResumeSupported returns true if resuming uploads is supported.
  499. func (fs *SFTPFs) IsUploadResumeSupported() bool {
  500. return fs.config.BufferSize == 0
  501. }
  502. // IsAtomicUploadSupported returns true if atomic upload is supported.
  503. func (fs *SFTPFs) IsAtomicUploadSupported() bool {
  504. return fs.config.BufferSize == 0
  505. }
  506. // IsNotExist returns a boolean indicating whether the error is known to
  507. // report that a file or directory does not exist
  508. func (*SFTPFs) IsNotExist(err error) bool {
  509. return errors.Is(err, fs.ErrNotExist)
  510. }
  511. // IsPermission returns a boolean indicating whether the error is known to
  512. // report that permission is denied.
  513. func (*SFTPFs) IsPermission(err error) bool {
  514. if _, ok := err.(*pathResolutionError); ok {
  515. return true
  516. }
  517. return errors.Is(err, fs.ErrPermission)
  518. }
  519. // IsNotSupported returns true if the error indicate an unsupported operation
  520. func (*SFTPFs) IsNotSupported(err error) bool {
  521. if err == nil {
  522. return false
  523. }
  524. return err == ErrVfsUnsupported
  525. }
  526. // CheckRootPath creates the specified local root directory if it does not exists
  527. func (fs *SFTPFs) CheckRootPath(username string, uid int, gid int) bool {
  528. // local directory for temporary files in buffer mode
  529. osFs := NewOsFs(fs.ConnectionID(), fs.localTempDir, "")
  530. osFs.CheckRootPath(username, uid, gid)
  531. if fs.config.Prefix == "/" {
  532. return true
  533. }
  534. client, err := fs.conn.getClient()
  535. if err != nil {
  536. return false
  537. }
  538. if err := client.MkdirAll(fs.config.Prefix); err != nil {
  539. fsLog(fs, logger.LevelDebug, "error creating root directory %q for user %q: %v", fs.config.Prefix, username, err)
  540. return false
  541. }
  542. return true
  543. }
  544. // ScanRootDirContents returns the number of files contained in a directory and
  545. // their size
  546. func (fs *SFTPFs) ScanRootDirContents() (int, int64, error) {
  547. return fs.GetDirSize(fs.config.Prefix)
  548. }
  549. // CheckMetadata checks the metadata consistency
  550. func (*SFTPFs) CheckMetadata() error {
  551. return nil
  552. }
  553. // GetAtomicUploadPath returns the path to use for an atomic upload
  554. func (*SFTPFs) GetAtomicUploadPath(name string) string {
  555. dir := path.Dir(name)
  556. guid := xid.New().String()
  557. return path.Join(dir, ".sftpgo-upload."+guid+"."+path.Base(name))
  558. }
  559. // GetRelativePath returns the path for a file relative to the sftp prefix if any.
  560. // This is the path as seen by SFTPGo users
  561. func (fs *SFTPFs) GetRelativePath(name string) string {
  562. rel := path.Clean(name)
  563. if rel == "." {
  564. rel = ""
  565. }
  566. if !path.IsAbs(rel) {
  567. return "/" + rel
  568. }
  569. if fs.config.Prefix != "/" {
  570. if !strings.HasPrefix(rel, fs.config.Prefix) {
  571. rel = "/"
  572. }
  573. rel = path.Clean("/" + strings.TrimPrefix(rel, fs.config.Prefix))
  574. }
  575. if fs.mountPath != "" {
  576. rel = path.Join(fs.mountPath, rel)
  577. }
  578. return rel
  579. }
  580. // Walk walks the file tree rooted at root, calling walkFn for each file or
  581. // directory in the tree, including root
  582. func (fs *SFTPFs) Walk(root string, walkFn filepath.WalkFunc) error {
  583. client, err := fs.conn.getClient()
  584. if err != nil {
  585. return err
  586. }
  587. walker := client.Walk(root)
  588. for walker.Step() {
  589. err := walker.Err()
  590. if err != nil {
  591. return err
  592. }
  593. err = walkFn(walker.Path(), walker.Stat(), err)
  594. if err != nil {
  595. return err
  596. }
  597. }
  598. return nil
  599. }
  600. // Join joins any number of path elements into a single path
  601. func (*SFTPFs) Join(elem ...string) string {
  602. return path.Join(elem...)
  603. }
  604. // HasVirtualFolders returns true if folders are emulated
  605. func (*SFTPFs) HasVirtualFolders() bool {
  606. return false
  607. }
  608. // ResolvePath returns the matching filesystem path for the specified virtual path
  609. func (fs *SFTPFs) ResolvePath(virtualPath string) (string, error) {
  610. if fs.mountPath != "" {
  611. virtualPath = strings.TrimPrefix(virtualPath, fs.mountPath)
  612. }
  613. if !path.IsAbs(virtualPath) {
  614. virtualPath = path.Clean("/" + virtualPath)
  615. }
  616. fsPath := fs.Join(fs.config.Prefix, virtualPath)
  617. if fs.config.Prefix != "/" && fsPath != "/" {
  618. // we need to check if this path is a symlink outside the given prefix
  619. // or a file/dir inside a dir symlinked outside the prefix
  620. var validatedPath string
  621. var err error
  622. validatedPath, err = fs.getRealPath(fsPath)
  623. isNotExist := fs.IsNotExist(err)
  624. if err != nil && !isNotExist {
  625. fsLog(fs, logger.LevelError, "Invalid path resolution, original path %v resolved %#v err: %v",
  626. virtualPath, fsPath, err)
  627. return "", err
  628. } else if isNotExist {
  629. for fs.IsNotExist(err) {
  630. validatedPath = path.Dir(validatedPath)
  631. if validatedPath == "/" {
  632. err = nil
  633. break
  634. }
  635. validatedPath, err = fs.getRealPath(validatedPath)
  636. }
  637. if err != nil {
  638. fsLog(fs, logger.LevelError, "Invalid path resolution, dir %#v original path %#v resolved %#v err: %v",
  639. validatedPath, virtualPath, fsPath, err)
  640. return "", err
  641. }
  642. }
  643. if err := fs.isSubDir(validatedPath); err != nil {
  644. fsLog(fs, logger.LevelError, "Invalid path resolution, dir %#v original path %#v resolved %#v err: %v",
  645. validatedPath, virtualPath, fsPath, err)
  646. return "", err
  647. }
  648. }
  649. return fsPath, nil
  650. }
  651. // RealPath implements the FsRealPather interface
  652. func (fs *SFTPFs) RealPath(p string) (string, error) {
  653. client, err := fs.conn.getClient()
  654. if err != nil {
  655. return "", err
  656. }
  657. resolved, err := client.RealPath(p)
  658. if err != nil {
  659. return "", err
  660. }
  661. if fs.config.Prefix != "/" {
  662. if err := fs.isSubDir(resolved); err != nil {
  663. fsLog(fs, logger.LevelError, "Invalid real path resolution, original path %q resolved %q err: %v",
  664. p, resolved, err)
  665. return "", err
  666. }
  667. }
  668. return fs.GetRelativePath(resolved), nil
  669. }
  670. // getRealPath returns the real remote path trying to resolve symbolic links if any
  671. func (fs *SFTPFs) getRealPath(name string) (string, error) {
  672. client, err := fs.conn.getClient()
  673. if err != nil {
  674. return "", err
  675. }
  676. linksWalked := 0
  677. for {
  678. info, err := client.Lstat(name)
  679. if err != nil {
  680. return name, err
  681. }
  682. if info.Mode()&os.ModeSymlink == 0 {
  683. return name, nil
  684. }
  685. resolvedLink, err := client.ReadLink(name)
  686. if err != nil {
  687. return name, fmt.Errorf("unable to resolve link to %q: %w", name, err)
  688. }
  689. resolvedLink = path.Clean(resolvedLink)
  690. if path.IsAbs(resolvedLink) {
  691. name = resolvedLink
  692. } else {
  693. name = path.Join(path.Dir(name), resolvedLink)
  694. }
  695. linksWalked++
  696. if linksWalked > 10 {
  697. fsLog(fs, logger.LevelError, "unable to get real path, too many links: %d", linksWalked)
  698. return "", &pathResolutionError{err: "too many links"}
  699. }
  700. }
  701. }
  702. func (fs *SFTPFs) isSubDir(name string) error {
  703. if name == fs.config.Prefix {
  704. return nil
  705. }
  706. if len(name) < len(fs.config.Prefix) {
  707. err := fmt.Errorf("path %q is not inside: %#v", name, fs.config.Prefix)
  708. return &pathResolutionError{err: err.Error()}
  709. }
  710. if !strings.HasPrefix(name, fs.config.Prefix+"/") {
  711. err := fmt.Errorf("path %q is not inside: %#v", name, fs.config.Prefix)
  712. return &pathResolutionError{err: err.Error()}
  713. }
  714. return nil
  715. }
  716. // GetDirSize returns the number of files and the size for a folder
  717. // including any subfolders
  718. func (fs *SFTPFs) GetDirSize(dirname string) (int, int64, error) {
  719. numFiles := 0
  720. size := int64(0)
  721. client, err := fs.conn.getClient()
  722. if err != nil {
  723. return numFiles, size, err
  724. }
  725. isDir, err := isDirectory(fs, dirname)
  726. if err == nil && isDir {
  727. walker := client.Walk(dirname)
  728. for walker.Step() {
  729. err := walker.Err()
  730. if err != nil {
  731. return numFiles, size, err
  732. }
  733. if walker.Stat().Mode().IsRegular() {
  734. size += walker.Stat().Size()
  735. numFiles++
  736. if numFiles%1000 == 0 {
  737. fsLog(fs, logger.LevelDebug, "dirname %q scan in progress, files: %d, size: %d", dirname, numFiles, size)
  738. }
  739. }
  740. }
  741. }
  742. return numFiles, size, err
  743. }
  744. // GetMimeType returns the content type
  745. func (fs *SFTPFs) GetMimeType(name string) (string, error) {
  746. client, err := fs.conn.getClient()
  747. if err != nil {
  748. return "", err
  749. }
  750. f, err := client.OpenFile(name, os.O_RDONLY)
  751. if err != nil {
  752. return "", err
  753. }
  754. defer f.Close()
  755. var buf [512]byte
  756. n, err := io.ReadFull(f, buf[:])
  757. if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF {
  758. return "", err
  759. }
  760. ctype := http.DetectContentType(buf[:n])
  761. // Rewind file.
  762. _, err = f.Seek(0, io.SeekStart)
  763. return ctype, err
  764. }
  765. // GetAvailableDiskSize returns the available size for the specified path
  766. func (fs *SFTPFs) GetAvailableDiskSize(dirName string) (*sftp.StatVFS, error) {
  767. client, err := fs.conn.getClient()
  768. if err != nil {
  769. return nil, err
  770. }
  771. if _, ok := client.HasExtension("[email protected]"); !ok {
  772. return nil, ErrStorageSizeUnavailable
  773. }
  774. return client.StatVFS(dirName)
  775. }
  776. // Close the connection
  777. func (fs *SFTPFs) Close() error {
  778. fs.conn.RemoveSession(fs.connectionID)
  779. return nil
  780. }
  781. func (fs *SFTPFs) copy(dst io.Writer, src io.Reader) (written int64, err error) {
  782. buf := make([]byte, 32768)
  783. for {
  784. nr, er := src.Read(buf)
  785. if nr > 0 {
  786. nw, ew := dst.Write(buf[0:nr])
  787. if nw < 0 || nr < nw {
  788. nw = 0
  789. if ew == nil {
  790. ew = errors.New("invalid write")
  791. }
  792. }
  793. written += int64(nw)
  794. if ew != nil {
  795. err = ew
  796. break
  797. }
  798. if nr != nw {
  799. err = io.ErrShortWrite
  800. break
  801. }
  802. }
  803. if er != nil {
  804. if er != io.EOF {
  805. err = er
  806. }
  807. break
  808. }
  809. }
  810. return written, err
  811. }
  812. func (fs *SFTPFs) createConnection() error {
  813. err := fs.conn.OpenConnection()
  814. if err != nil {
  815. fsLog(fs, logger.LevelError, "error opening connection: %v", err)
  816. return err
  817. }
  818. return nil
  819. }
  820. type sftpConnection struct {
  821. config *SFTPFsConfig
  822. logSender string
  823. sshClient *ssh.Client
  824. sftpClient *sftp.Client
  825. mu sync.RWMutex
  826. isConnected bool
  827. sessions map[string]bool
  828. lastActivity time.Time
  829. }
  830. func newSFTPConnection(config *SFTPFsConfig, sessionID string) *sftpConnection {
  831. c := &sftpConnection{
  832. config: config,
  833. logSender: fmt.Sprintf(`%s "%s@%s"`, sftpFsName, config.Username, config.Endpoint),
  834. isConnected: false,
  835. sessions: map[string]bool{},
  836. lastActivity: time.Now().UTC(),
  837. }
  838. c.sessions[sessionID] = true
  839. return c
  840. }
  841. func (c *sftpConnection) OpenConnection() error {
  842. c.mu.Lock()
  843. defer c.mu.Unlock()
  844. return c.openConnNoLock()
  845. }
  846. func (c *sftpConnection) openConnNoLock() error {
  847. if c.isConnected {
  848. logger.Debug(c.logSender, "", "reusing connection")
  849. return nil
  850. }
  851. logger.Debug(c.logSender, "", "try to open a new connection")
  852. clientConfig := &ssh.ClientConfig{
  853. User: c.config.Username,
  854. HostKeyCallback: func(_ string, _ net.Addr, key ssh.PublicKey) error {
  855. fp := ssh.FingerprintSHA256(key)
  856. if util.Contains(sftpFingerprints, fp) {
  857. if allowSelfConnections == 0 {
  858. logger.Log(logger.LevelError, c.logSender, "", "SFTP self connections not allowed")
  859. return ErrSFTPLoop
  860. }
  861. if util.Contains(c.config.forbiddenSelfUsernames, c.config.Username) {
  862. logger.Log(logger.LevelError, c.logSender, "",
  863. "SFTP loop or nested local SFTP folders detected, username %q, forbidden usernames: %+v",
  864. c.config.Username, c.config.forbiddenSelfUsernames)
  865. return ErrSFTPLoop
  866. }
  867. }
  868. if len(c.config.Fingerprints) > 0 {
  869. for _, provided := range c.config.Fingerprints {
  870. if provided == fp {
  871. return nil
  872. }
  873. }
  874. return fmt.Errorf("invalid fingerprint %q", fp)
  875. }
  876. logger.Log(logger.LevelWarn, c.logSender, "", "login without host key validation, please provide at least a fingerprint!")
  877. return nil
  878. },
  879. Timeout: 10 * time.Second,
  880. ClientVersion: fmt.Sprintf("SSH-2.0-SFTPGo_%v", version.Get().Version),
  881. }
  882. if c.config.PrivateKey.GetPayload() != "" {
  883. var signer ssh.Signer
  884. var err error
  885. if c.config.KeyPassphrase.GetPayload() != "" {
  886. signer, err = ssh.ParsePrivateKeyWithPassphrase([]byte(c.config.PrivateKey.GetPayload()),
  887. []byte(c.config.KeyPassphrase.GetPayload()))
  888. } else {
  889. signer, err = ssh.ParsePrivateKey([]byte(c.config.PrivateKey.GetPayload()))
  890. }
  891. if err != nil {
  892. return fmt.Errorf("sftpfs: unable to parse the private key: %w", err)
  893. }
  894. clientConfig.Auth = append(clientConfig.Auth, ssh.PublicKeys(signer))
  895. }
  896. if c.config.Password.GetPayload() != "" {
  897. clientConfig.Auth = append(clientConfig.Auth, ssh.Password(c.config.Password.GetPayload()))
  898. }
  899. // add more ciphers, KEXs and MACs, they are negotiated according to the order
  900. clientConfig.Ciphers = []string{"[email protected]", "[email protected]", "[email protected]",
  901. "aes128-ctr", "aes192-ctr", "aes256-ctr", "aes128-cbc", "aes192-cbc", "aes256-cbc"}
  902. clientConfig.KeyExchanges = []string{"curve25519-sha256", "[email protected]",
  903. "ecdh-sha2-nistp256", "ecdh-sha2-nistp384", "ecdh-sha2-nistp521",
  904. "diffie-hellman-group14-sha256", "diffie-hellman-group16-sha512", "diffie-hellman-group18-sha512",
  905. "diffie-hellman-group-exchange-sha256", "diffie-hellman-group-exchange-sha1",
  906. "diffie-hellman-group14-sha1", "diffie-hellman-group1-sha1"}
  907. clientConfig.MACs = []string{"[email protected]", "hmac-sha2-256",
  908. "[email protected]", "hmac-sha2-512",
  909. "hmac-sha1", "hmac-sha1-96"}
  910. sshClient, err := ssh.Dial("tcp", c.config.Endpoint, clientConfig)
  911. if err != nil {
  912. return fmt.Errorf("sftpfs: unable to connect: %w", err)
  913. }
  914. sftpClient, err := sftp.NewClient(sshClient, c.getClientOptions()...)
  915. if err != nil {
  916. sshClient.Close()
  917. return fmt.Errorf("sftpfs: unable to create SFTP client: %w", err)
  918. }
  919. c.sshClient = sshClient
  920. c.sftpClient = sftpClient
  921. c.isConnected = true
  922. go c.Wait()
  923. return nil
  924. }
  925. func (c *sftpConnection) getClientOptions() []sftp.ClientOption {
  926. var options []sftp.ClientOption
  927. if c.config.DisableCouncurrentReads {
  928. options = append(options, sftp.UseConcurrentReads(false))
  929. logger.Debug(c.logSender, "", "disabling concurrent reads")
  930. }
  931. if c.config.BufferSize > 0 {
  932. options = append(options, sftp.UseConcurrentWrites(true))
  933. logger.Debug(c.logSender, "", "enabling concurrent writes")
  934. }
  935. return options
  936. }
  937. func (c *sftpConnection) getClient() (*sftp.Client, error) {
  938. c.mu.Lock()
  939. defer c.mu.Unlock()
  940. if c.isConnected {
  941. return c.sftpClient, nil
  942. }
  943. err := c.openConnNoLock()
  944. return c.sftpClient, err
  945. }
  946. func (c *sftpConnection) Wait() {
  947. done := make(chan struct{})
  948. go func() {
  949. var watchdogInProgress atomic.Bool
  950. ticker := time.NewTicker(30 * time.Second)
  951. defer ticker.Stop()
  952. for {
  953. select {
  954. case <-ticker.C:
  955. if watchdogInProgress.Load() {
  956. logger.Error(c.logSender, "", "watchdog still in progress, closing hanging connection")
  957. c.sshClient.Close()
  958. return
  959. }
  960. go func() {
  961. watchdogInProgress.Store(true)
  962. defer watchdogInProgress.Store(false)
  963. _, err := c.sftpClient.Getwd()
  964. if err != nil {
  965. logger.Error(c.logSender, "", "watchdog error: %v", err)
  966. }
  967. }()
  968. case <-done:
  969. logger.Debug(c.logSender, "", "quitting watchdog")
  970. return
  971. }
  972. }
  973. }()
  974. // we wait on the sftp client otherwise if the channel is closed but not the connection
  975. // we don't detect the event.
  976. err := c.sftpClient.Wait()
  977. logger.Log(logger.LevelDebug, c.logSender, "", "sftp channel closed: %v", err)
  978. close(done)
  979. c.mu.Lock()
  980. defer c.mu.Unlock()
  981. c.isConnected = false
  982. if c.sshClient != nil {
  983. c.sshClient.Close()
  984. }
  985. }
  986. func (c *sftpConnection) Close() error {
  987. c.mu.Lock()
  988. defer c.mu.Unlock()
  989. logger.Debug(c.logSender, "", "closing connection")
  990. var sftpErr, sshErr error
  991. if c.sftpClient != nil {
  992. sftpErr = c.sftpClient.Close()
  993. }
  994. if c.sshClient != nil {
  995. sshErr = c.sshClient.Close()
  996. }
  997. if sftpErr != nil {
  998. return sftpErr
  999. }
  1000. c.isConnected = false
  1001. return sshErr
  1002. }
  1003. func (c *sftpConnection) AddSession(sessionID string) {
  1004. c.mu.Lock()
  1005. defer c.mu.Unlock()
  1006. c.sessions[sessionID] = true
  1007. logger.Debug(c.logSender, "", "added session %s, active sessions: %d", sessionID, len(c.sessions))
  1008. }
  1009. func (c *sftpConnection) RemoveSession(sessionID string) {
  1010. c.mu.Lock()
  1011. defer c.mu.Unlock()
  1012. delete(c.sessions, sessionID)
  1013. logger.Debug(c.logSender, "", "removed session %s, active sessions: %d", sessionID, len(c.sessions))
  1014. if len(c.sessions) == 0 {
  1015. c.lastActivity = time.Now().UTC()
  1016. }
  1017. }
  1018. func (c *sftpConnection) ActiveSessions() int {
  1019. c.mu.RLock()
  1020. defer c.mu.RUnlock()
  1021. return len(c.sessions)
  1022. }
  1023. func (c *sftpConnection) GetLastActivity() time.Time {
  1024. c.mu.RLock()
  1025. defer c.mu.RUnlock()
  1026. if len(c.sessions) > 0 {
  1027. return time.Now().UTC()
  1028. }
  1029. logger.Debug(c.logSender, "", "last activity %s", c.lastActivity)
  1030. return c.lastActivity
  1031. }
  1032. type sftpConnectionsCache struct {
  1033. scheduler *cron.Cron
  1034. sync.RWMutex
  1035. items map[uint64]*sftpConnection
  1036. }
  1037. func newSFTPConnectionCache() *sftpConnectionsCache {
  1038. c := &sftpConnectionsCache{
  1039. scheduler: cron.New(),
  1040. items: make(map[uint64]*sftpConnection),
  1041. }
  1042. _, err := c.scheduler.AddFunc("@every 1m", c.Cleanup)
  1043. util.PanicOnError(err)
  1044. c.scheduler.Start()
  1045. return c
  1046. }
  1047. func (c *sftpConnectionsCache) Get(config *SFTPFsConfig, sessionID string) *sftpConnection {
  1048. partition := 0
  1049. key := config.getUniqueID(partition)
  1050. c.Lock()
  1051. defer c.Unlock()
  1052. var oldKey uint64
  1053. for {
  1054. if val, ok := c.items[key]; ok {
  1055. activeSessions := val.ActiveSessions()
  1056. if activeSessions < maxSessionsPerConnection || key == oldKey {
  1057. logger.Debug(logSenderSFTPCache, "",
  1058. "reusing connection for session ID %q, key: %d, active sessions %d, active connections: %d",
  1059. sessionID, key, activeSessions+1, len(c.items))
  1060. val.AddSession(sessionID)
  1061. return val
  1062. }
  1063. partition++
  1064. oldKey = key
  1065. key = config.getUniqueID(partition)
  1066. logger.Debug(logSenderSFTPCache, "",
  1067. "connection full, generated new key for partition: %d, active sessions: %d, key: %d, old key: %d",
  1068. partition, activeSessions, oldKey, key)
  1069. } else {
  1070. conn := newSFTPConnection(config, sessionID)
  1071. c.items[key] = conn
  1072. logger.Debug(logSenderSFTPCache, "",
  1073. "adding new connection for session ID %q, partition: %d, key: %d, active connections: %d",
  1074. sessionID, partition, key, len(c.items))
  1075. return conn
  1076. }
  1077. }
  1078. }
  1079. func (c *sftpConnectionsCache) Remove(key uint64) {
  1080. c.Lock()
  1081. defer c.Unlock()
  1082. if conn, ok := c.items[key]; ok {
  1083. delete(c.items, key)
  1084. logger.Debug(logSenderSFTPCache, "", "removed connection with key %d, active connections: %d", key, len(c.items))
  1085. defer conn.Close()
  1086. }
  1087. }
  1088. func (c *sftpConnectionsCache) Cleanup() {
  1089. c.RLock()
  1090. for k, conn := range c.items {
  1091. if val := conn.GetLastActivity(); val.Before(time.Now().Add(-30 * time.Second)) {
  1092. logger.Debug(conn.logSender, "", "removing inactive connection, last activity %s", val)
  1093. defer func(key uint64) {
  1094. c.Remove(key)
  1095. }(k)
  1096. }
  1097. }
  1098. c.RUnlock()
  1099. }