server.go 26 KB

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