server.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  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"
  8. "crypto/rand"
  9. "crypto/rsa"
  10. "crypto/x509"
  11. "encoding/pem"
  12. "errors"
  13. "io"
  14. "math/big"
  15. "net"
  16. "sync"
  17. )
  18. type ServerConfig struct {
  19. rsa *rsa.PrivateKey
  20. rsaSerialized []byte
  21. // Rand provides the source of entropy for key exchange. If Rand is
  22. // nil, the cryptographic random reader in package crypto/rand will
  23. // be used.
  24. Rand io.Reader
  25. // NoClientAuth is true if clients are allowed to connect without
  26. // authenticating.
  27. NoClientAuth bool
  28. // PasswordCallback, if non-nil, is called when a user attempts to
  29. // authenticate using a password. It may be called concurrently from
  30. // several goroutines.
  31. PasswordCallback func(user, password string) bool
  32. // PublicKeyCallback, if non-nil, is called when a client attempts public
  33. // key authentication. It must return true iff the given public key is
  34. // valid for the given user.
  35. PublicKeyCallback func(user, algo string, pubkey []byte) bool
  36. // Cryptographic-related configuration.
  37. Crypto CryptoConfig
  38. }
  39. func (c *ServerConfig) rand() io.Reader {
  40. if c.Rand == nil {
  41. return rand.Reader
  42. }
  43. return c.Rand
  44. }
  45. // SetRSAPrivateKey sets the private key for a Server. A Server must have a
  46. // private key configured in order to accept connections. The private key must
  47. // be in the form of a PEM encoded, PKCS#1, RSA private key. The file "id_rsa"
  48. // typically contains such a key.
  49. func (s *ServerConfig) SetRSAPrivateKey(pemBytes []byte) error {
  50. block, _ := pem.Decode(pemBytes)
  51. if block == nil {
  52. return errors.New("ssh: no key found")
  53. }
  54. var err error
  55. s.rsa, err = x509.ParsePKCS1PrivateKey(block.Bytes)
  56. if err != nil {
  57. return err
  58. }
  59. s.rsaSerialized = marshalRSA(s.rsa)
  60. return nil
  61. }
  62. // marshalRSA serializes an RSA private key according to RFC 4256, section 6.6.
  63. func marshalRSA(priv *rsa.PrivateKey) []byte {
  64. e := new(big.Int).SetInt64(int64(priv.E))
  65. length := stringLength([]byte(hostAlgoRSA))
  66. length += intLength(e)
  67. length += intLength(priv.N)
  68. ret := make([]byte, length)
  69. r := marshalString(ret, []byte(hostAlgoRSA))
  70. r = marshalInt(r, e)
  71. r = marshalInt(r, priv.N)
  72. return ret
  73. }
  74. // parseRSA parses an RSA key according to RFC 4256, section 6.6.
  75. func parseRSA(in []byte) (pubKey *rsa.PublicKey, ok bool) {
  76. algo, in, ok := parseString(in)
  77. if !ok || string(algo) != hostAlgoRSA {
  78. return nil, false
  79. }
  80. bigE, in, ok := parseInt(in)
  81. if !ok || bigE.BitLen() > 24 {
  82. return nil, false
  83. }
  84. e := bigE.Int64()
  85. if e < 3 || e&1 == 0 {
  86. return nil, false
  87. }
  88. N, in, ok := parseInt(in)
  89. if !ok || len(in) > 0 {
  90. return nil, false
  91. }
  92. return &rsa.PublicKey{
  93. N: N,
  94. E: int(e),
  95. }, true
  96. }
  97. func parseRSASig(in []byte) (sig []byte, ok bool) {
  98. algo, in, ok := parseString(in)
  99. if !ok || string(algo) != hostAlgoRSA {
  100. return nil, false
  101. }
  102. sig, in, ok = parseString(in)
  103. if len(in) > 0 {
  104. ok = false
  105. }
  106. return
  107. }
  108. // cachedPubKey contains the results of querying whether a public key is
  109. // acceptable for a user. The cache only applies to a single ServerConn.
  110. type cachedPubKey struct {
  111. user, algo string
  112. pubKey []byte
  113. result bool
  114. }
  115. const maxCachedPubKeys = 16
  116. // A ServerConn represents an incomming connection.
  117. type ServerConn struct {
  118. *transport
  119. config *ServerConfig
  120. channels map[uint32]*channel
  121. nextChanId uint32
  122. // lock protects err and also allows Channels to serialise their writes
  123. // to out.
  124. lock sync.RWMutex
  125. err error
  126. // cachedPubKeys contains the cache results of tests for public keys.
  127. // Since SSH clients will query whether a public key is acceptable
  128. // before attempting to authenticate with it, we end up with duplicate
  129. // queries for public key validity.
  130. cachedPubKeys []cachedPubKey
  131. }
  132. // Server returns a new SSH server connection
  133. // using c as the underlying transport.
  134. func Server(c net.Conn, config *ServerConfig) *ServerConn {
  135. conn := &ServerConn{
  136. transport: newTransport(c, config.rand()),
  137. channels: make(map[uint32]*channel),
  138. config: config,
  139. }
  140. return conn
  141. }
  142. // kexDH performs Diffie-Hellman key agreement on a ServerConnection. The
  143. // returned values are given the same names as in RFC 4253, section 8.
  144. func (s *ServerConn) kexDH(group *dhGroup, hashFunc crypto.Hash, magics *handshakeMagics, hostKeyAlgo string) (H, K []byte, err error) {
  145. packet, err := s.readPacket()
  146. if err != nil {
  147. return
  148. }
  149. var kexDHInit kexDHInitMsg
  150. if err = unmarshal(&kexDHInit, packet, msgKexDHInit); err != nil {
  151. return
  152. }
  153. if kexDHInit.X.Sign() == 0 || kexDHInit.X.Cmp(group.p) >= 0 {
  154. return nil, nil, errors.New("client DH parameter out of bounds")
  155. }
  156. y, err := rand.Int(s.config.rand(), group.p)
  157. if err != nil {
  158. return
  159. }
  160. Y := new(big.Int).Exp(group.g, y, group.p)
  161. kInt := new(big.Int).Exp(kexDHInit.X, y, group.p)
  162. var serializedHostKey []byte
  163. switch hostKeyAlgo {
  164. case hostAlgoRSA:
  165. serializedHostKey = s.config.rsaSerialized
  166. default:
  167. return nil, nil, errors.New("internal error")
  168. }
  169. h := hashFunc.New()
  170. writeString(h, magics.clientVersion)
  171. writeString(h, magics.serverVersion)
  172. writeString(h, magics.clientKexInit)
  173. writeString(h, magics.serverKexInit)
  174. writeString(h, serializedHostKey)
  175. writeInt(h, kexDHInit.X)
  176. writeInt(h, Y)
  177. K = make([]byte, intLength(kInt))
  178. marshalInt(K, kInt)
  179. h.Write(K)
  180. H = h.Sum(nil)
  181. h.Reset()
  182. h.Write(H)
  183. hh := h.Sum(nil)
  184. var sig []byte
  185. switch hostKeyAlgo {
  186. case hostAlgoRSA:
  187. sig, err = rsa.SignPKCS1v15(s.config.rand(), s.config.rsa, hashFunc, hh)
  188. if err != nil {
  189. return
  190. }
  191. default:
  192. return nil, nil, errors.New("internal error")
  193. }
  194. serializedSig := serializeSignature(hostAlgoRSA, sig)
  195. kexDHReply := kexDHReplyMsg{
  196. HostKey: serializedHostKey,
  197. Y: Y,
  198. Signature: serializedSig,
  199. }
  200. packet = marshal(msgKexDHReply, kexDHReply)
  201. err = s.writePacket(packet)
  202. return
  203. }
  204. // serverVersion is the fixed identification string that Server will use.
  205. var serverVersion = []byte("SSH-2.0-Go\r\n")
  206. // Handshake performs an SSH transport and client authentication on the given ServerConn.
  207. func (s *ServerConn) Handshake() error {
  208. var magics handshakeMagics
  209. if _, err := s.Write(serverVersion); err != nil {
  210. return err
  211. }
  212. if err := s.Flush(); err != nil {
  213. return err
  214. }
  215. magics.serverVersion = serverVersion[:len(serverVersion)-2]
  216. version, err := readVersion(s)
  217. if err != nil {
  218. return err
  219. }
  220. magics.clientVersion = version
  221. serverKexInit := kexInitMsg{
  222. KexAlgos: supportedKexAlgos,
  223. ServerHostKeyAlgos: supportedHostKeyAlgos,
  224. CiphersClientServer: s.config.Crypto.ciphers(),
  225. CiphersServerClient: s.config.Crypto.ciphers(),
  226. MACsClientServer: supportedMACs,
  227. MACsServerClient: supportedMACs,
  228. CompressionClientServer: supportedCompressions,
  229. CompressionServerClient: supportedCompressions,
  230. }
  231. kexInitPacket := marshal(msgKexInit, serverKexInit)
  232. magics.serverKexInit = kexInitPacket
  233. if err := s.writePacket(kexInitPacket); err != nil {
  234. return err
  235. }
  236. packet, err := s.readPacket()
  237. if err != nil {
  238. return err
  239. }
  240. magics.clientKexInit = packet
  241. var clientKexInit kexInitMsg
  242. if err = unmarshal(&clientKexInit, packet, msgKexInit); err != nil {
  243. return err
  244. }
  245. kexAlgo, hostKeyAlgo, ok := findAgreedAlgorithms(s.transport, &clientKexInit, &serverKexInit)
  246. if !ok {
  247. return errors.New("ssh: no common algorithms")
  248. }
  249. if clientKexInit.FirstKexFollows && kexAlgo != clientKexInit.KexAlgos[0] {
  250. // The client sent a Kex message for the wrong algorithm,
  251. // which we have to ignore.
  252. if _, err := s.readPacket(); err != nil {
  253. return err
  254. }
  255. }
  256. var H, K []byte
  257. var hashFunc crypto.Hash
  258. switch kexAlgo {
  259. case kexAlgoDH14SHA1:
  260. hashFunc = crypto.SHA1
  261. dhGroup14Once.Do(initDHGroup14)
  262. H, K, err = s.kexDH(dhGroup14, hashFunc, &magics, hostKeyAlgo)
  263. default:
  264. err = errors.New("ssh: unexpected key exchange algorithm " + kexAlgo)
  265. }
  266. if err != nil {
  267. return err
  268. }
  269. if err = s.writePacket([]byte{msgNewKeys}); err != nil {
  270. return err
  271. }
  272. if err = s.transport.writer.setupKeys(serverKeys, K, H, H, hashFunc); err != nil {
  273. return err
  274. }
  275. if packet, err = s.readPacket(); err != nil {
  276. return err
  277. }
  278. if packet[0] != msgNewKeys {
  279. return UnexpectedMessageError{msgNewKeys, packet[0]}
  280. }
  281. if err = s.transport.reader.setupKeys(clientKeys, K, H, H, hashFunc); err != nil {
  282. return err
  283. }
  284. if packet, err = s.readPacket(); err != nil {
  285. return err
  286. }
  287. var serviceRequest serviceRequestMsg
  288. if err = unmarshal(&serviceRequest, packet, msgServiceRequest); err != nil {
  289. return err
  290. }
  291. if serviceRequest.Service != serviceUserAuth {
  292. return errors.New("ssh: requested service '" + serviceRequest.Service + "' before authenticating")
  293. }
  294. serviceAccept := serviceAcceptMsg{
  295. Service: serviceUserAuth,
  296. }
  297. if err = s.writePacket(marshal(msgServiceAccept, serviceAccept)); err != nil {
  298. return err
  299. }
  300. if err = s.authenticate(H); err != nil {
  301. return err
  302. }
  303. return nil
  304. }
  305. func isAcceptableAlgo(algo string) bool {
  306. return algo == hostAlgoRSA
  307. }
  308. // testPubKey returns true if the given public key is acceptable for the user.
  309. func (s *ServerConn) testPubKey(user, algo string, pubKey []byte) bool {
  310. if s.config.PublicKeyCallback == nil || !isAcceptableAlgo(algo) {
  311. return false
  312. }
  313. for _, c := range s.cachedPubKeys {
  314. if c.user == user && c.algo == algo && bytes.Equal(c.pubKey, pubKey) {
  315. return c.result
  316. }
  317. }
  318. result := s.config.PublicKeyCallback(user, algo, pubKey)
  319. if len(s.cachedPubKeys) < maxCachedPubKeys {
  320. c := cachedPubKey{
  321. user: user,
  322. algo: algo,
  323. pubKey: make([]byte, len(pubKey)),
  324. result: result,
  325. }
  326. copy(c.pubKey, pubKey)
  327. s.cachedPubKeys = append(s.cachedPubKeys, c)
  328. }
  329. return result
  330. }
  331. func (s *ServerConn) authenticate(H []byte) error {
  332. var userAuthReq userAuthRequestMsg
  333. var err error
  334. var packet []byte
  335. userAuthLoop:
  336. for {
  337. if packet, err = s.readPacket(); err != nil {
  338. return err
  339. }
  340. if err = unmarshal(&userAuthReq, packet, msgUserAuthRequest); err != nil {
  341. return err
  342. }
  343. if userAuthReq.Service != serviceSSH {
  344. return errors.New("ssh: client attempted to negotiate for unknown service: " + userAuthReq.Service)
  345. }
  346. switch userAuthReq.Method {
  347. case "none":
  348. if s.config.NoClientAuth {
  349. break userAuthLoop
  350. }
  351. case "password":
  352. if s.config.PasswordCallback == nil {
  353. break
  354. }
  355. payload := userAuthReq.Payload
  356. if len(payload) < 1 || payload[0] != 0 {
  357. return ParseError{msgUserAuthRequest}
  358. }
  359. payload = payload[1:]
  360. password, payload, ok := parseString(payload)
  361. if !ok || len(payload) > 0 {
  362. return ParseError{msgUserAuthRequest}
  363. }
  364. if s.config.PasswordCallback(userAuthReq.User, string(password)) {
  365. break userAuthLoop
  366. }
  367. case "publickey":
  368. if s.config.PublicKeyCallback == nil {
  369. break
  370. }
  371. payload := userAuthReq.Payload
  372. if len(payload) < 1 {
  373. return ParseError{msgUserAuthRequest}
  374. }
  375. isQuery := payload[0] == 0
  376. payload = payload[1:]
  377. algoBytes, payload, ok := parseString(payload)
  378. if !ok {
  379. return ParseError{msgUserAuthRequest}
  380. }
  381. algo := string(algoBytes)
  382. pubKey, payload, ok := parseString(payload)
  383. if !ok {
  384. return ParseError{msgUserAuthRequest}
  385. }
  386. if isQuery {
  387. // The client can query if the given public key
  388. // would be ok.
  389. if len(payload) > 0 {
  390. return ParseError{msgUserAuthRequest}
  391. }
  392. if s.testPubKey(userAuthReq.User, algo, pubKey) {
  393. okMsg := userAuthPubKeyOkMsg{
  394. Algo: algo,
  395. PubKey: string(pubKey),
  396. }
  397. if err = s.writePacket(marshal(msgUserAuthPubKeyOk, okMsg)); err != nil {
  398. return err
  399. }
  400. continue userAuthLoop
  401. }
  402. } else {
  403. sig, payload, ok := parseString(payload)
  404. if !ok || len(payload) > 0 {
  405. return ParseError{msgUserAuthRequest}
  406. }
  407. if !isAcceptableAlgo(algo) {
  408. break
  409. }
  410. rsaSig, ok := parseRSASig(sig)
  411. if !ok {
  412. return ParseError{msgUserAuthRequest}
  413. }
  414. signedData := buildDataSignedForAuth(H, userAuthReq, algoBytes, pubKey)
  415. switch algo {
  416. case hostAlgoRSA:
  417. hashFunc := crypto.SHA1
  418. h := hashFunc.New()
  419. h.Write(signedData)
  420. digest := h.Sum(nil)
  421. rsaKey, ok := parseRSA(pubKey)
  422. if !ok {
  423. return ParseError{msgUserAuthRequest}
  424. }
  425. if rsa.VerifyPKCS1v15(rsaKey, hashFunc, digest, rsaSig) != nil {
  426. return ParseError{msgUserAuthRequest}
  427. }
  428. default:
  429. return errors.New("ssh: isAcceptableAlgo incorrect")
  430. }
  431. if s.testPubKey(userAuthReq.User, algo, pubKey) {
  432. break userAuthLoop
  433. }
  434. }
  435. }
  436. var failureMsg userAuthFailureMsg
  437. if s.config.PasswordCallback != nil {
  438. failureMsg.Methods = append(failureMsg.Methods, "password")
  439. }
  440. if s.config.PublicKeyCallback != nil {
  441. failureMsg.Methods = append(failureMsg.Methods, "publickey")
  442. }
  443. if len(failureMsg.Methods) == 0 {
  444. return errors.New("ssh: no authentication methods configured but NoClientAuth is also false")
  445. }
  446. if err = s.writePacket(marshal(msgUserAuthFailure, failureMsg)); err != nil {
  447. return err
  448. }
  449. }
  450. packet = []byte{msgUserAuthSuccess}
  451. if err = s.writePacket(packet); err != nil {
  452. return err
  453. }
  454. return nil
  455. }
  456. const defaultWindowSize = 32768
  457. // Accept reads and processes messages on a ServerConn. It must be called
  458. // in order to demultiplex messages to any resulting Channels.
  459. func (s *ServerConn) Accept() (Channel, error) {
  460. if s.err != nil {
  461. return nil, s.err
  462. }
  463. for {
  464. packet, err := s.readPacket()
  465. if err != nil {
  466. s.lock.Lock()
  467. s.err = err
  468. s.lock.Unlock()
  469. for _, c := range s.channels {
  470. c.dead = true
  471. c.handleData(nil)
  472. }
  473. return nil, err
  474. }
  475. switch packet[0] {
  476. case msgChannelData:
  477. if len(packet) < 9 {
  478. // malformed data packet
  479. return nil, ParseError{msgChannelData}
  480. }
  481. peersId := uint32(packet[1])<<24 | uint32(packet[2])<<16 | uint32(packet[3])<<8 | uint32(packet[4])
  482. s.lock.Lock()
  483. c, ok := s.channels[peersId]
  484. if !ok {
  485. s.lock.Unlock()
  486. continue
  487. }
  488. if length := int(packet[5])<<24 | int(packet[6])<<16 | int(packet[7])<<8 | int(packet[8]); length > 0 {
  489. packet = packet[9:]
  490. c.handleData(packet[:length])
  491. }
  492. s.lock.Unlock()
  493. default:
  494. switch msg := decode(packet).(type) {
  495. case *channelOpenMsg:
  496. c := new(channel)
  497. c.chanType = msg.ChanType
  498. c.theirId = msg.PeersId
  499. c.theirWindow = msg.PeersWindow
  500. c.maxPacketSize = msg.MaxPacketSize
  501. c.extraData = msg.TypeSpecificData
  502. c.myWindow = defaultWindowSize
  503. c.serverConn = s
  504. c.cond = sync.NewCond(&c.lock)
  505. c.pendingData = make([]byte, c.myWindow)
  506. s.lock.Lock()
  507. c.myId = s.nextChanId
  508. s.nextChanId++
  509. s.channels[c.myId] = c
  510. s.lock.Unlock()
  511. return c, nil
  512. case *channelRequestMsg:
  513. s.lock.Lock()
  514. c, ok := s.channels[msg.PeersId]
  515. if !ok {
  516. s.lock.Unlock()
  517. continue
  518. }
  519. c.handlePacket(msg)
  520. s.lock.Unlock()
  521. case *channelEOFMsg:
  522. s.lock.Lock()
  523. c, ok := s.channels[msg.PeersId]
  524. if !ok {
  525. s.lock.Unlock()
  526. continue
  527. }
  528. c.handlePacket(msg)
  529. s.lock.Unlock()
  530. case *channelCloseMsg:
  531. s.lock.Lock()
  532. c, ok := s.channels[msg.PeersId]
  533. if !ok {
  534. s.lock.Unlock()
  535. continue
  536. }
  537. c.handlePacket(msg)
  538. s.lock.Unlock()
  539. case *globalRequestMsg:
  540. if msg.WantReply {
  541. if err := s.writePacket([]byte{msgRequestFailure}); err != nil {
  542. return nil, err
  543. }
  544. }
  545. case UnexpectedMessageError:
  546. return nil, msg
  547. case *disconnectMsg:
  548. return nil, io.EOF
  549. default:
  550. // Unknown message. Ignore.
  551. }
  552. }
  553. }
  554. panic("unreachable")
  555. }
  556. // A Listener implements a network listener (net.Listener) for SSH connections.
  557. type Listener struct {
  558. listener net.Listener
  559. config *ServerConfig
  560. }
  561. // Accept waits for and returns the next incoming SSH connection.
  562. // The receiver should call Handshake() in another goroutine
  563. // to avoid blocking the accepter.
  564. func (l *Listener) Accept() (*ServerConn, error) {
  565. c, err := l.listener.Accept()
  566. if err != nil {
  567. return nil, err
  568. }
  569. conn := Server(c, l.config)
  570. return conn, nil
  571. }
  572. // Addr returns the listener's network address.
  573. func (l *Listener) Addr() net.Addr {
  574. return l.listener.Addr()
  575. }
  576. // Close closes the listener.
  577. func (l *Listener) Close() error {
  578. return l.listener.Close()
  579. }
  580. // Listen creates an SSH listener accepting connections on
  581. // the given network address using net.Listen.
  582. func Listen(network, addr string, config *ServerConfig) (*Listener, error) {
  583. l, err := net.Listen(network, addr)
  584. if err != nil {
  585. return nil, err
  586. }
  587. return &Listener{
  588. l,
  589. config,
  590. }, nil
  591. }