server.go 17 KB

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