ssh_cmd.go 24 KB

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