server.go 24 KB

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