server.go 22 KB

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