ssh_cmd.go 19 KB

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