server.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927
  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 = defaultPubKeyAuthAlgos
  212. } else {
  213. for _, algo := range fullConf.PublicKeyAuthAlgorithms {
  214. if !contains(SupportedAlgorithms().PublicKeyAuths, algo) && !contains(InsecureAlgorithms().PublicKeyAuths, algo) {
  215. c.Close()
  216. return nil, nil, nil, fmt.Errorf("ssh: unsupported public key authentication algorithm %s", algo)
  217. }
  218. }
  219. }
  220. s := &connection{
  221. sshConn: sshConn{conn: c},
  222. }
  223. perms, err := s.serverHandshake(&fullConf)
  224. if err != nil {
  225. c.Close()
  226. return nil, nil, nil, err
  227. }
  228. return &ServerConn{s, perms}, s.mux.incomingChannels, s.mux.incomingRequests, nil
  229. }
  230. // signAndMarshal signs the data with the appropriate algorithm,
  231. // and serializes the result in SSH wire format. algo is the negotiate
  232. // algorithm and may be a certificate type.
  233. func signAndMarshal(k AlgorithmSigner, rand io.Reader, data []byte, algo string) ([]byte, error) {
  234. sig, err := k.SignWithAlgorithm(rand, data, underlyingAlgo(algo))
  235. if err != nil {
  236. return nil, err
  237. }
  238. return Marshal(sig), nil
  239. }
  240. // handshake performs key exchange and user authentication.
  241. func (s *connection) serverHandshake(config *ServerConfig) (*Permissions, error) {
  242. if len(config.hostKeys) == 0 {
  243. return nil, errors.New("ssh: server has no host keys")
  244. }
  245. if !config.NoClientAuth && config.PasswordCallback == nil && config.PublicKeyCallback == nil &&
  246. config.KeyboardInteractiveCallback == nil && (config.GSSAPIWithMICConfig == nil ||
  247. config.GSSAPIWithMICConfig.AllowLogin == nil || config.GSSAPIWithMICConfig.Server == nil) {
  248. return nil, errors.New("ssh: no authentication methods configured but NoClientAuth is also false")
  249. }
  250. if config.ServerVersion != "" {
  251. s.serverVersion = []byte(config.ServerVersion)
  252. } else {
  253. s.serverVersion = []byte(packageVersion)
  254. }
  255. var err error
  256. s.clientVersion, err = exchangeVersions(s.sshConn.conn, s.serverVersion)
  257. if err != nil {
  258. return nil, err
  259. }
  260. tr := newTransport(s.sshConn.conn, config.Rand, false /* not client */)
  261. s.transport = newServerTransport(tr, s.clientVersion, s.serverVersion, config)
  262. if err := s.transport.waitSession(); err != nil {
  263. return nil, err
  264. }
  265. // We just did the key change, so the session ID is established.
  266. s.sessionID = s.transport.getSessionID()
  267. s.algorithms = s.transport.getAlgorithms()
  268. var packet []byte
  269. if packet, err = s.transport.readPacket(); err != nil {
  270. return nil, err
  271. }
  272. var serviceRequest serviceRequestMsg
  273. if err = Unmarshal(packet, &serviceRequest); err != nil {
  274. return nil, err
  275. }
  276. if serviceRequest.Service != serviceUserAuth {
  277. return nil, errors.New("ssh: requested service '" + serviceRequest.Service + "' before authenticating")
  278. }
  279. serviceAccept := serviceAcceptMsg{
  280. Service: serviceUserAuth,
  281. }
  282. if err := s.transport.writePacket(Marshal(&serviceAccept)); err != nil {
  283. return nil, err
  284. }
  285. perms, err := s.serverAuthenticate(config)
  286. if err != nil {
  287. return nil, err
  288. }
  289. s.mux = newMux(s.transport)
  290. return perms, err
  291. }
  292. func checkSourceAddress(addr net.Addr, sourceAddrs string) error {
  293. if addr == nil {
  294. return errors.New("ssh: no address known for client, but source-address match required")
  295. }
  296. tcpAddr, ok := addr.(*net.TCPAddr)
  297. if !ok {
  298. return fmt.Errorf("ssh: remote address %v is not an TCP address when checking source-address match", addr)
  299. }
  300. for _, sourceAddr := range strings.Split(sourceAddrs, ",") {
  301. if allowedIP := net.ParseIP(sourceAddr); allowedIP != nil {
  302. if allowedIP.Equal(tcpAddr.IP) {
  303. return nil
  304. }
  305. } else {
  306. _, ipNet, err := net.ParseCIDR(sourceAddr)
  307. if err != nil {
  308. return fmt.Errorf("ssh: error parsing source-address restriction %q: %v", sourceAddr, err)
  309. }
  310. if ipNet.Contains(tcpAddr.IP) {
  311. return nil
  312. }
  313. }
  314. }
  315. return fmt.Errorf("ssh: remote address %v is not allowed because of source-address restriction", addr)
  316. }
  317. func gssExchangeToken(gssapiConfig *GSSAPIWithMICConfig, token []byte, s *connection,
  318. sessionID []byte, userAuthReq userAuthRequestMsg) (authErr error, perms *Permissions, err error) {
  319. gssAPIServer := gssapiConfig.Server
  320. defer gssAPIServer.DeleteSecContext()
  321. var srcName string
  322. for {
  323. var (
  324. outToken []byte
  325. needContinue bool
  326. )
  327. outToken, srcName, needContinue, err = gssAPIServer.AcceptSecContext(token)
  328. if err != nil {
  329. return err, nil, nil
  330. }
  331. if len(outToken) != 0 {
  332. if err := s.transport.writePacket(Marshal(&userAuthGSSAPIToken{
  333. Token: outToken,
  334. })); err != nil {
  335. return nil, nil, err
  336. }
  337. }
  338. if !needContinue {
  339. break
  340. }
  341. packet, err := s.transport.readPacket()
  342. if err != nil {
  343. return nil, nil, err
  344. }
  345. userAuthGSSAPITokenReq := &userAuthGSSAPIToken{}
  346. if err := Unmarshal(packet, userAuthGSSAPITokenReq); err != nil {
  347. return nil, nil, err
  348. }
  349. token = userAuthGSSAPITokenReq.Token
  350. }
  351. packet, err := s.transport.readPacket()
  352. if err != nil {
  353. return nil, nil, err
  354. }
  355. userAuthGSSAPIMICReq := &userAuthGSSAPIMIC{}
  356. if err := Unmarshal(packet, userAuthGSSAPIMICReq); err != nil {
  357. return nil, nil, err
  358. }
  359. mic := buildMIC(string(sessionID), userAuthReq.User, userAuthReq.Service, userAuthReq.Method)
  360. if err := gssAPIServer.VerifyMIC(mic, userAuthGSSAPIMICReq.MIC); err != nil {
  361. return err, nil, nil
  362. }
  363. perms, authErr = gssapiConfig.AllowLogin(s, srcName)
  364. return authErr, perms, nil
  365. }
  366. // isAlgoCompatible checks if the signature format is compatible with the
  367. // selected algorithm taking into account edge cases that occur with old
  368. // clients.
  369. func isAlgoCompatible(algo, sigFormat string) bool {
  370. // Compatibility for old clients.
  371. //
  372. // For certificate authentication with OpenSSH 7.2-7.7 signature format can
  373. // be rsa-sha2-256 or rsa-sha2-512 for the algorithm
  374. // ssh-rsa-cert-v01@openssh.com.
  375. //
  376. // With gpg-agent < 2.2.6 the algorithm can be rsa-sha2-256 or rsa-sha2-512
  377. // for signature format ssh-rsa.
  378. if isRSA(algo) && isRSA(sigFormat) {
  379. return true
  380. }
  381. // Standard case: the underlying algorithm must match the signature format.
  382. return underlyingAlgo(algo) == sigFormat
  383. }
  384. // ServerAuthError represents server authentication errors and is
  385. // sometimes returned by NewServerConn. It appends any authentication
  386. // errors that may occur, and is returned if all of the authentication
  387. // methods provided by the user failed to authenticate.
  388. type ServerAuthError struct {
  389. // Errors contains authentication errors returned by the authentication
  390. // callback methods. The first entry is typically ErrNoAuth.
  391. Errors []error
  392. }
  393. func (l ServerAuthError) Error() string {
  394. var errs []string
  395. for _, err := range l.Errors {
  396. errs = append(errs, err.Error())
  397. }
  398. return "[" + strings.Join(errs, ", ") + "]"
  399. }
  400. // ServerAuthCallbacks defines server-side authentication callbacks.
  401. type ServerAuthCallbacks struct {
  402. // PasswordCallback behaves like [ServerConfig.PasswordCallback].
  403. PasswordCallback func(conn ConnMetadata, password []byte) (*Permissions, error)
  404. // PublicKeyCallback behaves like [ServerConfig.PublicKeyCallback].
  405. PublicKeyCallback func(conn ConnMetadata, key PublicKey) (*Permissions, error)
  406. // KeyboardInteractiveCallback behaves like [ServerConfig.KeyboardInteractiveCallback].
  407. KeyboardInteractiveCallback func(conn ConnMetadata, client KeyboardInteractiveChallenge) (*Permissions, error)
  408. // GSSAPIWithMICConfig behaves like [ServerConfig.GSSAPIWithMICConfig].
  409. GSSAPIWithMICConfig *GSSAPIWithMICConfig
  410. }
  411. // PartialSuccessError can be returned by any of the [ServerConfig]
  412. // authentication callbacks to indicate to the client that authentication has
  413. // partially succeeded, but further steps are required.
  414. type PartialSuccessError struct {
  415. // Next defines the authentication callbacks to apply to further steps. The
  416. // available methods communicated to the client are based on the non-nil
  417. // ServerAuthCallbacks fields.
  418. Next ServerAuthCallbacks
  419. }
  420. func (p *PartialSuccessError) Error() string {
  421. return "ssh: authenticated with partial success"
  422. }
  423. // ErrNoAuth is the error value returned if no
  424. // authentication method has been passed yet. This happens as a normal
  425. // part of the authentication loop, since the client first tries
  426. // 'none' authentication to discover available methods.
  427. // It is returned in ServerAuthError.Errors from NewServerConn.
  428. var ErrNoAuth = errors.New("ssh: no auth passed yet")
  429. // BannerError is an error that can be returned by authentication handlers in
  430. // ServerConfig to send a banner message to the client.
  431. type BannerError struct {
  432. Err error
  433. Message string
  434. }
  435. func (b *BannerError) Unwrap() error {
  436. return b.Err
  437. }
  438. func (b *BannerError) Error() string {
  439. if b.Err == nil {
  440. return b.Message
  441. }
  442. return b.Err.Error()
  443. }
  444. func (s *connection) serverAuthenticate(config *ServerConfig) (*Permissions, error) {
  445. if config.PreAuthConnCallback != nil {
  446. config.PreAuthConnCallback(s)
  447. }
  448. sessionID := s.transport.getSessionID()
  449. var cache pubKeyCache
  450. var perms *Permissions
  451. authFailures := 0
  452. noneAuthCount := 0
  453. var authErrs []error
  454. var calledBannerCallback bool
  455. partialSuccessReturned := false
  456. // Set the initial authentication callbacks from the config. They can be
  457. // changed if a PartialSuccessError is returned.
  458. authConfig := ServerAuthCallbacks{
  459. PasswordCallback: config.PasswordCallback,
  460. PublicKeyCallback: config.PublicKeyCallback,
  461. KeyboardInteractiveCallback: config.KeyboardInteractiveCallback,
  462. GSSAPIWithMICConfig: config.GSSAPIWithMICConfig,
  463. }
  464. userAuthLoop:
  465. for {
  466. if authFailures >= config.MaxAuthTries && config.MaxAuthTries > 0 {
  467. discMsg := &disconnectMsg{
  468. Reason: 2,
  469. Message: "too many authentication failures",
  470. }
  471. if err := s.transport.writePacket(Marshal(discMsg)); err != nil {
  472. return nil, err
  473. }
  474. authErrs = append(authErrs, discMsg)
  475. return nil, &ServerAuthError{Errors: authErrs}
  476. }
  477. var userAuthReq userAuthRequestMsg
  478. if packet, err := s.transport.readPacket(); err != nil {
  479. if err == io.EOF {
  480. return nil, &ServerAuthError{Errors: authErrs}
  481. }
  482. return nil, err
  483. } else if err = Unmarshal(packet, &userAuthReq); err != nil {
  484. return nil, err
  485. }
  486. if userAuthReq.Service != serviceSSH {
  487. return nil, errors.New("ssh: client attempted to negotiate for unknown service: " + userAuthReq.Service)
  488. }
  489. if s.user != userAuthReq.User && partialSuccessReturned {
  490. return nil, fmt.Errorf("ssh: client changed the user after a partial success authentication, previous user %q, current user %q",
  491. s.user, userAuthReq.User)
  492. }
  493. s.user = userAuthReq.User
  494. if !calledBannerCallback && config.BannerCallback != nil {
  495. calledBannerCallback = true
  496. if msg := config.BannerCallback(s); msg != "" {
  497. if err := s.SendAuthBanner(msg); err != nil {
  498. return nil, err
  499. }
  500. }
  501. }
  502. perms = nil
  503. authErr := ErrNoAuth
  504. switch userAuthReq.Method {
  505. case "none":
  506. noneAuthCount++
  507. // We don't allow none authentication after a partial success
  508. // response.
  509. if config.NoClientAuth && !partialSuccessReturned {
  510. if config.NoClientAuthCallback != nil {
  511. perms, authErr = config.NoClientAuthCallback(s)
  512. } else {
  513. authErr = nil
  514. }
  515. }
  516. case "password":
  517. if authConfig.PasswordCallback == nil {
  518. authErr = errors.New("ssh: password auth not configured")
  519. break
  520. }
  521. payload := userAuthReq.Payload
  522. if len(payload) < 1 || payload[0] != 0 {
  523. return nil, parseError(msgUserAuthRequest)
  524. }
  525. payload = payload[1:]
  526. password, payload, ok := parseString(payload)
  527. if !ok || len(payload) > 0 {
  528. return nil, parseError(msgUserAuthRequest)
  529. }
  530. perms, authErr = authConfig.PasswordCallback(s, password)
  531. case "keyboard-interactive":
  532. if authConfig.KeyboardInteractiveCallback == nil {
  533. authErr = errors.New("ssh: keyboard-interactive auth not configured")
  534. break
  535. }
  536. prompter := &sshClientKeyboardInteractive{s}
  537. perms, authErr = authConfig.KeyboardInteractiveCallback(s, prompter.Challenge)
  538. case "publickey":
  539. if authConfig.PublicKeyCallback == nil {
  540. authErr = errors.New("ssh: publickey auth not configured")
  541. break
  542. }
  543. payload := userAuthReq.Payload
  544. if len(payload) < 1 {
  545. return nil, parseError(msgUserAuthRequest)
  546. }
  547. isQuery := payload[0] == 0
  548. payload = payload[1:]
  549. algoBytes, payload, ok := parseString(payload)
  550. if !ok {
  551. return nil, parseError(msgUserAuthRequest)
  552. }
  553. algo := string(algoBytes)
  554. if !contains(config.PublicKeyAuthAlgorithms, underlyingAlgo(algo)) {
  555. authErr = fmt.Errorf("ssh: algorithm %q not accepted", algo)
  556. break
  557. }
  558. pubKeyData, payload, ok := parseString(payload)
  559. if !ok {
  560. return nil, parseError(msgUserAuthRequest)
  561. }
  562. pubKey, err := ParsePublicKey(pubKeyData)
  563. if err != nil {
  564. return nil, err
  565. }
  566. candidate, ok := cache.get(s.user, pubKeyData)
  567. if !ok {
  568. candidate.user = s.user
  569. candidate.pubKeyData = pubKeyData
  570. candidate.perms, candidate.result = authConfig.PublicKeyCallback(s, pubKey)
  571. _, isPartialSuccessError := candidate.result.(*PartialSuccessError)
  572. if (candidate.result == nil || isPartialSuccessError) &&
  573. candidate.perms != nil &&
  574. candidate.perms.CriticalOptions != nil &&
  575. candidate.perms.CriticalOptions[sourceAddressCriticalOption] != "" {
  576. if err := checkSourceAddress(
  577. s.RemoteAddr(),
  578. candidate.perms.CriticalOptions[sourceAddressCriticalOption]); err != nil {
  579. candidate.result = err
  580. }
  581. }
  582. cache.add(candidate)
  583. }
  584. if isQuery {
  585. // The client can query if the given public key
  586. // would be okay.
  587. if len(payload) > 0 {
  588. return nil, parseError(msgUserAuthRequest)
  589. }
  590. _, isPartialSuccessError := candidate.result.(*PartialSuccessError)
  591. if candidate.result == nil || isPartialSuccessError {
  592. okMsg := userAuthPubKeyOkMsg{
  593. Algo: algo,
  594. PubKey: pubKeyData,
  595. }
  596. if err = s.transport.writePacket(Marshal(&okMsg)); err != nil {
  597. return nil, err
  598. }
  599. continue userAuthLoop
  600. }
  601. authErr = candidate.result
  602. } else {
  603. sig, payload, ok := parseSignature(payload)
  604. if !ok || len(payload) > 0 {
  605. return nil, parseError(msgUserAuthRequest)
  606. }
  607. // Ensure the declared public key algo is compatible with the
  608. // decoded one. This check will ensure we don't accept e.g.
  609. // ssh-rsa-cert-v01@openssh.com algorithm with ssh-rsa public
  610. // key type. The algorithm and public key type must be
  611. // consistent: both must be certificate algorithms, or neither.
  612. if !contains(algorithmsForKeyFormat(pubKey.Type()), algo) {
  613. authErr = fmt.Errorf("ssh: public key type %q not compatible with selected algorithm %q",
  614. pubKey.Type(), algo)
  615. break
  616. }
  617. // Ensure the public key algo and signature algo
  618. // are supported. Compare the private key
  619. // algorithm name that corresponds to algo with
  620. // sig.Format. This is usually the same, but
  621. // for certs, the names differ.
  622. if !contains(config.PublicKeyAuthAlgorithms, sig.Format) {
  623. authErr = fmt.Errorf("ssh: algorithm %q not accepted", sig.Format)
  624. break
  625. }
  626. if !isAlgoCompatible(algo, sig.Format) {
  627. authErr = fmt.Errorf("ssh: signature %q not compatible with selected algorithm %q", sig.Format, algo)
  628. break
  629. }
  630. signedData := buildDataSignedForAuth(sessionID, userAuthReq, algo, pubKeyData)
  631. if err := pubKey.Verify(signedData, sig); err != nil {
  632. return nil, err
  633. }
  634. authErr = candidate.result
  635. perms = candidate.perms
  636. }
  637. case "gssapi-with-mic":
  638. if authConfig.GSSAPIWithMICConfig == nil {
  639. authErr = errors.New("ssh: gssapi-with-mic auth not configured")
  640. break
  641. }
  642. gssapiConfig := authConfig.GSSAPIWithMICConfig
  643. userAuthRequestGSSAPI, err := parseGSSAPIPayload(userAuthReq.Payload)
  644. if err != nil {
  645. return nil, parseError(msgUserAuthRequest)
  646. }
  647. // OpenSSH supports Kerberos V5 mechanism only for GSS-API authentication.
  648. if userAuthRequestGSSAPI.N == 0 {
  649. authErr = fmt.Errorf("ssh: Mechanism negotiation is not supported")
  650. break
  651. }
  652. var i uint32
  653. present := false
  654. for i = 0; i < userAuthRequestGSSAPI.N; i++ {
  655. if userAuthRequestGSSAPI.OIDS[i].Equal(krb5Mesh) {
  656. present = true
  657. break
  658. }
  659. }
  660. if !present {
  661. authErr = fmt.Errorf("ssh: GSSAPI authentication must use the Kerberos V5 mechanism")
  662. break
  663. }
  664. // Initial server response, see RFC 4462 section 3.3.
  665. if err := s.transport.writePacket(Marshal(&userAuthGSSAPIResponse{
  666. SupportMech: krb5OID,
  667. })); err != nil {
  668. return nil, err
  669. }
  670. // Exchange token, see RFC 4462 section 3.4.
  671. packet, err := s.transport.readPacket()
  672. if err != nil {
  673. return nil, err
  674. }
  675. userAuthGSSAPITokenReq := &userAuthGSSAPIToken{}
  676. if err := Unmarshal(packet, userAuthGSSAPITokenReq); err != nil {
  677. return nil, err
  678. }
  679. authErr, perms, err = gssExchangeToken(gssapiConfig, userAuthGSSAPITokenReq.Token, s, sessionID,
  680. userAuthReq)
  681. if err != nil {
  682. return nil, err
  683. }
  684. default:
  685. authErr = fmt.Errorf("ssh: unknown method %q", userAuthReq.Method)
  686. }
  687. authErrs = append(authErrs, authErr)
  688. if config.AuthLogCallback != nil {
  689. config.AuthLogCallback(s, userAuthReq.Method, authErr)
  690. }
  691. var bannerErr *BannerError
  692. if errors.As(authErr, &bannerErr) {
  693. if bannerErr.Message != "" {
  694. if err := s.SendAuthBanner(bannerErr.Message); err != nil {
  695. return nil, err
  696. }
  697. }
  698. }
  699. if authErr == nil {
  700. break userAuthLoop
  701. }
  702. var failureMsg userAuthFailureMsg
  703. if partialSuccess, ok := authErr.(*PartialSuccessError); ok {
  704. // After a partial success error we don't allow changing the user
  705. // name and execute the NoClientAuthCallback.
  706. partialSuccessReturned = true
  707. // In case a partial success is returned, the server may send
  708. // a new set of authentication methods.
  709. authConfig = partialSuccess.Next
  710. // Reset pubkey cache, as the new PublicKeyCallback might
  711. // accept a different set of public keys.
  712. cache = pubKeyCache{}
  713. // Send back a partial success message to the user.
  714. failureMsg.PartialSuccess = true
  715. } else {
  716. // Allow initial attempt of 'none' without penalty.
  717. if authFailures > 0 || userAuthReq.Method != "none" || noneAuthCount != 1 {
  718. authFailures++
  719. }
  720. if config.MaxAuthTries > 0 && authFailures >= config.MaxAuthTries {
  721. // If we have hit the max attempts, don't bother sending the
  722. // final SSH_MSG_USERAUTH_FAILURE message, since there are
  723. // no more authentication methods which can be attempted,
  724. // and this message may cause the client to re-attempt
  725. // authentication while we send the disconnect message.
  726. // Continue, and trigger the disconnect at the start of
  727. // the loop.
  728. //
  729. // The SSH specification is somewhat confusing about this,
  730. // RFC 4252 Section 5.1 requires each authentication failure
  731. // be responded to with a respective SSH_MSG_USERAUTH_FAILURE
  732. // message, but Section 4 says the server should disconnect
  733. // after some number of attempts, but it isn't explicit which
  734. // message should take precedence (i.e. should there be a failure
  735. // message than a disconnect message, or if we are going to
  736. // disconnect, should we only send that message.)
  737. //
  738. // Either way, OpenSSH disconnects immediately after the last
  739. // failed authentication attempt, and given they are typically
  740. // considered the golden implementation it seems reasonable
  741. // to match that behavior.
  742. continue
  743. }
  744. }
  745. if authConfig.PasswordCallback != nil {
  746. failureMsg.Methods = append(failureMsg.Methods, "password")
  747. }
  748. if authConfig.PublicKeyCallback != nil {
  749. failureMsg.Methods = append(failureMsg.Methods, "publickey")
  750. }
  751. if authConfig.KeyboardInteractiveCallback != nil {
  752. failureMsg.Methods = append(failureMsg.Methods, "keyboard-interactive")
  753. }
  754. if authConfig.GSSAPIWithMICConfig != nil && authConfig.GSSAPIWithMICConfig.Server != nil &&
  755. authConfig.GSSAPIWithMICConfig.AllowLogin != nil {
  756. failureMsg.Methods = append(failureMsg.Methods, "gssapi-with-mic")
  757. }
  758. if len(failureMsg.Methods) == 0 {
  759. return nil, errors.New("ssh: no authentication methods available")
  760. }
  761. if err := s.transport.writePacket(Marshal(&failureMsg)); err != nil {
  762. return nil, err
  763. }
  764. }
  765. if err := s.transport.writePacket([]byte{msgUserAuthSuccess}); err != nil {
  766. return nil, err
  767. }
  768. return perms, nil
  769. }
  770. // sshClientKeyboardInteractive implements a ClientKeyboardInteractive by
  771. // asking the client on the other side of a ServerConn.
  772. type sshClientKeyboardInteractive struct {
  773. *connection
  774. }
  775. func (c *sshClientKeyboardInteractive) Challenge(name, instruction string, questions []string, echos []bool) (answers []string, err error) {
  776. if len(questions) != len(echos) {
  777. return nil, errors.New("ssh: echos and questions must have equal length")
  778. }
  779. var prompts []byte
  780. for i := range questions {
  781. prompts = appendString(prompts, questions[i])
  782. prompts = appendBool(prompts, echos[i])
  783. }
  784. if err := c.transport.writePacket(Marshal(&userAuthInfoRequestMsg{
  785. Name: name,
  786. Instruction: instruction,
  787. NumPrompts: uint32(len(questions)),
  788. Prompts: prompts,
  789. })); err != nil {
  790. return nil, err
  791. }
  792. packet, err := c.transport.readPacket()
  793. if err != nil {
  794. return nil, err
  795. }
  796. if packet[0] != msgUserAuthInfoResponse {
  797. return nil, unexpectedMessageError(msgUserAuthInfoResponse, packet[0])
  798. }
  799. packet = packet[1:]
  800. n, packet, ok := parseUint32(packet)
  801. if !ok || int(n) != len(questions) {
  802. return nil, parseError(msgUserAuthInfoResponse)
  803. }
  804. for i := uint32(0); i < n; i++ {
  805. ans, rest, ok := parseString(packet)
  806. if !ok {
  807. return nil, parseError(msgUserAuthInfoResponse)
  808. }
  809. answers = append(answers, string(ans))
  810. packet = rest
  811. }
  812. if len(packet) != 0 {
  813. return nil, errors.New("ssh: junk at end of message")
  814. }
  815. return answers, nil
  816. }