server.go 17 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"
  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(conn *ServerConn, 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(conn *ServerConn, 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. // User holds the successfully authenticated user name.
  132. // It is empty if no authentication is used. It is populated before
  133. // any authentication callback is called and not assigned to after that.
  134. User string
  135. }
  136. // Server returns a new SSH server connection
  137. // using c as the underlying transport.
  138. func Server(c net.Conn, config *ServerConfig) *ServerConn {
  139. conn := &ServerConn{
  140. transport: newTransport(c, config.rand()),
  141. channels: make(map[uint32]*channel),
  142. config: config,
  143. }
  144. return conn
  145. }
  146. // kexDH performs Diffie-Hellman key agreement on a ServerConnection. The
  147. // returned values are given the same names as in RFC 4253, section 8.
  148. func (s *ServerConn) kexDH(group *dhGroup, hashFunc crypto.Hash, magics *handshakeMagics, hostKeyAlgo string) (H, K []byte, err error) {
  149. packet, err := s.readPacket()
  150. if err != nil {
  151. return
  152. }
  153. var kexDHInit kexDHInitMsg
  154. if err = unmarshal(&kexDHInit, packet, msgKexDHInit); err != nil {
  155. return
  156. }
  157. if kexDHInit.X.Sign() == 0 || kexDHInit.X.Cmp(group.p) >= 0 {
  158. return nil, nil, errors.New("client DH parameter out of bounds")
  159. }
  160. y, err := rand.Int(s.config.rand(), group.p)
  161. if err != nil {
  162. return
  163. }
  164. Y := new(big.Int).Exp(group.g, y, group.p)
  165. kInt := new(big.Int).Exp(kexDHInit.X, y, group.p)
  166. var serializedHostKey []byte
  167. switch hostKeyAlgo {
  168. case hostAlgoRSA:
  169. serializedHostKey = s.config.rsaSerialized
  170. default:
  171. return nil, nil, errors.New("internal error")
  172. }
  173. h := hashFunc.New()
  174. writeString(h, magics.clientVersion)
  175. writeString(h, magics.serverVersion)
  176. writeString(h, magics.clientKexInit)
  177. writeString(h, magics.serverKexInit)
  178. writeString(h, serializedHostKey)
  179. writeInt(h, kexDHInit.X)
  180. writeInt(h, Y)
  181. K = make([]byte, intLength(kInt))
  182. marshalInt(K, kInt)
  183. h.Write(K)
  184. H = h.Sum(nil)
  185. h.Reset()
  186. h.Write(H)
  187. hh := h.Sum(nil)
  188. var sig []byte
  189. switch hostKeyAlgo {
  190. case hostAlgoRSA:
  191. sig, err = rsa.SignPKCS1v15(s.config.rand(), s.config.rsa, hashFunc, hh)
  192. if err != nil {
  193. return
  194. }
  195. default:
  196. return nil, nil, errors.New("internal error")
  197. }
  198. serializedSig := serializeSignature(hostAlgoRSA, sig)
  199. kexDHReply := kexDHReplyMsg{
  200. HostKey: serializedHostKey,
  201. Y: Y,
  202. Signature: serializedSig,
  203. }
  204. packet = marshal(msgKexDHReply, kexDHReply)
  205. err = s.writePacket(packet)
  206. return
  207. }
  208. // serverVersion is the fixed identification string that Server will use.
  209. var serverVersion = []byte("SSH-2.0-Go\r\n")
  210. // Handshake performs an SSH transport and client authentication on the given ServerConn.
  211. func (s *ServerConn) Handshake() error {
  212. var magics handshakeMagics
  213. if _, err := s.Write(serverVersion); err != nil {
  214. return err
  215. }
  216. if err := s.Flush(); err != nil {
  217. return err
  218. }
  219. magics.serverVersion = serverVersion[:len(serverVersion)-2]
  220. version, err := readVersion(s)
  221. if err != nil {
  222. return err
  223. }
  224. magics.clientVersion = version
  225. serverKexInit := kexInitMsg{
  226. KexAlgos: supportedKexAlgos,
  227. ServerHostKeyAlgos: supportedHostKeyAlgos,
  228. CiphersClientServer: s.config.Crypto.ciphers(),
  229. CiphersServerClient: s.config.Crypto.ciphers(),
  230. MACsClientServer: supportedMACs,
  231. MACsServerClient: supportedMACs,
  232. CompressionClientServer: supportedCompressions,
  233. CompressionServerClient: supportedCompressions,
  234. }
  235. kexInitPacket := marshal(msgKexInit, serverKexInit)
  236. magics.serverKexInit = kexInitPacket
  237. if err := s.writePacket(kexInitPacket); err != nil {
  238. return err
  239. }
  240. packet, err := s.readPacket()
  241. if err != nil {
  242. return err
  243. }
  244. magics.clientKexInit = packet
  245. var clientKexInit kexInitMsg
  246. if err = unmarshal(&clientKexInit, packet, msgKexInit); err != nil {
  247. return err
  248. }
  249. kexAlgo, hostKeyAlgo, ok := findAgreedAlgorithms(s.transport, &clientKexInit, &serverKexInit)
  250. if !ok {
  251. return errors.New("ssh: no common algorithms")
  252. }
  253. if clientKexInit.FirstKexFollows && kexAlgo != clientKexInit.KexAlgos[0] {
  254. // The client sent a Kex message for the wrong algorithm,
  255. // which we have to ignore.
  256. if _, err := s.readPacket(); err != nil {
  257. return err
  258. }
  259. }
  260. var H, K []byte
  261. var hashFunc crypto.Hash
  262. switch kexAlgo {
  263. case kexAlgoDH14SHA1:
  264. hashFunc = crypto.SHA1
  265. dhGroup14Once.Do(initDHGroup14)
  266. H, K, err = s.kexDH(dhGroup14, hashFunc, &magics, hostKeyAlgo)
  267. default:
  268. err = errors.New("ssh: unexpected key exchange algorithm " + kexAlgo)
  269. }
  270. if err != nil {
  271. return err
  272. }
  273. if err = s.writePacket([]byte{msgNewKeys}); err != nil {
  274. return err
  275. }
  276. if err = s.transport.writer.setupKeys(serverKeys, K, H, H, hashFunc); err != nil {
  277. return err
  278. }
  279. if packet, err = s.readPacket(); err != nil {
  280. return err
  281. }
  282. if packet[0] != msgNewKeys {
  283. return UnexpectedMessageError{msgNewKeys, packet[0]}
  284. }
  285. if err = s.transport.reader.setupKeys(clientKeys, K, H, H, hashFunc); err != nil {
  286. return err
  287. }
  288. if packet, err = s.readPacket(); err != nil {
  289. return err
  290. }
  291. var serviceRequest serviceRequestMsg
  292. if err = unmarshal(&serviceRequest, packet, msgServiceRequest); err != nil {
  293. return err
  294. }
  295. if serviceRequest.Service != serviceUserAuth {
  296. return errors.New("ssh: requested service '" + serviceRequest.Service + "' before authenticating")
  297. }
  298. serviceAccept := serviceAcceptMsg{
  299. Service: serviceUserAuth,
  300. }
  301. if err = s.writePacket(marshal(msgServiceAccept, serviceAccept)); err != nil {
  302. return err
  303. }
  304. if err = s.authenticate(H); err != nil {
  305. return err
  306. }
  307. return nil
  308. }
  309. func isAcceptableAlgo(algo string) bool {
  310. return algo == hostAlgoRSA
  311. }
  312. // testPubKey returns true if the given public key is acceptable for the user.
  313. func (s *ServerConn) testPubKey(user, algo string, pubKey []byte) bool {
  314. if s.config.PublicKeyCallback == nil || !isAcceptableAlgo(algo) {
  315. return false
  316. }
  317. for _, c := range s.cachedPubKeys {
  318. if c.user == user && c.algo == algo && bytes.Equal(c.pubKey, pubKey) {
  319. return c.result
  320. }
  321. }
  322. result := s.config.PublicKeyCallback(s, user, algo, pubKey)
  323. if len(s.cachedPubKeys) < maxCachedPubKeys {
  324. c := cachedPubKey{
  325. user: user,
  326. algo: algo,
  327. pubKey: make([]byte, len(pubKey)),
  328. result: result,
  329. }
  330. copy(c.pubKey, pubKey)
  331. s.cachedPubKeys = append(s.cachedPubKeys, c)
  332. }
  333. return result
  334. }
  335. func (s *ServerConn) authenticate(H []byte) error {
  336. var userAuthReq userAuthRequestMsg
  337. var err error
  338. var packet []byte
  339. userAuthLoop:
  340. for {
  341. if packet, err = s.readPacket(); err != nil {
  342. return err
  343. }
  344. if err = unmarshal(&userAuthReq, packet, msgUserAuthRequest); err != nil {
  345. return err
  346. }
  347. if userAuthReq.Service != serviceSSH {
  348. return errors.New("ssh: client attempted to negotiate for unknown service: " + userAuthReq.Service)
  349. }
  350. switch userAuthReq.Method {
  351. case "none":
  352. if s.config.NoClientAuth {
  353. break userAuthLoop
  354. }
  355. case "password":
  356. if s.config.PasswordCallback == nil {
  357. break
  358. }
  359. payload := userAuthReq.Payload
  360. if len(payload) < 1 || payload[0] != 0 {
  361. return ParseError{msgUserAuthRequest}
  362. }
  363. payload = payload[1:]
  364. password, payload, ok := parseString(payload)
  365. if !ok || len(payload) > 0 {
  366. return ParseError{msgUserAuthRequest}
  367. }
  368. s.User = userAuthReq.User
  369. if s.config.PasswordCallback(s, userAuthReq.User, string(password)) {
  370. break userAuthLoop
  371. }
  372. case "publickey":
  373. if s.config.PublicKeyCallback == nil {
  374. break
  375. }
  376. payload := userAuthReq.Payload
  377. if len(payload) < 1 {
  378. return ParseError{msgUserAuthRequest}
  379. }
  380. isQuery := payload[0] == 0
  381. payload = payload[1:]
  382. algoBytes, payload, ok := parseString(payload)
  383. if !ok {
  384. return ParseError{msgUserAuthRequest}
  385. }
  386. algo := string(algoBytes)
  387. pubKey, payload, ok := parseString(payload)
  388. if !ok {
  389. return ParseError{msgUserAuthRequest}
  390. }
  391. if isQuery {
  392. // The client can query if the given public key
  393. // would be ok.
  394. if len(payload) > 0 {
  395. return ParseError{msgUserAuthRequest}
  396. }
  397. if s.testPubKey(userAuthReq.User, algo, pubKey) {
  398. okMsg := userAuthPubKeyOkMsg{
  399. Algo: algo,
  400. PubKey: string(pubKey),
  401. }
  402. if err = s.writePacket(marshal(msgUserAuthPubKeyOk, okMsg)); err != nil {
  403. return err
  404. }
  405. continue userAuthLoop
  406. }
  407. } else {
  408. sig, payload, ok := parseString(payload)
  409. if !ok || len(payload) > 0 {
  410. return ParseError{msgUserAuthRequest}
  411. }
  412. if !isAcceptableAlgo(algo) {
  413. break
  414. }
  415. rsaSig, ok := parseRSASig(sig)
  416. if !ok {
  417. return ParseError{msgUserAuthRequest}
  418. }
  419. signedData := buildDataSignedForAuth(H, userAuthReq, algoBytes, pubKey)
  420. switch algo {
  421. case hostAlgoRSA:
  422. hashFunc := crypto.SHA1
  423. h := hashFunc.New()
  424. h.Write(signedData)
  425. digest := h.Sum(nil)
  426. rsaKey, ok := parseRSA(pubKey)
  427. if !ok {
  428. return ParseError{msgUserAuthRequest}
  429. }
  430. if rsa.VerifyPKCS1v15(rsaKey, hashFunc, digest, rsaSig) != nil {
  431. return ParseError{msgUserAuthRequest}
  432. }
  433. default:
  434. return errors.New("ssh: isAcceptableAlgo incorrect")
  435. }
  436. s.User = userAuthReq.User
  437. if s.testPubKey(userAuthReq.User, algo, pubKey) {
  438. break userAuthLoop
  439. }
  440. }
  441. }
  442. var failureMsg userAuthFailureMsg
  443. if s.config.PasswordCallback != nil {
  444. failureMsg.Methods = append(failureMsg.Methods, "password")
  445. }
  446. if s.config.PublicKeyCallback != nil {
  447. failureMsg.Methods = append(failureMsg.Methods, "publickey")
  448. }
  449. if len(failureMsg.Methods) == 0 {
  450. return errors.New("ssh: no authentication methods configured but NoClientAuth is also false")
  451. }
  452. if err = s.writePacket(marshal(msgUserAuthFailure, failureMsg)); err != nil {
  453. return err
  454. }
  455. }
  456. packet = []byte{msgUserAuthSuccess}
  457. if err = s.writePacket(packet); err != nil {
  458. return err
  459. }
  460. return nil
  461. }
  462. const defaultWindowSize = 32768
  463. // Accept reads and processes messages on a ServerConn. It must be called
  464. // in order to demultiplex messages to any resulting Channels.
  465. func (s *ServerConn) Accept() (Channel, error) {
  466. if s.err != nil {
  467. return nil, s.err
  468. }
  469. for {
  470. packet, err := s.readPacket()
  471. if err != nil {
  472. s.lock.Lock()
  473. s.err = err
  474. s.lock.Unlock()
  475. for _, c := range s.channels {
  476. c.dead = true
  477. c.handleData(nil)
  478. }
  479. return nil, err
  480. }
  481. switch packet[0] {
  482. case msgChannelData:
  483. if len(packet) < 9 {
  484. // malformed data packet
  485. return nil, ParseError{msgChannelData}
  486. }
  487. peersId := uint32(packet[1])<<24 | uint32(packet[2])<<16 | uint32(packet[3])<<8 | uint32(packet[4])
  488. s.lock.Lock()
  489. c, ok := s.channels[peersId]
  490. if !ok {
  491. s.lock.Unlock()
  492. continue
  493. }
  494. if length := int(packet[5])<<24 | int(packet[6])<<16 | int(packet[7])<<8 | int(packet[8]); length > 0 {
  495. packet = packet[9:]
  496. c.handleData(packet[:length])
  497. }
  498. s.lock.Unlock()
  499. default:
  500. switch msg := decode(packet).(type) {
  501. case *channelOpenMsg:
  502. c := new(channel)
  503. c.chanType = msg.ChanType
  504. c.theirId = msg.PeersId
  505. c.theirWindow = msg.PeersWindow
  506. c.maxPacketSize = msg.MaxPacketSize
  507. c.extraData = msg.TypeSpecificData
  508. c.myWindow = defaultWindowSize
  509. c.serverConn = s
  510. c.cond = sync.NewCond(&c.lock)
  511. c.pendingData = make([]byte, c.myWindow)
  512. s.lock.Lock()
  513. c.myId = s.nextChanId
  514. s.nextChanId++
  515. s.channels[c.myId] = c
  516. s.lock.Unlock()
  517. return c, nil
  518. case *channelRequestMsg:
  519. s.lock.Lock()
  520. c, ok := s.channels[msg.PeersId]
  521. if !ok {
  522. s.lock.Unlock()
  523. continue
  524. }
  525. c.handlePacket(msg)
  526. s.lock.Unlock()
  527. case *channelEOFMsg:
  528. s.lock.Lock()
  529. c, ok := s.channels[msg.PeersId]
  530. if !ok {
  531. s.lock.Unlock()
  532. continue
  533. }
  534. c.handlePacket(msg)
  535. s.lock.Unlock()
  536. case *channelCloseMsg:
  537. s.lock.Lock()
  538. c, ok := s.channels[msg.PeersId]
  539. if !ok {
  540. s.lock.Unlock()
  541. continue
  542. }
  543. c.handlePacket(msg)
  544. s.lock.Unlock()
  545. case *globalRequestMsg:
  546. if msg.WantReply {
  547. if err := s.writePacket([]byte{msgRequestFailure}); err != nil {
  548. return nil, err
  549. }
  550. }
  551. case UnexpectedMessageError:
  552. return nil, msg
  553. case *disconnectMsg:
  554. return nil, io.EOF
  555. default:
  556. // Unknown message. Ignore.
  557. }
  558. }
  559. }
  560. panic("unreachable")
  561. }
  562. // A Listener implements a network listener (net.Listener) for SSH connections.
  563. type Listener struct {
  564. listener net.Listener
  565. config *ServerConfig
  566. }
  567. // Accept waits for and returns the next incoming SSH connection.
  568. // The receiver should call Handshake() in another goroutine
  569. // to avoid blocking the accepter.
  570. func (l *Listener) Accept() (*ServerConn, error) {
  571. c, err := l.listener.Accept()
  572. if err != nil {
  573. return nil, err
  574. }
  575. conn := Server(c, l.config)
  576. return conn, nil
  577. }
  578. // Addr returns the listener's network address.
  579. func (l *Listener) Addr() net.Addr {
  580. return l.listener.Addr()
  581. }
  582. // Close closes the listener.
  583. func (l *Listener) Close() error {
  584. return l.listener.Close()
  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. }