server.go 15 KB

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