ssh_cmd.go 19 KB

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