server.go 16 KB

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