ssh_cmd.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. // Copyright (C) 2019-2023 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. "time"
  31. "github.com/google/shlex"
  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. startTime time.Time
  53. }
  54. type systemCommand struct {
  55. cmd *exec.Cmd
  56. fsPath string
  57. quotaCheckPath string
  58. fs vfs.Fs
  59. }
  60. func (c *systemCommand) GetSTDs() (io.WriteCloser, io.ReadCloser, io.ReadCloser, error) {
  61. stdin, err := c.cmd.StdinPipe()
  62. if err != nil {
  63. return nil, nil, nil, err
  64. }
  65. stdout, err := c.cmd.StdoutPipe()
  66. if err != nil {
  67. stdin.Close()
  68. return nil, nil, nil, err
  69. }
  70. stderr, err := c.cmd.StderrPipe()
  71. if err != nil {
  72. stdin.Close()
  73. stdout.Close()
  74. return nil, nil, nil, err
  75. }
  76. return stdin, stdout, stderr, nil
  77. }
  78. func processSSHCommand(payload []byte, connection *Connection, enabledSSHCommands []string) bool {
  79. var msg sshSubsystemExecMsg
  80. if err := ssh.Unmarshal(payload, &msg); err == nil {
  81. name, args, err := parseCommandPayload(msg.Command)
  82. connection.Log(logger.LevelDebug, "new ssh command: %q args: %v num args: %d user: %s, error: %v",
  83. name, args, len(args), connection.User.Username, err)
  84. if err == nil && util.Contains(enabledSSHCommands, name) {
  85. connection.command = msg.Command
  86. if name == scpCmdName && len(args) >= 2 {
  87. connection.SetProtocol(common.ProtocolSCP)
  88. scpCommand := scpCommand{
  89. sshCommand: sshCommand{
  90. command: name,
  91. connection: connection,
  92. startTime: time.Now(),
  93. args: args},
  94. }
  95. go scpCommand.handle() //nolint:errcheck
  96. return true
  97. }
  98. if name != scpCmdName {
  99. connection.SetProtocol(common.ProtocolSSH)
  100. sshCommand := sshCommand{
  101. command: name,
  102. connection: connection,
  103. startTime: time.Now(),
  104. args: args,
  105. }
  106. go sshCommand.handle() //nolint:errcheck
  107. return true
  108. }
  109. } else {
  110. connection.Log(logger.LevelInfo, "ssh command not enabled/supported: %q", name)
  111. }
  112. }
  113. err := connection.CloseFS()
  114. connection.Log(logger.LevelError, "unable to unmarshal ssh command, close fs, err: %v", err)
  115. return false
  116. }
  117. func (c *sshCommand) handle() (err error) {
  118. defer func() {
  119. if r := recover(); r != nil {
  120. logger.Error(logSender, "", "panic in handle ssh command: %q stack trace: %v", r, string(debug.Stack()))
  121. err = common.ErrGenericFailure
  122. }
  123. }()
  124. if err := common.Connections.Add(c.connection); err != nil {
  125. logger.Info(logSender, "", "unable to add SSH command connection: %v", err)
  126. return err
  127. }
  128. defer common.Connections.Remove(c.connection.GetID())
  129. c.connection.UpdateLastActivity()
  130. if util.Contains(sshHashCommands, c.command) {
  131. return c.handleHashCommands()
  132. } else if util.Contains(systemCommands, c.command) {
  133. command, err := c.getSystemCommand()
  134. if err != nil {
  135. return c.sendErrorResponse(err)
  136. }
  137. return c.executeSystemCommand(command)
  138. } else if c.command == "cd" {
  139. c.sendExitStatus(nil)
  140. } else if c.command == "pwd" {
  141. // hard coded response to the start directory
  142. c.connection.channel.Write([]byte(util.CleanPath(c.connection.User.Filters.StartDirectory) + "\n")) //nolint:errcheck
  143. c.sendExitStatus(nil)
  144. } else if c.command == "sftpgo-copy" {
  145. return c.handleSFTPGoCopy()
  146. } else if c.command == "sftpgo-remove" {
  147. return c.handleSFTPGoRemove()
  148. }
  149. return
  150. }
  151. func (c *sshCommand) handleSFTPGoCopy() error {
  152. sshSourcePath := c.getSourcePath()
  153. sshDestPath := c.getDestPath()
  154. if sshSourcePath == "" || sshDestPath == "" || len(c.args) != 2 {
  155. return c.sendErrorResponse(errors.New("usage sftpgo-copy <source dir path> <destination dir path>"))
  156. }
  157. c.connection.Log(logger.LevelDebug, "requested copy %q -> %q", sshSourcePath, sshDestPath)
  158. if err := c.connection.Copy(sshSourcePath, sshDestPath); err != nil {
  159. return c.sendErrorResponse(err)
  160. }
  161. c.connection.channel.Write([]byte("OK\n")) //nolint:errcheck
  162. c.sendExitStatus(nil)
  163. return nil
  164. }
  165. func (c *sshCommand) handleSFTPGoRemove() error {
  166. sshDestPath, err := c.getRemovePath()
  167. if err != nil {
  168. return c.sendErrorResponse(err)
  169. }
  170. if err := c.connection.RemoveAll(sshDestPath); err != nil {
  171. return c.sendErrorResponse(err)
  172. }
  173. c.connection.channel.Write([]byte("OK\n")) //nolint:errcheck
  174. c.sendExitStatus(nil)
  175. return nil
  176. }
  177. func (c *sshCommand) updateQuota(sshDestPath string, filesNum int, filesSize int64) {
  178. vfolder, err := c.connection.User.GetVirtualFolderForPath(sshDestPath)
  179. if err == nil {
  180. dataprovider.UpdateVirtualFolderQuota(&vfolder.BaseVirtualFolder, filesNum, filesSize, false) //nolint:errcheck
  181. if vfolder.IsIncludedInUserQuota() {
  182. dataprovider.UpdateUserQuota(&c.connection.User, filesNum, filesSize, false) //nolint:errcheck
  183. }
  184. } else {
  185. dataprovider.UpdateUserQuota(&c.connection.User, filesNum, filesSize, false) //nolint:errcheck
  186. }
  187. }
  188. func (c *sshCommand) handleHashCommands() error {
  189. var h hash.Hash
  190. if c.command == "md5sum" {
  191. h = md5.New()
  192. } else if c.command == "sha1sum" {
  193. h = sha1.New()
  194. } else if c.command == "sha256sum" {
  195. h = sha256.New()
  196. } else if c.command == "sha384sum" {
  197. h = sha512.New384()
  198. } else {
  199. h = sha512.New()
  200. }
  201. var response string
  202. if len(c.args) == 0 {
  203. // without args we need to read the string to hash from stdin
  204. buf := make([]byte, 4096)
  205. n, err := c.connection.channel.Read(buf)
  206. if err != nil && err != io.EOF {
  207. return c.sendErrorResponse(err)
  208. }
  209. h.Write(buf[:n]) //nolint:errcheck
  210. response = fmt.Sprintf("%x -\n", h.Sum(nil))
  211. } else {
  212. sshPath := c.getDestPath()
  213. if ok, policy := c.connection.User.IsFileAllowed(sshPath); !ok {
  214. c.connection.Log(logger.LevelInfo, "hash not allowed for file %q", sshPath)
  215. return c.sendErrorResponse(c.connection.GetErrorForDeniedFile(policy))
  216. }
  217. fs, fsPath, err := c.connection.GetFsAndResolvedPath(sshPath)
  218. if err != nil {
  219. return c.sendErrorResponse(err)
  220. }
  221. if !c.connection.User.HasPerm(dataprovider.PermListItems, sshPath) {
  222. return c.sendErrorResponse(c.connection.GetPermissionDeniedError())
  223. }
  224. hash, err := c.computeHashForFile(fs, h, fsPath)
  225. if err != nil {
  226. return c.sendErrorResponse(c.connection.GetFsError(fs, err))
  227. }
  228. response = fmt.Sprintf("%v %v\n", hash, sshPath)
  229. }
  230. c.connection.channel.Write([]byte(response)) //nolint:errcheck
  231. c.sendExitStatus(nil)
  232. return nil
  233. }
  234. func (c *sshCommand) executeSystemCommand(command systemCommand) error {
  235. sshDestPath := c.getDestPath()
  236. if !c.isLocalPath(sshDestPath) {
  237. return c.sendErrorResponse(errUnsupportedConfig)
  238. }
  239. diskQuota, transferQuota := c.connection.HasSpace(true, false, command.quotaCheckPath)
  240. if !diskQuota.HasSpace || !transferQuota.HasUploadSpace() || !transferQuota.HasDownloadSpace() {
  241. return c.sendErrorResponse(common.ErrQuotaExceeded)
  242. }
  243. perms := []string{dataprovider.PermDownload, dataprovider.PermUpload, dataprovider.PermCreateDirs, dataprovider.PermListItems,
  244. dataprovider.PermOverwrite, dataprovider.PermDelete}
  245. if !c.connection.User.HasPerms(perms, sshDestPath) {
  246. return c.sendErrorResponse(c.connection.GetPermissionDeniedError())
  247. }
  248. initialFiles, initialSize, err := c.getSizeForPath(command.fs, command.fsPath)
  249. if err != nil {
  250. return c.sendErrorResponse(err)
  251. }
  252. stdin, stdout, stderr, err := command.GetSTDs()
  253. if err != nil {
  254. return c.sendErrorResponse(err)
  255. }
  256. err = command.cmd.Start()
  257. if err != nil {
  258. return c.sendErrorResponse(err)
  259. }
  260. closeCmdOnError := func() {
  261. c.connection.Log(logger.LevelDebug, "kill cmd: %q and close ssh channel after read or write error",
  262. c.connection.command)
  263. killerr := command.cmd.Process.Kill()
  264. closerr := c.connection.channel.Close()
  265. c.connection.Log(logger.LevelDebug, "kill cmd error: %v close channel error: %v", killerr, closerr)
  266. }
  267. var once sync.Once
  268. commandResponse := make(chan bool)
  269. remainingQuotaSize := diskQuota.GetRemainingSize()
  270. go func() {
  271. defer stdin.Close()
  272. baseTransfer := common.NewBaseTransfer(nil, c.connection.BaseConnection, nil, command.fsPath, command.fsPath, sshDestPath,
  273. common.TransferUpload, 0, 0, remainingQuotaSize, 0, false, command.fs, transferQuota)
  274. transfer := newTransfer(baseTransfer, nil, nil, nil)
  275. w, e := transfer.copyFromReaderToWriter(stdin, c.connection.channel)
  276. c.connection.Log(logger.LevelDebug, "command: %q, copy from remote command to sdtin ended, written: %v, "+
  277. "initial remaining quota: %v, err: %v", c.connection.command, w, remainingQuotaSize, e)
  278. if e != nil {
  279. once.Do(closeCmdOnError)
  280. }
  281. }()
  282. go func() {
  283. baseTransfer := common.NewBaseTransfer(nil, c.connection.BaseConnection, nil, command.fsPath, command.fsPath, sshDestPath,
  284. common.TransferDownload, 0, 0, 0, 0, false, command.fs, transferQuota)
  285. transfer := newTransfer(baseTransfer, nil, nil, nil)
  286. w, e := transfer.copyFromReaderToWriter(c.connection.channel, stdout)
  287. c.connection.Log(logger.LevelDebug, "command: %q, copy from sdtout to remote command ended, written: %v err: %v",
  288. c.connection.command, w, e)
  289. if e != nil {
  290. once.Do(closeCmdOnError)
  291. }
  292. commandResponse <- true
  293. }()
  294. go func() {
  295. baseTransfer := common.NewBaseTransfer(nil, c.connection.BaseConnection, nil, command.fsPath, command.fsPath, sshDestPath,
  296. common.TransferDownload, 0, 0, 0, 0, false, command.fs, transferQuota)
  297. transfer := newTransfer(baseTransfer, nil, nil, nil)
  298. w, e := transfer.copyFromReaderToWriter(c.connection.channel.(ssh.Channel).Stderr(), stderr)
  299. c.connection.Log(logger.LevelDebug, "command: %q, copy from sdterr to remote command ended, written: %v err: %v",
  300. c.connection.command, w, e)
  301. // os.ErrClosed means that the command is finished so we don't need to do anything
  302. if (e != nil && !errors.Is(e, os.ErrClosed)) || w > 0 {
  303. once.Do(closeCmdOnError)
  304. }
  305. }()
  306. <-commandResponse
  307. err = command.cmd.Wait()
  308. c.sendExitStatus(err)
  309. numFiles, dirSize, errSize := c.getSizeForPath(command.fs, command.fsPath)
  310. if errSize == nil {
  311. c.updateQuota(sshDestPath, numFiles-initialFiles, dirSize-initialSize)
  312. }
  313. c.connection.Log(logger.LevelDebug, "command %q finished for path %q, initial files %v initial size %v "+
  314. "current files %v current size %v size err: %v", c.connection.command, command.fsPath, initialFiles, initialSize,
  315. numFiles, dirSize, errSize)
  316. return c.connection.GetFsError(command.fs, err)
  317. }
  318. func (c *sshCommand) isSystemCommandAllowed() error {
  319. sshDestPath := c.getDestPath()
  320. if c.connection.User.IsVirtualFolder(sshDestPath) {
  321. // overlapped virtual path are not allowed
  322. return nil
  323. }
  324. if c.connection.User.HasVirtualFoldersInside(sshDestPath) {
  325. c.connection.Log(logger.LevelDebug, "command %q is not allowed, path %q has virtual folders inside it, user %q",
  326. c.command, sshDestPath, c.connection.User.Username)
  327. return errUnsupportedConfig
  328. }
  329. for _, f := range c.connection.User.Filters.FilePatterns {
  330. if f.Path == sshDestPath {
  331. c.connection.Log(logger.LevelDebug,
  332. "command %q is not allowed inside folders with file patterns filters %q user %q",
  333. c.command, sshDestPath, c.connection.User.Username)
  334. return errUnsupportedConfig
  335. }
  336. if len(sshDestPath) > len(f.Path) {
  337. if strings.HasPrefix(sshDestPath, f.Path+"/") || f.Path == "/" {
  338. c.connection.Log(logger.LevelDebug,
  339. "command %q is not allowed it includes folders with file patterns filters %q user %q",
  340. c.command, sshDestPath, c.connection.User.Username)
  341. return errUnsupportedConfig
  342. }
  343. }
  344. if len(sshDestPath) < len(f.Path) {
  345. if strings.HasPrefix(sshDestPath+"/", f.Path) || sshDestPath == "/" {
  346. c.connection.Log(logger.LevelDebug,
  347. "command %q is not allowed inside folder with file patterns filters %q user %q",
  348. c.command, sshDestPath, c.connection.User.Username)
  349. return errUnsupportedConfig
  350. }
  351. }
  352. }
  353. return nil
  354. }
  355. func (c *sshCommand) getSystemCommand() (systemCommand, error) {
  356. command := systemCommand{
  357. cmd: nil,
  358. fs: nil,
  359. fsPath: "",
  360. quotaCheckPath: "",
  361. }
  362. if err := common.CheckClosing(); err != nil {
  363. return command, err
  364. }
  365. args := make([]string, len(c.args))
  366. copy(args, c.args)
  367. var fsPath, quotaPath string
  368. sshPath := c.getDestPath()
  369. fs, err := c.connection.User.GetFilesystemForPath(sshPath, c.connection.ID)
  370. if err != nil {
  371. return command, err
  372. }
  373. if len(c.args) > 0 {
  374. var err error
  375. fsPath, err = fs.ResolvePath(sshPath)
  376. if err != nil {
  377. return command, c.connection.GetFsError(fs, err)
  378. }
  379. quotaPath = sshPath
  380. fi, err := fs.Stat(fsPath)
  381. if err == nil && fi.IsDir() {
  382. // if the target is an existing dir the command will write inside this dir
  383. // so we need to check the quota for this directory and not its parent dir
  384. quotaPath = path.Join(sshPath, "fakecontent")
  385. }
  386. if strings.HasSuffix(sshPath, "/") && !strings.HasSuffix(fsPath, string(os.PathSeparator)) {
  387. fsPath += string(os.PathSeparator)
  388. c.connection.Log(logger.LevelDebug, "path separator added to fsPath %q", fsPath)
  389. }
  390. args = args[:len(args)-1]
  391. args = append(args, fsPath)
  392. }
  393. if err := c.isSystemCommandAllowed(); err != nil {
  394. return command, errUnsupportedConfig
  395. }
  396. if c.command == "rsync" {
  397. // we cannot avoid that rsync creates symlinks so if the user has the permission
  398. // to create symlinks we add the option --safe-links to the received rsync command if
  399. // it is not already set. This should prevent to create symlinks that point outside
  400. // the home dir.
  401. // If the user cannot create symlinks we add the option --munge-links, if it is not
  402. // already set. This should make symlinks unusable (but manually recoverable)
  403. if c.connection.User.HasPerm(dataprovider.PermCreateSymlinks, c.getDestPath()) {
  404. if !util.Contains(args, "--safe-links") {
  405. args = append([]string{"--safe-links"}, args...)
  406. }
  407. } else {
  408. if !util.Contains(args, "--munge-links") {
  409. args = append([]string{"--munge-links"}, args...)
  410. }
  411. }
  412. }
  413. c.connection.Log(logger.LevelDebug, "new system command %q, with args: %+v fs path %q quota check path %q",
  414. c.command, args, fsPath, quotaPath)
  415. cmd := exec.Command(c.command, args...)
  416. uid := c.connection.User.GetUID()
  417. gid := c.connection.User.GetGID()
  418. cmd = wrapCmd(cmd, uid, gid)
  419. command.cmd = cmd
  420. command.fsPath = fsPath
  421. command.quotaCheckPath = quotaPath
  422. command.fs = fs
  423. return command, nil
  424. }
  425. // for the supported commands, the destination path, if any, is the last argument
  426. func (c *sshCommand) getDestPath() string {
  427. if len(c.args) == 0 {
  428. return ""
  429. }
  430. return c.cleanCommandPath(c.args[len(c.args)-1])
  431. }
  432. // for the supported commands, the destination path, if any, is the second-last argument
  433. func (c *sshCommand) getSourcePath() string {
  434. if len(c.args) < 2 {
  435. return ""
  436. }
  437. return c.cleanCommandPath(c.args[len(c.args)-2])
  438. }
  439. func (c *sshCommand) cleanCommandPath(name string) string {
  440. name = strings.Trim(name, "'")
  441. name = strings.Trim(name, "\"")
  442. result := c.connection.User.GetCleanedPath(name)
  443. if strings.HasSuffix(name, "/") && !strings.HasSuffix(result, "/") {
  444. result += "/"
  445. }
  446. return result
  447. }
  448. func (c *sshCommand) getRemovePath() (string, error) {
  449. sshDestPath := c.getDestPath()
  450. if sshDestPath == "" || len(c.args) != 1 {
  451. err := errors.New("usage sftpgo-remove <destination path>")
  452. return "", err
  453. }
  454. if len(sshDestPath) > 1 {
  455. sshDestPath = strings.TrimSuffix(sshDestPath, "/")
  456. }
  457. return sshDestPath, nil
  458. }
  459. func (c *sshCommand) isLocalPath(virtualPath string) bool {
  460. folder, err := c.connection.User.GetVirtualFolderForPath(virtualPath)
  461. if err != nil {
  462. return c.connection.User.FsConfig.Provider == sdk.LocalFilesystemProvider
  463. }
  464. return folder.FsConfig.Provider == sdk.LocalFilesystemProvider
  465. }
  466. func (c *sshCommand) getSizeForPath(fs vfs.Fs, name string) (int, int64, error) {
  467. if dataprovider.GetQuotaTracking() > 0 {
  468. fi, err := fs.Lstat(name)
  469. if err != nil {
  470. if fs.IsNotExist(err) {
  471. return 0, 0, nil
  472. }
  473. c.connection.Log(logger.LevelDebug, "unable to stat %q error: %v", name, err)
  474. return 0, 0, err
  475. }
  476. if fi.IsDir() {
  477. files, size, err := fs.GetDirSize(name)
  478. if err != nil {
  479. c.connection.Log(logger.LevelDebug, "unable to get size for dir %q error: %v", name, err)
  480. }
  481. return files, size, err
  482. } else if fi.Mode().IsRegular() {
  483. return 1, fi.Size(), nil
  484. }
  485. }
  486. return 0, 0, nil
  487. }
  488. func (c *sshCommand) sendErrorResponse(err error) error {
  489. errorString := fmt.Sprintf("%v: %v %v\n", c.command, c.getDestPath(), err)
  490. c.connection.channel.Write([]byte(errorString)) //nolint:errcheck
  491. c.sendExitStatus(err)
  492. return err
  493. }
  494. func (c *sshCommand) sendExitStatus(err error) {
  495. status := uint32(0)
  496. vCmdPath := c.getDestPath()
  497. cmdPath := ""
  498. targetPath := ""
  499. vTargetPath := ""
  500. if c.command == "sftpgo-copy" {
  501. vTargetPath = vCmdPath
  502. vCmdPath = c.getSourcePath()
  503. }
  504. if err != nil {
  505. status = uint32(1)
  506. c.connection.Log(logger.LevelError, "command failed: %q args: %v user: %s err: %v",
  507. c.command, c.args, c.connection.User.Username, err)
  508. }
  509. exitStatus := sshSubsystemExitStatus{
  510. Status: status,
  511. }
  512. _, errClose := c.connection.channel.(ssh.Channel).SendRequest("exit-status", false, ssh.Marshal(&exitStatus))
  513. c.connection.Log(logger.LevelDebug, "exit status sent, error: %v", errClose)
  514. c.connection.channel.Close()
  515. // for scp we notify single uploads/downloads
  516. if c.command != scpCmdName {
  517. elapsed := time.Since(c.startTime).Nanoseconds() / 1000000
  518. metric.SSHCommandCompleted(err)
  519. if vCmdPath != "" {
  520. _, p, errFs := c.connection.GetFsAndResolvedPath(vCmdPath)
  521. if errFs == nil {
  522. cmdPath = p
  523. }
  524. }
  525. if vTargetPath != "" {
  526. _, p, errFs := c.connection.GetFsAndResolvedPath(vTargetPath)
  527. if errFs == nil {
  528. targetPath = p
  529. }
  530. }
  531. common.ExecuteActionNotification(c.connection.BaseConnection, common.OperationSSHCmd, cmdPath, vCmdPath, //nolint:errcheck
  532. targetPath, vTargetPath, c.command, 0, err, elapsed)
  533. if err == nil {
  534. logger.CommandLog(sshCommandLogSender, cmdPath, targetPath, c.connection.User.Username, "", c.connection.ID,
  535. common.ProtocolSSH, -1, -1, "", "", c.connection.command, -1, c.connection.GetLocalAddress(),
  536. c.connection.GetRemoteAddress(), elapsed)
  537. }
  538. }
  539. }
  540. func (c *sshCommand) computeHashForFile(fs vfs.Fs, hasher hash.Hash, path string) (string, error) {
  541. hash := ""
  542. f, r, _, err := fs.Open(path, 0)
  543. if err != nil {
  544. return hash, err
  545. }
  546. var reader io.ReadCloser
  547. if f != nil {
  548. reader = f
  549. } else {
  550. reader = r
  551. }
  552. defer reader.Close()
  553. _, err = io.Copy(hasher, reader)
  554. if err == nil {
  555. hash = fmt.Sprintf("%x", hasher.Sum(nil))
  556. }
  557. return hash, err
  558. }
  559. func parseCommandPayload(command string) (string, []string, error) {
  560. parts, err := shlex.Split(command)
  561. if err == nil && len(parts) == 0 {
  562. err = fmt.Errorf("invalid command: %q", command)
  563. }
  564. if err != nil {
  565. return "", []string{}, err
  566. }
  567. if len(parts) < 2 {
  568. return parts[0], []string{}, nil
  569. }
  570. return parts[0], parts[1:], nil
  571. }