sftpfs.go 32 KB

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