server.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  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. if kexDHInit.X.Sign() == 0 || kexDHInit.X.Cmp(group.p) >= 0 {
  123. return nil, nil, errors.New("client DH parameter out of bounds")
  124. }
  125. y, err := rand.Int(s.config.rand(), group.p)
  126. if err != nil {
  127. return
  128. }
  129. Y := new(big.Int).Exp(group.g, y, group.p)
  130. kInt := new(big.Int).Exp(kexDHInit.X, y, group.p)
  131. var serializedHostKey []byte
  132. switch hostKeyAlgo {
  133. case hostAlgoRSA:
  134. serializedHostKey = s.config.rsaSerialized
  135. default:
  136. return nil, nil, errors.New("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("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. default:
  233. err = errors.New("ssh: unexpected key exchange algorithm " + kexAlgo)
  234. }
  235. if err != nil {
  236. return err
  237. }
  238. if err = s.writePacket([]byte{msgNewKeys}); err != nil {
  239. return err
  240. }
  241. if err = s.transport.writer.setupKeys(serverKeys, K, H, H, hashFunc); err != nil {
  242. return err
  243. }
  244. if packet, err = s.readPacket(); err != nil {
  245. return err
  246. }
  247. if packet[0] != msgNewKeys {
  248. return UnexpectedMessageError{msgNewKeys, packet[0]}
  249. }
  250. if err = s.transport.reader.setupKeys(clientKeys, K, H, H, hashFunc); err != nil {
  251. return err
  252. }
  253. if packet, err = s.readPacket(); err != nil {
  254. return err
  255. }
  256. var serviceRequest serviceRequestMsg
  257. if err = unmarshal(&serviceRequest, packet, msgServiceRequest); err != nil {
  258. return err
  259. }
  260. if serviceRequest.Service != serviceUserAuth {
  261. return errors.New("ssh: requested service '" + serviceRequest.Service + "' before authenticating")
  262. }
  263. serviceAccept := serviceAcceptMsg{
  264. Service: serviceUserAuth,
  265. }
  266. if err = s.writePacket(marshal(msgServiceAccept, serviceAccept)); err != nil {
  267. return err
  268. }
  269. if err = s.authenticate(H); err != nil {
  270. return err
  271. }
  272. return nil
  273. }
  274. func isAcceptableAlgo(algo string) bool {
  275. return algo == hostAlgoRSA
  276. }
  277. // testPubKey returns true if the given public key is acceptable for the user.
  278. func (s *ServerConn) testPubKey(user, algo string, pubKey []byte) bool {
  279. if s.config.PublicKeyCallback == nil || !isAcceptableAlgo(algo) {
  280. return false
  281. }
  282. for _, c := range s.cachedPubKeys {
  283. if c.user == user && c.algo == algo && bytes.Equal(c.pubKey, pubKey) {
  284. return c.result
  285. }
  286. }
  287. result := s.config.PublicKeyCallback(s, user, algo, pubKey)
  288. if len(s.cachedPubKeys) < maxCachedPubKeys {
  289. c := cachedPubKey{
  290. user: user,
  291. algo: algo,
  292. pubKey: make([]byte, len(pubKey)),
  293. result: result,
  294. }
  295. copy(c.pubKey, pubKey)
  296. s.cachedPubKeys = append(s.cachedPubKeys, c)
  297. }
  298. return result
  299. }
  300. func (s *ServerConn) authenticate(H []byte) error {
  301. var userAuthReq userAuthRequestMsg
  302. var err error
  303. var packet []byte
  304. userAuthLoop:
  305. for {
  306. if packet, err = s.readPacket(); err != nil {
  307. return err
  308. }
  309. if err = unmarshal(&userAuthReq, packet, msgUserAuthRequest); err != nil {
  310. return err
  311. }
  312. if userAuthReq.Service != serviceSSH {
  313. return errors.New("ssh: client attempted to negotiate for unknown service: " + userAuthReq.Service)
  314. }
  315. switch userAuthReq.Method {
  316. case "none":
  317. if s.config.NoClientAuth {
  318. break userAuthLoop
  319. }
  320. case "password":
  321. if s.config.PasswordCallback == nil {
  322. break
  323. }
  324. payload := userAuthReq.Payload
  325. if len(payload) < 1 || payload[0] != 0 {
  326. return ParseError{msgUserAuthRequest}
  327. }
  328. payload = payload[1:]
  329. password, payload, ok := parseString(payload)
  330. if !ok || len(payload) > 0 {
  331. return ParseError{msgUserAuthRequest}
  332. }
  333. s.User = userAuthReq.User
  334. if s.config.PasswordCallback(s, userAuthReq.User, string(password)) {
  335. break userAuthLoop
  336. }
  337. case "publickey":
  338. if s.config.PublicKeyCallback == nil {
  339. break
  340. }
  341. payload := userAuthReq.Payload
  342. if len(payload) < 1 {
  343. return ParseError{msgUserAuthRequest}
  344. }
  345. isQuery := payload[0] == 0
  346. payload = payload[1:]
  347. algoBytes, payload, ok := parseString(payload)
  348. if !ok {
  349. return ParseError{msgUserAuthRequest}
  350. }
  351. algo := string(algoBytes)
  352. pubKey, payload, ok := parseString(payload)
  353. if !ok {
  354. return ParseError{msgUserAuthRequest}
  355. }
  356. if isQuery {
  357. // The client can query if the given public key
  358. // would be ok.
  359. if len(payload) > 0 {
  360. return ParseError{msgUserAuthRequest}
  361. }
  362. if s.testPubKey(userAuthReq.User, algo, pubKey) {
  363. okMsg := userAuthPubKeyOkMsg{
  364. Algo: algo,
  365. PubKey: string(pubKey),
  366. }
  367. if err = s.writePacket(marshal(msgUserAuthPubKeyOk, okMsg)); err != nil {
  368. return err
  369. }
  370. continue userAuthLoop
  371. }
  372. } else {
  373. sig, payload, ok := parseString(payload)
  374. if !ok || len(payload) > 0 {
  375. return ParseError{msgUserAuthRequest}
  376. }
  377. if !isAcceptableAlgo(algo) {
  378. break
  379. }
  380. rsaSig, ok := parseRSASig(sig)
  381. if !ok {
  382. return ParseError{msgUserAuthRequest}
  383. }
  384. signedData := buildDataSignedForAuth(H, userAuthReq, algoBytes, pubKey)
  385. switch algo {
  386. case hostAlgoRSA:
  387. hashFunc := crypto.SHA1
  388. h := hashFunc.New()
  389. h.Write(signedData)
  390. digest := h.Sum(nil)
  391. key, _, ok := parsePubKey(pubKey)
  392. if !ok {
  393. return ParseError{msgUserAuthRequest}
  394. }
  395. rsaKey, ok := key.(*rsa.PublicKey)
  396. if !ok {
  397. return ParseError{msgUserAuthRequest}
  398. }
  399. if rsa.VerifyPKCS1v15(rsaKey, hashFunc, digest, rsaSig) != nil {
  400. return ParseError{msgUserAuthRequest}
  401. }
  402. default:
  403. return errors.New("ssh: isAcceptableAlgo incorrect")
  404. }
  405. s.User = userAuthReq.User
  406. if s.testPubKey(userAuthReq.User, algo, pubKey) {
  407. break userAuthLoop
  408. }
  409. }
  410. }
  411. var failureMsg userAuthFailureMsg
  412. if s.config.PasswordCallback != nil {
  413. failureMsg.Methods = append(failureMsg.Methods, "password")
  414. }
  415. if s.config.PublicKeyCallback != nil {
  416. failureMsg.Methods = append(failureMsg.Methods, "publickey")
  417. }
  418. if len(failureMsg.Methods) == 0 {
  419. return errors.New("ssh: no authentication methods configured but NoClientAuth is also false")
  420. }
  421. if err = s.writePacket(marshal(msgUserAuthFailure, failureMsg)); err != nil {
  422. return err
  423. }
  424. }
  425. packet = []byte{msgUserAuthSuccess}
  426. if err = s.writePacket(packet); err != nil {
  427. return err
  428. }
  429. return nil
  430. }
  431. const defaultWindowSize = 32768
  432. // Accept reads and processes messages on a ServerConn. It must be called
  433. // in order to demultiplex messages to any resulting Channels.
  434. func (s *ServerConn) Accept() (Channel, error) {
  435. if s.err != nil {
  436. return nil, s.err
  437. }
  438. for {
  439. packet, err := s.readPacket()
  440. if err != nil {
  441. s.lock.Lock()
  442. s.err = err
  443. s.lock.Unlock()
  444. for _, c := range s.channels {
  445. c.dead = true
  446. c.handleData(nil)
  447. }
  448. return nil, err
  449. }
  450. switch packet[0] {
  451. case msgChannelData:
  452. if len(packet) < 9 {
  453. // malformed data packet
  454. return nil, ParseError{msgChannelData}
  455. }
  456. peersId := uint32(packet[1])<<24 | uint32(packet[2])<<16 | uint32(packet[3])<<8 | uint32(packet[4])
  457. s.lock.Lock()
  458. c, ok := s.channels[peersId]
  459. if !ok {
  460. s.lock.Unlock()
  461. continue
  462. }
  463. if length := int(packet[5])<<24 | int(packet[6])<<16 | int(packet[7])<<8 | int(packet[8]); length > 0 {
  464. packet = packet[9:]
  465. c.handleData(packet[:length])
  466. }
  467. s.lock.Unlock()
  468. default:
  469. switch msg := decode(packet).(type) {
  470. case *channelOpenMsg:
  471. c := new(channel)
  472. c.chanType = msg.ChanType
  473. c.theirId = msg.PeersId
  474. c.theirWindow = msg.PeersWindow
  475. c.maxPacketSize = msg.MaxPacketSize
  476. c.extraData = msg.TypeSpecificData
  477. c.myWindow = defaultWindowSize
  478. c.serverConn = s
  479. c.cond = sync.NewCond(&c.lock)
  480. c.pendingData = make([]byte, c.myWindow)
  481. s.lock.Lock()
  482. c.myId = s.nextChanId
  483. s.nextChanId++
  484. s.channels[c.myId] = c
  485. s.lock.Unlock()
  486. return c, nil
  487. case *channelRequestMsg:
  488. s.lock.Lock()
  489. c, ok := s.channels[msg.PeersId]
  490. if !ok {
  491. s.lock.Unlock()
  492. continue
  493. }
  494. c.handlePacket(msg)
  495. s.lock.Unlock()
  496. case *channelEOFMsg:
  497. s.lock.Lock()
  498. c, ok := s.channels[msg.PeersId]
  499. if !ok {
  500. s.lock.Unlock()
  501. continue
  502. }
  503. c.handlePacket(msg)
  504. s.lock.Unlock()
  505. case *channelCloseMsg:
  506. s.lock.Lock()
  507. c, ok := s.channels[msg.PeersId]
  508. if !ok {
  509. s.lock.Unlock()
  510. continue
  511. }
  512. c.handlePacket(msg)
  513. s.lock.Unlock()
  514. case *globalRequestMsg:
  515. if msg.WantReply {
  516. if err := s.writePacket([]byte{msgRequestFailure}); err != nil {
  517. return nil, err
  518. }
  519. }
  520. case UnexpectedMessageError:
  521. return nil, msg
  522. case *disconnectMsg:
  523. return nil, io.EOF
  524. default:
  525. // Unknown message. Ignore.
  526. }
  527. }
  528. }
  529. panic("unreachable")
  530. }
  531. // A Listener implements a network listener (net.Listener) for SSH connections.
  532. type Listener struct {
  533. listener net.Listener
  534. config *ServerConfig
  535. }
  536. // Accept waits for and returns the next incoming SSH connection.
  537. // The receiver should call Handshake() in another goroutine
  538. // to avoid blocking the accepter.
  539. func (l *Listener) Accept() (*ServerConn, error) {
  540. c, err := l.listener.Accept()
  541. if err != nil {
  542. return nil, err
  543. }
  544. conn := Server(c, l.config)
  545. return conn, nil
  546. }
  547. // Addr returns the listener's network address.
  548. func (l *Listener) Addr() net.Addr {
  549. return l.listener.Addr()
  550. }
  551. // Close closes the listener.
  552. func (l *Listener) Close() error {
  553. return l.listener.Close()
  554. }
  555. // Listen creates an SSH listener accepting connections on
  556. // the given network address using net.Listen.
  557. func Listen(network, addr string, config *ServerConfig) (*Listener, error) {
  558. l, err := net.Listen(network, addr)
  559. if err != nil {
  560. return nil, err
  561. }
  562. return &Listener{
  563. l,
  564. config,
  565. }, nil
  566. }