kex.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  1. // Copyright 2013 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. "crypto"
  7. "crypto/ecdsa"
  8. "crypto/elliptic"
  9. "crypto/rand"
  10. "crypto/subtle"
  11. "encoding/binary"
  12. "errors"
  13. "fmt"
  14. "io"
  15. "math/big"
  16. "golang.org/x/crypto/curve25519"
  17. )
  18. const (
  19. kexAlgoDH1SHA1 = "diffie-hellman-group1-sha1"
  20. kexAlgoDH14SHA1 = "diffie-hellman-group14-sha1"
  21. kexAlgoDH14SHA256 = "diffie-hellman-group14-sha256"
  22. kexAlgoDH16SHA512 = "diffie-hellman-group16-sha512"
  23. kexAlgoECDH256 = "ecdh-sha2-nistp256"
  24. kexAlgoECDH384 = "ecdh-sha2-nistp384"
  25. kexAlgoECDH521 = "ecdh-sha2-nistp521"
  26. kexAlgoCurve25519SHA256LibSSH = "curve25519-sha256@libssh.org"
  27. kexAlgoCurve25519SHA256 = "curve25519-sha256"
  28. // For the following kex only the client half contains a production
  29. // ready implementation. The server half only consists of a minimal
  30. // implementation to satisfy the automated tests.
  31. kexAlgoDHGEXSHA1 = "diffie-hellman-group-exchange-sha1"
  32. kexAlgoDHGEXSHA256 = "diffie-hellman-group-exchange-sha256"
  33. )
  34. // kexResult captures the outcome of a key exchange.
  35. type kexResult struct {
  36. // Session hash. See also RFC 4253, section 8.
  37. H []byte
  38. // Shared secret. See also RFC 4253, section 8.
  39. K []byte
  40. // Host key as hashed into H.
  41. HostKey []byte
  42. // Signature of H.
  43. Signature []byte
  44. // A cryptographic hash function that matches the security
  45. // level of the key exchange algorithm. It is used for
  46. // calculating H, and for deriving keys from H and K.
  47. Hash crypto.Hash
  48. // The session ID, which is the first H computed. This is used
  49. // to derive key material inside the transport.
  50. SessionID []byte
  51. }
  52. // handshakeMagics contains data that is always included in the
  53. // session hash.
  54. type handshakeMagics struct {
  55. clientVersion, serverVersion []byte
  56. clientKexInit, serverKexInit []byte
  57. }
  58. func (m *handshakeMagics) write(w io.Writer) {
  59. writeString(w, m.clientVersion)
  60. writeString(w, m.serverVersion)
  61. writeString(w, m.clientKexInit)
  62. writeString(w, m.serverKexInit)
  63. }
  64. // kexAlgorithm abstracts different key exchange algorithms.
  65. type kexAlgorithm interface {
  66. // Server runs server-side key agreement, signing the result
  67. // with a hostkey. algo is the negotiated algorithm, and may
  68. // be a certificate type.
  69. Server(p packetConn, rand io.Reader, magics *handshakeMagics, s AlgorithmSigner, algo string) (*kexResult, error)
  70. // Client runs the client-side key agreement. Caller is
  71. // responsible for verifying the host key signature.
  72. Client(p packetConn, rand io.Reader, magics *handshakeMagics) (*kexResult, error)
  73. }
  74. // dhGroup is a multiplicative group suitable for implementing Diffie-Hellman key agreement.
  75. type dhGroup struct {
  76. g, p, pMinus1 *big.Int
  77. hashFunc crypto.Hash
  78. }
  79. func (group *dhGroup) diffieHellman(theirPublic, myPrivate *big.Int) (*big.Int, error) {
  80. if theirPublic.Cmp(bigOne) <= 0 || theirPublic.Cmp(group.pMinus1) >= 0 {
  81. return nil, errors.New("ssh: DH parameter out of bounds")
  82. }
  83. return new(big.Int).Exp(theirPublic, myPrivate, group.p), nil
  84. }
  85. func (group *dhGroup) Client(c packetConn, randSource io.Reader, magics *handshakeMagics) (*kexResult, error) {
  86. var x *big.Int
  87. for {
  88. var err error
  89. if x, err = rand.Int(randSource, group.pMinus1); err != nil {
  90. return nil, err
  91. }
  92. if x.Sign() > 0 {
  93. break
  94. }
  95. }
  96. X := new(big.Int).Exp(group.g, x, group.p)
  97. kexDHInit := kexDHInitMsg{
  98. X: X,
  99. }
  100. if err := c.writePacket(Marshal(&kexDHInit)); err != nil {
  101. return nil, err
  102. }
  103. packet, err := c.readPacket()
  104. if err != nil {
  105. return nil, err
  106. }
  107. var kexDHReply kexDHReplyMsg
  108. if err = Unmarshal(packet, &kexDHReply); err != nil {
  109. return nil, err
  110. }
  111. ki, err := group.diffieHellman(kexDHReply.Y, x)
  112. if err != nil {
  113. return nil, err
  114. }
  115. h := group.hashFunc.New()
  116. magics.write(h)
  117. writeString(h, kexDHReply.HostKey)
  118. writeInt(h, X)
  119. writeInt(h, kexDHReply.Y)
  120. K := make([]byte, intLength(ki))
  121. marshalInt(K, ki)
  122. h.Write(K)
  123. return &kexResult{
  124. H: h.Sum(nil),
  125. K: K,
  126. HostKey: kexDHReply.HostKey,
  127. Signature: kexDHReply.Signature,
  128. Hash: group.hashFunc,
  129. }, nil
  130. }
  131. func (group *dhGroup) Server(c packetConn, randSource io.Reader, magics *handshakeMagics, priv AlgorithmSigner, algo string) (result *kexResult, err error) {
  132. packet, err := c.readPacket()
  133. if err != nil {
  134. return
  135. }
  136. var kexDHInit kexDHInitMsg
  137. if err = Unmarshal(packet, &kexDHInit); err != nil {
  138. return
  139. }
  140. var y *big.Int
  141. for {
  142. if y, err = rand.Int(randSource, group.pMinus1); err != nil {
  143. return
  144. }
  145. if y.Sign() > 0 {
  146. break
  147. }
  148. }
  149. Y := new(big.Int).Exp(group.g, y, group.p)
  150. ki, err := group.diffieHellman(kexDHInit.X, y)
  151. if err != nil {
  152. return nil, err
  153. }
  154. hostKeyBytes := priv.PublicKey().Marshal()
  155. h := group.hashFunc.New()
  156. magics.write(h)
  157. writeString(h, hostKeyBytes)
  158. writeInt(h, kexDHInit.X)
  159. writeInt(h, Y)
  160. K := make([]byte, intLength(ki))
  161. marshalInt(K, ki)
  162. h.Write(K)
  163. H := h.Sum(nil)
  164. // H is already a hash, but the hostkey signing will apply its
  165. // own key-specific hash algorithm.
  166. sig, err := signAndMarshal(priv, randSource, H, algo)
  167. if err != nil {
  168. return nil, err
  169. }
  170. kexDHReply := kexDHReplyMsg{
  171. HostKey: hostKeyBytes,
  172. Y: Y,
  173. Signature: sig,
  174. }
  175. packet = Marshal(&kexDHReply)
  176. err = c.writePacket(packet)
  177. return &kexResult{
  178. H: H,
  179. K: K,
  180. HostKey: hostKeyBytes,
  181. Signature: sig,
  182. Hash: group.hashFunc,
  183. }, err
  184. }
  185. // ecdh performs Elliptic Curve Diffie-Hellman key exchange as
  186. // described in RFC 5656, section 4.
  187. type ecdh struct {
  188. curve elliptic.Curve
  189. }
  190. func (kex *ecdh) Client(c packetConn, rand io.Reader, magics *handshakeMagics) (*kexResult, error) {
  191. ephKey, err := ecdsa.GenerateKey(kex.curve, rand)
  192. if err != nil {
  193. return nil, err
  194. }
  195. kexInit := kexECDHInitMsg{
  196. ClientPubKey: elliptic.Marshal(kex.curve, ephKey.PublicKey.X, ephKey.PublicKey.Y),
  197. }
  198. serialized := Marshal(&kexInit)
  199. if err := c.writePacket(serialized); err != nil {
  200. return nil, err
  201. }
  202. packet, err := c.readPacket()
  203. if err != nil {
  204. return nil, err
  205. }
  206. var reply kexECDHReplyMsg
  207. if err = Unmarshal(packet, &reply); err != nil {
  208. return nil, err
  209. }
  210. x, y, err := unmarshalECKey(kex.curve, reply.EphemeralPubKey)
  211. if err != nil {
  212. return nil, err
  213. }
  214. // generate shared secret
  215. secret, _ := kex.curve.ScalarMult(x, y, ephKey.D.Bytes())
  216. h := ecHash(kex.curve).New()
  217. magics.write(h)
  218. writeString(h, reply.HostKey)
  219. writeString(h, kexInit.ClientPubKey)
  220. writeString(h, reply.EphemeralPubKey)
  221. K := make([]byte, intLength(secret))
  222. marshalInt(K, secret)
  223. h.Write(K)
  224. return &kexResult{
  225. H: h.Sum(nil),
  226. K: K,
  227. HostKey: reply.HostKey,
  228. Signature: reply.Signature,
  229. Hash: ecHash(kex.curve),
  230. }, nil
  231. }
  232. // unmarshalECKey parses and checks an EC key.
  233. func unmarshalECKey(curve elliptic.Curve, pubkey []byte) (x, y *big.Int, err error) {
  234. x, y = elliptic.Unmarshal(curve, pubkey)
  235. if x == nil {
  236. return nil, nil, errors.New("ssh: elliptic.Unmarshal failure")
  237. }
  238. if !validateECPublicKey(curve, x, y) {
  239. return nil, nil, errors.New("ssh: public key not on curve")
  240. }
  241. return x, y, nil
  242. }
  243. // validateECPublicKey checks that the point is a valid public key for
  244. // the given curve. See [SEC1], 3.2.2
  245. func validateECPublicKey(curve elliptic.Curve, x, y *big.Int) bool {
  246. if x.Sign() == 0 && y.Sign() == 0 {
  247. return false
  248. }
  249. if x.Cmp(curve.Params().P) >= 0 {
  250. return false
  251. }
  252. if y.Cmp(curve.Params().P) >= 0 {
  253. return false
  254. }
  255. if !curve.IsOnCurve(x, y) {
  256. return false
  257. }
  258. // We don't check if N * PubKey == 0, since
  259. //
  260. // - the NIST curves have cofactor = 1, so this is implicit.
  261. // (We don't foresee an implementation that supports non NIST
  262. // curves)
  263. //
  264. // - for ephemeral keys, we don't need to worry about small
  265. // subgroup attacks.
  266. return true
  267. }
  268. func (kex *ecdh) Server(c packetConn, rand io.Reader, magics *handshakeMagics, priv AlgorithmSigner, algo string) (result *kexResult, err error) {
  269. packet, err := c.readPacket()
  270. if err != nil {
  271. return nil, err
  272. }
  273. var kexECDHInit kexECDHInitMsg
  274. if err = Unmarshal(packet, &kexECDHInit); err != nil {
  275. return nil, err
  276. }
  277. clientX, clientY, err := unmarshalECKey(kex.curve, kexECDHInit.ClientPubKey)
  278. if err != nil {
  279. return nil, err
  280. }
  281. // We could cache this key across multiple users/multiple
  282. // connection attempts, but the benefit is small. OpenSSH
  283. // generates a new key for each incoming connection.
  284. ephKey, err := ecdsa.GenerateKey(kex.curve, rand)
  285. if err != nil {
  286. return nil, err
  287. }
  288. hostKeyBytes := priv.PublicKey().Marshal()
  289. serializedEphKey := elliptic.Marshal(kex.curve, ephKey.PublicKey.X, ephKey.PublicKey.Y)
  290. // generate shared secret
  291. secret, _ := kex.curve.ScalarMult(clientX, clientY, ephKey.D.Bytes())
  292. h := ecHash(kex.curve).New()
  293. magics.write(h)
  294. writeString(h, hostKeyBytes)
  295. writeString(h, kexECDHInit.ClientPubKey)
  296. writeString(h, serializedEphKey)
  297. K := make([]byte, intLength(secret))
  298. marshalInt(K, secret)
  299. h.Write(K)
  300. H := h.Sum(nil)
  301. // H is already a hash, but the hostkey signing will apply its
  302. // own key-specific hash algorithm.
  303. sig, err := signAndMarshal(priv, rand, H, algo)
  304. if err != nil {
  305. return nil, err
  306. }
  307. reply := kexECDHReplyMsg{
  308. EphemeralPubKey: serializedEphKey,
  309. HostKey: hostKeyBytes,
  310. Signature: sig,
  311. }
  312. serialized := Marshal(&reply)
  313. if err := c.writePacket(serialized); err != nil {
  314. return nil, err
  315. }
  316. return &kexResult{
  317. H: H,
  318. K: K,
  319. HostKey: reply.HostKey,
  320. Signature: sig,
  321. Hash: ecHash(kex.curve),
  322. }, nil
  323. }
  324. // ecHash returns the hash to match the given elliptic curve, see RFC
  325. // 5656, section 6.2.1
  326. func ecHash(curve elliptic.Curve) crypto.Hash {
  327. bitSize := curve.Params().BitSize
  328. switch {
  329. case bitSize <= 256:
  330. return crypto.SHA256
  331. case bitSize <= 384:
  332. return crypto.SHA384
  333. }
  334. return crypto.SHA512
  335. }
  336. var kexAlgoMap = map[string]kexAlgorithm{}
  337. func init() {
  338. // This is the group called diffie-hellman-group1-sha1 in
  339. // RFC 4253 and Oakley Group 2 in RFC 2409.
  340. p, _ := new(big.Int).SetString("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF", 16)
  341. kexAlgoMap[kexAlgoDH1SHA1] = &dhGroup{
  342. g: new(big.Int).SetInt64(2),
  343. p: p,
  344. pMinus1: new(big.Int).Sub(p, bigOne),
  345. hashFunc: crypto.SHA1,
  346. }
  347. // This are the groups called diffie-hellman-group14-sha1 and
  348. // diffie-hellman-group14-sha256 in RFC 4253 and RFC 8268,
  349. // and Oakley Group 14 in RFC 3526.
  350. p, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF", 16)
  351. group14 := &dhGroup{
  352. g: new(big.Int).SetInt64(2),
  353. p: p,
  354. pMinus1: new(big.Int).Sub(p, bigOne),
  355. }
  356. kexAlgoMap[kexAlgoDH14SHA1] = &dhGroup{
  357. g: group14.g, p: group14.p, pMinus1: group14.pMinus1,
  358. hashFunc: crypto.SHA1,
  359. }
  360. kexAlgoMap[kexAlgoDH14SHA256] = &dhGroup{
  361. g: group14.g, p: group14.p, pMinus1: group14.pMinus1,
  362. hashFunc: crypto.SHA256,
  363. }
  364. // This is the group called diffie-hellman-group16-sha512 in RFC
  365. // 8268 and Oakley Group 16 in RFC 3526.
  366. p, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199FFFFFFFFFFFFFFFF", 16)
  367. kexAlgoMap[kexAlgoDH16SHA512] = &dhGroup{
  368. g: new(big.Int).SetInt64(2),
  369. p: p,
  370. pMinus1: new(big.Int).Sub(p, bigOne),
  371. hashFunc: crypto.SHA512,
  372. }
  373. kexAlgoMap[kexAlgoECDH521] = &ecdh{elliptic.P521()}
  374. kexAlgoMap[kexAlgoECDH384] = &ecdh{elliptic.P384()}
  375. kexAlgoMap[kexAlgoECDH256] = &ecdh{elliptic.P256()}
  376. kexAlgoMap[kexAlgoCurve25519SHA256] = &curve25519sha256{}
  377. kexAlgoMap[kexAlgoCurve25519SHA256LibSSH] = &curve25519sha256{}
  378. kexAlgoMap[kexAlgoDHGEXSHA1] = &dhGEXSHA{hashFunc: crypto.SHA1}
  379. kexAlgoMap[kexAlgoDHGEXSHA256] = &dhGEXSHA{hashFunc: crypto.SHA256}
  380. }
  381. // curve25519sha256 implements the curve25519-sha256 (formerly known as
  382. // curve25519-sha256@libssh.org) key exchange method, as described in RFC 8731.
  383. type curve25519sha256 struct{}
  384. type curve25519KeyPair struct {
  385. priv [32]byte
  386. pub [32]byte
  387. }
  388. func (kp *curve25519KeyPair) generate(rand io.Reader) error {
  389. if _, err := io.ReadFull(rand, kp.priv[:]); err != nil {
  390. return err
  391. }
  392. curve25519.ScalarBaseMult(&kp.pub, &kp.priv)
  393. return nil
  394. }
  395. // curve25519Zeros is just an array of 32 zero bytes so that we have something
  396. // convenient to compare against in order to reject curve25519 points with the
  397. // wrong order.
  398. var curve25519Zeros [32]byte
  399. func (kex *curve25519sha256) Client(c packetConn, rand io.Reader, magics *handshakeMagics) (*kexResult, error) {
  400. var kp curve25519KeyPair
  401. if err := kp.generate(rand); err != nil {
  402. return nil, err
  403. }
  404. if err := c.writePacket(Marshal(&kexECDHInitMsg{kp.pub[:]})); err != nil {
  405. return nil, err
  406. }
  407. packet, err := c.readPacket()
  408. if err != nil {
  409. return nil, err
  410. }
  411. var reply kexECDHReplyMsg
  412. if err = Unmarshal(packet, &reply); err != nil {
  413. return nil, err
  414. }
  415. if len(reply.EphemeralPubKey) != 32 {
  416. return nil, errors.New("ssh: peer's curve25519 public value has wrong length")
  417. }
  418. var servPub, secret [32]byte
  419. copy(servPub[:], reply.EphemeralPubKey)
  420. curve25519.ScalarMult(&secret, &kp.priv, &servPub)
  421. if subtle.ConstantTimeCompare(secret[:], curve25519Zeros[:]) == 1 {
  422. return nil, errors.New("ssh: peer's curve25519 public value has wrong order")
  423. }
  424. h := crypto.SHA256.New()
  425. magics.write(h)
  426. writeString(h, reply.HostKey)
  427. writeString(h, kp.pub[:])
  428. writeString(h, reply.EphemeralPubKey)
  429. ki := new(big.Int).SetBytes(secret[:])
  430. K := make([]byte, intLength(ki))
  431. marshalInt(K, ki)
  432. h.Write(K)
  433. return &kexResult{
  434. H: h.Sum(nil),
  435. K: K,
  436. HostKey: reply.HostKey,
  437. Signature: reply.Signature,
  438. Hash: crypto.SHA256,
  439. }, nil
  440. }
  441. func (kex *curve25519sha256) Server(c packetConn, rand io.Reader, magics *handshakeMagics, priv AlgorithmSigner, algo string) (result *kexResult, err error) {
  442. packet, err := c.readPacket()
  443. if err != nil {
  444. return
  445. }
  446. var kexInit kexECDHInitMsg
  447. if err = Unmarshal(packet, &kexInit); err != nil {
  448. return
  449. }
  450. if len(kexInit.ClientPubKey) != 32 {
  451. return nil, errors.New("ssh: peer's curve25519 public value has wrong length")
  452. }
  453. var kp curve25519KeyPair
  454. if err := kp.generate(rand); err != nil {
  455. return nil, err
  456. }
  457. var clientPub, secret [32]byte
  458. copy(clientPub[:], kexInit.ClientPubKey)
  459. curve25519.ScalarMult(&secret, &kp.priv, &clientPub)
  460. if subtle.ConstantTimeCompare(secret[:], curve25519Zeros[:]) == 1 {
  461. return nil, errors.New("ssh: peer's curve25519 public value has wrong order")
  462. }
  463. hostKeyBytes := priv.PublicKey().Marshal()
  464. h := crypto.SHA256.New()
  465. magics.write(h)
  466. writeString(h, hostKeyBytes)
  467. writeString(h, kexInit.ClientPubKey)
  468. writeString(h, kp.pub[:])
  469. ki := new(big.Int).SetBytes(secret[:])
  470. K := make([]byte, intLength(ki))
  471. marshalInt(K, ki)
  472. h.Write(K)
  473. H := h.Sum(nil)
  474. sig, err := signAndMarshal(priv, rand, H, algo)
  475. if err != nil {
  476. return nil, err
  477. }
  478. reply := kexECDHReplyMsg{
  479. EphemeralPubKey: kp.pub[:],
  480. HostKey: hostKeyBytes,
  481. Signature: sig,
  482. }
  483. if err := c.writePacket(Marshal(&reply)); err != nil {
  484. return nil, err
  485. }
  486. return &kexResult{
  487. H: H,
  488. K: K,
  489. HostKey: hostKeyBytes,
  490. Signature: sig,
  491. Hash: crypto.SHA256,
  492. }, nil
  493. }
  494. // dhGEXSHA implements the diffie-hellman-group-exchange-sha1 and
  495. // diffie-hellman-group-exchange-sha256 key agreement protocols,
  496. // as described in RFC 4419
  497. type dhGEXSHA struct {
  498. hashFunc crypto.Hash
  499. }
  500. const (
  501. dhGroupExchangeMinimumBits = 2048
  502. dhGroupExchangePreferredBits = 2048
  503. dhGroupExchangeMaximumBits = 8192
  504. )
  505. func (gex *dhGEXSHA) Client(c packetConn, randSource io.Reader, magics *handshakeMagics) (*kexResult, error) {
  506. // Send GexRequest
  507. kexDHGexRequest := kexDHGexRequestMsg{
  508. MinBits: dhGroupExchangeMinimumBits,
  509. PreferedBits: dhGroupExchangePreferredBits,
  510. MaxBits: dhGroupExchangeMaximumBits,
  511. }
  512. if err := c.writePacket(Marshal(&kexDHGexRequest)); err != nil {
  513. return nil, err
  514. }
  515. // Receive GexGroup
  516. packet, err := c.readPacket()
  517. if err != nil {
  518. return nil, err
  519. }
  520. var msg kexDHGexGroupMsg
  521. if err = Unmarshal(packet, &msg); err != nil {
  522. return nil, err
  523. }
  524. // reject if p's bit length < dhGroupExchangeMinimumBits or > dhGroupExchangeMaximumBits
  525. if msg.P.BitLen() < dhGroupExchangeMinimumBits || msg.P.BitLen() > dhGroupExchangeMaximumBits {
  526. return nil, fmt.Errorf("ssh: server-generated gex p is out of range (%d bits)", msg.P.BitLen())
  527. }
  528. // Check if g is safe by verifying that 1 < g < p-1
  529. pMinusOne := new(big.Int).Sub(msg.P, bigOne)
  530. if msg.G.Cmp(bigOne) <= 0 || msg.G.Cmp(pMinusOne) >= 0 {
  531. return nil, fmt.Errorf("ssh: server provided gex g is not safe")
  532. }
  533. // Send GexInit
  534. pHalf := new(big.Int).Rsh(msg.P, 1)
  535. x, err := rand.Int(randSource, pHalf)
  536. if err != nil {
  537. return nil, err
  538. }
  539. X := new(big.Int).Exp(msg.G, x, msg.P)
  540. kexDHGexInit := kexDHGexInitMsg{
  541. X: X,
  542. }
  543. if err := c.writePacket(Marshal(&kexDHGexInit)); err != nil {
  544. return nil, err
  545. }
  546. // Receive GexReply
  547. packet, err = c.readPacket()
  548. if err != nil {
  549. return nil, err
  550. }
  551. var kexDHGexReply kexDHGexReplyMsg
  552. if err = Unmarshal(packet, &kexDHGexReply); err != nil {
  553. return nil, err
  554. }
  555. if kexDHGexReply.Y.Cmp(bigOne) <= 0 || kexDHGexReply.Y.Cmp(pMinusOne) >= 0 {
  556. return nil, errors.New("ssh: DH parameter out of bounds")
  557. }
  558. kInt := new(big.Int).Exp(kexDHGexReply.Y, x, msg.P)
  559. // Check if k is safe by verifying that k > 1 and k < p - 1
  560. if kInt.Cmp(bigOne) <= 0 || kInt.Cmp(pMinusOne) >= 0 {
  561. return nil, fmt.Errorf("ssh: derived k is not safe")
  562. }
  563. h := gex.hashFunc.New()
  564. magics.write(h)
  565. writeString(h, kexDHGexReply.HostKey)
  566. binary.Write(h, binary.BigEndian, uint32(dhGroupExchangeMinimumBits))
  567. binary.Write(h, binary.BigEndian, uint32(dhGroupExchangePreferredBits))
  568. binary.Write(h, binary.BigEndian, uint32(dhGroupExchangeMaximumBits))
  569. writeInt(h, msg.P)
  570. writeInt(h, msg.G)
  571. writeInt(h, X)
  572. writeInt(h, kexDHGexReply.Y)
  573. K := make([]byte, intLength(kInt))
  574. marshalInt(K, kInt)
  575. h.Write(K)
  576. return &kexResult{
  577. H: h.Sum(nil),
  578. K: K,
  579. HostKey: kexDHGexReply.HostKey,
  580. Signature: kexDHGexReply.Signature,
  581. Hash: gex.hashFunc,
  582. }, nil
  583. }
  584. // Server half implementation of the Diffie Hellman Key Exchange with SHA1 and SHA256.
  585. //
  586. // This is a minimal implementation to satisfy the automated tests.
  587. func (gex dhGEXSHA) Server(c packetConn, randSource io.Reader, magics *handshakeMagics, priv AlgorithmSigner, algo string) (result *kexResult, err error) {
  588. // Receive GexRequest
  589. packet, err := c.readPacket()
  590. if err != nil {
  591. return
  592. }
  593. var kexDHGexRequest kexDHGexRequestMsg
  594. if err = Unmarshal(packet, &kexDHGexRequest); err != nil {
  595. return
  596. }
  597. // Send GexGroup
  598. // This is the group called diffie-hellman-group14-sha1 in RFC
  599. // 4253 and Oakley Group 14 in RFC 3526.
  600. p, _ := new(big.Int).SetString("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF", 16)
  601. g := big.NewInt(2)
  602. msg := &kexDHGexGroupMsg{
  603. P: p,
  604. G: g,
  605. }
  606. if err := c.writePacket(Marshal(msg)); err != nil {
  607. return nil, err
  608. }
  609. // Receive GexInit
  610. packet, err = c.readPacket()
  611. if err != nil {
  612. return
  613. }
  614. var kexDHGexInit kexDHGexInitMsg
  615. if err = Unmarshal(packet, &kexDHGexInit); err != nil {
  616. return
  617. }
  618. pHalf := new(big.Int).Rsh(p, 1)
  619. y, err := rand.Int(randSource, pHalf)
  620. if err != nil {
  621. return
  622. }
  623. Y := new(big.Int).Exp(g, y, p)
  624. pMinusOne := new(big.Int).Sub(p, bigOne)
  625. if kexDHGexInit.X.Cmp(bigOne) <= 0 || kexDHGexInit.X.Cmp(pMinusOne) >= 0 {
  626. return nil, errors.New("ssh: DH parameter out of bounds")
  627. }
  628. kInt := new(big.Int).Exp(kexDHGexInit.X, y, p)
  629. hostKeyBytes := priv.PublicKey().Marshal()
  630. h := gex.hashFunc.New()
  631. magics.write(h)
  632. writeString(h, hostKeyBytes)
  633. binary.Write(h, binary.BigEndian, uint32(dhGroupExchangeMinimumBits))
  634. binary.Write(h, binary.BigEndian, uint32(dhGroupExchangePreferredBits))
  635. binary.Write(h, binary.BigEndian, uint32(dhGroupExchangeMaximumBits))
  636. writeInt(h, p)
  637. writeInt(h, g)
  638. writeInt(h, kexDHGexInit.X)
  639. writeInt(h, Y)
  640. K := make([]byte, intLength(kInt))
  641. marshalInt(K, kInt)
  642. h.Write(K)
  643. H := h.Sum(nil)
  644. // H is already a hash, but the hostkey signing will apply its
  645. // own key-specific hash algorithm.
  646. sig, err := signAndMarshal(priv, randSource, H, algo)
  647. if err != nil {
  648. return nil, err
  649. }
  650. kexDHGexReply := kexDHGexReplyMsg{
  651. HostKey: hostKeyBytes,
  652. Y: Y,
  653. Signature: sig,
  654. }
  655. packet = Marshal(&kexDHGexReply)
  656. err = c.writePacket(packet)
  657. return &kexResult{
  658. H: H,
  659. K: K,
  660. HostKey: hostKeyBytes,
  661. Signature: sig,
  662. Hash: gex.hashFunc,
  663. }, err
  664. }