server.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. // Copyright 2011 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package ssh
  5. import (
  6. "bytes"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "net"
  11. "strings"
  12. )
  13. // The Permissions type holds fine-grained permissions that are
  14. // specific to a user or a specific authentication method for a user.
  15. // The Permissions value for a successful authentication attempt is
  16. // available in ServerConn, so it can be used to pass information from
  17. // the user-authentication phase to the application layer.
  18. type Permissions struct {
  19. // CriticalOptions indicate restrictions to the default
  20. // permissions, and are typically used in conjunction with
  21. // user certificates. The standard for SSH certificates
  22. // defines "force-command" (only allow the given command to
  23. // execute) and "source-address" (only allow connections from
  24. // the given address). The SSH package currently only enforces
  25. // the "source-address" critical option. It is up to server
  26. // implementations to enforce other critical options, such as
  27. // "force-command", by checking them after the SSH handshake
  28. // is successful. In general, SSH servers should reject
  29. // connections that specify critical options that are unknown
  30. // or not supported.
  31. CriticalOptions map[string]string
  32. // Extensions are extra functionality that the server may
  33. // offer on authenticated connections. Lack of support for an
  34. // extension does not preclude authenticating a user. Common
  35. // extensions are "permit-agent-forwarding",
  36. // "permit-X11-forwarding". The Go SSH library currently does
  37. // not act on any extension, and it is up to server
  38. // implementations to honor them. Extensions can be used to
  39. // pass data from the authentication callbacks to the server
  40. // application layer.
  41. Extensions map[string]string
  42. }
  43. // ServerConfig holds server specific configuration data.
  44. type ServerConfig struct {
  45. // Config contains configuration shared between client and server.
  46. Config
  47. hostKeys []Signer
  48. // NoClientAuth is true if clients are allowed to connect without
  49. // authenticating.
  50. NoClientAuth bool
  51. // MaxAuthTries specifies the maximum number of authentication attempts
  52. // permitted per connection. If set to a negative number, the number of
  53. // attempts are unlimited. If set to zero, the number of attempts are limited
  54. // to 6.
  55. MaxAuthTries int
  56. // PasswordCallback, if non-nil, is called when a user
  57. // attempts to authenticate using a password.
  58. PasswordCallback func(conn ConnMetadata, password []byte) (*Permissions, error)
  59. // PublicKeyCallback, if non-nil, is called when a client
  60. // offers a public key for authentication. It must return a nil error
  61. // if the given public key can be used to authenticate the
  62. // given user. For example, see CertChecker.Authenticate. A
  63. // call to this function does not guarantee that the key
  64. // offered is in fact used to authenticate. To record any data
  65. // depending on the public key, store it inside a
  66. // Permissions.Extensions entry.
  67. PublicKeyCallback func(conn ConnMetadata, key PublicKey) (*Permissions, error)
  68. // KeyboardInteractiveCallback, if non-nil, is called when
  69. // keyboard-interactive authentication is selected (RFC
  70. // 4256). The client object's Challenge function should be
  71. // used to query the user. The callback may offer multiple
  72. // Challenge rounds. To avoid information leaks, the client
  73. // should be presented a challenge even if the user is
  74. // unknown.
  75. KeyboardInteractiveCallback func(conn ConnMetadata, client KeyboardInteractiveChallenge) (*Permissions, error)
  76. // AuthLogCallback, if non-nil, is called to log all authentication
  77. // attempts.
  78. AuthLogCallback func(conn ConnMetadata, method string, err error)
  79. // ServerVersion is the version identification string to announce in
  80. // the public handshake.
  81. // If empty, a reasonable default is used.
  82. // Note that RFC 4253 section 4.2 requires that this string start with
  83. // "SSH-2.0-".
  84. ServerVersion string
  85. }
  86. // AddHostKey adds a private key as a host key. If an existing host
  87. // key exists with the same algorithm, it is overwritten. Each server
  88. // config must have at least one host key.
  89. func (s *ServerConfig) AddHostKey(key Signer) {
  90. for i, k := range s.hostKeys {
  91. if k.PublicKey().Type() == key.PublicKey().Type() {
  92. s.hostKeys[i] = key
  93. return
  94. }
  95. }
  96. s.hostKeys = append(s.hostKeys, key)
  97. }
  98. // cachedPubKey contains the results of querying whether a public key is
  99. // acceptable for a user.
  100. type cachedPubKey struct {
  101. user string
  102. pubKeyData []byte
  103. result error
  104. perms *Permissions
  105. }
  106. const maxCachedPubKeys = 16
  107. // pubKeyCache caches tests for public keys. Since SSH clients
  108. // will query whether a public key is acceptable before attempting to
  109. // authenticate with it, we end up with duplicate queries for public
  110. // key validity. The cache only applies to a single ServerConn.
  111. type pubKeyCache struct {
  112. keys []cachedPubKey
  113. }
  114. // get returns the result for a given user/algo/key tuple.
  115. func (c *pubKeyCache) get(user string, pubKeyData []byte) (cachedPubKey, bool) {
  116. for _, k := range c.keys {
  117. if k.user == user && bytes.Equal(k.pubKeyData, pubKeyData) {
  118. return k, true
  119. }
  120. }
  121. return cachedPubKey{}, false
  122. }
  123. // add adds the given tuple to the cache.
  124. func (c *pubKeyCache) add(candidate cachedPubKey) {
  125. if len(c.keys) < maxCachedPubKeys {
  126. c.keys = append(c.keys, candidate)
  127. }
  128. }
  129. // ServerConn is an authenticated SSH connection, as seen from the
  130. // server
  131. type ServerConn struct {
  132. Conn
  133. // If the succeeding authentication callback returned a
  134. // non-nil Permissions pointer, it is stored here.
  135. Permissions *Permissions
  136. }
  137. // NewServerConn starts a new SSH server with c as the underlying
  138. // transport. It starts with a handshake and, if the handshake is
  139. // unsuccessful, it closes the connection and returns an error. The
  140. // Request and NewChannel channels must be serviced, or the connection
  141. // will hang.
  142. func NewServerConn(c net.Conn, config *ServerConfig) (*ServerConn, <-chan NewChannel, <-chan *Request, error) {
  143. fullConf := *config
  144. fullConf.SetDefaults()
  145. if fullConf.MaxAuthTries == 0 {
  146. fullConf.MaxAuthTries = 6
  147. }
  148. s := &connection{
  149. sshConn: sshConn{conn: c},
  150. }
  151. perms, err := s.serverHandshake(&fullConf)
  152. if err != nil {
  153. c.Close()
  154. return nil, nil, nil, err
  155. }
  156. return &ServerConn{s, perms}, s.mux.incomingChannels, s.mux.incomingRequests, nil
  157. }
  158. // signAndMarshal signs the data with the appropriate algorithm,
  159. // and serializes the result in SSH wire format.
  160. func signAndMarshal(k Signer, rand io.Reader, data []byte) ([]byte, error) {
  161. sig, err := k.Sign(rand, data)
  162. if err != nil {
  163. return nil, err
  164. }
  165. return Marshal(sig), nil
  166. }
  167. // handshake performs key exchange and user authentication.
  168. func (s *connection) serverHandshake(config *ServerConfig) (*Permissions, error) {
  169. if len(config.hostKeys) == 0 {
  170. return nil, errors.New("ssh: server has no host keys")
  171. }
  172. if !config.NoClientAuth && config.PasswordCallback == nil && config.PublicKeyCallback == nil && config.KeyboardInteractiveCallback == nil {
  173. return nil, errors.New("ssh: no authentication methods configured but NoClientAuth is also false")
  174. }
  175. if config.ServerVersion != "" {
  176. s.serverVersion = []byte(config.ServerVersion)
  177. } else {
  178. s.serverVersion = []byte(packageVersion)
  179. }
  180. var err error
  181. s.clientVersion, err = exchangeVersions(s.sshConn.conn, s.serverVersion)
  182. if err != nil {
  183. return nil, err
  184. }
  185. tr := newTransport(s.sshConn.conn, config.Rand, false /* not client */)
  186. s.transport = newServerTransport(tr, s.clientVersion, s.serverVersion, config)
  187. if err := s.transport.waitSession(); err != nil {
  188. return nil, err
  189. }
  190. // We just did the key change, so the session ID is established.
  191. s.sessionID = s.transport.getSessionID()
  192. var packet []byte
  193. if packet, err = s.transport.readPacket(); err != nil {
  194. return nil, err
  195. }
  196. var serviceRequest serviceRequestMsg
  197. if err = Unmarshal(packet, &serviceRequest); err != nil {
  198. return nil, err
  199. }
  200. if serviceRequest.Service != serviceUserAuth {
  201. return nil, errors.New("ssh: requested service '" + serviceRequest.Service + "' before authenticating")
  202. }
  203. serviceAccept := serviceAcceptMsg{
  204. Service: serviceUserAuth,
  205. }
  206. if err := s.transport.writePacket(Marshal(&serviceAccept)); err != nil {
  207. return nil, err
  208. }
  209. perms, err := s.serverAuthenticate(config)
  210. if err != nil {
  211. return nil, err
  212. }
  213. s.mux = newMux(s.transport)
  214. return perms, err
  215. }
  216. func isAcceptableAlgo(algo string) bool {
  217. switch algo {
  218. case KeyAlgoRSA, KeyAlgoDSA, KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521, KeyAlgoED25519,
  219. CertAlgoRSAv01, CertAlgoDSAv01, CertAlgoECDSA256v01, CertAlgoECDSA384v01, CertAlgoECDSA521v01:
  220. return true
  221. }
  222. return false
  223. }
  224. func checkSourceAddress(addr net.Addr, sourceAddrs string) error {
  225. if addr == nil {
  226. return errors.New("ssh: no address known for client, but source-address match required")
  227. }
  228. tcpAddr, ok := addr.(*net.TCPAddr)
  229. if !ok {
  230. return fmt.Errorf("ssh: remote address %v is not an TCP address when checking source-address match", addr)
  231. }
  232. for _, sourceAddr := range strings.Split(sourceAddrs, ",") {
  233. if allowedIP := net.ParseIP(sourceAddr); allowedIP != nil {
  234. if allowedIP.Equal(tcpAddr.IP) {
  235. return nil
  236. }
  237. } else {
  238. _, ipNet, err := net.ParseCIDR(sourceAddr)
  239. if err != nil {
  240. return fmt.Errorf("ssh: error parsing source-address restriction %q: %v", sourceAddr, err)
  241. }
  242. if ipNet.Contains(tcpAddr.IP) {
  243. return nil
  244. }
  245. }
  246. }
  247. return fmt.Errorf("ssh: remote address %v is not allowed because of source-address restriction", addr)
  248. }
  249. // ServerAuthError implements the error interface. It appends any authentication
  250. // errors that may occur, and is returned if all of the authentication methods
  251. // provided by the user failed to authenticate.
  252. type ServerAuthError struct {
  253. // Errors contains authentication errors returned by the authentication
  254. // callback methods.
  255. Errors []error
  256. }
  257. func (l ServerAuthError) Error() string {
  258. var errs []string
  259. for _, err := range l.Errors {
  260. errs = append(errs, err.Error())
  261. }
  262. return "[" + strings.Join(errs, ", ") + "]"
  263. }
  264. func (s *connection) serverAuthenticate(config *ServerConfig) (*Permissions, error) {
  265. sessionID := s.transport.getSessionID()
  266. var cache pubKeyCache
  267. var perms *Permissions
  268. authFailures := 0
  269. var authErrs []error
  270. userAuthLoop:
  271. for {
  272. if authFailures >= config.MaxAuthTries && config.MaxAuthTries > 0 {
  273. discMsg := &disconnectMsg{
  274. Reason: 2,
  275. Message: "too many authentication failures",
  276. }
  277. if err := s.transport.writePacket(Marshal(discMsg)); err != nil {
  278. return nil, err
  279. }
  280. return nil, discMsg
  281. }
  282. var userAuthReq userAuthRequestMsg
  283. if packet, err := s.transport.readPacket(); err != nil {
  284. if err == io.EOF {
  285. return nil, &ServerAuthError{Errors: authErrs}
  286. }
  287. return nil, err
  288. } else if err = Unmarshal(packet, &userAuthReq); err != nil {
  289. return nil, err
  290. }
  291. if userAuthReq.Service != serviceSSH {
  292. return nil, errors.New("ssh: client attempted to negotiate for unknown service: " + userAuthReq.Service)
  293. }
  294. s.user = userAuthReq.User
  295. perms = nil
  296. authErr := errors.New("no auth passed yet")
  297. switch userAuthReq.Method {
  298. case "none":
  299. if config.NoClientAuth {
  300. authErr = nil
  301. }
  302. // allow initial attempt of 'none' without penalty
  303. if authFailures == 0 {
  304. authFailures--
  305. }
  306. case "password":
  307. if config.PasswordCallback == nil {
  308. authErr = errors.New("ssh: password auth not configured")
  309. break
  310. }
  311. payload := userAuthReq.Payload
  312. if len(payload) < 1 || payload[0] != 0 {
  313. return nil, parseError(msgUserAuthRequest)
  314. }
  315. payload = payload[1:]
  316. password, payload, ok := parseString(payload)
  317. if !ok || len(payload) > 0 {
  318. return nil, parseError(msgUserAuthRequest)
  319. }
  320. perms, authErr = config.PasswordCallback(s, password)
  321. case "keyboard-interactive":
  322. if config.KeyboardInteractiveCallback == nil {
  323. authErr = errors.New("ssh: keyboard-interactive auth not configubred")
  324. break
  325. }
  326. prompter := &sshClientKeyboardInteractive{s}
  327. perms, authErr = config.KeyboardInteractiveCallback(s, prompter.Challenge)
  328. case "publickey":
  329. if config.PublicKeyCallback == nil {
  330. authErr = errors.New("ssh: publickey auth not configured")
  331. break
  332. }
  333. payload := userAuthReq.Payload
  334. if len(payload) < 1 {
  335. return nil, parseError(msgUserAuthRequest)
  336. }
  337. isQuery := payload[0] == 0
  338. payload = payload[1:]
  339. algoBytes, payload, ok := parseString(payload)
  340. if !ok {
  341. return nil, parseError(msgUserAuthRequest)
  342. }
  343. algo := string(algoBytes)
  344. if !isAcceptableAlgo(algo) {
  345. authErr = fmt.Errorf("ssh: algorithm %q not accepted", algo)
  346. break
  347. }
  348. pubKeyData, payload, ok := parseString(payload)
  349. if !ok {
  350. return nil, parseError(msgUserAuthRequest)
  351. }
  352. pubKey, err := ParsePublicKey(pubKeyData)
  353. if err != nil {
  354. return nil, err
  355. }
  356. candidate, ok := cache.get(s.user, pubKeyData)
  357. if !ok {
  358. candidate.user = s.user
  359. candidate.pubKeyData = pubKeyData
  360. candidate.perms, candidate.result = config.PublicKeyCallback(s, pubKey)
  361. if candidate.result == nil && candidate.perms != nil && candidate.perms.CriticalOptions != nil && candidate.perms.CriticalOptions[sourceAddressCriticalOption] != "" {
  362. candidate.result = checkSourceAddress(
  363. s.RemoteAddr(),
  364. candidate.perms.CriticalOptions[sourceAddressCriticalOption])
  365. }
  366. cache.add(candidate)
  367. }
  368. if isQuery {
  369. // The client can query if the given public key
  370. // would be okay.
  371. if len(payload) > 0 {
  372. return nil, parseError(msgUserAuthRequest)
  373. }
  374. if candidate.result == nil {
  375. okMsg := userAuthPubKeyOkMsg{
  376. Algo: algo,
  377. PubKey: pubKeyData,
  378. }
  379. if err = s.transport.writePacket(Marshal(&okMsg)); err != nil {
  380. return nil, err
  381. }
  382. continue userAuthLoop
  383. }
  384. authErr = candidate.result
  385. } else {
  386. sig, payload, ok := parseSignature(payload)
  387. if !ok || len(payload) > 0 {
  388. return nil, parseError(msgUserAuthRequest)
  389. }
  390. // Ensure the public key algo and signature algo
  391. // are supported. Compare the private key
  392. // algorithm name that corresponds to algo with
  393. // sig.Format. This is usually the same, but
  394. // for certs, the names differ.
  395. if !isAcceptableAlgo(sig.Format) {
  396. break
  397. }
  398. signedData := buildDataSignedForAuth(sessionID, userAuthReq, algoBytes, pubKeyData)
  399. if err := pubKey.Verify(signedData, sig); err != nil {
  400. return nil, err
  401. }
  402. authErr = candidate.result
  403. perms = candidate.perms
  404. }
  405. default:
  406. authErr = fmt.Errorf("ssh: unknown method %q", userAuthReq.Method)
  407. }
  408. authErrs = append(authErrs, authErr)
  409. if config.AuthLogCallback != nil {
  410. config.AuthLogCallback(s, userAuthReq.Method, authErr)
  411. }
  412. if authErr == nil {
  413. break userAuthLoop
  414. }
  415. authFailures++
  416. var failureMsg userAuthFailureMsg
  417. if config.PasswordCallback != nil {
  418. failureMsg.Methods = append(failureMsg.Methods, "password")
  419. }
  420. if config.PublicKeyCallback != nil {
  421. failureMsg.Methods = append(failureMsg.Methods, "publickey")
  422. }
  423. if config.KeyboardInteractiveCallback != nil {
  424. failureMsg.Methods = append(failureMsg.Methods, "keyboard-interactive")
  425. }
  426. if len(failureMsg.Methods) == 0 {
  427. return nil, errors.New("ssh: no authentication methods configured but NoClientAuth is also false")
  428. }
  429. if err := s.transport.writePacket(Marshal(&failureMsg)); err != nil {
  430. return nil, err
  431. }
  432. }
  433. if err := s.transport.writePacket([]byte{msgUserAuthSuccess}); err != nil {
  434. return nil, err
  435. }
  436. return perms, nil
  437. }
  438. // sshClientKeyboardInteractive implements a ClientKeyboardInteractive by
  439. // asking the client on the other side of a ServerConn.
  440. type sshClientKeyboardInteractive struct {
  441. *connection
  442. }
  443. func (c *sshClientKeyboardInteractive) Challenge(user, instruction string, questions []string, echos []bool) (answers []string, err error) {
  444. if len(questions) != len(echos) {
  445. return nil, errors.New("ssh: echos and questions must have equal length")
  446. }
  447. var prompts []byte
  448. for i := range questions {
  449. prompts = appendString(prompts, questions[i])
  450. prompts = appendBool(prompts, echos[i])
  451. }
  452. if err := c.transport.writePacket(Marshal(&userAuthInfoRequestMsg{
  453. Instruction: instruction,
  454. NumPrompts: uint32(len(questions)),
  455. Prompts: prompts,
  456. })); err != nil {
  457. return nil, err
  458. }
  459. packet, err := c.transport.readPacket()
  460. if err != nil {
  461. return nil, err
  462. }
  463. if packet[0] != msgUserAuthInfoResponse {
  464. return nil, unexpectedMessageError(msgUserAuthInfoResponse, packet[0])
  465. }
  466. packet = packet[1:]
  467. n, packet, ok := parseUint32(packet)
  468. if !ok || int(n) != len(questions) {
  469. return nil, parseError(msgUserAuthInfoResponse)
  470. }
  471. for i := uint32(0); i < n; i++ {
  472. ans, rest, ok := parseString(packet)
  473. if !ok {
  474. return nil, parseError(msgUserAuthInfoResponse)
  475. }
  476. answers = append(answers, string(ans))
  477. packet = rest
  478. }
  479. if len(packet) != 0 {
  480. return nil, errors.New("ssh: junk at end of message")
  481. }
  482. return answers, nil
  483. }