server.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  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 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. // isAlgoCompatible checks if the signature format is compatible with the
  327. // selected algorithm taking into account edge cases that occur with old
  328. // clients.
  329. func isAlgoCompatible(algo, sigFormat string) bool {
  330. // Compatibility for old clients.
  331. //
  332. // For certificate authentication with OpenSSH 7.2-7.7 signature format can
  333. // be rsa-sha2-256 or rsa-sha2-512 for the algorithm
  334. // ssh-rsa-cert-v01@openssh.com.
  335. //
  336. // With gpg-agent < 2.2.6 the algorithm can be rsa-sha2-256 or rsa-sha2-512
  337. // for signature format ssh-rsa.
  338. if isRSA(algo) && isRSA(sigFormat) {
  339. return true
  340. }
  341. // Standard case: the underlying algorithm must match the signature format.
  342. return underlyingAlgo(algo) == sigFormat
  343. }
  344. // ServerAuthError represents server authentication errors and is
  345. // sometimes returned by NewServerConn. It appends any authentication
  346. // errors that may occur, and is returned if all of the authentication
  347. // methods provided by the user failed to authenticate.
  348. type ServerAuthError struct {
  349. // Errors contains authentication errors returned by the authentication
  350. // callback methods. The first entry is typically ErrNoAuth.
  351. Errors []error
  352. }
  353. func (l ServerAuthError) Error() string {
  354. var errs []string
  355. for _, err := range l.Errors {
  356. errs = append(errs, err.Error())
  357. }
  358. return "[" + strings.Join(errs, ", ") + "]"
  359. }
  360. // ErrNoAuth is the error value returned if no
  361. // authentication method has been passed yet. This happens as a normal
  362. // part of the authentication loop, since the client first tries
  363. // 'none' authentication to discover available methods.
  364. // It is returned in ServerAuthError.Errors from NewServerConn.
  365. var ErrNoAuth = errors.New("ssh: no auth passed yet")
  366. func (s *connection) serverAuthenticate(config *ServerConfig) (*Permissions, error) {
  367. sessionID := s.transport.getSessionID()
  368. var cache pubKeyCache
  369. var perms *Permissions
  370. authFailures := 0
  371. var authErrs []error
  372. var displayedBanner bool
  373. userAuthLoop:
  374. for {
  375. if authFailures >= config.MaxAuthTries && config.MaxAuthTries > 0 {
  376. discMsg := &disconnectMsg{
  377. Reason: 2,
  378. Message: "too many authentication failures",
  379. }
  380. if err := s.transport.writePacket(Marshal(discMsg)); err != nil {
  381. return nil, err
  382. }
  383. return nil, discMsg
  384. }
  385. var userAuthReq userAuthRequestMsg
  386. if packet, err := s.transport.readPacket(); err != nil {
  387. if err == io.EOF {
  388. return nil, &ServerAuthError{Errors: authErrs}
  389. }
  390. return nil, err
  391. } else if err = Unmarshal(packet, &userAuthReq); err != nil {
  392. return nil, err
  393. }
  394. if userAuthReq.Service != serviceSSH {
  395. return nil, errors.New("ssh: client attempted to negotiate for unknown service: " + userAuthReq.Service)
  396. }
  397. s.user = userAuthReq.User
  398. if !displayedBanner && config.BannerCallback != nil {
  399. displayedBanner = true
  400. msg := config.BannerCallback(s)
  401. if msg != "" {
  402. bannerMsg := &userAuthBannerMsg{
  403. Message: msg,
  404. }
  405. if err := s.transport.writePacket(Marshal(bannerMsg)); err != nil {
  406. return nil, err
  407. }
  408. }
  409. }
  410. perms = nil
  411. authErr := ErrNoAuth
  412. switch userAuthReq.Method {
  413. case "none":
  414. if config.NoClientAuth {
  415. if config.NoClientAuthCallback != nil {
  416. perms, authErr = config.NoClientAuthCallback(s)
  417. } else {
  418. authErr = nil
  419. }
  420. }
  421. // allow initial attempt of 'none' without penalty
  422. if authFailures == 0 {
  423. authFailures--
  424. }
  425. case "password":
  426. if config.PasswordCallback == nil {
  427. authErr = errors.New("ssh: password auth not configured")
  428. break
  429. }
  430. payload := userAuthReq.Payload
  431. if len(payload) < 1 || payload[0] != 0 {
  432. return nil, parseError(msgUserAuthRequest)
  433. }
  434. payload = payload[1:]
  435. password, payload, ok := parseString(payload)
  436. if !ok || len(payload) > 0 {
  437. return nil, parseError(msgUserAuthRequest)
  438. }
  439. perms, authErr = config.PasswordCallback(s, password)
  440. case "keyboard-interactive":
  441. if config.KeyboardInteractiveCallback == nil {
  442. authErr = errors.New("ssh: keyboard-interactive auth not configured")
  443. break
  444. }
  445. prompter := &sshClientKeyboardInteractive{s}
  446. perms, authErr = config.KeyboardInteractiveCallback(s, prompter.Challenge)
  447. case "publickey":
  448. if config.PublicKeyCallback == nil {
  449. authErr = errors.New("ssh: publickey auth not configured")
  450. break
  451. }
  452. payload := userAuthReq.Payload
  453. if len(payload) < 1 {
  454. return nil, parseError(msgUserAuthRequest)
  455. }
  456. isQuery := payload[0] == 0
  457. payload = payload[1:]
  458. algoBytes, payload, ok := parseString(payload)
  459. if !ok {
  460. return nil, parseError(msgUserAuthRequest)
  461. }
  462. algo := string(algoBytes)
  463. if !contains(supportedPubKeyAuthAlgos, underlyingAlgo(algo)) {
  464. authErr = fmt.Errorf("ssh: algorithm %q not accepted", algo)
  465. break
  466. }
  467. pubKeyData, payload, ok := parseString(payload)
  468. if !ok {
  469. return nil, parseError(msgUserAuthRequest)
  470. }
  471. pubKey, err := ParsePublicKey(pubKeyData)
  472. if err != nil {
  473. return nil, err
  474. }
  475. candidate, ok := cache.get(s.user, pubKeyData)
  476. if !ok {
  477. candidate.user = s.user
  478. candidate.pubKeyData = pubKeyData
  479. candidate.perms, candidate.result = config.PublicKeyCallback(s, pubKey)
  480. if candidate.result == nil && candidate.perms != nil && candidate.perms.CriticalOptions != nil && candidate.perms.CriticalOptions[sourceAddressCriticalOption] != "" {
  481. candidate.result = checkSourceAddress(
  482. s.RemoteAddr(),
  483. candidate.perms.CriticalOptions[sourceAddressCriticalOption])
  484. }
  485. cache.add(candidate)
  486. }
  487. if isQuery {
  488. // The client can query if the given public key
  489. // would be okay.
  490. if len(payload) > 0 {
  491. return nil, parseError(msgUserAuthRequest)
  492. }
  493. if candidate.result == nil {
  494. okMsg := userAuthPubKeyOkMsg{
  495. Algo: algo,
  496. PubKey: pubKeyData,
  497. }
  498. if err = s.transport.writePacket(Marshal(&okMsg)); err != nil {
  499. return nil, err
  500. }
  501. continue userAuthLoop
  502. }
  503. authErr = candidate.result
  504. } else {
  505. sig, payload, ok := parseSignature(payload)
  506. if !ok || len(payload) > 0 {
  507. return nil, parseError(msgUserAuthRequest)
  508. }
  509. // Ensure the declared public key algo is compatible with the
  510. // decoded one. This check will ensure we don't accept e.g.
  511. // ssh-rsa-cert-v01@openssh.com algorithm with ssh-rsa public
  512. // key type. The algorithm and public key type must be
  513. // consistent: both must be certificate algorithms, or neither.
  514. if !contains(algorithmsForKeyFormat(pubKey.Type()), algo) {
  515. authErr = fmt.Errorf("ssh: public key type %q not compatible with selected algorithm %q",
  516. pubKey.Type(), algo)
  517. break
  518. }
  519. // Ensure the public key algo and signature algo
  520. // are supported. Compare the private key
  521. // algorithm name that corresponds to algo with
  522. // sig.Format. This is usually the same, but
  523. // for certs, the names differ.
  524. if !contains(supportedPubKeyAuthAlgos, sig.Format) {
  525. authErr = fmt.Errorf("ssh: algorithm %q not accepted", sig.Format)
  526. break
  527. }
  528. if !isAlgoCompatible(algo, sig.Format) {
  529. authErr = fmt.Errorf("ssh: signature %q not compatible with selected algorithm %q", sig.Format, algo)
  530. break
  531. }
  532. signedData := buildDataSignedForAuth(sessionID, userAuthReq, algo, pubKeyData)
  533. if err := pubKey.Verify(signedData, sig); err != nil {
  534. return nil, err
  535. }
  536. authErr = candidate.result
  537. perms = candidate.perms
  538. }
  539. case "gssapi-with-mic":
  540. if config.GSSAPIWithMICConfig == nil {
  541. authErr = errors.New("ssh: gssapi-with-mic auth not configured")
  542. break
  543. }
  544. gssapiConfig := config.GSSAPIWithMICConfig
  545. userAuthRequestGSSAPI, err := parseGSSAPIPayload(userAuthReq.Payload)
  546. if err != nil {
  547. return nil, parseError(msgUserAuthRequest)
  548. }
  549. // OpenSSH supports Kerberos V5 mechanism only for GSS-API authentication.
  550. if userAuthRequestGSSAPI.N == 0 {
  551. authErr = fmt.Errorf("ssh: Mechanism negotiation is not supported")
  552. break
  553. }
  554. var i uint32
  555. present := false
  556. for i = 0; i < userAuthRequestGSSAPI.N; i++ {
  557. if userAuthRequestGSSAPI.OIDS[i].Equal(krb5Mesh) {
  558. present = true
  559. break
  560. }
  561. }
  562. if !present {
  563. authErr = fmt.Errorf("ssh: GSSAPI authentication must use the Kerberos V5 mechanism")
  564. break
  565. }
  566. // Initial server response, see RFC 4462 section 3.3.
  567. if err := s.transport.writePacket(Marshal(&userAuthGSSAPIResponse{
  568. SupportMech: krb5OID,
  569. })); err != nil {
  570. return nil, err
  571. }
  572. // Exchange token, see RFC 4462 section 3.4.
  573. packet, err := s.transport.readPacket()
  574. if err != nil {
  575. return nil, err
  576. }
  577. userAuthGSSAPITokenReq := &userAuthGSSAPIToken{}
  578. if err := Unmarshal(packet, userAuthGSSAPITokenReq); err != nil {
  579. return nil, err
  580. }
  581. authErr, perms, err = gssExchangeToken(gssapiConfig, userAuthGSSAPITokenReq.Token, s, sessionID,
  582. userAuthReq)
  583. if err != nil {
  584. return nil, err
  585. }
  586. default:
  587. authErr = fmt.Errorf("ssh: unknown method %q", userAuthReq.Method)
  588. }
  589. authErrs = append(authErrs, authErr)
  590. if config.AuthLogCallback != nil {
  591. config.AuthLogCallback(s, userAuthReq.Method, authErr)
  592. }
  593. if authErr == nil {
  594. break userAuthLoop
  595. }
  596. authFailures++
  597. if config.MaxAuthTries > 0 && authFailures >= config.MaxAuthTries {
  598. // If we have hit the max attempts, don't bother sending the
  599. // final SSH_MSG_USERAUTH_FAILURE message, since there are
  600. // no more authentication methods which can be attempted,
  601. // and this message may cause the client to re-attempt
  602. // authentication while we send the disconnect message.
  603. // Continue, and trigger the disconnect at the start of
  604. // the loop.
  605. //
  606. // The SSH specification is somewhat confusing about this,
  607. // RFC 4252 Section 5.1 requires each authentication failure
  608. // be responded to with a respective SSH_MSG_USERAUTH_FAILURE
  609. // message, but Section 4 says the server should disconnect
  610. // after some number of attempts, but it isn't explicit which
  611. // message should take precedence (i.e. should there be a failure
  612. // message than a disconnect message, or if we are going to
  613. // disconnect, should we only send that message.)
  614. //
  615. // Either way, OpenSSH disconnects immediately after the last
  616. // failed authnetication attempt, and given they are typically
  617. // considered the golden implementation it seems reasonable
  618. // to match that behavior.
  619. continue
  620. }
  621. var failureMsg userAuthFailureMsg
  622. if config.PasswordCallback != nil {
  623. failureMsg.Methods = append(failureMsg.Methods, "password")
  624. }
  625. if config.PublicKeyCallback != nil {
  626. failureMsg.Methods = append(failureMsg.Methods, "publickey")
  627. }
  628. if config.KeyboardInteractiveCallback != nil {
  629. failureMsg.Methods = append(failureMsg.Methods, "keyboard-interactive")
  630. }
  631. if config.GSSAPIWithMICConfig != nil && config.GSSAPIWithMICConfig.Server != nil &&
  632. config.GSSAPIWithMICConfig.AllowLogin != nil {
  633. failureMsg.Methods = append(failureMsg.Methods, "gssapi-with-mic")
  634. }
  635. if len(failureMsg.Methods) == 0 {
  636. return nil, errors.New("ssh: no authentication methods configured but NoClientAuth is also false")
  637. }
  638. if err := s.transport.writePacket(Marshal(&failureMsg)); err != nil {
  639. return nil, err
  640. }
  641. }
  642. if err := s.transport.writePacket([]byte{msgUserAuthSuccess}); err != nil {
  643. return nil, err
  644. }
  645. return perms, nil
  646. }
  647. // sshClientKeyboardInteractive implements a ClientKeyboardInteractive by
  648. // asking the client on the other side of a ServerConn.
  649. type sshClientKeyboardInteractive struct {
  650. *connection
  651. }
  652. func (c *sshClientKeyboardInteractive) Challenge(name, instruction string, questions []string, echos []bool) (answers []string, err error) {
  653. if len(questions) != len(echos) {
  654. return nil, errors.New("ssh: echos and questions must have equal length")
  655. }
  656. var prompts []byte
  657. for i := range questions {
  658. prompts = appendString(prompts, questions[i])
  659. prompts = appendBool(prompts, echos[i])
  660. }
  661. if err := c.transport.writePacket(Marshal(&userAuthInfoRequestMsg{
  662. Name: name,
  663. Instruction: instruction,
  664. NumPrompts: uint32(len(questions)),
  665. Prompts: prompts,
  666. })); err != nil {
  667. return nil, err
  668. }
  669. packet, err := c.transport.readPacket()
  670. if err != nil {
  671. return nil, err
  672. }
  673. if packet[0] != msgUserAuthInfoResponse {
  674. return nil, unexpectedMessageError(msgUserAuthInfoResponse, packet[0])
  675. }
  676. packet = packet[1:]
  677. n, packet, ok := parseUint32(packet)
  678. if !ok || int(n) != len(questions) {
  679. return nil, parseError(msgUserAuthInfoResponse)
  680. }
  681. for i := uint32(0); i < n; i++ {
  682. ans, rest, ok := parseString(packet)
  683. if !ok {
  684. return nil, parseError(msgUserAuthInfoResponse)
  685. }
  686. answers = append(answers, string(ans))
  687. packet = rest
  688. }
  689. if len(packet) != 0 {
  690. return nil, errors.New("ssh: junk at end of message")
  691. }
  692. return answers, nil
  693. }