server.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  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. "crypto/rand"
  8. "encoding/binary"
  9. "errors"
  10. "fmt"
  11. "io"
  12. "net"
  13. "sync"
  14. _ "crypto/sha1"
  15. )
  16. type ServerConfig struct {
  17. hostKeys []Signer
  18. // Rand provides the source of entropy for key exchange. If Rand is
  19. // nil, the cryptographic random reader in package crypto/rand will
  20. // be used.
  21. Rand io.Reader
  22. // NoClientAuth is true if clients are allowed to connect without
  23. // authenticating.
  24. NoClientAuth bool
  25. // PasswordCallback, if non-nil, is called when a user attempts to
  26. // authenticate using a password. It may be called concurrently from
  27. // several goroutines.
  28. PasswordCallback func(conn *ServerConn, user, password string) bool
  29. // PublicKeyCallback, if non-nil, is called when a client attempts public
  30. // key authentication. It must return true if the given public key is
  31. // valid for the given user.
  32. PublicKeyCallback func(conn *ServerConn, user, algo string, pubkey []byte) bool
  33. // KeyboardInteractiveCallback, if non-nil, is called when
  34. // keyboard-interactive authentication is selected (RFC
  35. // 4256). The client object's Challenge function should be
  36. // used to query the user. The callback may offer multiple
  37. // Challenge rounds. To avoid information leaks, the client
  38. // should be presented a challenge even if the user is
  39. // unknown.
  40. KeyboardInteractiveCallback func(conn *ServerConn, user string, client ClientKeyboardInteractive) bool
  41. // Cryptographic-related configuration.
  42. Crypto CryptoConfig
  43. }
  44. func (c *ServerConfig) rand() io.Reader {
  45. if c.Rand == nil {
  46. return rand.Reader
  47. }
  48. return c.Rand
  49. }
  50. // AddHostKey adds a private key as a host key. If an existing host
  51. // key exists with the same algorithm, it is overwritten.
  52. func (s *ServerConfig) AddHostKey(key Signer) {
  53. for i, k := range s.hostKeys {
  54. if k.PublicKey().PublicKeyAlgo() == key.PublicKey().PublicKeyAlgo() {
  55. s.hostKeys[i] = key
  56. return
  57. }
  58. }
  59. s.hostKeys = append(s.hostKeys, key)
  60. }
  61. // SetRSAPrivateKey sets the private key for a Server. A Server must have a
  62. // private key configured in order to accept connections. The private key must
  63. // be in the form of a PEM encoded, PKCS#1, RSA private key. The file "id_rsa"
  64. // typically contains such a key.
  65. func (s *ServerConfig) SetRSAPrivateKey(pemBytes []byte) error {
  66. priv, err := ParsePrivateKey(pemBytes)
  67. if err != nil {
  68. return err
  69. }
  70. s.AddHostKey(priv)
  71. return nil
  72. }
  73. // cachedPubKey contains the results of querying whether a public key is
  74. // acceptable for a user. The cache only applies to a single ServerConn.
  75. type cachedPubKey struct {
  76. user, algo string
  77. pubKey []byte
  78. result bool
  79. }
  80. const maxCachedPubKeys = 16
  81. // A ServerConn represents an incoming connection.
  82. type ServerConn struct {
  83. *transport
  84. config *ServerConfig
  85. channels map[uint32]*serverChan
  86. nextChanId uint32
  87. // lock protects err and channels.
  88. lock sync.Mutex
  89. err error
  90. // cachedPubKeys contains the cache results of tests for public keys.
  91. // Since SSH clients will query whether a public key is acceptable
  92. // before attempting to authenticate with it, we end up with duplicate
  93. // queries for public key validity.
  94. cachedPubKeys []cachedPubKey
  95. // User holds the successfully authenticated user name.
  96. // It is empty if no authentication is used. It is populated before
  97. // any authentication callback is called and not assigned to after that.
  98. User string
  99. // ClientVersion is the client's version, populated after
  100. // Handshake is called. It should not be modified.
  101. ClientVersion []byte
  102. // Our version.
  103. serverVersion []byte
  104. }
  105. // Server returns a new SSH server connection
  106. // using c as the underlying transport.
  107. func Server(c net.Conn, config *ServerConfig) *ServerConn {
  108. return &ServerConn{
  109. transport: newTransport(c, config.rand(), false /* not client */),
  110. channels: make(map[uint32]*serverChan),
  111. config: config,
  112. }
  113. }
  114. // signAndMarshal signs the data with the appropriate algorithm,
  115. // and serializes the result in SSH wire format.
  116. func signAndMarshal(k Signer, rand io.Reader, data []byte) ([]byte, error) {
  117. sig, err := k.Sign(rand, data)
  118. if err != nil {
  119. return nil, err
  120. }
  121. return serializeSignature(k.PublicKey().PrivateKeyAlgo(), sig), nil
  122. }
  123. // Handshake performs an SSH transport and client authentication on the given ServerConn.
  124. func (s *ServerConn) Handshake() error {
  125. var err error
  126. s.serverVersion = []byte(packageVersion)
  127. s.ClientVersion, err = exchangeVersions(s.transport.Conn, s.serverVersion)
  128. if err != nil {
  129. return err
  130. }
  131. if err := s.clientInitHandshake(nil, nil); err != nil {
  132. return err
  133. }
  134. var packet []byte
  135. if packet, err = s.readPacket(); err != nil {
  136. return err
  137. }
  138. var serviceRequest serviceRequestMsg
  139. if err := unmarshal(&serviceRequest, packet, msgServiceRequest); err != nil {
  140. return err
  141. }
  142. if serviceRequest.Service != serviceUserAuth {
  143. return errors.New("ssh: requested service '" + serviceRequest.Service + "' before authenticating")
  144. }
  145. serviceAccept := serviceAcceptMsg{
  146. Service: serviceUserAuth,
  147. }
  148. if err := s.writePacket(marshal(msgServiceAccept, serviceAccept)); err != nil {
  149. return err
  150. }
  151. if err := s.authenticate(s.transport.sessionID); err != nil {
  152. return err
  153. }
  154. return err
  155. }
  156. func (s *ServerConn) clientInitHandshake(clientKexInit *kexInitMsg, clientKexInitPacket []byte) (err error) {
  157. serverKexInit := kexInitMsg{
  158. KexAlgos: s.config.Crypto.kexes(),
  159. CiphersClientServer: s.config.Crypto.ciphers(),
  160. CiphersServerClient: s.config.Crypto.ciphers(),
  161. MACsClientServer: s.config.Crypto.macs(),
  162. MACsServerClient: s.config.Crypto.macs(),
  163. CompressionClientServer: supportedCompressions,
  164. CompressionServerClient: supportedCompressions,
  165. }
  166. for _, k := range s.config.hostKeys {
  167. serverKexInit.ServerHostKeyAlgos = append(
  168. serverKexInit.ServerHostKeyAlgos, k.PublicKey().PublicKeyAlgo())
  169. }
  170. serverKexInitPacket := marshal(msgKexInit, serverKexInit)
  171. if err = s.writePacket(serverKexInitPacket); err != nil {
  172. return
  173. }
  174. if clientKexInitPacket == nil {
  175. clientKexInit = new(kexInitMsg)
  176. if clientKexInitPacket, err = s.readPacket(); err != nil {
  177. return
  178. }
  179. if err = unmarshal(clientKexInit, clientKexInitPacket, msgKexInit); err != nil {
  180. return
  181. }
  182. }
  183. algs := findAgreedAlgorithms(clientKexInit, &serverKexInit)
  184. if algs == nil {
  185. return errors.New("ssh: no common algorithms")
  186. }
  187. if clientKexInit.FirstKexFollows && algs.kex != clientKexInit.KexAlgos[0] {
  188. // The client sent a Kex message for the wrong algorithm,
  189. // which we have to ignore.
  190. if _, err = s.readPacket(); err != nil {
  191. return
  192. }
  193. }
  194. var hostKey Signer
  195. for _, k := range s.config.hostKeys {
  196. if algs.hostKey == k.PublicKey().PublicKeyAlgo() {
  197. hostKey = k
  198. }
  199. }
  200. kex, ok := kexAlgoMap[algs.kex]
  201. if !ok {
  202. return fmt.Errorf("ssh: unexpected key exchange algorithm %v", algs.kex)
  203. }
  204. magics := handshakeMagics{
  205. serverVersion: s.serverVersion,
  206. clientVersion: s.ClientVersion,
  207. serverKexInit: marshal(msgKexInit, serverKexInit),
  208. clientKexInit: clientKexInitPacket,
  209. }
  210. result, err := kex.Server(s, s.config.rand(), &magics, hostKey)
  211. if err != nil {
  212. return err
  213. }
  214. if err = s.transport.prepareKeyChange(algs, result); err != nil {
  215. return err
  216. }
  217. if err = s.writePacket([]byte{msgNewKeys}); err != nil {
  218. return
  219. }
  220. if packet, err := s.readPacket(); err != nil {
  221. return err
  222. } else if packet[0] != msgNewKeys {
  223. return UnexpectedMessageError{msgNewKeys, packet[0]}
  224. }
  225. return
  226. }
  227. func isAcceptableAlgo(algo string) bool {
  228. switch algo {
  229. case KeyAlgoRSA, KeyAlgoDSA, KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521,
  230. CertAlgoRSAv01, CertAlgoDSAv01, CertAlgoECDSA256v01, CertAlgoECDSA384v01, CertAlgoECDSA521v01:
  231. return true
  232. }
  233. return false
  234. }
  235. // testPubKey returns true if the given public key is acceptable for the user.
  236. func (s *ServerConn) testPubKey(user, algo string, pubKey []byte) bool {
  237. if s.config.PublicKeyCallback == nil || !isAcceptableAlgo(algo) {
  238. return false
  239. }
  240. for _, c := range s.cachedPubKeys {
  241. if c.user == user && c.algo == algo && bytes.Equal(c.pubKey, pubKey) {
  242. return c.result
  243. }
  244. }
  245. result := s.config.PublicKeyCallback(s, user, algo, pubKey)
  246. if len(s.cachedPubKeys) < maxCachedPubKeys {
  247. c := cachedPubKey{
  248. user: user,
  249. algo: algo,
  250. pubKey: make([]byte, len(pubKey)),
  251. result: result,
  252. }
  253. copy(c.pubKey, pubKey)
  254. s.cachedPubKeys = append(s.cachedPubKeys, c)
  255. }
  256. return result
  257. }
  258. func (s *ServerConn) authenticate(H []byte) error {
  259. var userAuthReq userAuthRequestMsg
  260. var err error
  261. var packet []byte
  262. userAuthLoop:
  263. for {
  264. if packet, err = s.readPacket(); err != nil {
  265. return err
  266. }
  267. if err = unmarshal(&userAuthReq, packet, msgUserAuthRequest); err != nil {
  268. return err
  269. }
  270. if userAuthReq.Service != serviceSSH {
  271. return errors.New("ssh: client attempted to negotiate for unknown service: " + userAuthReq.Service)
  272. }
  273. switch userAuthReq.Method {
  274. case "none":
  275. if s.config.NoClientAuth {
  276. break userAuthLoop
  277. }
  278. case "password":
  279. if s.config.PasswordCallback == nil {
  280. break
  281. }
  282. payload := userAuthReq.Payload
  283. if len(payload) < 1 || payload[0] != 0 {
  284. return ParseError{msgUserAuthRequest}
  285. }
  286. payload = payload[1:]
  287. password, payload, ok := parseString(payload)
  288. if !ok || len(payload) > 0 {
  289. return ParseError{msgUserAuthRequest}
  290. }
  291. s.User = userAuthReq.User
  292. if s.config.PasswordCallback(s, userAuthReq.User, string(password)) {
  293. break userAuthLoop
  294. }
  295. case "keyboard-interactive":
  296. if s.config.KeyboardInteractiveCallback == nil {
  297. break
  298. }
  299. s.User = userAuthReq.User
  300. if s.config.KeyboardInteractiveCallback(s, s.User, &sshClientKeyboardInteractive{s}) {
  301. break userAuthLoop
  302. }
  303. case "publickey":
  304. if s.config.PublicKeyCallback == nil {
  305. break
  306. }
  307. payload := userAuthReq.Payload
  308. if len(payload) < 1 {
  309. return ParseError{msgUserAuthRequest}
  310. }
  311. isQuery := payload[0] == 0
  312. payload = payload[1:]
  313. algoBytes, payload, ok := parseString(payload)
  314. if !ok {
  315. return ParseError{msgUserAuthRequest}
  316. }
  317. algo := string(algoBytes)
  318. pubKey, payload, ok := parseString(payload)
  319. if !ok {
  320. return ParseError{msgUserAuthRequest}
  321. }
  322. if isQuery {
  323. // The client can query if the given public key
  324. // would be okay.
  325. if len(payload) > 0 {
  326. return ParseError{msgUserAuthRequest}
  327. }
  328. if s.testPubKey(userAuthReq.User, algo, pubKey) {
  329. okMsg := userAuthPubKeyOkMsg{
  330. Algo: algo,
  331. PubKey: string(pubKey),
  332. }
  333. if err = s.writePacket(marshal(msgUserAuthPubKeyOk, okMsg)); err != nil {
  334. return err
  335. }
  336. continue userAuthLoop
  337. }
  338. } else {
  339. sig, payload, ok := parseSignature(payload)
  340. if !ok || len(payload) > 0 {
  341. return ParseError{msgUserAuthRequest}
  342. }
  343. // Ensure the public key algo and signature algo
  344. // are supported. Compare the private key
  345. // algorithm name that corresponds to algo with
  346. // sig.Format. This is usually the same, but
  347. // for certs, the names differ.
  348. if !isAcceptableAlgo(algo) || !isAcceptableAlgo(sig.Format) || pubAlgoToPrivAlgo(algo) != sig.Format {
  349. break
  350. }
  351. signedData := buildDataSignedForAuth(H, userAuthReq, algoBytes, pubKey)
  352. key, _, ok := ParsePublicKey(pubKey)
  353. if !ok {
  354. return ParseError{msgUserAuthRequest}
  355. }
  356. if !key.Verify(signedData, sig.Blob) {
  357. return ParseError{msgUserAuthRequest}
  358. }
  359. // TODO(jmpittman): Implement full validation for certificates.
  360. s.User = userAuthReq.User
  361. if s.testPubKey(userAuthReq.User, algo, pubKey) {
  362. break userAuthLoop
  363. }
  364. }
  365. }
  366. var failureMsg userAuthFailureMsg
  367. if s.config.PasswordCallback != nil {
  368. failureMsg.Methods = append(failureMsg.Methods, "password")
  369. }
  370. if s.config.PublicKeyCallback != nil {
  371. failureMsg.Methods = append(failureMsg.Methods, "publickey")
  372. }
  373. if s.config.KeyboardInteractiveCallback != nil {
  374. failureMsg.Methods = append(failureMsg.Methods, "keyboard-interactive")
  375. }
  376. if len(failureMsg.Methods) == 0 {
  377. return errors.New("ssh: no authentication methods configured but NoClientAuth is also false")
  378. }
  379. if err = s.writePacket(marshal(msgUserAuthFailure, failureMsg)); err != nil {
  380. return err
  381. }
  382. }
  383. packet = []byte{msgUserAuthSuccess}
  384. if err = s.writePacket(packet); err != nil {
  385. return err
  386. }
  387. return nil
  388. }
  389. // sshClientKeyboardInteractive implements a ClientKeyboardInteractive by
  390. // asking the client on the other side of a ServerConn.
  391. type sshClientKeyboardInteractive struct {
  392. *ServerConn
  393. }
  394. func (c *sshClientKeyboardInteractive) Challenge(user, instruction string, questions []string, echos []bool) (answers []string, err error) {
  395. if len(questions) != len(echos) {
  396. return nil, errors.New("ssh: echos and questions must have equal length")
  397. }
  398. var prompts []byte
  399. for i := range questions {
  400. prompts = appendString(prompts, questions[i])
  401. prompts = appendBool(prompts, echos[i])
  402. }
  403. if err := c.writePacket(marshal(msgUserAuthInfoRequest, userAuthInfoRequestMsg{
  404. Instruction: instruction,
  405. NumPrompts: uint32(len(questions)),
  406. Prompts: prompts,
  407. })); err != nil {
  408. return nil, err
  409. }
  410. packet, err := c.readPacket()
  411. if err != nil {
  412. return nil, err
  413. }
  414. if packet[0] != msgUserAuthInfoResponse {
  415. return nil, UnexpectedMessageError{msgUserAuthInfoResponse, packet[0]}
  416. }
  417. packet = packet[1:]
  418. n, packet, ok := parseUint32(packet)
  419. if !ok || int(n) != len(questions) {
  420. return nil, &ParseError{msgUserAuthInfoResponse}
  421. }
  422. for i := uint32(0); i < n; i++ {
  423. ans, rest, ok := parseString(packet)
  424. if !ok {
  425. return nil, &ParseError{msgUserAuthInfoResponse}
  426. }
  427. answers = append(answers, string(ans))
  428. packet = rest
  429. }
  430. if len(packet) != 0 {
  431. return nil, errors.New("ssh: junk at end of message")
  432. }
  433. return answers, nil
  434. }
  435. const defaultWindowSize = 32768
  436. // Accept reads and processes messages on a ServerConn. It must be called
  437. // in order to demultiplex messages to any resulting Channels.
  438. func (s *ServerConn) Accept() (Channel, error) {
  439. // TODO(dfc) s.lock is not held here so visibility of s.err is not guaranteed.
  440. if s.err != nil {
  441. return nil, s.err
  442. }
  443. for {
  444. packet, err := s.readPacket()
  445. if err != nil {
  446. s.lock.Lock()
  447. s.err = err
  448. s.lock.Unlock()
  449. // TODO(dfc) s.lock protects s.channels but isn't being held here.
  450. for _, c := range s.channels {
  451. c.setDead()
  452. c.handleData(nil)
  453. }
  454. return nil, err
  455. }
  456. switch packet[0] {
  457. case msgChannelData:
  458. if len(packet) < 9 {
  459. // malformed data packet
  460. return nil, ParseError{msgChannelData}
  461. }
  462. remoteId := binary.BigEndian.Uint32(packet[1:5])
  463. s.lock.Lock()
  464. c, ok := s.channels[remoteId]
  465. if !ok {
  466. s.lock.Unlock()
  467. continue
  468. }
  469. if length := binary.BigEndian.Uint32(packet[5:9]); length > 0 {
  470. packet = packet[9:]
  471. c.handleData(packet[:length])
  472. }
  473. s.lock.Unlock()
  474. default:
  475. decoded, err := decode(packet)
  476. if err != nil {
  477. return nil, err
  478. }
  479. switch msg := decoded.(type) {
  480. case *channelOpenMsg:
  481. if msg.MaxPacketSize < minPacketLength || msg.MaxPacketSize > 1<<31 {
  482. return nil, errors.New("ssh: invalid MaxPacketSize from peer")
  483. }
  484. c := &serverChan{
  485. channel: channel{
  486. packetConn: s,
  487. remoteId: msg.PeersId,
  488. remoteWin: window{Cond: newCond()},
  489. maxPacket: msg.MaxPacketSize,
  490. },
  491. chanType: msg.ChanType,
  492. extraData: msg.TypeSpecificData,
  493. myWindow: defaultWindowSize,
  494. serverConn: s,
  495. cond: newCond(),
  496. pendingData: make([]byte, defaultWindowSize),
  497. }
  498. c.remoteWin.add(msg.PeersWindow)
  499. s.lock.Lock()
  500. c.localId = s.nextChanId
  501. s.nextChanId++
  502. s.channels[c.localId] = c
  503. s.lock.Unlock()
  504. return c, nil
  505. case *channelRequestMsg:
  506. s.lock.Lock()
  507. c, ok := s.channels[msg.PeersId]
  508. if !ok {
  509. s.lock.Unlock()
  510. continue
  511. }
  512. c.handlePacket(msg)
  513. s.lock.Unlock()
  514. case *windowAdjustMsg:
  515. s.lock.Lock()
  516. c, ok := s.channels[msg.PeersId]
  517. if !ok {
  518. s.lock.Unlock()
  519. continue
  520. }
  521. c.handlePacket(msg)
  522. s.lock.Unlock()
  523. case *channelEOFMsg:
  524. s.lock.Lock()
  525. c, ok := s.channels[msg.PeersId]
  526. if !ok {
  527. s.lock.Unlock()
  528. continue
  529. }
  530. c.handlePacket(msg)
  531. s.lock.Unlock()
  532. case *channelCloseMsg:
  533. s.lock.Lock()
  534. c, ok := s.channels[msg.PeersId]
  535. if !ok {
  536. s.lock.Unlock()
  537. continue
  538. }
  539. c.handlePacket(msg)
  540. s.lock.Unlock()
  541. case *globalRequestMsg:
  542. if msg.WantReply {
  543. if err := s.writePacket([]byte{msgRequestFailure}); err != nil {
  544. return nil, err
  545. }
  546. }
  547. case *kexInitMsg:
  548. s.lock.Lock()
  549. if err := s.clientInitHandshake(msg, packet); err != nil {
  550. s.lock.Unlock()
  551. return nil, err
  552. }
  553. s.lock.Unlock()
  554. case *disconnectMsg:
  555. return nil, io.EOF
  556. default:
  557. // Unknown message. Ignore.
  558. }
  559. }
  560. }
  561. panic("unreachable")
  562. }
  563. // A Listener implements a network listener (net.Listener) for SSH connections.
  564. type Listener struct {
  565. listener net.Listener
  566. config *ServerConfig
  567. }
  568. // Addr returns the listener's network address.
  569. func (l *Listener) Addr() net.Addr {
  570. return l.listener.Addr()
  571. }
  572. // Close closes the listener.
  573. func (l *Listener) Close() error {
  574. return l.listener.Close()
  575. }
  576. // Accept waits for and returns the next incoming SSH connection.
  577. // The receiver should call Handshake() in another goroutine
  578. // to avoid blocking the accepter.
  579. func (l *Listener) Accept() (*ServerConn, error) {
  580. c, err := l.listener.Accept()
  581. if err != nil {
  582. return nil, err
  583. }
  584. return Server(c, l.config), nil
  585. }
  586. // Listen creates an SSH listener accepting connections on
  587. // the given network address using net.Listen.
  588. func Listen(network, addr string, config *ServerConfig) (*Listener, error) {
  589. l, err := net.Listen(network, addr)
  590. if err != nil {
  591. return nil, err
  592. }
  593. return &Listener{
  594. l,
  595. config,
  596. }, nil
  597. }