sftpfs.go 33 KB

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