server.go 14 KB

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