server.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  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. type GSSAPIWithMICConfig struct {
  44. // AllowLogin, must be set, is called when gssapi-with-mic
  45. // authentication is selected (RFC 4462 section 3). The srcName is from the
  46. // results of the GSS-API authentication. The format is username@DOMAIN.
  47. // GSSAPI just guarantees to the server who the user is, but not if they can log in, and with what permissions.
  48. // This callback is called after the user identity is established with GSSAPI to decide if the user can login with
  49. // which permissions. If the user is allowed to login, it should return a nil error.
  50. AllowLogin func(conn ConnMetadata, srcName string) (*Permissions, error)
  51. // Server must be set. It's the implementation
  52. // of the GSSAPIServer interface. See GSSAPIServer interface for details.
  53. Server GSSAPIServer
  54. }
  55. // ServerConfig holds server specific configuration data.
  56. type ServerConfig struct {
  57. // Config contains configuration shared between client and server.
  58. Config
  59. // PublicKeyAuthAlgorithms specifies the supported client public key
  60. // authentication algorithms. Note that this should not include certificate
  61. // types since those use the underlying algorithm. This list is sent to the
  62. // client if it supports the server-sig-algs extension. Order is irrelevant.
  63. // If unspecified then a default set of algorithms is used.
  64. PublicKeyAuthAlgorithms []string
  65. hostKeys []Signer
  66. // NoClientAuth is true if clients are allowed to connect without
  67. // authenticating.
  68. // To determine NoClientAuth at runtime, set NoClientAuth to true
  69. // and the optional NoClientAuthCallback to a non-nil value.
  70. NoClientAuth bool
  71. // NoClientAuthCallback, if non-nil, is called when a user
  72. // attempts to authenticate with auth method "none".
  73. // NoClientAuth must also be set to true for this be used, or
  74. // this func is unused.
  75. NoClientAuthCallback func(ConnMetadata) (*Permissions, error)
  76. // MaxAuthTries specifies the maximum number of authentication attempts
  77. // permitted per connection. If set to a negative number, the number of
  78. // attempts are unlimited. If set to zero, the number of attempts are limited
  79. // to 6.
  80. MaxAuthTries int
  81. // PasswordCallback, if non-nil, is called when a user
  82. // attempts to authenticate using a password.
  83. PasswordCallback func(conn ConnMetadata, password []byte) (*Permissions, error)
  84. // PublicKeyCallback, if non-nil, is called when a client
  85. // offers a public key for authentication. It must return a nil error
  86. // if the given public key can be used to authenticate the
  87. // given user. For example, see CertChecker.Authenticate. A
  88. // call to this function does not guarantee that the key
  89. // offered is in fact used to authenticate. To record any data
  90. // depending on the public key, store it inside a
  91. // Permissions.Extensions entry.
  92. PublicKeyCallback func(conn ConnMetadata, key PublicKey) (*Permissions, error)
  93. // KeyboardInteractiveCallback, if non-nil, is called when
  94. // keyboard-interactive authentication is selected (RFC
  95. // 4256). The client object's Challenge function should be
  96. // used to query the user. The callback may offer multiple
  97. // Challenge rounds. To avoid information leaks, the client
  98. // should be presented a challenge even if the user is
  99. // unknown.
  100. KeyboardInteractiveCallback func(conn ConnMetadata, client KeyboardInteractiveChallenge) (*Permissions, error)
  101. // AuthLogCallback, if non-nil, is called to log all authentication
  102. // attempts.
  103. AuthLogCallback func(conn ConnMetadata, method string, err error)
  104. // ServerVersion is the version identification string to announce in
  105. // the public handshake.
  106. // If empty, a reasonable default is used.
  107. // Note that RFC 4253 section 4.2 requires that this string start with
  108. // "SSH-2.0-".
  109. ServerVersion string
  110. // BannerCallback, if present, is called and the return string is sent to
  111. // the client after key exchange completed but before authentication.
  112. BannerCallback func(conn ConnMetadata) string
  113. // GSSAPIWithMICConfig includes gssapi server and callback, which if both non-nil, is used
  114. // when gssapi-with-mic authentication is selected (RFC 4462 section 3).
  115. GSSAPIWithMICConfig *GSSAPIWithMICConfig
  116. }
  117. // AddHostKey adds a private key as a host key. If an existing host
  118. // key exists with the same public key format, it is replaced. Each server
  119. // config must have at least one host key.
  120. func (s *ServerConfig) AddHostKey(key Signer) {
  121. for i, k := range s.hostKeys {
  122. if k.PublicKey().Type() == key.PublicKey().Type() {
  123. s.hostKeys[i] = key
  124. return
  125. }
  126. }
  127. s.hostKeys = append(s.hostKeys, key)
  128. }
  129. // cachedPubKey contains the results of querying whether a public key is
  130. // acceptable for a user.
  131. type cachedPubKey struct {
  132. user string
  133. pubKeyData []byte
  134. result error
  135. perms *Permissions
  136. }
  137. const maxCachedPubKeys = 16
  138. // pubKeyCache caches tests for public keys. Since SSH clients
  139. // will query whether a public key is acceptable before attempting to
  140. // authenticate with it, we end up with duplicate queries for public
  141. // key validity. The cache only applies to a single ServerConn.
  142. type pubKeyCache struct {
  143. keys []cachedPubKey
  144. }
  145. // get returns the result for a given user/algo/key tuple.
  146. func (c *pubKeyCache) get(user string, pubKeyData []byte) (cachedPubKey, bool) {
  147. for _, k := range c.keys {
  148. if k.user == user && bytes.Equal(k.pubKeyData, pubKeyData) {
  149. return k, true
  150. }
  151. }
  152. return cachedPubKey{}, false
  153. }
  154. // add adds the given tuple to the cache.
  155. func (c *pubKeyCache) add(candidate cachedPubKey) {
  156. if len(c.keys) < maxCachedPubKeys {
  157. c.keys = append(c.keys, candidate)
  158. }
  159. }
  160. // ServerConn is an authenticated SSH connection, as seen from the
  161. // server
  162. type ServerConn struct {
  163. Conn
  164. // If the succeeding authentication callback returned a
  165. // non-nil Permissions pointer, it is stored here.
  166. Permissions *Permissions
  167. }
  168. // NewServerConn starts a new SSH server with c as the underlying
  169. // transport. It starts with a handshake and, if the handshake is
  170. // unsuccessful, it closes the connection and returns an error. The
  171. // Request and NewChannel channels must be serviced, or the connection
  172. // will hang.
  173. //
  174. // The returned error may be of type *ServerAuthError for
  175. // authentication errors.
  176. func NewServerConn(c net.Conn, config *ServerConfig) (*ServerConn, <-chan NewChannel, <-chan *Request, error) {
  177. fullConf := *config
  178. fullConf.SetDefaults()
  179. if fullConf.MaxAuthTries == 0 {
  180. fullConf.MaxAuthTries = 6
  181. }
  182. if len(fullConf.PublicKeyAuthAlgorithms) == 0 {
  183. fullConf.PublicKeyAuthAlgorithms = supportedPubKeyAuthAlgos
  184. } else {
  185. for _, algo := range fullConf.PublicKeyAuthAlgorithms {
  186. if !contains(supportedPubKeyAuthAlgos, algo) {
  187. c.Close()
  188. return nil, nil, nil, fmt.Errorf("ssh: unsupported public key authentication algorithm %s", algo)
  189. }
  190. }
  191. }
  192. // Check if the config contains any unsupported key exchanges
  193. for _, kex := range fullConf.KeyExchanges {
  194. if _, ok := serverForbiddenKexAlgos[kex]; ok {
  195. c.Close()
  196. return nil, nil, nil, fmt.Errorf("ssh: unsupported key exchange %s for server", kex)
  197. }
  198. }
  199. s := &connection{
  200. sshConn: sshConn{conn: c},
  201. }
  202. perms, err := s.serverHandshake(&fullConf)
  203. if err != nil {
  204. c.Close()
  205. return nil, nil, nil, err
  206. }
  207. return &ServerConn{s, perms}, s.mux.incomingChannels, s.mux.incomingRequests, nil
  208. }
  209. // signAndMarshal signs the data with the appropriate algorithm,
  210. // and serializes the result in SSH wire format. algo is the negotiate
  211. // algorithm and may be a certificate type.
  212. func signAndMarshal(k AlgorithmSigner, rand io.Reader, data []byte, algo string) ([]byte, error) {
  213. sig, err := k.SignWithAlgorithm(rand, data, underlyingAlgo(algo))
  214. if err != nil {
  215. return nil, err
  216. }
  217. return Marshal(sig), nil
  218. }
  219. // handshake performs key exchange and user authentication.
  220. func (s *connection) serverHandshake(config *ServerConfig) (*Permissions, error) {
  221. if len(config.hostKeys) == 0 {
  222. return nil, errors.New("ssh: server has no host keys")
  223. }
  224. if !config.NoClientAuth && config.PasswordCallback == nil && config.PublicKeyCallback == nil &&
  225. config.KeyboardInteractiveCallback == nil && (config.GSSAPIWithMICConfig == nil ||
  226. config.GSSAPIWithMICConfig.AllowLogin == nil || config.GSSAPIWithMICConfig.Server == nil) {
  227. return nil, errors.New("ssh: no authentication methods configured but NoClientAuth is also false")
  228. }
  229. if config.ServerVersion != "" {
  230. s.serverVersion = []byte(config.ServerVersion)
  231. } else {
  232. s.serverVersion = []byte(packageVersion)
  233. }
  234. var err error
  235. s.clientVersion, err = exchangeVersions(s.sshConn.conn, s.serverVersion)
  236. if err != nil {
  237. return nil, err
  238. }
  239. tr := newTransport(s.sshConn.conn, config.Rand, false /* not client */)
  240. s.transport = newServerTransport(tr, s.clientVersion, s.serverVersion, config)
  241. if err := s.transport.waitSession(); err != nil {
  242. return nil, err
  243. }
  244. // We just did the key change, so the session ID is established.
  245. s.sessionID = s.transport.getSessionID()
  246. var packet []byte
  247. if packet, err = s.transport.readPacket(); err != nil {
  248. return nil, err
  249. }
  250. var serviceRequest serviceRequestMsg
  251. if err = Unmarshal(packet, &serviceRequest); err != nil {
  252. return nil, err
  253. }
  254. if serviceRequest.Service != serviceUserAuth {
  255. return nil, errors.New("ssh: requested service '" + serviceRequest.Service + "' before authenticating")
  256. }
  257. serviceAccept := serviceAcceptMsg{
  258. Service: serviceUserAuth,
  259. }
  260. if err := s.transport.writePacket(Marshal(&serviceAccept)); err != nil {
  261. return nil, err
  262. }
  263. perms, err := s.serverAuthenticate(config)
  264. if err != nil {
  265. return nil, err
  266. }
  267. s.mux = newMux(s.transport)
  268. return perms, err
  269. }
  270. func checkSourceAddress(addr net.Addr, sourceAddrs string) error {
  271. if addr == nil {
  272. return errors.New("ssh: no address known for client, but source-address match required")
  273. }
  274. tcpAddr, ok := addr.(*net.TCPAddr)
  275. if !ok {
  276. return fmt.Errorf("ssh: remote address %v is not an TCP address when checking source-address match", addr)
  277. }
  278. for _, sourceAddr := range strings.Split(sourceAddrs, ",") {
  279. if allowedIP := net.ParseIP(sourceAddr); allowedIP != nil {
  280. if allowedIP.Equal(tcpAddr.IP) {
  281. return nil
  282. }
  283. } else {
  284. _, ipNet, err := net.ParseCIDR(sourceAddr)
  285. if err != nil {
  286. return fmt.Errorf("ssh: error parsing source-address restriction %q: %v", sourceAddr, err)
  287. }
  288. if ipNet.Contains(tcpAddr.IP) {
  289. return nil
  290. }
  291. }
  292. }
  293. return fmt.Errorf("ssh: remote address %v is not allowed because of source-address restriction", addr)
  294. }
  295. func gssExchangeToken(gssapiConfig *GSSAPIWithMICConfig, token []byte, s *connection,
  296. sessionID []byte, userAuthReq userAuthRequestMsg) (authErr error, perms *Permissions, err error) {
  297. gssAPIServer := gssapiConfig.Server
  298. defer gssAPIServer.DeleteSecContext()
  299. var srcName string
  300. for {
  301. var (
  302. outToken []byte
  303. needContinue bool
  304. )
  305. outToken, srcName, needContinue, err = gssAPIServer.AcceptSecContext(token)
  306. if err != nil {
  307. return err, nil, nil
  308. }
  309. if len(outToken) != 0 {
  310. if err := s.transport.writePacket(Marshal(&userAuthGSSAPIToken{
  311. Token: outToken,
  312. })); err != nil {
  313. return nil, nil, err
  314. }
  315. }
  316. if !needContinue {
  317. break
  318. }
  319. packet, err := s.transport.readPacket()
  320. if err != nil {
  321. return nil, nil, err
  322. }
  323. userAuthGSSAPITokenReq := &userAuthGSSAPIToken{}
  324. if err := Unmarshal(packet, userAuthGSSAPITokenReq); err != nil {
  325. return nil, nil, err
  326. }
  327. token = userAuthGSSAPITokenReq.Token
  328. }
  329. packet, err := s.transport.readPacket()
  330. if err != nil {
  331. return nil, nil, err
  332. }
  333. userAuthGSSAPIMICReq := &userAuthGSSAPIMIC{}
  334. if err := Unmarshal(packet, userAuthGSSAPIMICReq); err != nil {
  335. return nil, nil, err
  336. }
  337. mic := buildMIC(string(sessionID), userAuthReq.User, userAuthReq.Service, userAuthReq.Method)
  338. if err := gssAPIServer.VerifyMIC(mic, userAuthGSSAPIMICReq.MIC); err != nil {
  339. return err, nil, nil
  340. }
  341. perms, authErr = gssapiConfig.AllowLogin(s, srcName)
  342. return authErr, perms, nil
  343. }
  344. // isAlgoCompatible checks if the signature format is compatible with the
  345. // selected algorithm taking into account edge cases that occur with old
  346. // clients.
  347. func isAlgoCompatible(algo, sigFormat string) bool {
  348. // Compatibility for old clients.
  349. //
  350. // For certificate authentication with OpenSSH 7.2-7.7 signature format can
  351. // be rsa-sha2-256 or rsa-sha2-512 for the algorithm
  352. // ssh-rsa-cert-v01@openssh.com.
  353. //
  354. // With gpg-agent < 2.2.6 the algorithm can be rsa-sha2-256 or rsa-sha2-512
  355. // for signature format ssh-rsa.
  356. if isRSA(algo) && isRSA(sigFormat) {
  357. return true
  358. }
  359. // Standard case: the underlying algorithm must match the signature format.
  360. return underlyingAlgo(algo) == sigFormat
  361. }
  362. // ServerAuthError represents server authentication errors and is
  363. // sometimes returned by NewServerConn. It appends any authentication
  364. // errors that may occur, and is returned if all of the authentication
  365. // methods provided by the user failed to authenticate.
  366. type ServerAuthError struct {
  367. // Errors contains authentication errors returned by the authentication
  368. // callback methods. The first entry is typically ErrNoAuth.
  369. Errors []error
  370. }
  371. func (l ServerAuthError) Error() string {
  372. var errs []string
  373. for _, err := range l.Errors {
  374. errs = append(errs, err.Error())
  375. }
  376. return "[" + strings.Join(errs, ", ") + "]"
  377. }
  378. // ErrNoAuth is the error value returned if no
  379. // authentication method has been passed yet. This happens as a normal
  380. // part of the authentication loop, since the client first tries
  381. // 'none' authentication to discover available methods.
  382. // It is returned in ServerAuthError.Errors from NewServerConn.
  383. var ErrNoAuth = errors.New("ssh: no auth passed yet")
  384. func (s *connection) serverAuthenticate(config *ServerConfig) (*Permissions, error) {
  385. sessionID := s.transport.getSessionID()
  386. var cache pubKeyCache
  387. var perms *Permissions
  388. authFailures := 0
  389. var authErrs []error
  390. var displayedBanner bool
  391. userAuthLoop:
  392. for {
  393. if authFailures >= config.MaxAuthTries && config.MaxAuthTries > 0 {
  394. discMsg := &disconnectMsg{
  395. Reason: 2,
  396. Message: "too many authentication failures",
  397. }
  398. if err := s.transport.writePacket(Marshal(discMsg)); err != nil {
  399. return nil, err
  400. }
  401. return nil, discMsg
  402. }
  403. var userAuthReq userAuthRequestMsg
  404. if packet, err := s.transport.readPacket(); err != nil {
  405. if err == io.EOF {
  406. return nil, &ServerAuthError{Errors: authErrs}
  407. }
  408. return nil, err
  409. } else if err = Unmarshal(packet, &userAuthReq); err != nil {
  410. return nil, err
  411. }
  412. if userAuthReq.Service != serviceSSH {
  413. return nil, errors.New("ssh: client attempted to negotiate for unknown service: " + userAuthReq.Service)
  414. }
  415. s.user = userAuthReq.User
  416. if !displayedBanner && config.BannerCallback != nil {
  417. displayedBanner = true
  418. msg := config.BannerCallback(s)
  419. if msg != "" {
  420. bannerMsg := &userAuthBannerMsg{
  421. Message: msg,
  422. }
  423. if err := s.transport.writePacket(Marshal(bannerMsg)); err != nil {
  424. return nil, err
  425. }
  426. }
  427. }
  428. perms = nil
  429. authErr := ErrNoAuth
  430. switch userAuthReq.Method {
  431. case "none":
  432. if config.NoClientAuth {
  433. if config.NoClientAuthCallback != nil {
  434. perms, authErr = config.NoClientAuthCallback(s)
  435. } else {
  436. authErr = nil
  437. }
  438. }
  439. // allow initial attempt of 'none' without penalty
  440. if authFailures == 0 {
  441. authFailures--
  442. }
  443. case "password":
  444. if config.PasswordCallback == nil {
  445. authErr = errors.New("ssh: password auth not configured")
  446. break
  447. }
  448. payload := userAuthReq.Payload
  449. if len(payload) < 1 || payload[0] != 0 {
  450. return nil, parseError(msgUserAuthRequest)
  451. }
  452. payload = payload[1:]
  453. password, payload, ok := parseString(payload)
  454. if !ok || len(payload) > 0 {
  455. return nil, parseError(msgUserAuthRequest)
  456. }
  457. perms, authErr = config.PasswordCallback(s, password)
  458. case "keyboard-interactive":
  459. if config.KeyboardInteractiveCallback == nil {
  460. authErr = errors.New("ssh: keyboard-interactive auth not configured")
  461. break
  462. }
  463. prompter := &sshClientKeyboardInteractive{s}
  464. perms, authErr = config.KeyboardInteractiveCallback(s, prompter.Challenge)
  465. case "publickey":
  466. if config.PublicKeyCallback == nil {
  467. authErr = errors.New("ssh: publickey auth not configured")
  468. break
  469. }
  470. payload := userAuthReq.Payload
  471. if len(payload) < 1 {
  472. return nil, parseError(msgUserAuthRequest)
  473. }
  474. isQuery := payload[0] == 0
  475. payload = payload[1:]
  476. algoBytes, payload, ok := parseString(payload)
  477. if !ok {
  478. return nil, parseError(msgUserAuthRequest)
  479. }
  480. algo := string(algoBytes)
  481. if !contains(config.PublicKeyAuthAlgorithms, underlyingAlgo(algo)) {
  482. authErr = fmt.Errorf("ssh: algorithm %q not accepted", algo)
  483. break
  484. }
  485. pubKeyData, payload, ok := parseString(payload)
  486. if !ok {
  487. return nil, parseError(msgUserAuthRequest)
  488. }
  489. pubKey, err := ParsePublicKey(pubKeyData)
  490. if err != nil {
  491. return nil, err
  492. }
  493. candidate, ok := cache.get(s.user, pubKeyData)
  494. if !ok {
  495. candidate.user = s.user
  496. candidate.pubKeyData = pubKeyData
  497. candidate.perms, candidate.result = config.PublicKeyCallback(s, pubKey)
  498. if candidate.result == nil && candidate.perms != nil && candidate.perms.CriticalOptions != nil && candidate.perms.CriticalOptions[sourceAddressCriticalOption] != "" {
  499. candidate.result = checkSourceAddress(
  500. s.RemoteAddr(),
  501. candidate.perms.CriticalOptions[sourceAddressCriticalOption])
  502. }
  503. cache.add(candidate)
  504. }
  505. if isQuery {
  506. // The client can query if the given public key
  507. // would be okay.
  508. if len(payload) > 0 {
  509. return nil, parseError(msgUserAuthRequest)
  510. }
  511. if candidate.result == nil {
  512. okMsg := userAuthPubKeyOkMsg{
  513. Algo: algo,
  514. PubKey: pubKeyData,
  515. }
  516. if err = s.transport.writePacket(Marshal(&okMsg)); err != nil {
  517. return nil, err
  518. }
  519. continue userAuthLoop
  520. }
  521. authErr = candidate.result
  522. } else {
  523. sig, payload, ok := parseSignature(payload)
  524. if !ok || len(payload) > 0 {
  525. return nil, parseError(msgUserAuthRequest)
  526. }
  527. // Ensure the declared public key algo is compatible with the
  528. // decoded one. This check will ensure we don't accept e.g.
  529. // ssh-rsa-cert-v01@openssh.com algorithm with ssh-rsa public
  530. // key type. The algorithm and public key type must be
  531. // consistent: both must be certificate algorithms, or neither.
  532. if !contains(algorithmsForKeyFormat(pubKey.Type()), algo) {
  533. authErr = fmt.Errorf("ssh: public key type %q not compatible with selected algorithm %q",
  534. pubKey.Type(), algo)
  535. break
  536. }
  537. // Ensure the public key algo and signature algo
  538. // are supported. Compare the private key
  539. // algorithm name that corresponds to algo with
  540. // sig.Format. This is usually the same, but
  541. // for certs, the names differ.
  542. if !contains(config.PublicKeyAuthAlgorithms, sig.Format) {
  543. authErr = fmt.Errorf("ssh: algorithm %q not accepted", sig.Format)
  544. break
  545. }
  546. if !isAlgoCompatible(algo, sig.Format) {
  547. authErr = fmt.Errorf("ssh: signature %q not compatible with selected algorithm %q", sig.Format, algo)
  548. break
  549. }
  550. signedData := buildDataSignedForAuth(sessionID, userAuthReq, algo, pubKeyData)
  551. if err := pubKey.Verify(signedData, sig); err != nil {
  552. return nil, err
  553. }
  554. authErr = candidate.result
  555. perms = candidate.perms
  556. }
  557. case "gssapi-with-mic":
  558. if config.GSSAPIWithMICConfig == nil {
  559. authErr = errors.New("ssh: gssapi-with-mic auth not configured")
  560. break
  561. }
  562. gssapiConfig := config.GSSAPIWithMICConfig
  563. userAuthRequestGSSAPI, err := parseGSSAPIPayload(userAuthReq.Payload)
  564. if err != nil {
  565. return nil, parseError(msgUserAuthRequest)
  566. }
  567. // OpenSSH supports Kerberos V5 mechanism only for GSS-API authentication.
  568. if userAuthRequestGSSAPI.N == 0 {
  569. authErr = fmt.Errorf("ssh: Mechanism negotiation is not supported")
  570. break
  571. }
  572. var i uint32
  573. present := false
  574. for i = 0; i < userAuthRequestGSSAPI.N; i++ {
  575. if userAuthRequestGSSAPI.OIDS[i].Equal(krb5Mesh) {
  576. present = true
  577. break
  578. }
  579. }
  580. if !present {
  581. authErr = fmt.Errorf("ssh: GSSAPI authentication must use the Kerberos V5 mechanism")
  582. break
  583. }
  584. // Initial server response, see RFC 4462 section 3.3.
  585. if err := s.transport.writePacket(Marshal(&userAuthGSSAPIResponse{
  586. SupportMech: krb5OID,
  587. })); err != nil {
  588. return nil, err
  589. }
  590. // Exchange token, see RFC 4462 section 3.4.
  591. packet, err := s.transport.readPacket()
  592. if err != nil {
  593. return nil, err
  594. }
  595. userAuthGSSAPITokenReq := &userAuthGSSAPIToken{}
  596. if err := Unmarshal(packet, userAuthGSSAPITokenReq); err != nil {
  597. return nil, err
  598. }
  599. authErr, perms, err = gssExchangeToken(gssapiConfig, userAuthGSSAPITokenReq.Token, s, sessionID,
  600. userAuthReq)
  601. if err != nil {
  602. return nil, err
  603. }
  604. default:
  605. authErr = fmt.Errorf("ssh: unknown method %q", userAuthReq.Method)
  606. }
  607. authErrs = append(authErrs, authErr)
  608. if config.AuthLogCallback != nil {
  609. config.AuthLogCallback(s, userAuthReq.Method, authErr)
  610. }
  611. if authErr == nil {
  612. break userAuthLoop
  613. }
  614. authFailures++
  615. if config.MaxAuthTries > 0 && authFailures >= config.MaxAuthTries {
  616. // If we have hit the max attempts, don't bother sending the
  617. // final SSH_MSG_USERAUTH_FAILURE message, since there are
  618. // no more authentication methods which can be attempted,
  619. // and this message may cause the client to re-attempt
  620. // authentication while we send the disconnect message.
  621. // Continue, and trigger the disconnect at the start of
  622. // the loop.
  623. //
  624. // The SSH specification is somewhat confusing about this,
  625. // RFC 4252 Section 5.1 requires each authentication failure
  626. // be responded to with a respective SSH_MSG_USERAUTH_FAILURE
  627. // message, but Section 4 says the server should disconnect
  628. // after some number of attempts, but it isn't explicit which
  629. // message should take precedence (i.e. should there be a failure
  630. // message than a disconnect message, or if we are going to
  631. // disconnect, should we only send that message.)
  632. //
  633. // Either way, OpenSSH disconnects immediately after the last
  634. // failed authnetication attempt, and given they are typically
  635. // considered the golden implementation it seems reasonable
  636. // to match that behavior.
  637. continue
  638. }
  639. var failureMsg userAuthFailureMsg
  640. if config.PasswordCallback != nil {
  641. failureMsg.Methods = append(failureMsg.Methods, "password")
  642. }
  643. if config.PublicKeyCallback != nil {
  644. failureMsg.Methods = append(failureMsg.Methods, "publickey")
  645. }
  646. if config.KeyboardInteractiveCallback != nil {
  647. failureMsg.Methods = append(failureMsg.Methods, "keyboard-interactive")
  648. }
  649. if config.GSSAPIWithMICConfig != nil && config.GSSAPIWithMICConfig.Server != nil &&
  650. config.GSSAPIWithMICConfig.AllowLogin != nil {
  651. failureMsg.Methods = append(failureMsg.Methods, "gssapi-with-mic")
  652. }
  653. if len(failureMsg.Methods) == 0 {
  654. return nil, errors.New("ssh: no authentication methods configured but NoClientAuth is also false")
  655. }
  656. if err := s.transport.writePacket(Marshal(&failureMsg)); err != nil {
  657. return nil, err
  658. }
  659. }
  660. if err := s.transport.writePacket([]byte{msgUserAuthSuccess}); err != nil {
  661. return nil, err
  662. }
  663. return perms, nil
  664. }
  665. // sshClientKeyboardInteractive implements a ClientKeyboardInteractive by
  666. // asking the client on the other side of a ServerConn.
  667. type sshClientKeyboardInteractive struct {
  668. *connection
  669. }
  670. func (c *sshClientKeyboardInteractive) Challenge(name, instruction string, questions []string, echos []bool) (answers []string, err error) {
  671. if len(questions) != len(echos) {
  672. return nil, errors.New("ssh: echos and questions must have equal length")
  673. }
  674. var prompts []byte
  675. for i := range questions {
  676. prompts = appendString(prompts, questions[i])
  677. prompts = appendBool(prompts, echos[i])
  678. }
  679. if err := c.transport.writePacket(Marshal(&userAuthInfoRequestMsg{
  680. Name: name,
  681. Instruction: instruction,
  682. NumPrompts: uint32(len(questions)),
  683. Prompts: prompts,
  684. })); err != nil {
  685. return nil, err
  686. }
  687. packet, err := c.transport.readPacket()
  688. if err != nil {
  689. return nil, err
  690. }
  691. if packet[0] != msgUserAuthInfoResponse {
  692. return nil, unexpectedMessageError(msgUserAuthInfoResponse, packet[0])
  693. }
  694. packet = packet[1:]
  695. n, packet, ok := parseUint32(packet)
  696. if !ok || int(n) != len(questions) {
  697. return nil, parseError(msgUserAuthInfoResponse)
  698. }
  699. for i := uint32(0); i < n; i++ {
  700. ans, rest, ok := parseString(packet)
  701. if !ok {
  702. return nil, parseError(msgUserAuthInfoResponse)
  703. }
  704. answers = append(answers, string(ans))
  705. packet = rest
  706. }
  707. if len(packet) != 0 {
  708. return nil, errors.New("ssh: junk at end of message")
  709. }
  710. return answers, nil
  711. }