server.go 14 KB

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