server.go 19 KB

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