ssh_cmd.go 25 KB

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