ssh_cmd.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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. "path/filepath"
  15. "strings"
  16. "sync"
  17. "time"
  18. "github.com/drakkan/sftpgo/dataprovider"
  19. "github.com/drakkan/sftpgo/logger"
  20. "github.com/drakkan/sftpgo/metrics"
  21. "github.com/drakkan/sftpgo/utils"
  22. "github.com/drakkan/sftpgo/vfs"
  23. "golang.org/x/crypto/ssh"
  24. )
  25. var (
  26. errQuotaExceeded = errors.New("denying write due to space limit")
  27. errPermissionDenied = errors.New("Permission denied. You don't have the permissions to execute this command")
  28. errUnsupportedConfig = errors.New("command unsupported for this configuration")
  29. )
  30. type sshCommand struct {
  31. command string
  32. args []string
  33. connection Connection
  34. }
  35. type systemCommand struct {
  36. cmd *exec.Cmd
  37. realPath string
  38. }
  39. func processSSHCommand(payload []byte, connection *Connection, channel ssh.Channel, enabledSSHCommands []string) bool {
  40. var msg sshSubsystemExecMsg
  41. if err := ssh.Unmarshal(payload, &msg); err == nil {
  42. name, args, err := parseCommandPayload(msg.Command)
  43. connection.Log(logger.LevelDebug, logSenderSSH, "new ssh command: %#v args: %v user: %v, error: %v",
  44. name, args, connection.User.Username, err)
  45. if err == nil && utils.IsStringInSlice(name, enabledSSHCommands) {
  46. connection.command = fmt.Sprintf("%v %v", name, strings.Join(args, " "))
  47. if name == "scp" && len(args) >= 2 {
  48. connection.protocol = protocolSCP
  49. connection.channel = channel
  50. scpCommand := scpCommand{
  51. sshCommand: sshCommand{
  52. command: name,
  53. connection: *connection,
  54. args: args},
  55. }
  56. go scpCommand.handle()
  57. return true
  58. }
  59. if name != "scp" {
  60. connection.protocol = protocolSSH
  61. connection.channel = channel
  62. sshCommand := sshCommand{
  63. command: name,
  64. connection: *connection,
  65. args: args,
  66. }
  67. go sshCommand.handle()
  68. return true
  69. }
  70. } else {
  71. connection.Log(logger.LevelInfo, logSenderSSH, "ssh command not enabled/supported: %#v", name)
  72. }
  73. }
  74. return false
  75. }
  76. func (c *sshCommand) handle() error {
  77. addConnection(c.connection)
  78. defer removeConnection(c.connection)
  79. updateConnectionActivity(c.connection.ID)
  80. if utils.IsStringInSlice(c.command, sshHashCommands) {
  81. return c.handleHashCommands()
  82. } else if utils.IsStringInSlice(c.command, systemCommands) {
  83. command, err := c.getSystemCommand()
  84. if err != nil {
  85. return c.sendErrorResponse(err)
  86. }
  87. return c.executeSystemCommand(command)
  88. } else if c.command == "cd" {
  89. c.sendExitStatus(nil)
  90. } else if c.command == "pwd" {
  91. // hard coded response to "/"
  92. c.connection.channel.Write([]byte("/\n"))
  93. c.sendExitStatus(nil)
  94. }
  95. return nil
  96. }
  97. func (c *sshCommand) handleHashCommands() error {
  98. if !vfs.IsLocalOsFs(c.connection.fs) {
  99. return c.sendErrorResponse(errUnsupportedConfig)
  100. }
  101. var h hash.Hash
  102. if c.command == "md5sum" {
  103. h = md5.New()
  104. } else if c.command == "sha1sum" {
  105. h = sha1.New()
  106. } else if c.command == "sha256sum" {
  107. h = sha256.New()
  108. } else if c.command == "sha384sum" {
  109. h = sha512.New384()
  110. } else {
  111. h = sha512.New()
  112. }
  113. var response string
  114. if len(c.args) == 0 {
  115. // without args we need to read the string to hash from stdin
  116. buf := make([]byte, 4096)
  117. n, err := c.connection.channel.Read(buf)
  118. if err != nil && err != io.EOF {
  119. return c.sendErrorResponse(err)
  120. }
  121. h.Write(buf[:n])
  122. response = fmt.Sprintf("%x -\n", h.Sum(nil))
  123. } else {
  124. sshPath := c.getDestPath()
  125. fsPath, err := c.connection.fs.ResolvePath(sshPath)
  126. if err != nil {
  127. return c.sendErrorResponse(err)
  128. }
  129. if !c.connection.User.HasPerm(dataprovider.PermListItems, sshPath) {
  130. return c.sendErrorResponse(errPermissionDenied)
  131. }
  132. hash, err := computeHashForFile(h, fsPath)
  133. if err != nil {
  134. return c.sendErrorResponse(err)
  135. }
  136. response = fmt.Sprintf("%v %v\n", hash, sshPath)
  137. }
  138. c.connection.channel.Write([]byte(response))
  139. c.sendExitStatus(nil)
  140. return nil
  141. }
  142. func (c *sshCommand) executeSystemCommand(command systemCommand) error {
  143. if !vfs.IsLocalOsFs(c.connection.fs) {
  144. return c.sendErrorResponse(errUnsupportedConfig)
  145. }
  146. if c.connection.User.QuotaFiles > 0 && c.connection.User.UsedQuotaFiles > c.connection.User.QuotaFiles {
  147. return c.sendErrorResponse(errQuotaExceeded)
  148. }
  149. perms := []string{dataprovider.PermDownload, dataprovider.PermUpload, dataprovider.PermCreateDirs, dataprovider.PermListItems,
  150. dataprovider.PermOverwrite, dataprovider.PermDelete, dataprovider.PermRename}
  151. if !c.connection.User.HasPerms(perms, c.getDestPath()) {
  152. return c.sendErrorResponse(errPermissionDenied)
  153. }
  154. stdin, err := command.cmd.StdinPipe()
  155. if err != nil {
  156. return c.sendErrorResponse(err)
  157. }
  158. stdout, err := command.cmd.StdoutPipe()
  159. if err != nil {
  160. return c.sendErrorResponse(err)
  161. }
  162. stderr, err := command.cmd.StderrPipe()
  163. if err != nil {
  164. return c.sendErrorResponse(err)
  165. }
  166. err = command.cmd.Start()
  167. if err != nil {
  168. return c.sendErrorResponse(err)
  169. }
  170. closeCmdOnError := func() {
  171. c.connection.Log(logger.LevelDebug, logSenderSSH, "kill cmd: %#v and close ssh channel after read or write error",
  172. c.connection.command)
  173. command.cmd.Process.Kill()
  174. c.connection.channel.Close()
  175. }
  176. var once sync.Once
  177. commandResponse := make(chan bool)
  178. go func() {
  179. defer stdin.Close()
  180. remainingQuotaSize := int64(0)
  181. if c.connection.User.QuotaSize > 0 {
  182. remainingQuotaSize = c.connection.User.QuotaSize - c.connection.User.UsedQuotaSize
  183. }
  184. transfer := Transfer{
  185. file: nil,
  186. path: command.realPath,
  187. start: time.Now(),
  188. bytesSent: 0,
  189. bytesReceived: 0,
  190. user: c.connection.User,
  191. connectionID: c.connection.ID,
  192. transferType: transferUpload,
  193. lastActivity: time.Now(),
  194. isNewFile: false,
  195. protocol: c.connection.protocol,
  196. transferError: nil,
  197. isFinished: false,
  198. minWriteOffset: 0,
  199. lock: new(sync.Mutex),
  200. }
  201. addTransfer(&transfer)
  202. defer removeTransfer(&transfer)
  203. w, e := transfer.copyFromReaderToWriter(stdin, c.connection.channel, remainingQuotaSize)
  204. c.connection.Log(logger.LevelDebug, logSenderSSH, "command: %#v, copy from remote command to sdtin ended, written: %v, "+
  205. "initial remaining quota: %v, err: %v", c.connection.command, w, remainingQuotaSize, e)
  206. if e != nil {
  207. once.Do(closeCmdOnError)
  208. }
  209. }()
  210. go func() {
  211. transfer := Transfer{
  212. file: nil,
  213. path: command.realPath,
  214. start: time.Now(),
  215. bytesSent: 0,
  216. bytesReceived: 0,
  217. user: c.connection.User,
  218. connectionID: c.connection.ID,
  219. transferType: transferDownload,
  220. lastActivity: time.Now(),
  221. isNewFile: false,
  222. protocol: c.connection.protocol,
  223. transferError: nil,
  224. isFinished: false,
  225. minWriteOffset: 0,
  226. lock: new(sync.Mutex),
  227. }
  228. addTransfer(&transfer)
  229. defer removeTransfer(&transfer)
  230. w, e := transfer.copyFromReaderToWriter(c.connection.channel, stdout, 0)
  231. c.connection.Log(logger.LevelDebug, logSenderSSH, "command: %#v, copy from sdtout to remote command ended, written: %v err: %v",
  232. c.connection.command, w, e)
  233. if e != nil {
  234. once.Do(closeCmdOnError)
  235. }
  236. commandResponse <- true
  237. }()
  238. go func() {
  239. transfer := Transfer{
  240. file: nil,
  241. path: command.realPath,
  242. start: time.Now(),
  243. bytesSent: 0,
  244. bytesReceived: 0,
  245. user: c.connection.User,
  246. connectionID: c.connection.ID,
  247. transferType: transferDownload,
  248. lastActivity: time.Now(),
  249. isNewFile: false,
  250. protocol: c.connection.protocol,
  251. transferError: nil,
  252. isFinished: false,
  253. minWriteOffset: 0,
  254. lock: new(sync.Mutex),
  255. }
  256. addTransfer(&transfer)
  257. defer removeTransfer(&transfer)
  258. w, e := transfer.copyFromReaderToWriter(c.connection.channel.Stderr(), stderr, 0)
  259. c.connection.Log(logger.LevelDebug, logSenderSSH, "command: %#v, copy from sdterr to remote command ended, written: %v err: %v",
  260. c.connection.command, w, e)
  261. // os.ErrClosed means that the command is finished so we don't need to do anything
  262. if (e != nil && !errors.Is(e, os.ErrClosed)) || w > 0 {
  263. once.Do(closeCmdOnError)
  264. }
  265. }()
  266. <-commandResponse
  267. err = command.cmd.Wait()
  268. c.sendExitStatus(err)
  269. c.rescanHomeDir()
  270. return err
  271. }
  272. func (c *sshCommand) getSystemCommand() (systemCommand, error) {
  273. command := systemCommand{
  274. cmd: nil,
  275. realPath: "",
  276. }
  277. args := make([]string, len(c.args))
  278. copy(args, c.args)
  279. var path string
  280. if len(c.args) > 0 {
  281. var err error
  282. sshPath := c.getDestPath()
  283. path, err = c.connection.fs.ResolvePath(sshPath)
  284. if err != nil {
  285. return command, err
  286. }
  287. args = args[:len(args)-1]
  288. args = append(args, path)
  289. }
  290. if c.command == "rsync" {
  291. // we cannot avoid that rsync create symlinks so if the user has the permission
  292. // to create symlinks we add the option --safe-links to the received rsync command if
  293. // it is not already set. This should prevent to create symlinks that point outside
  294. // the home dir.
  295. // If the user cannot create symlinks we add the option --munge-links, if it is not
  296. // already set. This should make symlinks unusable (but manually recoverable)
  297. if c.connection.User.HasPerm(dataprovider.PermCreateSymlinks, c.getDestPath()) {
  298. if !utils.IsStringInSlice("--safe-links", args) {
  299. args = append([]string{"--safe-links"}, args...)
  300. }
  301. } else {
  302. if !utils.IsStringInSlice("--munge-links", args) {
  303. args = append([]string{"--munge-links"}, args...)
  304. }
  305. }
  306. }
  307. c.connection.Log(logger.LevelDebug, logSenderSSH, "new system command %#v, with args: %v path: %v", c.command, args, path)
  308. cmd := exec.Command(c.command, args...)
  309. uid := c.connection.User.GetUID()
  310. gid := c.connection.User.GetGID()
  311. cmd = wrapCmd(cmd, uid, gid)
  312. command.cmd = cmd
  313. command.realPath = path
  314. return command, nil
  315. }
  316. func (c *sshCommand) rescanHomeDir() error {
  317. quotaTracking := dataprovider.GetQuotaTracking()
  318. if (!c.connection.User.HasQuotaRestrictions() && quotaTracking == 2) || quotaTracking == 0 {
  319. return nil
  320. }
  321. var err error
  322. var numFiles int
  323. var size int64
  324. if AddQuotaScan(c.connection.User.Username) {
  325. numFiles, size, err = c.connection.fs.ScanRootDirContents()
  326. if err != nil {
  327. c.connection.Log(logger.LevelWarn, logSenderSSH, "error scanning user home dir %#v: %v", c.connection.User.HomeDir, err)
  328. } else {
  329. err := dataprovider.UpdateUserQuota(dataProvider, c.connection.User, numFiles, size, true)
  330. c.connection.Log(logger.LevelDebug, logSenderSSH, "user home dir scanned, user: %#v, dir: %#v, error: %v",
  331. c.connection.User.Username, c.connection.User.HomeDir, err)
  332. }
  333. RemoveQuotaScan(c.connection.User.Username)
  334. }
  335. return err
  336. }
  337. // for the supported command, the path, if any, is the last argument
  338. func (c *sshCommand) getDestPath() string {
  339. if len(c.args) == 0 {
  340. return ""
  341. }
  342. destPath := strings.Trim(c.args[len(c.args)-1], "'")
  343. destPath = strings.Trim(destPath, "\"")
  344. destPath = filepath.ToSlash(destPath)
  345. if !path.IsAbs(destPath) {
  346. destPath = "/" + destPath
  347. }
  348. result := path.Clean(destPath)
  349. if strings.HasSuffix(destPath, "/") && !strings.HasSuffix(result, "/") {
  350. result += "/"
  351. }
  352. return result
  353. }
  354. func (c *sshCommand) sendErrorResponse(err error) error {
  355. errorString := fmt.Sprintf("%v: %v %v\n", c.command, c.getDestPath(), err)
  356. c.connection.channel.Write([]byte(errorString))
  357. c.sendExitStatus(err)
  358. return err
  359. }
  360. func (c *sshCommand) sendExitStatus(err error) {
  361. status := uint32(0)
  362. if err != nil {
  363. status = uint32(1)
  364. c.connection.Log(logger.LevelWarn, logSenderSSH, "command failed: %#v args: %v user: %v err: %v",
  365. c.command, c.args, c.connection.User.Username, err)
  366. } else {
  367. logger.CommandLog(sshCommandLogSender, c.getDestPath(), "", c.connection.User.Username, "", c.connection.ID,
  368. protocolSSH, -1, -1, "", "", c.connection.command)
  369. }
  370. exitStatus := sshSubsystemExitStatus{
  371. Status: status,
  372. }
  373. c.connection.channel.SendRequest("exit-status", false, ssh.Marshal(&exitStatus))
  374. c.connection.channel.Close()
  375. metrics.SSHCommandCompleted(err)
  376. // for scp we notify single uploads/downloads
  377. if err == nil && c.command != "scp" {
  378. realPath := c.getDestPath()
  379. if len(realPath) > 0 {
  380. p, err := c.connection.fs.ResolvePath(realPath)
  381. if err == nil {
  382. realPath = p
  383. }
  384. }
  385. go executeAction(operationSSHCmd, c.connection.User.Username, realPath, "", c.command, 0)
  386. }
  387. }
  388. func computeHashForFile(hasher hash.Hash, path string) (string, error) {
  389. hash := ""
  390. f, err := os.Open(path)
  391. if err != nil {
  392. return hash, err
  393. }
  394. defer f.Close()
  395. _, err = io.Copy(hasher, f)
  396. if err == nil {
  397. hash = fmt.Sprintf("%x", hasher.Sum(nil))
  398. }
  399. return hash, err
  400. }
  401. func parseCommandPayload(command string) (string, []string, error) {
  402. parts := strings.Split(command, " ")
  403. if len(parts) < 2 {
  404. return parts[0], []string{}, nil
  405. }
  406. return parts[0], parts[1:], nil
  407. }