server.go 14 KB

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