server.go 16 KB

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