ssh_cmd.go 27 KB

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