server.go 17 KB

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