ssh_cmd.go 26 KB

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