ssh_cmd.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  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 { //nolint:gocyclo
  233. sshDestPath := c.getDestPath()
  234. if !c.isLocalPath(sshDestPath) {
  235. return c.sendErrorResponse(errUnsupportedConfig)
  236. }
  237. if err := common.Connections.IsNewTransferAllowed(c.connection.User.Username); err != nil {
  238. err := fmt.Errorf("denying command due to transfer count limits")
  239. return c.sendErrorResponse(err)
  240. }
  241. diskQuota, transferQuota := c.connection.HasSpace(true, false, command.quotaCheckPath)
  242. if !diskQuota.HasSpace || !transferQuota.HasUploadSpace() || !transferQuota.HasDownloadSpace() {
  243. return c.sendErrorResponse(common.ErrQuotaExceeded)
  244. }
  245. perms := []string{dataprovider.PermDownload, dataprovider.PermUpload, dataprovider.PermCreateDirs, dataprovider.PermListItems,
  246. dataprovider.PermOverwrite, dataprovider.PermDelete}
  247. if !c.connection.User.HasPerms(perms, sshDestPath) {
  248. return c.sendErrorResponse(c.connection.GetPermissionDeniedError())
  249. }
  250. initialFiles, initialSize, err := c.getSizeForPath(command.fs, command.fsPath)
  251. if err != nil {
  252. return c.sendErrorResponse(err)
  253. }
  254. stdin, stdout, stderr, err := command.GetSTDs()
  255. if err != nil {
  256. return c.sendErrorResponse(err)
  257. }
  258. err = command.cmd.Start()
  259. if err != nil {
  260. return c.sendErrorResponse(err)
  261. }
  262. closeCmdOnError := func() {
  263. c.connection.Log(logger.LevelDebug, "kill cmd: %q and close ssh channel after read or write error",
  264. c.connection.command)
  265. killerr := command.cmd.Process.Kill()
  266. closerr := c.connection.channel.Close()
  267. c.connection.Log(logger.LevelDebug, "kill cmd error: %v close channel error: %v", killerr, closerr)
  268. }
  269. var once sync.Once
  270. commandResponse := make(chan bool)
  271. remainingQuotaSize := diskQuota.GetRemainingSize()
  272. go func() {
  273. defer stdin.Close()
  274. baseTransfer := common.NewBaseTransfer(nil, c.connection.BaseConnection, nil, command.fsPath, command.fsPath, sshDestPath,
  275. common.TransferUpload, 0, 0, remainingQuotaSize, 0, false, command.fs, transferQuota)
  276. transfer := newTransfer(baseTransfer, nil, nil, nil)
  277. w, e := transfer.copyFromReaderToWriter(stdin, c.connection.channel)
  278. c.connection.Log(logger.LevelDebug, "command: %q, copy from remote command to sdtin ended, written: %v, "+
  279. "initial remaining quota: %v, err: %v", c.connection.command, w, remainingQuotaSize, e)
  280. if e != nil {
  281. once.Do(closeCmdOnError)
  282. }
  283. }()
  284. go func() {
  285. baseTransfer := common.NewBaseTransfer(nil, c.connection.BaseConnection, nil, command.fsPath, command.fsPath, sshDestPath,
  286. common.TransferDownload, 0, 0, 0, 0, false, command.fs, transferQuota)
  287. transfer := newTransfer(baseTransfer, nil, nil, nil)
  288. w, e := transfer.copyFromReaderToWriter(c.connection.channel, stdout)
  289. c.connection.Log(logger.LevelDebug, "command: %q, copy from sdtout to remote command ended, written: %v err: %v",
  290. c.connection.command, w, e)
  291. if e != nil {
  292. once.Do(closeCmdOnError)
  293. }
  294. commandResponse <- true
  295. }()
  296. go func() {
  297. baseTransfer := common.NewBaseTransfer(nil, c.connection.BaseConnection, nil, command.fsPath, command.fsPath, sshDestPath,
  298. common.TransferDownload, 0, 0, 0, 0, false, command.fs, transferQuota)
  299. transfer := newTransfer(baseTransfer, nil, nil, nil)
  300. w, e := transfer.copyFromReaderToWriter(c.connection.channel.(ssh.Channel).Stderr(), stderr)
  301. c.connection.Log(logger.LevelDebug, "command: %q, copy from sdterr to remote command ended, written: %v err: %v",
  302. c.connection.command, w, e)
  303. // os.ErrClosed means that the command is finished so we don't need to do anything
  304. if (e != nil && !errors.Is(e, os.ErrClosed)) || w > 0 {
  305. once.Do(closeCmdOnError)
  306. }
  307. }()
  308. <-commandResponse
  309. err = command.cmd.Wait()
  310. c.sendExitStatus(err)
  311. numFiles, dirSize, errSize := c.getSizeForPath(command.fs, command.fsPath)
  312. if errSize == nil {
  313. c.updateQuota(sshDestPath, numFiles-initialFiles, dirSize-initialSize)
  314. }
  315. c.connection.Log(logger.LevelDebug, "command %q finished for path %q, initial files %v initial size %v "+
  316. "current files %v current size %v size err: %v", c.connection.command, command.fsPath, initialFiles, initialSize,
  317. numFiles, dirSize, errSize)
  318. return c.connection.GetFsError(command.fs, err)
  319. }
  320. func (c *sshCommand) isSystemCommandAllowed() error {
  321. sshDestPath := c.getDestPath()
  322. if c.connection.User.IsVirtualFolder(sshDestPath) {
  323. // overlapped virtual path are not allowed
  324. return nil
  325. }
  326. if c.connection.User.HasVirtualFoldersInside(sshDestPath) {
  327. c.connection.Log(logger.LevelDebug, "command %q is not allowed, path %q has virtual folders inside it, user %q",
  328. c.command, sshDestPath, c.connection.User.Username)
  329. return errUnsupportedConfig
  330. }
  331. for _, f := range c.connection.User.Filters.FilePatterns {
  332. if f.Path == sshDestPath {
  333. c.connection.Log(logger.LevelDebug,
  334. "command %q is not allowed inside folders with file patterns filters %q user %q",
  335. c.command, sshDestPath, c.connection.User.Username)
  336. return errUnsupportedConfig
  337. }
  338. if len(sshDestPath) > len(f.Path) {
  339. if strings.HasPrefix(sshDestPath, f.Path+"/") || f.Path == "/" {
  340. c.connection.Log(logger.LevelDebug,
  341. "command %q is not allowed it includes folders with file patterns filters %q user %q",
  342. c.command, sshDestPath, c.connection.User.Username)
  343. return errUnsupportedConfig
  344. }
  345. }
  346. if len(sshDestPath) < len(f.Path) {
  347. if strings.HasPrefix(sshDestPath+"/", f.Path) || sshDestPath == "/" {
  348. c.connection.Log(logger.LevelDebug,
  349. "command %q is not allowed inside folder with file patterns filters %q user %q",
  350. c.command, sshDestPath, c.connection.User.Username)
  351. return errUnsupportedConfig
  352. }
  353. }
  354. }
  355. return nil
  356. }
  357. func (c *sshCommand) getSystemCommand() (systemCommand, error) {
  358. command := systemCommand{
  359. cmd: nil,
  360. fs: nil,
  361. fsPath: "",
  362. quotaCheckPath: "",
  363. }
  364. if err := common.CheckClosing(); err != nil {
  365. return command, err
  366. }
  367. args := make([]string, len(c.args))
  368. copy(args, c.args)
  369. var fsPath, quotaPath string
  370. sshPath := c.getDestPath()
  371. fs, err := c.connection.User.GetFilesystemForPath(sshPath, c.connection.ID)
  372. if err != nil {
  373. return command, err
  374. }
  375. if len(c.args) > 0 {
  376. var err error
  377. fsPath, err = fs.ResolvePath(sshPath)
  378. if err != nil {
  379. return command, c.connection.GetFsError(fs, err)
  380. }
  381. quotaPath = sshPath
  382. fi, err := fs.Stat(fsPath)
  383. if err == nil && fi.IsDir() {
  384. // if the target is an existing dir the command will write inside this dir
  385. // so we need to check the quota for this directory and not its parent dir
  386. quotaPath = path.Join(sshPath, "fakecontent")
  387. }
  388. if strings.HasSuffix(sshPath, "/") && !strings.HasSuffix(fsPath, string(os.PathSeparator)) {
  389. fsPath += string(os.PathSeparator)
  390. c.connection.Log(logger.LevelDebug, "path separator added to fsPath %q", fsPath)
  391. }
  392. args = args[:len(args)-1]
  393. args = append(args, fsPath)
  394. }
  395. if err := c.isSystemCommandAllowed(); err != nil {
  396. return command, errUnsupportedConfig
  397. }
  398. if c.command == "rsync" {
  399. // we cannot avoid that rsync creates symlinks so if the user has the permission
  400. // to create symlinks we add the option --safe-links to the received rsync command if
  401. // it is not already set. This should prevent to create symlinks that point outside
  402. // the home dir.
  403. // If the user cannot create symlinks we add the option --munge-links, if it is not
  404. // already set. This should make symlinks unusable (but manually recoverable)
  405. if c.connection.User.HasPerm(dataprovider.PermCreateSymlinks, c.getDestPath()) {
  406. if !slices.Contains(args, "--safe-links") {
  407. args = append([]string{"--safe-links"}, args...)
  408. }
  409. } else {
  410. if !slices.Contains(args, "--munge-links") {
  411. args = append([]string{"--munge-links"}, args...)
  412. }
  413. }
  414. }
  415. c.connection.Log(logger.LevelDebug, "new system command %q, with args: %+v fs path %q quota check path %q",
  416. c.command, args, fsPath, quotaPath)
  417. cmd := exec.Command(c.command, args...)
  418. uid := c.connection.User.GetUID()
  419. gid := c.connection.User.GetGID()
  420. cmd = wrapCmd(cmd, uid, gid)
  421. command.cmd = cmd
  422. command.fsPath = fsPath
  423. command.quotaCheckPath = quotaPath
  424. command.fs = fs
  425. return command, nil
  426. }
  427. // for the supported commands, the destination path, if any, is the last argument
  428. func (c *sshCommand) getDestPath() string {
  429. if len(c.args) == 0 {
  430. return ""
  431. }
  432. return c.cleanCommandPath(c.args[len(c.args)-1])
  433. }
  434. // for the supported commands, the destination path, if any, is the second-last argument
  435. func (c *sshCommand) getSourcePath() string {
  436. if len(c.args) < 2 {
  437. return ""
  438. }
  439. return c.cleanCommandPath(c.args[len(c.args)-2])
  440. }
  441. func (c *sshCommand) cleanCommandPath(name string) string {
  442. name = strings.Trim(name, "'")
  443. name = strings.Trim(name, "\"")
  444. result := c.connection.User.GetCleanedPath(name)
  445. if strings.HasSuffix(name, "/") && !strings.HasSuffix(result, "/") {
  446. result += "/"
  447. }
  448. return result
  449. }
  450. func (c *sshCommand) getRemovePath() (string, error) {
  451. sshDestPath := c.getDestPath()
  452. if sshDestPath == "" || len(c.args) != 1 {
  453. err := errors.New("usage sftpgo-remove <destination path>")
  454. return "", err
  455. }
  456. if len(sshDestPath) > 1 {
  457. sshDestPath = strings.TrimSuffix(sshDestPath, "/")
  458. }
  459. return sshDestPath, nil
  460. }
  461. func (c *sshCommand) isLocalPath(virtualPath string) bool {
  462. folder, err := c.connection.User.GetVirtualFolderForPath(virtualPath)
  463. if err != nil {
  464. return c.connection.User.FsConfig.Provider == sdk.LocalFilesystemProvider
  465. }
  466. return folder.FsConfig.Provider == sdk.LocalFilesystemProvider
  467. }
  468. func (c *sshCommand) getSizeForPath(fs vfs.Fs, name string) (int, int64, error) {
  469. if dataprovider.GetQuotaTracking() > 0 {
  470. fi, err := fs.Lstat(name)
  471. if err != nil {
  472. if fs.IsNotExist(err) {
  473. return 0, 0, nil
  474. }
  475. c.connection.Log(logger.LevelDebug, "unable to stat %q error: %v", name, err)
  476. return 0, 0, err
  477. }
  478. if fi.IsDir() {
  479. files, size, err := fs.GetDirSize(name)
  480. if err != nil {
  481. c.connection.Log(logger.LevelDebug, "unable to get size for dir %q error: %v", name, err)
  482. }
  483. return files, size, err
  484. } else if fi.Mode().IsRegular() {
  485. return 1, fi.Size(), nil
  486. }
  487. }
  488. return 0, 0, nil
  489. }
  490. func (c *sshCommand) sendErrorResponse(err error) error {
  491. errorString := fmt.Sprintf("%v: %v %v\n", c.command, c.getDestPath(), err)
  492. c.connection.channel.Write([]byte(errorString)) //nolint:errcheck
  493. c.sendExitStatus(err)
  494. return err
  495. }
  496. func (c *sshCommand) sendExitStatus(err error) {
  497. status := uint32(0)
  498. vCmdPath := c.getDestPath()
  499. cmdPath := ""
  500. targetPath := ""
  501. vTargetPath := ""
  502. if c.command == "sftpgo-copy" {
  503. vTargetPath = vCmdPath
  504. vCmdPath = c.getSourcePath()
  505. }
  506. if err != nil {
  507. status = uint32(1)
  508. c.connection.Log(logger.LevelError, "command failed: %q args: %v user: %s err: %v",
  509. c.command, c.args, c.connection.User.Username, err)
  510. }
  511. exitStatus := sshSubsystemExitStatus{
  512. Status: status,
  513. }
  514. _, errClose := c.connection.channel.(ssh.Channel).SendRequest("exit-status", false, ssh.Marshal(&exitStatus))
  515. c.connection.Log(logger.LevelDebug, "exit status sent, error: %v", errClose)
  516. c.connection.channel.Close()
  517. // for scp we notify single uploads/downloads
  518. if c.command != scpCmdName {
  519. elapsed := time.Since(c.startTime).Nanoseconds() / 1000000
  520. metric.SSHCommandCompleted(err)
  521. if vCmdPath != "" {
  522. _, p, errFs := c.connection.GetFsAndResolvedPath(vCmdPath)
  523. if errFs == nil {
  524. cmdPath = p
  525. }
  526. }
  527. if vTargetPath != "" {
  528. _, p, errFs := c.connection.GetFsAndResolvedPath(vTargetPath)
  529. if errFs == nil {
  530. targetPath = p
  531. }
  532. }
  533. common.ExecuteActionNotification(c.connection.BaseConnection, common.OperationSSHCmd, cmdPath, vCmdPath, //nolint:errcheck
  534. targetPath, vTargetPath, c.command, 0, err, elapsed, nil)
  535. if err == nil {
  536. logger.CommandLog(sshCommandLogSender, cmdPath, targetPath, c.connection.User.Username, "", c.connection.ID,
  537. common.ProtocolSSH, -1, -1, "", "", c.connection.command, -1, c.connection.GetLocalAddress(),
  538. c.connection.GetRemoteAddress(), elapsed)
  539. }
  540. }
  541. }
  542. func (c *sshCommand) computeHashForFile(fs vfs.Fs, hasher hash.Hash, path string) (string, error) {
  543. hash := ""
  544. f, r, _, err := fs.Open(path, 0)
  545. if err != nil {
  546. return hash, err
  547. }
  548. var reader io.ReadCloser
  549. if f != nil {
  550. reader = f
  551. } else {
  552. reader = r
  553. }
  554. defer reader.Close()
  555. _, err = io.Copy(hasher, reader)
  556. if err == nil {
  557. hash = fmt.Sprintf("%x", hasher.Sum(nil))
  558. }
  559. return hash, err
  560. }
  561. func parseCommandPayload(command string) (string, []string, error) {
  562. parts, err := shlex.Split(command)
  563. if err == nil && len(parts) == 0 {
  564. err = fmt.Errorf("invalid command: %q", command)
  565. }
  566. if err != nil {
  567. return "", []string{}, err
  568. }
  569. if len(parts) < 2 {
  570. return parts[0], []string{}, nil
  571. }
  572. return parts[0], parts[1:], nil
  573. }