ssh_cmd.go 26 KB

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