ssh_cmd.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  1. package sftpd
  2. import (
  3. "crypto/md5"
  4. "crypto/sha1"
  5. "crypto/sha256"
  6. "crypto/sha512"
  7. "errors"
  8. "fmt"
  9. "hash"
  10. "io"
  11. "os"
  12. "os/exec"
  13. "path"
  14. "runtime/debug"
  15. "strings"
  16. "sync"
  17. "github.com/google/shlex"
  18. fscopy "github.com/otiai10/copy"
  19. "github.com/sftpgo/sdk"
  20. "golang.org/x/crypto/ssh"
  21. "github.com/drakkan/sftpgo/v2/common"
  22. "github.com/drakkan/sftpgo/v2/dataprovider"
  23. "github.com/drakkan/sftpgo/v2/logger"
  24. "github.com/drakkan/sftpgo/v2/metric"
  25. "github.com/drakkan/sftpgo/v2/util"
  26. "github.com/drakkan/sftpgo/v2/vfs"
  27. )
  28. const (
  29. scpCmdName = "scp"
  30. sshCommandLogSender = "SSHCommand"
  31. )
  32. var (
  33. errUnsupportedConfig = errors.New("command unsupported for this configuration")
  34. )
  35. type sshCommand struct {
  36. command string
  37. args []string
  38. connection *Connection
  39. }
  40. type systemCommand struct {
  41. cmd *exec.Cmd
  42. fsPath string
  43. quotaCheckPath string
  44. fs vfs.Fs
  45. }
  46. func (c *systemCommand) GetSTDs() (io.WriteCloser, io.ReadCloser, io.ReadCloser, error) {
  47. stdin, err := c.cmd.StdinPipe()
  48. if err != nil {
  49. return nil, nil, nil, err
  50. }
  51. stdout, err := c.cmd.StdoutPipe()
  52. if err != nil {
  53. stdin.Close()
  54. return nil, nil, nil, err
  55. }
  56. stderr, err := c.cmd.StderrPipe()
  57. if err != nil {
  58. stdin.Close()
  59. stdout.Close()
  60. return nil, nil, nil, err
  61. }
  62. return stdin, stdout, stderr, nil
  63. }
  64. func processSSHCommand(payload []byte, connection *Connection, enabledSSHCommands []string) bool {
  65. var msg sshSubsystemExecMsg
  66. if err := ssh.Unmarshal(payload, &msg); err == nil {
  67. name, args, err := parseCommandPayload(msg.Command)
  68. connection.Log(logger.LevelDebug, "new ssh command: %#v args: %v num args: %v user: %v, error: %v",
  69. name, args, len(args), connection.User.Username, err)
  70. if err == nil && util.IsStringInSlice(name, enabledSSHCommands) {
  71. connection.command = msg.Command
  72. if name == scpCmdName && len(args) >= 2 {
  73. connection.SetProtocol(common.ProtocolSCP)
  74. scpCommand := scpCommand{
  75. sshCommand: sshCommand{
  76. command: name,
  77. connection: connection,
  78. args: args},
  79. }
  80. go scpCommand.handle() //nolint:errcheck
  81. return true
  82. }
  83. if name != scpCmdName {
  84. connection.SetProtocol(common.ProtocolSSH)
  85. sshCommand := sshCommand{
  86. command: name,
  87. connection: connection,
  88. args: args,
  89. }
  90. go sshCommand.handle() //nolint:errcheck
  91. return true
  92. }
  93. } else {
  94. connection.Log(logger.LevelInfo, "ssh command not enabled/supported: %#v", name)
  95. }
  96. }
  97. err := connection.CloseFS()
  98. connection.Log(logger.LevelError, "unable to unmarshal ssh command, close fs, err: %v", err)
  99. return false
  100. }
  101. func (c *sshCommand) handle() (err error) {
  102. defer func() {
  103. if r := recover(); r != nil {
  104. logger.Error(logSender, "", "panic in handle ssh command: %#v stack trace: %v", r, string(debug.Stack()))
  105. err = common.ErrGenericFailure
  106. }
  107. }()
  108. if err := common.Connections.Add(c.connection); err != nil {
  109. logger.Info(logSender, "", "unable to add SSH command connection: %v", err)
  110. return err
  111. }
  112. defer common.Connections.Remove(c.connection.GetID())
  113. c.connection.UpdateLastActivity()
  114. if util.IsStringInSlice(c.command, sshHashCommands) {
  115. return c.handleHashCommands()
  116. } else if util.IsStringInSlice(c.command, systemCommands) {
  117. command, err := c.getSystemCommand()
  118. if err != nil {
  119. return c.sendErrorResponse(err)
  120. }
  121. return c.executeSystemCommand(command)
  122. } else if c.command == "cd" {
  123. c.sendExitStatus(nil)
  124. } else if c.command == "pwd" {
  125. // hard coded response to "/"
  126. c.connection.channel.Write([]byte(util.CleanPath(c.connection.User.Filters.StartDirectory) + "\n")) //nolint:errcheck
  127. c.sendExitStatus(nil)
  128. } else if c.command == "sftpgo-copy" {
  129. return c.handleSFTPGoCopy()
  130. } else if c.command == "sftpgo-remove" {
  131. return c.handleSFTPGoRemove()
  132. }
  133. return
  134. }
  135. func (c *sshCommand) handleSFTPGoCopy() error {
  136. fsSrc, fsDst, sshSourcePath, sshDestPath, fsSourcePath, fsDestPath, err := c.getFsAndCopyPaths()
  137. if err != nil {
  138. return c.sendErrorResponse(err)
  139. }
  140. if !c.isLocalCopy(sshSourcePath, sshDestPath) {
  141. return c.sendErrorResponse(errUnsupportedConfig)
  142. }
  143. if err := c.checkCopyDestination(fsDst, fsDestPath); err != nil {
  144. return c.sendErrorResponse(c.connection.GetFsError(fsDst, err))
  145. }
  146. c.connection.Log(logger.LevelDebug, "requested copy %#v -> %#v sftp paths %#v -> %#v",
  147. fsSourcePath, fsDestPath, sshSourcePath, sshDestPath)
  148. fi, err := fsSrc.Lstat(fsSourcePath)
  149. if err != nil {
  150. return c.sendErrorResponse(c.connection.GetFsError(fsSrc, err))
  151. }
  152. if err := c.checkCopyPermissions(fsSrc, fsDst, fsSourcePath, fsDestPath, sshSourcePath, sshDestPath, fi); err != nil {
  153. return c.sendErrorResponse(err)
  154. }
  155. filesNum := 0
  156. filesSize := int64(0)
  157. if fi.IsDir() {
  158. filesNum, filesSize, err = fsSrc.GetDirSize(fsSourcePath)
  159. if err != nil {
  160. return c.sendErrorResponse(c.connection.GetFsError(fsSrc, err))
  161. }
  162. if c.connection.User.HasVirtualFoldersInside(sshSourcePath) {
  163. err := errors.New("unsupported copy source: the source directory contains virtual folders")
  164. return c.sendErrorResponse(err)
  165. }
  166. if c.connection.User.HasVirtualFoldersInside(sshDestPath) {
  167. err := errors.New("unsupported copy source: the destination directory contains virtual folders")
  168. return c.sendErrorResponse(err)
  169. }
  170. } else if fi.Mode().IsRegular() {
  171. if ok, _ := c.connection.User.IsFileAllowed(sshDestPath); !ok {
  172. err := errors.New("unsupported copy destination: this file is not allowed")
  173. return c.sendErrorResponse(err)
  174. }
  175. filesNum = 1
  176. filesSize = fi.Size()
  177. } else {
  178. err := errors.New("unsupported copy source: only files and directories are supported")
  179. return c.sendErrorResponse(err)
  180. }
  181. if err := c.checkCopyQuota(filesNum, filesSize, sshDestPath); err != nil {
  182. return c.sendErrorResponse(err)
  183. }
  184. c.connection.Log(logger.LevelDebug, "start copy %#v -> %#v", fsSourcePath, fsDestPath)
  185. err = fscopy.Copy(fsSourcePath, fsDestPath, fscopy.Options{
  186. OnSymlink: func(src string) fscopy.SymlinkAction {
  187. return fscopy.Skip
  188. },
  189. })
  190. if err != nil {
  191. return c.sendErrorResponse(c.connection.GetFsError(fsSrc, err))
  192. }
  193. c.updateQuota(sshDestPath, filesNum, filesSize)
  194. c.connection.channel.Write([]byte("OK\n")) //nolint:errcheck
  195. c.sendExitStatus(nil)
  196. return nil
  197. }
  198. func (c *sshCommand) handleSFTPGoRemove() error {
  199. sshDestPath, err := c.getRemovePath()
  200. if err != nil {
  201. return c.sendErrorResponse(err)
  202. }
  203. if !c.connection.User.HasPerm(dataprovider.PermDelete, path.Dir(sshDestPath)) {
  204. return c.sendErrorResponse(common.ErrPermissionDenied)
  205. }
  206. fs, fsDestPath, err := c.connection.GetFsAndResolvedPath(sshDestPath)
  207. if err != nil {
  208. return c.sendErrorResponse(err)
  209. }
  210. if !vfs.IsLocalOrCryptoFs(fs) {
  211. return c.sendErrorResponse(errUnsupportedConfig)
  212. }
  213. fi, err := fs.Lstat(fsDestPath)
  214. if err != nil {
  215. return c.sendErrorResponse(c.connection.GetFsError(fs, err))
  216. }
  217. filesNum := 0
  218. filesSize := int64(0)
  219. if fi.IsDir() {
  220. filesNum, filesSize, err = fs.GetDirSize(fsDestPath)
  221. if err != nil {
  222. return c.sendErrorResponse(c.connection.GetFsError(fs, err))
  223. }
  224. if sshDestPath == "/" {
  225. err := errors.New("removing root dir is not allowed")
  226. return c.sendErrorResponse(err)
  227. }
  228. if c.connection.User.HasVirtualFoldersInside(sshDestPath) {
  229. err := errors.New("unsupported remove source: this directory contains virtual folders")
  230. return c.sendErrorResponse(err)
  231. }
  232. if c.connection.User.IsVirtualFolder(sshDestPath) {
  233. err := errors.New("unsupported remove source: this directory is a virtual folder")
  234. return c.sendErrorResponse(err)
  235. }
  236. } else if fi.Mode().IsRegular() {
  237. filesNum = 1
  238. filesSize = fi.Size()
  239. } else {
  240. err := errors.New("unsupported remove source: only files and directories are supported")
  241. return c.sendErrorResponse(err)
  242. }
  243. err = os.RemoveAll(fsDestPath)
  244. if err != nil {
  245. return c.sendErrorResponse(err)
  246. }
  247. c.updateQuota(sshDestPath, -filesNum, -filesSize)
  248. c.connection.channel.Write([]byte("OK\n")) //nolint:errcheck
  249. c.sendExitStatus(nil)
  250. return nil
  251. }
  252. func (c *sshCommand) updateQuota(sshDestPath string, filesNum int, filesSize int64) {
  253. vfolder, err := c.connection.User.GetVirtualFolderForPath(sshDestPath)
  254. if err == nil {
  255. dataprovider.UpdateVirtualFolderQuota(&vfolder.BaseVirtualFolder, filesNum, filesSize, false) //nolint:errcheck
  256. if vfolder.IsIncludedInUserQuota() {
  257. dataprovider.UpdateUserQuota(&c.connection.User, filesNum, filesSize, false) //nolint:errcheck
  258. }
  259. } else {
  260. dataprovider.UpdateUserQuota(&c.connection.User, filesNum, filesSize, false) //nolint:errcheck
  261. }
  262. }
  263. func (c *sshCommand) handleHashCommands() error {
  264. var h hash.Hash
  265. if c.command == "md5sum" {
  266. h = md5.New()
  267. } else if c.command == "sha1sum" {
  268. h = sha1.New()
  269. } else if c.command == "sha256sum" {
  270. h = sha256.New()
  271. } else if c.command == "sha384sum" {
  272. h = sha512.New384()
  273. } else {
  274. h = sha512.New()
  275. }
  276. var response string
  277. if len(c.args) == 0 {
  278. // without args we need to read the string to hash from stdin
  279. buf := make([]byte, 4096)
  280. n, err := c.connection.channel.Read(buf)
  281. if err != nil && err != io.EOF {
  282. return c.sendErrorResponse(err)
  283. }
  284. h.Write(buf[:n]) //nolint:errcheck
  285. response = fmt.Sprintf("%x -\n", h.Sum(nil))
  286. } else {
  287. sshPath := c.getDestPath()
  288. if ok, policy := c.connection.User.IsFileAllowed(sshPath); !ok {
  289. c.connection.Log(logger.LevelInfo, "hash not allowed for file %#v", sshPath)
  290. return c.sendErrorResponse(c.connection.GetErrorForDeniedFile(policy))
  291. }
  292. fs, fsPath, err := c.connection.GetFsAndResolvedPath(sshPath)
  293. if err != nil {
  294. return c.sendErrorResponse(err)
  295. }
  296. if !c.connection.User.HasPerm(dataprovider.PermListItems, sshPath) {
  297. return c.sendErrorResponse(c.connection.GetPermissionDeniedError())
  298. }
  299. hash, err := c.computeHashForFile(fs, h, fsPath)
  300. if err != nil {
  301. return c.sendErrorResponse(c.connection.GetFsError(fs, err))
  302. }
  303. response = fmt.Sprintf("%v %v\n", hash, sshPath)
  304. }
  305. c.connection.channel.Write([]byte(response)) //nolint:errcheck
  306. c.sendExitStatus(nil)
  307. return nil
  308. }
  309. func (c *sshCommand) executeSystemCommand(command systemCommand) error {
  310. sshDestPath := c.getDestPath()
  311. if !c.isLocalPath(sshDestPath) {
  312. return c.sendErrorResponse(errUnsupportedConfig)
  313. }
  314. diskQuota, transferQuota := c.connection.HasSpace(true, false, command.quotaCheckPath)
  315. if !diskQuota.HasSpace || !transferQuota.HasUploadSpace() || !transferQuota.HasDownloadSpace() {
  316. return c.sendErrorResponse(common.ErrQuotaExceeded)
  317. }
  318. perms := []string{dataprovider.PermDownload, dataprovider.PermUpload, dataprovider.PermCreateDirs, dataprovider.PermListItems,
  319. dataprovider.PermOverwrite, dataprovider.PermDelete}
  320. if !c.connection.User.HasPerms(perms, sshDestPath) {
  321. return c.sendErrorResponse(c.connection.GetPermissionDeniedError())
  322. }
  323. initialFiles, initialSize, err := c.getSizeForPath(command.fs, command.fsPath)
  324. if err != nil {
  325. return c.sendErrorResponse(err)
  326. }
  327. stdin, stdout, stderr, err := command.GetSTDs()
  328. if err != nil {
  329. return c.sendErrorResponse(err)
  330. }
  331. err = command.cmd.Start()
  332. if err != nil {
  333. return c.sendErrorResponse(err)
  334. }
  335. closeCmdOnError := func() {
  336. c.connection.Log(logger.LevelDebug, "kill cmd: %#v and close ssh channel after read or write error",
  337. c.connection.command)
  338. killerr := command.cmd.Process.Kill()
  339. closerr := c.connection.channel.Close()
  340. c.connection.Log(logger.LevelDebug, "kill cmd error: %v close channel error: %v", killerr, closerr)
  341. }
  342. var once sync.Once
  343. commandResponse := make(chan bool)
  344. remainingQuotaSize := diskQuota.GetRemainingSize()
  345. go func() {
  346. defer stdin.Close()
  347. baseTransfer := common.NewBaseTransfer(nil, c.connection.BaseConnection, nil, command.fsPath, command.fsPath, sshDestPath,
  348. common.TransferUpload, 0, 0, remainingQuotaSize, 0, false, command.fs, transferQuota)
  349. transfer := newTransfer(baseTransfer, nil, nil, nil)
  350. w, e := transfer.copyFromReaderToWriter(stdin, c.connection.channel)
  351. c.connection.Log(logger.LevelDebug, "command: %#v, copy from remote command to sdtin ended, written: %v, "+
  352. "initial remaining quota: %v, err: %v", c.connection.command, w, remainingQuotaSize, e)
  353. if e != nil {
  354. once.Do(closeCmdOnError)
  355. }
  356. }()
  357. go func() {
  358. baseTransfer := common.NewBaseTransfer(nil, c.connection.BaseConnection, nil, command.fsPath, command.fsPath, sshDestPath,
  359. common.TransferDownload, 0, 0, 0, 0, false, command.fs, transferQuota)
  360. transfer := newTransfer(baseTransfer, nil, nil, nil)
  361. w, e := transfer.copyFromReaderToWriter(c.connection.channel, stdout)
  362. c.connection.Log(logger.LevelDebug, "command: %#v, copy from sdtout to remote command ended, written: %v err: %v",
  363. c.connection.command, w, e)
  364. if e != nil {
  365. once.Do(closeCmdOnError)
  366. }
  367. commandResponse <- true
  368. }()
  369. go func() {
  370. baseTransfer := common.NewBaseTransfer(nil, c.connection.BaseConnection, nil, command.fsPath, command.fsPath, sshDestPath,
  371. common.TransferDownload, 0, 0, 0, 0, false, command.fs, transferQuota)
  372. transfer := newTransfer(baseTransfer, nil, nil, nil)
  373. w, e := transfer.copyFromReaderToWriter(c.connection.channel.(ssh.Channel).Stderr(), stderr)
  374. c.connection.Log(logger.LevelDebug, "command: %#v, copy from sdterr to remote command ended, written: %v err: %v",
  375. c.connection.command, w, e)
  376. // os.ErrClosed means that the command is finished so we don't need to do anything
  377. if (e != nil && !errors.Is(e, os.ErrClosed)) || w > 0 {
  378. once.Do(closeCmdOnError)
  379. }
  380. }()
  381. <-commandResponse
  382. err = command.cmd.Wait()
  383. c.sendExitStatus(err)
  384. numFiles, dirSize, errSize := c.getSizeForPath(command.fs, command.fsPath)
  385. if errSize == nil {
  386. c.updateQuota(sshDestPath, numFiles-initialFiles, dirSize-initialSize)
  387. }
  388. c.connection.Log(logger.LevelDebug, "command %#v finished for path %#v, initial files %v initial size %v "+
  389. "current files %v current size %v size err: %v", c.connection.command, command.fsPath, initialFiles, initialSize,
  390. numFiles, dirSize, errSize)
  391. return c.connection.GetFsError(command.fs, err)
  392. }
  393. func (c *sshCommand) isSystemCommandAllowed() error {
  394. sshDestPath := c.getDestPath()
  395. if c.connection.User.IsVirtualFolder(sshDestPath) {
  396. // overlapped virtual path are not allowed
  397. return nil
  398. }
  399. if c.connection.User.HasVirtualFoldersInside(sshDestPath) {
  400. c.connection.Log(logger.LevelDebug, "command %#v is not allowed, path %#v has virtual folders inside it, user %#v",
  401. c.command, sshDestPath, c.connection.User.Username)
  402. return errUnsupportedConfig
  403. }
  404. for _, f := range c.connection.User.Filters.FilePatterns {
  405. if f.Path == sshDestPath {
  406. c.connection.Log(logger.LevelDebug,
  407. "command %#v is not allowed inside folders with file patterns filters %#v user %#v",
  408. c.command, sshDestPath, c.connection.User.Username)
  409. return errUnsupportedConfig
  410. }
  411. if len(sshDestPath) > len(f.Path) {
  412. if strings.HasPrefix(sshDestPath, f.Path+"/") || f.Path == "/" {
  413. c.connection.Log(logger.LevelDebug,
  414. "command %#v is not allowed it includes folders with file patterns filters %#v user %#v",
  415. c.command, sshDestPath, c.connection.User.Username)
  416. return errUnsupportedConfig
  417. }
  418. }
  419. if len(sshDestPath) < len(f.Path) {
  420. if strings.HasPrefix(sshDestPath+"/", f.Path) || sshDestPath == "/" {
  421. c.connection.Log(logger.LevelDebug,
  422. "command %#v is not allowed inside folder with file patterns filters %#v user %#v",
  423. c.command, sshDestPath, c.connection.User.Username)
  424. return errUnsupportedConfig
  425. }
  426. }
  427. }
  428. return nil
  429. }
  430. func (c *sshCommand) getSystemCommand() (systemCommand, error) {
  431. command := systemCommand{
  432. cmd: nil,
  433. fs: nil,
  434. fsPath: "",
  435. quotaCheckPath: "",
  436. }
  437. args := make([]string, len(c.args))
  438. copy(args, c.args)
  439. var fsPath, quotaPath string
  440. sshPath := c.getDestPath()
  441. fs, err := c.connection.User.GetFilesystemForPath(sshPath, c.connection.ID)
  442. if err != nil {
  443. return command, err
  444. }
  445. if len(c.args) > 0 {
  446. var err error
  447. fsPath, err = fs.ResolvePath(sshPath)
  448. if err != nil {
  449. return command, c.connection.GetFsError(fs, err)
  450. }
  451. quotaPath = sshPath
  452. fi, err := fs.Stat(fsPath)
  453. if err == nil && fi.IsDir() {
  454. // if the target is an existing dir the command will write inside this dir
  455. // so we need to check the quota for this directory and not its parent dir
  456. quotaPath = path.Join(sshPath, "fakecontent")
  457. }
  458. if strings.HasSuffix(sshPath, "/") && !strings.HasSuffix(fsPath, string(os.PathSeparator)) {
  459. fsPath += string(os.PathSeparator)
  460. c.connection.Log(logger.LevelDebug, "path separator added to fsPath %#v", fsPath)
  461. }
  462. args = args[:len(args)-1]
  463. args = append(args, fsPath)
  464. }
  465. if err := c.isSystemCommandAllowed(); err != nil {
  466. return command, errUnsupportedConfig
  467. }
  468. if c.command == "rsync" {
  469. // we cannot avoid that rsync creates symlinks so if the user has the permission
  470. // to create symlinks we add the option --safe-links to the received rsync command if
  471. // it is not already set. This should prevent to create symlinks that point outside
  472. // the home dir.
  473. // If the user cannot create symlinks we add the option --munge-links, if it is not
  474. // already set. This should make symlinks unusable (but manually recoverable)
  475. if c.connection.User.HasPerm(dataprovider.PermCreateSymlinks, c.getDestPath()) {
  476. if !util.IsStringInSlice("--safe-links", args) {
  477. args = append([]string{"--safe-links"}, args...)
  478. }
  479. } else {
  480. if !util.IsStringInSlice("--munge-links", args) {
  481. args = append([]string{"--munge-links"}, args...)
  482. }
  483. }
  484. }
  485. c.connection.Log(logger.LevelDebug, "new system command %#v, with args: %+v fs path %#v quota check path %#v",
  486. c.command, args, fsPath, quotaPath)
  487. cmd := exec.Command(c.command, args...)
  488. uid := c.connection.User.GetUID()
  489. gid := c.connection.User.GetGID()
  490. cmd = wrapCmd(cmd, uid, gid)
  491. command.cmd = cmd
  492. command.fsPath = fsPath
  493. command.quotaCheckPath = quotaPath
  494. command.fs = fs
  495. return command, nil
  496. }
  497. // for the supported commands, the destination path, if any, is the last argument
  498. func (c *sshCommand) getDestPath() string {
  499. if len(c.args) == 0 {
  500. return ""
  501. }
  502. return c.cleanCommandPath(c.args[len(c.args)-1])
  503. }
  504. // for the supported commands, the destination path, if any, is the second-last argument
  505. func (c *sshCommand) getSourcePath() string {
  506. if len(c.args) < 2 {
  507. return ""
  508. }
  509. return c.cleanCommandPath(c.args[len(c.args)-2])
  510. }
  511. func (c *sshCommand) cleanCommandPath(name string) string {
  512. name = strings.Trim(name, "'")
  513. name = strings.Trim(name, "\"")
  514. result := c.connection.User.GetCleanedPath(name)
  515. if strings.HasSuffix(name, "/") && !strings.HasSuffix(result, "/") {
  516. result += "/"
  517. }
  518. return result
  519. }
  520. func (c *sshCommand) getFsAndCopyPaths() (vfs.Fs, vfs.Fs, string, string, string, string, error) {
  521. sshSourcePath := strings.TrimSuffix(c.getSourcePath(), "/")
  522. sshDestPath := c.getDestPath()
  523. if strings.HasSuffix(sshDestPath, "/") {
  524. sshDestPath = path.Join(sshDestPath, path.Base(sshSourcePath))
  525. }
  526. if sshSourcePath == "" || sshDestPath == "" || len(c.args) != 2 {
  527. err := errors.New("usage sftpgo-copy <source dir path> <destination dir path>")
  528. return nil, nil, "", "", "", "", err
  529. }
  530. fsSrc, fsSourcePath, err := c.connection.GetFsAndResolvedPath(sshSourcePath)
  531. if err != nil {
  532. return nil, nil, "", "", "", "", err
  533. }
  534. fsDst, fsDestPath, err := c.connection.GetFsAndResolvedPath(sshDestPath)
  535. if err != nil {
  536. return nil, nil, "", "", "", "", err
  537. }
  538. return fsSrc, fsDst, sshSourcePath, sshDestPath, fsSourcePath, fsDestPath, nil
  539. }
  540. func (c *sshCommand) hasCopyPermissions(sshSourcePath, sshDestPath string, srcInfo os.FileInfo) bool {
  541. if !c.connection.User.HasPerm(dataprovider.PermListItems, path.Dir(sshSourcePath)) {
  542. return false
  543. }
  544. if srcInfo.IsDir() {
  545. return c.connection.User.HasPerm(dataprovider.PermCreateDirs, path.Dir(sshDestPath))
  546. } else if srcInfo.Mode()&os.ModeSymlink != 0 {
  547. return c.connection.User.HasPerm(dataprovider.PermCreateSymlinks, path.Dir(sshDestPath))
  548. }
  549. return c.connection.User.HasPerm(dataprovider.PermUpload, path.Dir(sshDestPath))
  550. }
  551. // fsSourcePath must be a directory
  552. func (c *sshCommand) checkRecursiveCopyPermissions(fsSrc vfs.Fs, fsDst vfs.Fs, fsSourcePath, fsDestPath, sshDestPath string) error {
  553. if !c.connection.User.HasPerm(dataprovider.PermCreateDirs, path.Dir(sshDestPath)) {
  554. return common.ErrPermissionDenied
  555. }
  556. dstPerms := []string{
  557. dataprovider.PermCreateDirs,
  558. dataprovider.PermCreateSymlinks,
  559. dataprovider.PermUpload,
  560. }
  561. err := fsSrc.Walk(fsSourcePath, func(walkedPath string, info os.FileInfo, err error) error {
  562. if err != nil {
  563. return c.connection.GetFsError(fsSrc, err)
  564. }
  565. fsDstSubPath := strings.Replace(walkedPath, fsSourcePath, fsDestPath, 1)
  566. sshSrcSubPath := fsSrc.GetRelativePath(walkedPath)
  567. sshDstSubPath := fsDst.GetRelativePath(fsDstSubPath)
  568. // If the current dir has no subdirs with defined permissions inside it
  569. // and it has all the possible permissions we can stop scanning
  570. if !c.connection.User.HasPermissionsInside(path.Dir(sshSrcSubPath)) &&
  571. !c.connection.User.HasPermissionsInside(path.Dir(sshDstSubPath)) {
  572. if c.connection.User.HasPerm(dataprovider.PermListItems, path.Dir(sshSrcSubPath)) &&
  573. c.connection.User.HasPerms(dstPerms, path.Dir(sshDstSubPath)) {
  574. return common.ErrSkipPermissionsCheck
  575. }
  576. }
  577. if !c.hasCopyPermissions(sshSrcSubPath, sshDstSubPath, info) {
  578. return common.ErrPermissionDenied
  579. }
  580. return nil
  581. })
  582. if err == common.ErrSkipPermissionsCheck {
  583. err = nil
  584. }
  585. return err
  586. }
  587. func (c *sshCommand) checkCopyPermissions(fsSrc vfs.Fs, fsDst vfs.Fs, fsSourcePath, fsDestPath, sshSourcePath, sshDestPath string, info os.FileInfo) error {
  588. if info.IsDir() {
  589. return c.checkRecursiveCopyPermissions(fsSrc, fsDst, fsSourcePath, fsDestPath, sshDestPath)
  590. }
  591. if !c.hasCopyPermissions(sshSourcePath, sshDestPath, info) {
  592. return c.connection.GetPermissionDeniedError()
  593. }
  594. return nil
  595. }
  596. func (c *sshCommand) getRemovePath() (string, error) {
  597. sshDestPath := c.getDestPath()
  598. if sshDestPath == "" || len(c.args) != 1 {
  599. err := errors.New("usage sftpgo-remove <destination path>")
  600. return "", err
  601. }
  602. if len(sshDestPath) > 1 {
  603. sshDestPath = strings.TrimSuffix(sshDestPath, "/")
  604. }
  605. return sshDestPath, nil
  606. }
  607. func (c *sshCommand) isLocalPath(virtualPath string) bool {
  608. folder, err := c.connection.User.GetVirtualFolderForPath(virtualPath)
  609. if err != nil {
  610. return c.connection.User.FsConfig.Provider == sdk.LocalFilesystemProvider
  611. }
  612. return folder.FsConfig.Provider == sdk.LocalFilesystemProvider
  613. }
  614. func (c *sshCommand) isLocalCopy(virtualSourcePath, virtualTargetPath string) bool {
  615. if !c.isLocalPath(virtualSourcePath) {
  616. return false
  617. }
  618. return c.isLocalPath(virtualTargetPath)
  619. }
  620. func (c *sshCommand) checkCopyDestination(fs vfs.Fs, fsDestPath string) error {
  621. _, err := fs.Lstat(fsDestPath)
  622. if err == nil {
  623. err := errors.New("invalid copy destination: cannot overwrite an existing file or directory")
  624. return err
  625. } else if !fs.IsNotExist(err) {
  626. return err
  627. }
  628. return nil
  629. }
  630. func (c *sshCommand) checkCopyQuota(numFiles int, filesSize int64, requestPath string) error {
  631. quotaResult, _ := c.connection.HasSpace(true, false, requestPath)
  632. if !quotaResult.HasSpace {
  633. return common.ErrQuotaExceeded
  634. }
  635. if quotaResult.QuotaFiles > 0 {
  636. remainingFiles := quotaResult.GetRemainingFiles()
  637. if remainingFiles < numFiles {
  638. c.connection.Log(logger.LevelDebug, "copy not allowed, file limit will be exceeded, "+
  639. "remaining files: %v to copy: %v", remainingFiles, numFiles)
  640. return common.ErrQuotaExceeded
  641. }
  642. }
  643. if quotaResult.QuotaSize > 0 {
  644. remainingSize := quotaResult.GetRemainingSize()
  645. if remainingSize < filesSize {
  646. c.connection.Log(logger.LevelDebug, "copy not allowed, size limit will be exceeded, "+
  647. "remaining size: %v to copy: %v", remainingSize, filesSize)
  648. return common.ErrQuotaExceeded
  649. }
  650. }
  651. return nil
  652. }
  653. func (c *sshCommand) getSizeForPath(fs vfs.Fs, name string) (int, int64, error) {
  654. if dataprovider.GetQuotaTracking() > 0 {
  655. fi, err := fs.Lstat(name)
  656. if err != nil {
  657. if fs.IsNotExist(err) {
  658. return 0, 0, nil
  659. }
  660. c.connection.Log(logger.LevelDebug, "unable to stat %#v error: %v", name, err)
  661. return 0, 0, err
  662. }
  663. if fi.IsDir() {
  664. files, size, err := fs.GetDirSize(name)
  665. if err != nil {
  666. c.connection.Log(logger.LevelDebug, "unable to get size for dir %#v error: %v", name, err)
  667. }
  668. return files, size, err
  669. } else if fi.Mode().IsRegular() {
  670. return 1, fi.Size(), nil
  671. }
  672. }
  673. return 0, 0, nil
  674. }
  675. func (c *sshCommand) sendErrorResponse(err error) error {
  676. errorString := fmt.Sprintf("%v: %v %v\n", c.command, c.getDestPath(), err)
  677. c.connection.channel.Write([]byte(errorString)) //nolint:errcheck
  678. c.sendExitStatus(err)
  679. return err
  680. }
  681. func (c *sshCommand) sendExitStatus(err error) {
  682. status := uint32(0)
  683. vCmdPath := c.getDestPath()
  684. cmdPath := ""
  685. targetPath := ""
  686. vTargetPath := ""
  687. if c.command == "sftpgo-copy" {
  688. vTargetPath = vCmdPath
  689. vCmdPath = c.getSourcePath()
  690. }
  691. if err != nil {
  692. status = uint32(1)
  693. c.connection.Log(logger.LevelError, "command failed: %#v args: %v user: %v err: %v",
  694. c.command, c.args, c.connection.User.Username, err)
  695. }
  696. exitStatus := sshSubsystemExitStatus{
  697. Status: status,
  698. }
  699. _, errClose := c.connection.channel.(ssh.Channel).SendRequest("exit-status", false, ssh.Marshal(&exitStatus))
  700. c.connection.Log(logger.LevelDebug, "exit status sent, error: %v", errClose)
  701. c.connection.channel.Close()
  702. // for scp we notify single uploads/downloads
  703. if c.command != scpCmdName {
  704. metric.SSHCommandCompleted(err)
  705. if vCmdPath != "" {
  706. _, p, errFs := c.connection.GetFsAndResolvedPath(vCmdPath)
  707. if errFs == nil {
  708. cmdPath = p
  709. }
  710. }
  711. if vTargetPath != "" {
  712. _, p, errFs := c.connection.GetFsAndResolvedPath(vTargetPath)
  713. if errFs == nil {
  714. targetPath = p
  715. }
  716. }
  717. common.ExecuteActionNotification(c.connection.BaseConnection, common.OperationSSHCmd, cmdPath, vCmdPath, targetPath,
  718. vTargetPath, c.command, 0, err)
  719. if err == nil {
  720. logger.CommandLog(sshCommandLogSender, cmdPath, targetPath, c.connection.User.Username, "", c.connection.ID,
  721. common.ProtocolSSH, -1, -1, "", "", c.connection.command, -1, c.connection.GetLocalAddress(),
  722. c.connection.GetRemoteAddress())
  723. }
  724. }
  725. }
  726. func (c *sshCommand) computeHashForFile(fs vfs.Fs, hasher hash.Hash, path string) (string, error) {
  727. hash := ""
  728. f, r, _, err := fs.Open(path, 0)
  729. if err != nil {
  730. return hash, err
  731. }
  732. var reader io.ReadCloser
  733. if f != nil {
  734. reader = f
  735. } else {
  736. reader = r
  737. }
  738. defer reader.Close()
  739. _, err = io.Copy(hasher, reader)
  740. if err == nil {
  741. hash = fmt.Sprintf("%x", hasher.Sum(nil))
  742. }
  743. return hash, err
  744. }
  745. func parseCommandPayload(command string) (string, []string, error) {
  746. parts, err := shlex.Split(command)
  747. if err == nil && len(parts) == 0 {
  748. err = fmt.Errorf("invalid command: %#v", command)
  749. }
  750. if err != nil {
  751. return "", []string{}, err
  752. }
  753. if len(parts) < 2 {
  754. return parts[0], []string{}, nil
  755. }
  756. return parts[0], parts[1:], nil
  757. }