sftpfs.go 33 KB

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