ssh_cmd.go 11 KB

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