kex.go 23 KB

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