server.go 23 KB

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