sftpfs.go 33 KB

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