server.go 31 KB

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