server.go 15 KB

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