You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

server.go 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  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 algorithm, it is overwritten. 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.
  187. func signAndMarshal(k Signer, rand io.Reader, data []byte) ([]byte, error) {
  188. sig, err := k.Sign(rand, data)
  189. if err != nil {
  190. return nil, err
  191. }
  192. return Marshal(sig), nil
  193. }
  194. // handshake performs key exchange and user authentication.
  195. func (s *connection) serverHandshake(config *ServerConfig) (*Permissions, error) {
  196. if len(config.hostKeys) == 0 {
  197. return nil, errors.New("ssh: server has no host keys")
  198. }
  199. if !config.NoClientAuth && config.PasswordCallback == nil && config.PublicKeyCallback == nil &&
  200. config.KeyboardInteractiveCallback == nil && (config.GSSAPIWithMICConfig == nil ||
  201. config.GSSAPIWithMICConfig.AllowLogin == nil || config.GSSAPIWithMICConfig.Server == nil) {
  202. return nil, errors.New("ssh: no authentication methods configured but NoClientAuth is also false")
  203. }
  204. if config.ServerVersion != "" {
  205. s.serverVersion = []byte(config.ServerVersion)
  206. } else {
  207. s.serverVersion = []byte(packageVersion)
  208. }
  209. var err error
  210. s.clientVersion, err = exchangeVersions(s.sshConn.conn, s.serverVersion)
  211. if err != nil {
  212. return nil, err
  213. }
  214. tr := newTransport(s.sshConn.conn, config.Rand, false /* not client */)
  215. s.transport = newServerTransport(tr, s.clientVersion, s.serverVersion, config)
  216. if err := s.transport.waitSession(); err != nil {
  217. return nil, err
  218. }
  219. // We just did the key change, so the session ID is established.
  220. s.sessionID = s.transport.getSessionID()
  221. var packet []byte
  222. if packet, err = s.transport.readPacket(); err != nil {
  223. return nil, err
  224. }
  225. var serviceRequest serviceRequestMsg
  226. if err = Unmarshal(packet, &serviceRequest); err != nil {
  227. return nil, err
  228. }
  229. if serviceRequest.Service != serviceUserAuth {
  230. return nil, errors.New("ssh: requested service '" + serviceRequest.Service + "' before authenticating")
  231. }
  232. serviceAccept := serviceAcceptMsg{
  233. Service: serviceUserAuth,
  234. }
  235. if err := s.transport.writePacket(Marshal(&serviceAccept)); err != nil {
  236. return nil, err
  237. }
  238. perms, err := s.serverAuthenticate(config)
  239. if err != nil {
  240. return nil, err
  241. }
  242. s.mux = newMux(s.transport)
  243. return perms, err
  244. }
  245. func isAcceptableAlgo(algo string) bool {
  246. switch algo {
  247. case KeyAlgoRSA, KeyAlgoDSA, KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521, KeyAlgoED25519,
  248. CertAlgoRSAv01, CertAlgoDSAv01, CertAlgoECDSA256v01, CertAlgoECDSA384v01, CertAlgoECDSA521v01, CertAlgoED25519v01:
  249. return true
  250. }
  251. return false
  252. }
  253. func checkSourceAddress(addr net.Addr, sourceAddrs string) error {
  254. if addr == nil {
  255. return errors.New("ssh: no address known for client, but source-address match required")
  256. }
  257. tcpAddr, ok := addr.(*net.TCPAddr)
  258. if !ok {
  259. return fmt.Errorf("ssh: remote address %v is not an TCP address when checking source-address match", addr)
  260. }
  261. for _, sourceAddr := range strings.Split(sourceAddrs, ",") {
  262. if allowedIP := net.ParseIP(sourceAddr); allowedIP != nil {
  263. if allowedIP.Equal(tcpAddr.IP) {
  264. return nil
  265. }
  266. } else {
  267. _, ipNet, err := net.ParseCIDR(sourceAddr)
  268. if err != nil {
  269. return fmt.Errorf("ssh: error parsing source-address restriction %q: %v", sourceAddr, err)
  270. }
  271. if ipNet.Contains(tcpAddr.IP) {
  272. return nil
  273. }
  274. }
  275. }
  276. return fmt.Errorf("ssh: remote address %v is not allowed because of source-address restriction", addr)
  277. }
  278. func gssExchangeToken(gssapiConfig *GSSAPIWithMICConfig, firstToken []byte, s *connection,
  279. sessionID []byte, userAuthReq userAuthRequestMsg) (authErr error, perms *Permissions, err error) {
  280. gssAPIServer := gssapiConfig.Server
  281. defer gssAPIServer.DeleteSecContext()
  282. var srcName string
  283. for {
  284. var (
  285. outToken []byte
  286. needContinue bool
  287. )
  288. outToken, srcName, needContinue, err = gssAPIServer.AcceptSecContext(firstToken)
  289. if err != nil {
  290. return err, nil, nil
  291. }
  292. if len(outToken) != 0 {
  293. if err := s.transport.writePacket(Marshal(&userAuthGSSAPIToken{
  294. Token: outToken,
  295. })); err != nil {
  296. return nil, nil, err
  297. }
  298. }
  299. if !needContinue {
  300. break
  301. }
  302. packet, err := s.transport.readPacket()
  303. if err != nil {
  304. return nil, nil, err
  305. }
  306. userAuthGSSAPITokenReq := &userAuthGSSAPIToken{}
  307. if err := Unmarshal(packet, userAuthGSSAPITokenReq); err != nil {
  308. return nil, nil, err
  309. }
  310. }
  311. packet, err := s.transport.readPacket()
  312. if err != nil {
  313. return nil, nil, err
  314. }
  315. userAuthGSSAPIMICReq := &userAuthGSSAPIMIC{}
  316. if err := Unmarshal(packet, userAuthGSSAPIMICReq); err != nil {
  317. return nil, nil, err
  318. }
  319. mic := buildMIC(string(sessionID), userAuthReq.User, userAuthReq.Service, userAuthReq.Method)
  320. if err := gssAPIServer.VerifyMIC(mic, userAuthGSSAPIMICReq.MIC); err != nil {
  321. return err, nil, nil
  322. }
  323. perms, authErr = gssapiConfig.AllowLogin(s, srcName)
  324. return authErr, perms, nil
  325. }
  326. // ServerAuthError represents server authentication errors and is
  327. // sometimes returned by NewServerConn. It appends any authentication
  328. // errors that may occur, and is returned if all of the authentication
  329. // methods provided by the user failed to authenticate.
  330. type ServerAuthError struct {
  331. // Errors contains authentication errors returned by the authentication
  332. // callback methods. The first entry is typically ErrNoAuth.
  333. Errors []error
  334. }
  335. func (l ServerAuthError) Error() string {
  336. var errs []string
  337. for _, err := range l.Errors {
  338. errs = append(errs, err.Error())
  339. }
  340. return "[" + strings.Join(errs, ", ") + "]"
  341. }
  342. // ErrNoAuth is the error value returned if no
  343. // authentication method has been passed yet. This happens as a normal
  344. // part of the authentication loop, since the client first tries
  345. // 'none' authentication to discover available methods.
  346. // It is returned in ServerAuthError.Errors from NewServerConn.
  347. var ErrNoAuth = errors.New("ssh: no auth passed yet")
  348. func (s *connection) serverAuthenticate(config *ServerConfig) (*Permissions, error) {
  349. sessionID := s.transport.getSessionID()
  350. var cache pubKeyCache
  351. var perms *Permissions
  352. authFailures := 0
  353. var authErrs []error
  354. var displayedBanner bool
  355. userAuthLoop:
  356. for {
  357. if authFailures >= config.MaxAuthTries && config.MaxAuthTries > 0 {
  358. discMsg := &disconnectMsg{
  359. Reason: 2,
  360. Message: "too many authentication failures",
  361. }
  362. if err := s.transport.writePacket(Marshal(discMsg)); err != nil {
  363. return nil, err
  364. }
  365. return nil, discMsg
  366. }
  367. var userAuthReq userAuthRequestMsg
  368. if packet, err := s.transport.readPacket(); err != nil {
  369. if err == io.EOF {
  370. return nil, &ServerAuthError{Errors: authErrs}
  371. }
  372. return nil, err
  373. } else if err = Unmarshal(packet, &userAuthReq); err != nil {
  374. return nil, err
  375. }
  376. if userAuthReq.Service != serviceSSH {
  377. return nil, errors.New("ssh: client attempted to negotiate for unknown service: " + userAuthReq.Service)
  378. }
  379. s.user = userAuthReq.User
  380. if !displayedBanner && config.BannerCallback != nil {
  381. displayedBanner = true
  382. msg := config.BannerCallback(s)
  383. if msg != "" {
  384. bannerMsg := &userAuthBannerMsg{
  385. Message: msg,
  386. }
  387. if err := s.transport.writePacket(Marshal(bannerMsg)); err != nil {
  388. return nil, err
  389. }
  390. }
  391. }
  392. perms = nil
  393. authErr := ErrNoAuth
  394. switch userAuthReq.Method {
  395. case "none":
  396. if config.NoClientAuth {
  397. authErr = nil
  398. }
  399. // allow initial attempt of 'none' without penalty
  400. if authFailures == 0 {
  401. authFailures--
  402. }
  403. case "password":
  404. if config.PasswordCallback == nil {
  405. authErr = errors.New("ssh: password auth not configured")
  406. break
  407. }
  408. payload := userAuthReq.Payload
  409. if len(payload) < 1 || payload[0] != 0 {
  410. return nil, parseError(msgUserAuthRequest)
  411. }
  412. payload = payload[1:]
  413. password, payload, ok := parseString(payload)
  414. if !ok || len(payload) > 0 {
  415. return nil, parseError(msgUserAuthRequest)
  416. }
  417. perms, authErr = config.PasswordCallback(s, password)
  418. case "keyboard-interactive":
  419. if config.KeyboardInteractiveCallback == nil {
  420. authErr = errors.New("ssh: keyboard-interactive auth not configured")
  421. break
  422. }
  423. prompter := &sshClientKeyboardInteractive{s}
  424. perms, authErr = config.KeyboardInteractiveCallback(s, prompter.Challenge)
  425. case "publickey":
  426. if config.PublicKeyCallback == nil {
  427. authErr = errors.New("ssh: publickey auth not configured")
  428. break
  429. }
  430. payload := userAuthReq.Payload
  431. if len(payload) < 1 {
  432. return nil, parseError(msgUserAuthRequest)
  433. }
  434. isQuery := payload[0] == 0
  435. payload = payload[1:]
  436. algoBytes, payload, ok := parseString(payload)
  437. if !ok {
  438. return nil, parseError(msgUserAuthRequest)
  439. }
  440. algo := string(algoBytes)
  441. if !isAcceptableAlgo(algo) {
  442. authErr = fmt.Errorf("ssh: algorithm %q not accepted", algo)
  443. break
  444. }
  445. pubKeyData, payload, ok := parseString(payload)
  446. if !ok {
  447. return nil, parseError(msgUserAuthRequest)
  448. }
  449. pubKey, err := ParsePublicKey(pubKeyData)
  450. if err != nil {
  451. return nil, err
  452. }
  453. candidate, ok := cache.get(s.user, pubKeyData)
  454. if !ok {
  455. candidate.user = s.user
  456. candidate.pubKeyData = pubKeyData
  457. candidate.perms, candidate.result = config.PublicKeyCallback(s, pubKey)
  458. if candidate.result == nil && candidate.perms != nil && candidate.perms.CriticalOptions != nil && candidate.perms.CriticalOptions[sourceAddressCriticalOption] != "" {
  459. candidate.result = checkSourceAddress(
  460. s.RemoteAddr(),
  461. candidate.perms.CriticalOptions[sourceAddressCriticalOption])
  462. }
  463. cache.add(candidate)
  464. }
  465. if isQuery {
  466. // The client can query if the given public key
  467. // would be okay.
  468. if len(payload) > 0 {
  469. return nil, parseError(msgUserAuthRequest)
  470. }
  471. if candidate.result == nil {
  472. okMsg := userAuthPubKeyOkMsg{
  473. Algo: algo,
  474. PubKey: pubKeyData,
  475. }
  476. if err = s.transport.writePacket(Marshal(&okMsg)); err != nil {
  477. return nil, err
  478. }
  479. continue userAuthLoop
  480. }
  481. authErr = candidate.result
  482. } else {
  483. sig, payload, ok := parseSignature(payload)
  484. if !ok || len(payload) > 0 {
  485. return nil, parseError(msgUserAuthRequest)
  486. }
  487. // Ensure the public key algo and signature algo
  488. // are supported. Compare the private key
  489. // algorithm name that corresponds to algo with
  490. // sig.Format. This is usually the same, but
  491. // for certs, the names differ.
  492. if !isAcceptableAlgo(sig.Format) {
  493. authErr = fmt.Errorf("ssh: algorithm %q not accepted", sig.Format)
  494. break
  495. }
  496. signedData := buildDataSignedForAuth(sessionID, userAuthReq, algoBytes, pubKeyData)
  497. if err := pubKey.Verify(signedData, sig); err != nil {
  498. return nil, err
  499. }
  500. authErr = candidate.result
  501. perms = candidate.perms
  502. }
  503. case "gssapi-with-mic":
  504. gssapiConfig := config.GSSAPIWithMICConfig
  505. userAuthRequestGSSAPI, err := parseGSSAPIPayload(userAuthReq.Payload)
  506. if err != nil {
  507. return nil, parseError(msgUserAuthRequest)
  508. }
  509. // OpenSSH supports Kerberos V5 mechanism only for GSS-API authentication.
  510. if userAuthRequestGSSAPI.N == 0 {
  511. authErr = fmt.Errorf("ssh: Mechanism negotiation is not supported")
  512. break
  513. }
  514. var i uint32
  515. present := false
  516. for i = 0; i < userAuthRequestGSSAPI.N; i++ {
  517. if userAuthRequestGSSAPI.OIDS[i].Equal(krb5Mesh) {
  518. present = true
  519. break
  520. }
  521. }
  522. if !present {
  523. authErr = fmt.Errorf("ssh: GSSAPI authentication must use the Kerberos V5 mechanism")
  524. break
  525. }
  526. // Initial server response, see RFC 4462 section 3.3.
  527. if err := s.transport.writePacket(Marshal(&userAuthGSSAPIResponse{
  528. SupportMech: krb5OID,
  529. })); err != nil {
  530. return nil, err
  531. }
  532. // Exchange token, see RFC 4462 section 3.4.
  533. packet, err := s.transport.readPacket()
  534. if err != nil {
  535. return nil, err
  536. }
  537. userAuthGSSAPITokenReq := &userAuthGSSAPIToken{}
  538. if err := Unmarshal(packet, userAuthGSSAPITokenReq); err != nil {
  539. return nil, err
  540. }
  541. authErr, perms, err = gssExchangeToken(gssapiConfig, userAuthGSSAPITokenReq.Token, s, sessionID,
  542. userAuthReq)
  543. if err != nil {
  544. return nil, err
  545. }
  546. default:
  547. authErr = fmt.Errorf("ssh: unknown method %q", userAuthReq.Method)
  548. }
  549. authErrs = append(authErrs, authErr)
  550. if config.AuthLogCallback != nil {
  551. config.AuthLogCallback(s, userAuthReq.Method, authErr)
  552. }
  553. if authErr == nil {
  554. break userAuthLoop
  555. }
  556. authFailures++
  557. var failureMsg userAuthFailureMsg
  558. if config.PasswordCallback != nil {
  559. failureMsg.Methods = append(failureMsg.Methods, "password")
  560. }
  561. if config.PublicKeyCallback != nil {
  562. failureMsg.Methods = append(failureMsg.Methods, "publickey")
  563. }
  564. if config.KeyboardInteractiveCallback != nil {
  565. failureMsg.Methods = append(failureMsg.Methods, "keyboard-interactive")
  566. }
  567. if config.GSSAPIWithMICConfig != nil && config.GSSAPIWithMICConfig.Server != nil &&
  568. config.GSSAPIWithMICConfig.AllowLogin != nil {
  569. failureMsg.Methods = append(failureMsg.Methods, "gssapi-with-mic")
  570. }
  571. if len(failureMsg.Methods) == 0 {
  572. return nil, errors.New("ssh: no authentication methods configured but NoClientAuth is also false")
  573. }
  574. if err := s.transport.writePacket(Marshal(&failureMsg)); err != nil {
  575. return nil, err
  576. }
  577. }
  578. if err := s.transport.writePacket([]byte{msgUserAuthSuccess}); err != nil {
  579. return nil, err
  580. }
  581. return perms, nil
  582. }
  583. // sshClientKeyboardInteractive implements a ClientKeyboardInteractive by
  584. // asking the client on the other side of a ServerConn.
  585. type sshClientKeyboardInteractive struct {
  586. *connection
  587. }
  588. func (c *sshClientKeyboardInteractive) Challenge(user, instruction string, questions []string, echos []bool) (answers []string, err error) {
  589. if len(questions) != len(echos) {
  590. return nil, errors.New("ssh: echos and questions must have equal length")
  591. }
  592. var prompts []byte
  593. for i := range questions {
  594. prompts = appendString(prompts, questions[i])
  595. prompts = appendBool(prompts, echos[i])
  596. }
  597. if err := c.transport.writePacket(Marshal(&userAuthInfoRequestMsg{
  598. Instruction: instruction,
  599. NumPrompts: uint32(len(questions)),
  600. Prompts: prompts,
  601. })); err != nil {
  602. return nil, err
  603. }
  604. packet, err := c.transport.readPacket()
  605. if err != nil {
  606. return nil, err
  607. }
  608. if packet[0] != msgUserAuthInfoResponse {
  609. return nil, unexpectedMessageError(msgUserAuthInfoResponse, packet[0])
  610. }
  611. packet = packet[1:]
  612. n, packet, ok := parseUint32(packet)
  613. if !ok || int(n) != len(questions) {
  614. return nil, parseError(msgUserAuthInfoResponse)
  615. }
  616. for i := uint32(0); i < n; i++ {
  617. ans, rest, ok := parseString(packet)
  618. if !ok {
  619. return nil, parseError(msgUserAuthInfoResponse)
  620. }
  621. answers = append(answers, string(ans))
  622. packet = rest
  623. }
  624. if len(packet) != 0 {
  625. return nil, errors.New("ssh: junk at end of message")
  626. }
  627. return answers, nil
  628. }