server.go 23 KB

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