server.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. package sftpd
  2. import (
  3. "crypto/rand"
  4. "crypto/rsa"
  5. "crypto/x509"
  6. "encoding/hex"
  7. "encoding/json"
  8. "encoding/pem"
  9. "fmt"
  10. "io"
  11. "io/ioutil"
  12. "net"
  13. "os"
  14. "path/filepath"
  15. "strconv"
  16. "strings"
  17. "sync"
  18. "time"
  19. "github.com/drakkan/sftpgo/dataprovider"
  20. "github.com/drakkan/sftpgo/logger"
  21. "github.com/drakkan/sftpgo/metrics"
  22. "github.com/drakkan/sftpgo/utils"
  23. "github.com/pkg/sftp"
  24. "golang.org/x/crypto/ssh"
  25. )
  26. const defaultPrivateKeyName = "id_rsa"
  27. var sftpExtensions = []string{"[email protected]"}
  28. // Configuration for the SFTP server
  29. type Configuration struct {
  30. // Identification string used by the server
  31. Banner string `json:"banner" mapstructure:"banner"`
  32. // The port used for serving SFTP requests
  33. BindPort int `json:"bind_port" mapstructure:"bind_port"`
  34. // The address to listen on. A blank value means listen on all available network interfaces.
  35. BindAddress string `json:"bind_address" mapstructure:"bind_address"`
  36. // Maximum idle timeout as minutes. If a client is idle for a time that exceeds this setting it will be disconnected
  37. IdleTimeout int `json:"idle_timeout" mapstructure:"idle_timeout"`
  38. // Maximum number of authentication attempts permitted per connection.
  39. // If set to a negative number, the number of attempts are unlimited.
  40. // If set to zero, the number of attempts are limited to 6.
  41. MaxAuthTries int `json:"max_auth_tries" mapstructure:"max_auth_tries"`
  42. // Umask for new files
  43. Umask string `json:"umask" mapstructure:"umask"`
  44. // UploadMode 0 means standard, the files are uploaded directly to the requested path.
  45. // 1 means atomic: the files are uploaded to a temporary path and renamed to the requested path
  46. // when the client ends the upload. Atomic mode avoid problems such as a web server that
  47. // serves partial files when the files are being uploaded.
  48. // In atomic mode if there is an upload error the temporary file is deleted and so the requested
  49. // upload path will not contain a partial file.
  50. // 2 means atomic with resume support: as atomic but if there is an upload error the temporary
  51. // file is renamed to the requested path and not deleted, this way a client can reconnect and resume
  52. // the upload.
  53. UploadMode int `json:"upload_mode" mapstructure:"upload_mode"`
  54. // Actions to execute on SFTP create, download, delete and rename
  55. Actions Actions `json:"actions" mapstructure:"actions"`
  56. // Keys are a list of host keys
  57. Keys []Key `json:"keys" mapstructure:"keys"`
  58. // IsSCPEnabled determines if experimental SCP support is enabled.
  59. // We have our own SCP implementation since we can't rely on scp system
  60. // command to properly handle permissions, quota and user's home dir restrictions.
  61. // The SCP protocol is quite simple but there is no official docs about it,
  62. // so we need more testing and feedbacks before enabling it by default.
  63. // We may not handle some borderline cases or have sneaky bugs.
  64. // Please do accurate tests yourself before enabling SCP and let us known
  65. // if something does not work as expected for your use cases
  66. IsSCPEnabled bool `json:"enable_scp" mapstructure:"enable_scp"`
  67. // KexAlgorithms specifies the available KEX (Key Exchange) algorithms in
  68. // preference order.
  69. KexAlgorithms []string `json:"kex_algorithms" mapstructure:"kex_algorithms"`
  70. // Ciphers specifies the ciphers allowed
  71. Ciphers []string `json:"ciphers" mapstructure:"ciphers"`
  72. // MACs Specifies the available MAC (message authentication code) algorithms
  73. // in preference order
  74. MACs []string `json:"macs" mapstructure:"macs"`
  75. // LoginBannerFile the contents of the specified file, if any, are sent to
  76. // the remote user before authentication is allowed.
  77. LoginBannerFile string `json:"login_banner_file" mapstructure:"login_banner_file"`
  78. // SetstatMode 0 means "normal mode": requests for changing permissions and owner/group are executed.
  79. // 1 means "ignore mode": requests for changing permissions and owner/group are silently ignored.
  80. SetstatMode int `json:"setstat_mode" mapstructure:"setstat_mode"`
  81. }
  82. // Key contains information about host keys
  83. type Key struct {
  84. // The private key path relative to the configuration directory or absolute
  85. PrivateKey string `json:"private_key" mapstructure:"private_key"`
  86. }
  87. type authenticationError struct {
  88. err string
  89. }
  90. func (e *authenticationError) Error() string {
  91. return fmt.Sprintf("Authentication error: %s", e.err)
  92. }
  93. // Initialize the SFTP server and add a persistent listener to handle inbound SFTP connections.
  94. func (c Configuration) Initialize(configDir string) error {
  95. umask, err := strconv.ParseUint(c.Umask, 8, 8)
  96. if err == nil {
  97. utils.SetUmask(int(umask), c.Umask)
  98. } else {
  99. logger.Warn(logSender, "", "error reading umask, please fix your config file: %v", err)
  100. logger.WarnToConsole("error reading umask, please fix your config file: %v", err)
  101. }
  102. serverConfig := &ssh.ServerConfig{
  103. NoClientAuth: false,
  104. MaxAuthTries: c.MaxAuthTries,
  105. PasswordCallback: func(conn ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
  106. sp, err := c.validatePasswordCredentials(conn, pass)
  107. if err != nil {
  108. return nil, &authenticationError{err: fmt.Sprintf("could not validate password credentials: %v", err)}
  109. }
  110. return sp, nil
  111. },
  112. PublicKeyCallback: func(conn ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) {
  113. sp, err := c.validatePublicKeyCredentials(conn, string(pubKey.Marshal()))
  114. if err != nil {
  115. return nil, &authenticationError{err: fmt.Sprintf("could not validate public key credentials: %v", err)}
  116. }
  117. return sp, nil
  118. },
  119. ServerVersion: "SSH-2.0-" + c.Banner,
  120. }
  121. err = c.checkHostKeys(configDir)
  122. if err != nil {
  123. return err
  124. }
  125. for _, k := range c.Keys {
  126. privateFile := k.PrivateKey
  127. if !filepath.IsAbs(privateFile) {
  128. privateFile = filepath.Join(configDir, privateFile)
  129. }
  130. logger.Info(logSender, "", "Loading private key: %s", privateFile)
  131. privateBytes, err := ioutil.ReadFile(privateFile)
  132. if err != nil {
  133. return err
  134. }
  135. private, err := ssh.ParsePrivateKey(privateBytes)
  136. if err != nil {
  137. return err
  138. }
  139. // Add private key to the server configuration.
  140. serverConfig.AddHostKey(private)
  141. }
  142. c.configureSecurityOptions(serverConfig)
  143. c.configureLoginBanner(serverConfig, configDir)
  144. c.configureSFTPExtensions()
  145. listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", c.BindAddress, c.BindPort))
  146. if err != nil {
  147. logger.Warn(logSender, "", "error starting listener on address %s:%d: %v", c.BindAddress, c.BindPort, err)
  148. return err
  149. }
  150. actions = c.Actions
  151. uploadMode = c.UploadMode
  152. setstatMode = c.SetstatMode
  153. logger.Info(logSender, "", "server listener registered address: %v", listener.Addr().String())
  154. if c.IdleTimeout > 0 {
  155. startIdleTimer(time.Duration(c.IdleTimeout) * time.Minute)
  156. }
  157. for {
  158. conn, _ := listener.Accept()
  159. if conn != nil {
  160. go c.AcceptInboundConnection(conn, serverConfig)
  161. }
  162. }
  163. }
  164. func (c Configuration) configureSecurityOptions(serverConfig *ssh.ServerConfig) {
  165. if len(c.KexAlgorithms) > 0 {
  166. serverConfig.KeyExchanges = c.KexAlgorithms
  167. }
  168. if len(c.Ciphers) > 0 {
  169. serverConfig.Ciphers = c.Ciphers
  170. }
  171. if len(c.MACs) > 0 {
  172. serverConfig.MACs = c.MACs
  173. }
  174. }
  175. func (c Configuration) configureLoginBanner(serverConfig *ssh.ServerConfig, configDir string) error {
  176. var err error
  177. if len(c.LoginBannerFile) > 0 {
  178. bannerFilePath := c.LoginBannerFile
  179. if !filepath.IsAbs(bannerFilePath) {
  180. bannerFilePath = filepath.Join(configDir, bannerFilePath)
  181. }
  182. var banner []byte
  183. banner, err = ioutil.ReadFile(bannerFilePath)
  184. if err == nil {
  185. serverConfig.BannerCallback = func(conn ssh.ConnMetadata) string {
  186. return string(banner)
  187. }
  188. } else {
  189. logger.WarnToConsole("unable to read login banner file: %v", err)
  190. logger.Warn(logSender, "", "unable to read login banner file: %v", err)
  191. }
  192. }
  193. return err
  194. }
  195. func (c Configuration) configureSFTPExtensions() error {
  196. err := sftp.SetSFTPExtensions(sftpExtensions...)
  197. if err != nil {
  198. logger.WarnToConsole("unable to configure SFTP extensions: %v", err)
  199. logger.Warn(logSender, "", "unable to configure SFTP extensions: %v", err)
  200. }
  201. return err
  202. }
  203. // AcceptInboundConnection handles an inbound connection to the server instance and determines if the request should be served or not.
  204. func (c Configuration) AcceptInboundConnection(conn net.Conn, config *ssh.ServerConfig) {
  205. // Before beginning a handshake must be performed on the incoming net.Conn
  206. // we'll set a Deadline for handshake to complete, the default is 2 minutes as OpenSSH
  207. conn.SetDeadline(time.Now().Add(handshakeTimeout))
  208. remoteAddr := conn.RemoteAddr()
  209. sconn, chans, reqs, err := ssh.NewServerConn(conn, config)
  210. if err != nil {
  211. logger.Warn(logSender, "", "failed to accept an incoming connection: %v", err)
  212. if _, ok := err.(*ssh.ServerAuthError); !ok {
  213. logger.ConnectionFailedLog("", utils.GetIPFromRemoteAddress(remoteAddr.String()), "no_auth_tryed", err.Error())
  214. }
  215. return
  216. }
  217. // handshake completed so remove the deadline, we'll use IdleTimeout configuration from now on
  218. conn.SetDeadline(time.Time{})
  219. var user dataprovider.User
  220. var loginType string
  221. // Unmarshal cannot fails here and even if it fails we'll have a user with no permissions
  222. json.Unmarshal([]byte(sconn.Permissions.Extensions["user"]), &user)
  223. loginType = sconn.Permissions.Extensions["login_type"]
  224. connectionID := hex.EncodeToString(sconn.SessionID())
  225. connection := Connection{
  226. ID: connectionID,
  227. User: user,
  228. ClientVersion: string(sconn.ClientVersion()),
  229. RemoteAddr: remoteAddr,
  230. StartTime: time.Now(),
  231. lastActivity: time.Now(),
  232. lock: new(sync.Mutex),
  233. netConn: conn,
  234. channel: nil,
  235. }
  236. connection.Log(logger.LevelInfo, logSender, "User id: %d, logged in with: %#v, username: %#v, home_dir: %#v remote addr: %#v",
  237. user.ID, loginType, user.Username, user.HomeDir, remoteAddr.String())
  238. dataprovider.UpdateLastLogin(dataProvider, user)
  239. go ssh.DiscardRequests(reqs)
  240. for newChannel := range chans {
  241. // If its not a session channel we just move on because its not something we
  242. // know how to handle at this point.
  243. if newChannel.ChannelType() != "session" {
  244. connection.Log(logger.LevelDebug, logSender, "received an unknown channel type: %v", newChannel.ChannelType())
  245. newChannel.Reject(ssh.UnknownChannelType, "unknown channel type")
  246. continue
  247. }
  248. channel, requests, err := newChannel.Accept()
  249. if err != nil {
  250. connection.Log(logger.LevelWarn, logSender, "could not accept a channel: %v", err)
  251. continue
  252. }
  253. // Channels have a type that is dependent on the protocol. For SFTP this is "subsystem"
  254. // with a payload that (should) be "sftp". Discard anything else we receive ("pty", "shell", etc)
  255. go func(in <-chan *ssh.Request) {
  256. for req := range in {
  257. ok := false
  258. switch req.Type {
  259. case "subsystem":
  260. if string(req.Payload[4:]) == "sftp" {
  261. ok = true
  262. connection.protocol = protocolSFTP
  263. connection.channel = channel
  264. go c.handleSftpConnection(channel, connection)
  265. }
  266. case "exec":
  267. if c.IsSCPEnabled {
  268. var msg execMsg
  269. if err := ssh.Unmarshal(req.Payload, &msg); err == nil {
  270. name, scpArgs, err := parseCommandPayload(msg.Command)
  271. connection.Log(logger.LevelDebug, logSender, "new exec command: %#v args: %v user: %v, error: %v",
  272. name, scpArgs, connection.User.Username, err)
  273. if err == nil && name == "scp" && len(scpArgs) >= 2 {
  274. ok = true
  275. connection.protocol = protocolSCP
  276. connection.channel = channel
  277. scpCommand := scpCommand{
  278. connection: connection,
  279. args: scpArgs,
  280. }
  281. go scpCommand.handle()
  282. }
  283. }
  284. }
  285. }
  286. req.Reply(ok, nil)
  287. }
  288. }(requests)
  289. }
  290. }
  291. func (c Configuration) handleSftpConnection(channel ssh.Channel, connection Connection) {
  292. addConnection(connection)
  293. defer removeConnection(connection)
  294. // Create a new handler for the currently logged in user's server.
  295. handler := c.createHandler(connection)
  296. // Create the server instance for the channel using the handler we created above.
  297. server := sftp.NewRequestServer(channel, handler)
  298. if err := server.Serve(); err == io.EOF {
  299. connection.Log(logger.LevelDebug, logSender, "connection closed, sending exit status")
  300. exitStatus := sshSubsystemExitStatus{Status: uint32(0)}
  301. _, err = channel.SendRequest("exit-status", false, ssh.Marshal(&exitStatus))
  302. connection.Log(logger.LevelDebug, logSender, "sent exit status %+v error: %v", exitStatus, err)
  303. server.Close()
  304. } else if err != nil {
  305. connection.Log(logger.LevelWarn, logSender, "connection closed with error: %v", err)
  306. }
  307. }
  308. func (c Configuration) createHandler(connection Connection) sftp.Handlers {
  309. return sftp.Handlers{
  310. FileGet: connection,
  311. FilePut: connection,
  312. FileCmd: connection,
  313. FileList: connection,
  314. }
  315. }
  316. func loginUser(user dataprovider.User, loginType string) (*ssh.Permissions, error) {
  317. if !filepath.IsAbs(user.HomeDir) {
  318. logger.Warn(logSender, "", "user %#v has an invalid home dir: %#v. Home dir must be an absolute path, login not allowed",
  319. user.Username, user.HomeDir)
  320. return nil, fmt.Errorf("cannot login user with invalid home dir: %#v", user.HomeDir)
  321. }
  322. if _, err := os.Stat(user.HomeDir); os.IsNotExist(err) {
  323. err := os.MkdirAll(user.HomeDir, 0777)
  324. logger.Debug(logSender, "", "home directory %#v for user %#v does not exist, try to create, mkdir error: %v",
  325. user.HomeDir, user.Username, err)
  326. if err == nil {
  327. utils.SetPathPermissions(user.HomeDir, user.GetUID(), user.GetGID())
  328. }
  329. }
  330. if user.MaxSessions > 0 {
  331. activeSessions := getActiveSessions(user.Username)
  332. if activeSessions >= user.MaxSessions {
  333. logger.Debug(logSender, "", "authentication refused for user: %#v, too many open sessions: %v/%v", user.Username,
  334. activeSessions, user.MaxSessions)
  335. return nil, fmt.Errorf("too many open sessions: %v", activeSessions)
  336. }
  337. }
  338. json, err := json.Marshal(user)
  339. if err != nil {
  340. logger.Warn(logSender, "", "error serializing user info: %v, authentication rejected", err)
  341. return nil, err
  342. }
  343. p := &ssh.Permissions{}
  344. p.Extensions = make(map[string]string)
  345. p.Extensions["user"] = string(json)
  346. p.Extensions["login_type"] = loginType
  347. return p, nil
  348. }
  349. // If no host keys are defined we try to use or generate the default one.
  350. func (c *Configuration) checkHostKeys(configDir string) error {
  351. var err error
  352. if len(c.Keys) == 0 {
  353. autoFile := filepath.Join(configDir, defaultPrivateKeyName)
  354. if _, err = os.Stat(autoFile); os.IsNotExist(err) {
  355. logger.Info(logSender, "", "No host keys configured and %#v does not exist; creating new private key for server", autoFile)
  356. logger.InfoToConsole("No host keys configured and %#v does not exist; creating new private key for server", autoFile)
  357. err = c.generatePrivateKey(autoFile)
  358. }
  359. c.Keys = append(c.Keys, Key{PrivateKey: defaultPrivateKeyName})
  360. }
  361. return err
  362. }
  363. func (c Configuration) validatePublicKeyCredentials(conn ssh.ConnMetadata, pubKey string) (*ssh.Permissions, error) {
  364. var err error
  365. var user dataprovider.User
  366. var keyID string
  367. var sshPerm *ssh.Permissions
  368. metrics.AddLoginAttempt(true)
  369. if user, keyID, err = dataprovider.CheckUserAndPubKey(dataProvider, conn.User(), pubKey); err == nil {
  370. sshPerm, err = loginUser(user, "public_key:"+keyID)
  371. } else {
  372. logger.ConnectionFailedLog(conn.User(), utils.GetIPFromRemoteAddress(conn.RemoteAddr().String()), "public_key", err.Error())
  373. }
  374. metrics.AddLoginResult(true, err)
  375. return sshPerm, err
  376. }
  377. func (c Configuration) validatePasswordCredentials(conn ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
  378. var err error
  379. var user dataprovider.User
  380. var sshPerm *ssh.Permissions
  381. metrics.AddLoginAttempt(false)
  382. if user, err = dataprovider.CheckUserAndPass(dataProvider, conn.User(), string(pass)); err == nil {
  383. sshPerm, err = loginUser(user, "password")
  384. } else {
  385. logger.ConnectionFailedLog(conn.User(), utils.GetIPFromRemoteAddress(conn.RemoteAddr().String()), "password", err.Error())
  386. }
  387. metrics.AddLoginResult(false, err)
  388. return sshPerm, err
  389. }
  390. // Generates a private key that will be used by the SFTP server.
  391. func (c Configuration) generatePrivateKey(file string) error {
  392. key, err := rsa.GenerateKey(rand.Reader, 4096)
  393. if err != nil {
  394. return err
  395. }
  396. o, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  397. if err != nil {
  398. return err
  399. }
  400. defer o.Close()
  401. pkey := &pem.Block{
  402. Type: "RSA PRIVATE KEY",
  403. Bytes: x509.MarshalPKCS1PrivateKey(key),
  404. }
  405. if err := pem.Encode(o, pkey); err != nil {
  406. return err
  407. }
  408. return nil
  409. }
  410. func parseCommandPayload(command string) (string, []string, error) {
  411. parts := strings.Split(command, " ")
  412. if len(parts) < 2 {
  413. return parts[0], []string{}, nil
  414. }
  415. return parts[0], parts[1:], nil
  416. }