server.go 24 KB

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