You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

582 lines
17 KiB

  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. // ServerConfig holds server specific configuration data.
  44. type ServerConfig struct {
  45. // Config contains configuration shared between client and server.
  46. Config
  47. hostKeys []Signer
  48. // NoClientAuth is true if clients are allowed to connect without
  49. // authenticating.
  50. NoClientAuth bool
  51. // MaxAuthTries specifies the maximum number of authentication attempts
  52. // permitted per connection. If set to a negative number, the number of
  53. // attempts are unlimited. If set to zero, the number of attempts are limited
  54. // to 6.
  55. MaxAuthTries int
  56. // PasswordCallback, if non-nil, is called when a user
  57. // attempts to authenticate using a password.
  58. PasswordCallback func(conn ConnMetadata, password []byte) (*Permissions, error)
  59. // PublicKeyCallback, if non-nil, is called when a client
  60. // offers a public key for authentication. It must return a nil error
  61. // if the given public key can be used to authenticate the
  62. // given user. For example, see CertChecker.Authenticate. A
  63. // call to this function does not guarantee that the key
  64. // offered is in fact used to authenticate. To record any data
  65. // depending on the public key, store it inside a
  66. // Permissions.Extensions entry.
  67. PublicKeyCallback func(conn ConnMetadata, key PublicKey) (*Permissions, error)
  68. // KeyboardInteractiveCallback, if non-nil, is called when
  69. // keyboard-interactive authentication is selected (RFC
  70. // 4256). The client object's Challenge function should be
  71. // used to query the user. The callback may offer multiple
  72. // Challenge rounds. To avoid information leaks, the client
  73. // should be presented a challenge even if the user is
  74. // unknown.
  75. KeyboardInteractiveCallback func(conn ConnMetadata, client KeyboardInteractiveChallenge) (*Permissions, error)
  76. // AuthLogCallback, if non-nil, is called to log all authentication
  77. // attempts.
  78. AuthLogCallback func(conn ConnMetadata, method string, err error)
  79. // ServerVersion is the version identification string to announce in
  80. // the public handshake.
  81. // If empty, a reasonable default is used.
  82. // Note that RFC 4253 section 4.2 requires that this string start with
  83. // "SSH-2.0-".
  84. ServerVersion string
  85. // BannerCallback, if present, is called and the return string is sent to
  86. // the client after key exchange completed but before authentication.
  87. BannerCallback func(conn ConnMetadata) string
  88. }
  89. // AddHostKey adds a private key as a host key. If an existing host
  90. // key exists with the same algorithm, it is overwritten. Each server
  91. // config must have at least one host key.
  92. func (s *ServerConfig) AddHostKey(key Signer) {
  93. for i, k := range s.hostKeys {
  94. if k.PublicKey().Type() == key.PublicKey().Type() {
  95. s.hostKeys[i] = key
  96. return
  97. }
  98. }
  99. s.hostKeys = append(s.hostKeys, key)
  100. }
  101. // cachedPubKey contains the results of querying whether a public key is
  102. // acceptable for a user.
  103. type cachedPubKey struct {
  104. user string
  105. pubKeyData []byte
  106. result error
  107. perms *Permissions
  108. }
  109. const maxCachedPubKeys = 16
  110. // pubKeyCache caches tests for public keys. Since SSH clients
  111. // will query whether a public key is acceptable before attempting to
  112. // authenticate with it, we end up with duplicate queries for public
  113. // key validity. The cache only applies to a single ServerConn.
  114. type pubKeyCache struct {
  115. keys []cachedPubKey
  116. }
  117. // get returns the result for a given user/algo/key tuple.
  118. func (c *pubKeyCache) get(user string, pubKeyData []byte) (cachedPubKey, bool) {
  119. for _, k := range c.keys {
  120. if k.user == user && bytes.Equal(k.pubKeyData, pubKeyData) {
  121. return k, true
  122. }
  123. }
  124. return cachedPubKey{}, false
  125. }
  126. // add adds the given tuple to the cache.
  127. func (c *pubKeyCache) add(candidate cachedPubKey) {
  128. if len(c.keys) < maxCachedPubKeys {
  129. c.keys = append(c.keys, candidate)
  130. }
  131. }
  132. // ServerConn is an authenticated SSH connection, as seen from the
  133. // server
  134. type ServerConn struct {
  135. Conn
  136. // If the succeeding authentication callback returned a
  137. // non-nil Permissions pointer, it is stored here.
  138. Permissions *Permissions
  139. }
  140. // NewServerConn starts a new SSH server with c as the underlying
  141. // transport. It starts with a handshake and, if the handshake is
  142. // unsuccessful, it closes the connection and returns an error. The
  143. // Request and NewChannel channels must be serviced, or the connection
  144. // will hang.
  145. func NewServerConn(c net.Conn, config *ServerConfig) (*ServerConn, <-chan NewChannel, <-chan *Request, error) {
  146. fullConf := *config
  147. fullConf.SetDefaults()
  148. if fullConf.MaxAuthTries == 0 {
  149. fullConf.MaxAuthTries = 6
  150. }
  151. s := &connection{
  152. sshConn: sshConn{conn: c},
  153. }
  154. perms, err := s.serverHandshake(&fullConf)
  155. if err != nil {
  156. c.Close()
  157. return nil, nil, nil, err
  158. }
  159. return &ServerConn{s, perms}, s.mux.incomingChannels, s.mux.incomingRequests, nil
  160. }
  161. // signAndMarshal signs the data with the appropriate algorithm,
  162. // and serializes the result in SSH wire format.
  163. func signAndMarshal(k Signer, rand io.Reader, data []byte) ([]byte, error) {
  164. sig, err := k.Sign(rand, data)
  165. if err != nil {
  166. return nil, err
  167. }
  168. return Marshal(sig), nil
  169. }
  170. // handshake performs key exchange and user authentication.
  171. func (s *connection) serverHandshake(config *ServerConfig) (*Permissions, error) {
  172. if len(config.hostKeys) == 0 {
  173. return nil, errors.New("ssh: server has no host keys")
  174. }
  175. if !config.NoClientAuth && config.PasswordCallback == nil && config.PublicKeyCallback == nil && config.KeyboardInteractiveCallback == nil {
  176. return nil, errors.New("ssh: no authentication methods configured but NoClientAuth is also false")
  177. }
  178. if config.ServerVersion != "" {
  179. s.serverVersion = []byte(config.ServerVersion)
  180. } else {
  181. s.serverVersion = []byte(packageVersion)
  182. }
  183. var err error
  184. s.clientVersion, err = exchangeVersions(s.sshConn.conn, s.serverVersion)
  185. if err != nil {
  186. return nil, err
  187. }
  188. tr := newTransport(s.sshConn.conn, config.Rand, false /* not client */)
  189. s.transport = newServerTransport(tr, s.clientVersion, s.serverVersion, config)
  190. if err := s.transport.waitSession(); err != nil {
  191. return nil, err
  192. }
  193. // We just did the key change, so the session ID is established.
  194. s.sessionID = s.transport.getSessionID()
  195. var packet []byte
  196. if packet, err = s.transport.readPacket(); err != nil {
  197. return nil, err
  198. }
  199. var serviceRequest serviceRequestMsg
  200. if err = Unmarshal(packet, &serviceRequest); err != nil {
  201. return nil, err
  202. }
  203. if serviceRequest.Service != serviceUserAuth {
  204. return nil, errors.New("ssh: requested service '" + serviceRequest.Service + "' before authenticating")
  205. }
  206. serviceAccept := serviceAcceptMsg{
  207. Service: serviceUserAuth,
  208. }
  209. if err := s.transport.writePacket(Marshal(&serviceAccept)); err != nil {
  210. return nil, err
  211. }
  212. perms, err := s.serverAuthenticate(config)
  213. if err != nil {
  214. return nil, err
  215. }
  216. s.mux = newMux(s.transport)
  217. return perms, err
  218. }
  219. func isAcceptableAlgo(algo string) bool {
  220. switch algo {
  221. case KeyAlgoRSA, KeyAlgoDSA, KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521, KeyAlgoED25519,
  222. CertAlgoRSAv01, CertAlgoDSAv01, CertAlgoECDSA256v01, CertAlgoECDSA384v01, CertAlgoECDSA521v01, CertAlgoED25519v01:
  223. return true
  224. }
  225. return false
  226. }
  227. func checkSourceAddress(addr net.Addr, sourceAddrs string) error {
  228. if addr == nil {
  229. return errors.New("ssh: no address known for client, but source-address match required")
  230. }
  231. tcpAddr, ok := addr.(*net.TCPAddr)
  232. if !ok {
  233. return fmt.Errorf("ssh: remote address %v is not an TCP address when checking source-address match", addr)
  234. }
  235. for _, sourceAddr := range strings.Split(sourceAddrs, ",") {
  236. if allowedIP := net.ParseIP(sourceAddr); allowedIP != nil {
  237. if allowedIP.Equal(tcpAddr.IP) {
  238. return nil
  239. }
  240. } else {
  241. _, ipNet, err := net.ParseCIDR(sourceAddr)
  242. if err != nil {
  243. return fmt.Errorf("ssh: error parsing source-address restriction %q: %v", sourceAddr, err)
  244. }
  245. if ipNet.Contains(tcpAddr.IP) {
  246. return nil
  247. }
  248. }
  249. }
  250. return fmt.Errorf("ssh: remote address %v is not allowed because of source-address restriction", addr)
  251. }
  252. // ServerAuthError implements the error interface. It appends any authentication
  253. // errors that may occur, and is returned if all of the authentication methods
  254. // provided by the user failed to authenticate.
  255. type ServerAuthError struct {
  256. // Errors contains authentication errors returned by the authentication
  257. // callback methods.
  258. Errors []error
  259. }
  260. func (l ServerAuthError) Error() string {
  261. var errs []string
  262. for _, err := range l.Errors {
  263. errs = append(errs, err.Error())
  264. }
  265. return "[" + strings.Join(errs, ", ") + "]"
  266. }
  267. func (s *connection) serverAuthenticate(config *ServerConfig) (*Permissions, error) {
  268. sessionID := s.transport.getSessionID()
  269. var cache pubKeyCache
  270. var perms *Permissions
  271. authFailures := 0
  272. var authErrs []error
  273. var displayedBanner bool
  274. userAuthLoop:
  275. for {
  276. if authFailures >= config.MaxAuthTries && config.MaxAuthTries > 0 {
  277. discMsg := &disconnectMsg{
  278. Reason: 2,
  279. Message: "too many authentication failures",
  280. }
  281. if err := s.transport.writePacket(Marshal(discMsg)); err != nil {
  282. return nil, err
  283. }
  284. return nil, discMsg
  285. }
  286. var userAuthReq userAuthRequestMsg
  287. if packet, err := s.transport.readPacket(); err != nil {
  288. if err == io.EOF {
  289. return nil, &ServerAuthError{Errors: authErrs}
  290. }
  291. return nil, err
  292. } else if err = Unmarshal(packet, &userAuthReq); err != nil {
  293. return nil, err
  294. }
  295. if userAuthReq.Service != serviceSSH {
  296. return nil, errors.New("ssh: client attempted to negotiate for unknown service: " + userAuthReq.Service)
  297. }
  298. s.user = userAuthReq.User
  299. if !displayedBanner && config.BannerCallback != nil {
  300. displayedBanner = true
  301. msg := config.BannerCallback(s)
  302. if msg != "" {
  303. bannerMsg := &userAuthBannerMsg{
  304. Message: msg,
  305. }
  306. if err := s.transport.writePacket(Marshal(bannerMsg)); err != nil {
  307. return nil, err
  308. }
  309. }
  310. }
  311. perms = nil
  312. authErr := errors.New("no auth passed yet")
  313. switch userAuthReq.Method {
  314. case "none":
  315. if config.NoClientAuth {
  316. authErr = nil
  317. }
  318. // allow initial attempt of 'none' without penalty
  319. if authFailures == 0 {
  320. authFailures--
  321. }
  322. case "password":
  323. if config.PasswordCallback == nil {
  324. authErr = errors.New("ssh: password auth not configured")
  325. break
  326. }
  327. payload := userAuthReq.Payload
  328. if len(payload) < 1 || payload[0] != 0 {
  329. return nil, parseError(msgUserAuthRequest)
  330. }
  331. payload = payload[1:]
  332. password, payload, ok := parseString(payload)
  333. if !ok || len(payload) > 0 {
  334. return nil, parseError(msgUserAuthRequest)
  335. }
  336. perms, authErr = config.PasswordCallback(s, password)
  337. case "keyboard-interactive":
  338. if config.KeyboardInteractiveCallback == nil {
  339. authErr = errors.New("ssh: keyboard-interactive auth not configubred")
  340. break
  341. }
  342. prompter := &sshClientKeyboardInteractive{s}
  343. perms, authErr = config.KeyboardInteractiveCallback(s, prompter.Challenge)
  344. case "publickey":
  345. if config.PublicKeyCallback == nil {
  346. authErr = errors.New("ssh: publickey auth not configured")
  347. break
  348. }
  349. payload := userAuthReq.Payload
  350. if len(payload) < 1 {
  351. return nil, parseError(msgUserAuthRequest)
  352. }
  353. isQuery := payload[0] == 0
  354. payload = payload[1:]
  355. algoBytes, payload, ok := parseString(payload)
  356. if !ok {
  357. return nil, parseError(msgUserAuthRequest)
  358. }
  359. algo := string(algoBytes)
  360. if !isAcceptableAlgo(algo) {
  361. authErr = fmt.Errorf("ssh: algorithm %q not accepted", algo)
  362. break
  363. }
  364. pubKeyData, payload, ok := parseString(payload)
  365. if !ok {
  366. return nil, parseError(msgUserAuthRequest)
  367. }
  368. pubKey, err := ParsePublicKey(pubKeyData)
  369. if err != nil {
  370. return nil, err
  371. }
  372. candidate, ok := cache.get(s.user, pubKeyData)
  373. if !ok {
  374. candidate.user = s.user
  375. candidate.pubKeyData = pubKeyData
  376. candidate.perms, candidate.result = config.PublicKeyCallback(s, pubKey)
  377. if candidate.result == nil && candidate.perms != nil && candidate.perms.CriticalOptions != nil && candidate.perms.CriticalOptions[sourceAddressCriticalOption] != "" {
  378. candidate.result = checkSourceAddress(
  379. s.RemoteAddr(),
  380. candidate.perms.CriticalOptions[sourceAddressCriticalOption])
  381. }
  382. cache.add(candidate)
  383. }
  384. if isQuery {
  385. // The client can query if the given public key
  386. // would be okay.
  387. if len(payload) > 0 {
  388. return nil, parseError(msgUserAuthRequest)
  389. }
  390. if candidate.result == nil {
  391. okMsg := userAuthPubKeyOkMsg{
  392. Algo: algo,
  393. PubKey: pubKeyData,
  394. }
  395. if err = s.transport.writePacket(Marshal(&okMsg)); err != nil {
  396. return nil, err
  397. }
  398. continue userAuthLoop
  399. }
  400. authErr = candidate.result
  401. } else {
  402. sig, payload, ok := parseSignature(payload)
  403. if !ok || len(payload) > 0 {
  404. return nil, parseError(msgUserAuthRequest)
  405. }
  406. // Ensure the public key algo and signature algo
  407. // are supported. Compare the private key
  408. // algorithm name that corresponds to algo with
  409. // sig.Format. This is usually the same, but
  410. // for certs, the names differ.
  411. if !isAcceptableAlgo(sig.Format) {
  412. break
  413. }
  414. signedData := buildDataSignedForAuth(sessionID, userAuthReq, algoBytes, pubKeyData)
  415. if err := pubKey.Verify(signedData, sig); err != nil {
  416. return nil, err
  417. }
  418. authErr = candidate.result
  419. perms = candidate.perms
  420. }
  421. default:
  422. authErr = fmt.Errorf("ssh: unknown method %q", userAuthReq.Method)
  423. }
  424. authErrs = append(authErrs, authErr)
  425. if config.AuthLogCallback != nil {
  426. config.AuthLogCallback(s, userAuthReq.Method, authErr)
  427. }
  428. if authErr == nil {
  429. break userAuthLoop
  430. }
  431. authFailures++
  432. var failureMsg userAuthFailureMsg
  433. if config.PasswordCallback != nil {
  434. failureMsg.Methods = append(failureMsg.Methods, "password")
  435. }
  436. if config.PublicKeyCallback != nil {
  437. failureMsg.Methods = append(failureMsg.Methods, "publickey")
  438. }
  439. if config.KeyboardInteractiveCallback != nil {
  440. failureMsg.Methods = append(failureMsg.Methods, "keyboard-interactive")
  441. }
  442. if len(failureMsg.Methods) == 0 {
  443. return nil, errors.New("ssh: no authentication methods configured but NoClientAuth is also false")
  444. }
  445. if err := s.transport.writePacket(Marshal(&failureMsg)); err != nil {
  446. return nil, err
  447. }
  448. }
  449. if err := s.transport.writePacket([]byte{msgUserAuthSuccess}); err != nil {
  450. return nil, err
  451. }
  452. return perms, nil
  453. }
  454. // sshClientKeyboardInteractive implements a ClientKeyboardInteractive by
  455. // asking the client on the other side of a ServerConn.
  456. type sshClientKeyboardInteractive struct {
  457. *connection
  458. }
  459. func (c *sshClientKeyboardInteractive) Challenge(user, instruction string, questions []string, echos []bool) (answers []string, err error) {
  460. if len(questions) != len(echos) {
  461. return nil, errors.New("ssh: echos and questions must have equal length")
  462. }
  463. var prompts []byte
  464. for i := range questions {
  465. prompts = appendString(prompts, questions[i])
  466. prompts = appendBool(prompts, echos[i])
  467. }
  468. if err := c.transport.writePacket(Marshal(&userAuthInfoRequestMsg{
  469. Instruction: instruction,
  470. NumPrompts: uint32(len(questions)),
  471. Prompts: prompts,
  472. })); err != nil {
  473. return nil, err
  474. }
  475. packet, err := c.transport.readPacket()
  476. if err != nil {
  477. return nil, err
  478. }
  479. if packet[0] != msgUserAuthInfoResponse {
  480. return nil, unexpectedMessageError(msgUserAuthInfoResponse, packet[0])
  481. }
  482. packet = packet[1:]
  483. n, packet, ok := parseUint32(packet)
  484. if !ok || int(n) != len(questions) {
  485. return nil, parseError(msgUserAuthInfoResponse)
  486. }
  487. for i := uint32(0); i < n; i++ {
  488. ans, rest, ok := parseString(packet)
  489. if !ok {
  490. return nil, parseError(msgUserAuthInfoResponse)
  491. }
  492. answers = append(answers, string(ans))
  493. packet = rest
  494. }
  495. if len(packet) != 0 {
  496. return nil, errors.New("ssh: junk at end of message")
  497. }
  498. return answers, nil
  499. }