server.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  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. The first entry typically is NoAuthError.
  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. // NoAuthError is the unique error that is returned if no
  268. // authentication method has been passed yet. This happens as a normal
  269. // part of the authentication loop, since the client first tries
  270. // 'none' authentication to discover available methods.
  271. var NoAuthError = errors.New("ssh: no auth passed yet")
  272. func (s *connection) serverAuthenticate(config *ServerConfig) (*Permissions, error) {
  273. sessionID := s.transport.getSessionID()
  274. var cache pubKeyCache
  275. var perms *Permissions
  276. authFailures := 0
  277. var authErrs []error
  278. var displayedBanner bool
  279. userAuthLoop:
  280. for {
  281. if authFailures >= config.MaxAuthTries && config.MaxAuthTries > 0 {
  282. discMsg := &disconnectMsg{
  283. Reason: 2,
  284. Message: "too many authentication failures",
  285. }
  286. if err := s.transport.writePacket(Marshal(discMsg)); err != nil {
  287. return nil, err
  288. }
  289. return nil, discMsg
  290. }
  291. var userAuthReq userAuthRequestMsg
  292. if packet, err := s.transport.readPacket(); err != nil {
  293. if err == io.EOF {
  294. return nil, &ServerAuthError{Errors: authErrs}
  295. }
  296. return nil, err
  297. } else if err = Unmarshal(packet, &userAuthReq); err != nil {
  298. return nil, err
  299. }
  300. if userAuthReq.Service != serviceSSH {
  301. return nil, errors.New("ssh: client attempted to negotiate for unknown service: " + userAuthReq.Service)
  302. }
  303. s.user = userAuthReq.User
  304. if !displayedBanner && config.BannerCallback != nil {
  305. displayedBanner = true
  306. msg := config.BannerCallback(s)
  307. if msg != "" {
  308. bannerMsg := &userAuthBannerMsg{
  309. Message: msg,
  310. }
  311. if err := s.transport.writePacket(Marshal(bannerMsg)); err != nil {
  312. return nil, err
  313. }
  314. }
  315. }
  316. perms = nil
  317. authErr := NoAuthError
  318. switch userAuthReq.Method {
  319. case "none":
  320. if config.NoClientAuth {
  321. authErr = nil
  322. }
  323. // allow initial attempt of 'none' without penalty
  324. if authFailures == 0 {
  325. authFailures--
  326. }
  327. case "password":
  328. if config.PasswordCallback == nil {
  329. authErr = errors.New("ssh: password auth not configured")
  330. break
  331. }
  332. payload := userAuthReq.Payload
  333. if len(payload) < 1 || payload[0] != 0 {
  334. return nil, parseError(msgUserAuthRequest)
  335. }
  336. payload = payload[1:]
  337. password, payload, ok := parseString(payload)
  338. if !ok || len(payload) > 0 {
  339. return nil, parseError(msgUserAuthRequest)
  340. }
  341. perms, authErr = config.PasswordCallback(s, password)
  342. case "keyboard-interactive":
  343. if config.KeyboardInteractiveCallback == nil {
  344. authErr = errors.New("ssh: keyboard-interactive auth not configubred")
  345. break
  346. }
  347. prompter := &sshClientKeyboardInteractive{s}
  348. perms, authErr = config.KeyboardInteractiveCallback(s, prompter.Challenge)
  349. case "publickey":
  350. if config.PublicKeyCallback == nil {
  351. authErr = errors.New("ssh: publickey auth not configured")
  352. break
  353. }
  354. payload := userAuthReq.Payload
  355. if len(payload) < 1 {
  356. return nil, parseError(msgUserAuthRequest)
  357. }
  358. isQuery := payload[0] == 0
  359. payload = payload[1:]
  360. algoBytes, payload, ok := parseString(payload)
  361. if !ok {
  362. return nil, parseError(msgUserAuthRequest)
  363. }
  364. algo := string(algoBytes)
  365. if !isAcceptableAlgo(algo) {
  366. authErr = fmt.Errorf("ssh: algorithm %q not accepted", algo)
  367. break
  368. }
  369. pubKeyData, payload, ok := parseString(payload)
  370. if !ok {
  371. return nil, parseError(msgUserAuthRequest)
  372. }
  373. pubKey, err := ParsePublicKey(pubKeyData)
  374. if err != nil {
  375. return nil, err
  376. }
  377. candidate, ok := cache.get(s.user, pubKeyData)
  378. if !ok {
  379. candidate.user = s.user
  380. candidate.pubKeyData = pubKeyData
  381. candidate.perms, candidate.result = config.PublicKeyCallback(s, pubKey)
  382. if candidate.result == nil && candidate.perms != nil && candidate.perms.CriticalOptions != nil && candidate.perms.CriticalOptions[sourceAddressCriticalOption] != "" {
  383. candidate.result = checkSourceAddress(
  384. s.RemoteAddr(),
  385. candidate.perms.CriticalOptions[sourceAddressCriticalOption])
  386. }
  387. cache.add(candidate)
  388. }
  389. if isQuery {
  390. // The client can query if the given public key
  391. // would be okay.
  392. if len(payload) > 0 {
  393. return nil, parseError(msgUserAuthRequest)
  394. }
  395. if candidate.result == nil {
  396. okMsg := userAuthPubKeyOkMsg{
  397. Algo: algo,
  398. PubKey: pubKeyData,
  399. }
  400. if err = s.transport.writePacket(Marshal(&okMsg)); err != nil {
  401. return nil, err
  402. }
  403. continue userAuthLoop
  404. }
  405. authErr = candidate.result
  406. } else {
  407. sig, payload, ok := parseSignature(payload)
  408. if !ok || len(payload) > 0 {
  409. return nil, parseError(msgUserAuthRequest)
  410. }
  411. // Ensure the public key algo and signature algo
  412. // are supported. Compare the private key
  413. // algorithm name that corresponds to algo with
  414. // sig.Format. This is usually the same, but
  415. // for certs, the names differ.
  416. if !isAcceptableAlgo(sig.Format) {
  417. break
  418. }
  419. signedData := buildDataSignedForAuth(sessionID, userAuthReq, algoBytes, pubKeyData)
  420. if err := pubKey.Verify(signedData, sig); err != nil {
  421. return nil, err
  422. }
  423. authErr = candidate.result
  424. perms = candidate.perms
  425. }
  426. default:
  427. authErr = fmt.Errorf("ssh: unknown method %q", userAuthReq.Method)
  428. }
  429. authErrs = append(authErrs, authErr)
  430. if config.AuthLogCallback != nil {
  431. config.AuthLogCallback(s, userAuthReq.Method, authErr)
  432. }
  433. if authErr == nil {
  434. break userAuthLoop
  435. }
  436. authFailures++
  437. var failureMsg userAuthFailureMsg
  438. if config.PasswordCallback != nil {
  439. failureMsg.Methods = append(failureMsg.Methods, "password")
  440. }
  441. if config.PublicKeyCallback != nil {
  442. failureMsg.Methods = append(failureMsg.Methods, "publickey")
  443. }
  444. if config.KeyboardInteractiveCallback != nil {
  445. failureMsg.Methods = append(failureMsg.Methods, "keyboard-interactive")
  446. }
  447. if len(failureMsg.Methods) == 0 {
  448. return nil, errors.New("ssh: no authentication methods configured but NoClientAuth is also false")
  449. }
  450. if err := s.transport.writePacket(Marshal(&failureMsg)); err != nil {
  451. return nil, err
  452. }
  453. }
  454. if err := s.transport.writePacket([]byte{msgUserAuthSuccess}); err != nil {
  455. return nil, err
  456. }
  457. return perms, nil
  458. }
  459. // sshClientKeyboardInteractive implements a ClientKeyboardInteractive by
  460. // asking the client on the other side of a ServerConn.
  461. type sshClientKeyboardInteractive struct {
  462. *connection
  463. }
  464. func (c *sshClientKeyboardInteractive) Challenge(user, instruction string, questions []string, echos []bool) (answers []string, err error) {
  465. if len(questions) != len(echos) {
  466. return nil, errors.New("ssh: echos and questions must have equal length")
  467. }
  468. var prompts []byte
  469. for i := range questions {
  470. prompts = appendString(prompts, questions[i])
  471. prompts = appendBool(prompts, echos[i])
  472. }
  473. if err := c.transport.writePacket(Marshal(&userAuthInfoRequestMsg{
  474. Instruction: instruction,
  475. NumPrompts: uint32(len(questions)),
  476. Prompts: prompts,
  477. })); err != nil {
  478. return nil, err
  479. }
  480. packet, err := c.transport.readPacket()
  481. if err != nil {
  482. return nil, err
  483. }
  484. if packet[0] != msgUserAuthInfoResponse {
  485. return nil, unexpectedMessageError(msgUserAuthInfoResponse, packet[0])
  486. }
  487. packet = packet[1:]
  488. n, packet, ok := parseUint32(packet)
  489. if !ok || int(n) != len(questions) {
  490. return nil, parseError(msgUserAuthInfoResponse)
  491. }
  492. for i := uint32(0); i < n; i++ {
  493. ans, rest, ok := parseString(packet)
  494. if !ok {
  495. return nil, parseError(msgUserAuthInfoResponse)
  496. }
  497. answers = append(answers, string(ans))
  498. packet = rest
  499. }
  500. if len(packet) != 0 {
  501. return nil, errors.New("ssh: junk at end of message")
  502. }
  503. return answers, nil
  504. }