kex.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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/subtle"
  10. "crypto/rand"
  11. "errors"
  12. "io"
  13. "math/big"
  14. "golang.org/x/crypto/curve25519"
  15. )
  16. const (
  17. kexAlgoDH1SHA1 = "diffie-hellman-group1-sha1"
  18. kexAlgoDH14SHA1 = "diffie-hellman-group14-sha1"
  19. kexAlgoECDH256 = "ecdh-sha2-nistp256"
  20. kexAlgoECDH384 = "ecdh-sha2-nistp384"
  21. kexAlgoECDH521 = "ecdh-sha2-nistp521"
  22. kexAlgoCurve25519SHA256 = "curve25519-sha256@libssh.org"
  23. )
  24. // kexResult captures the outcome of a key exchange.
  25. type kexResult struct {
  26. // Session hash. See also RFC 4253, section 8.
  27. H []byte
  28. // Shared secret. See also RFC 4253, section 8.
  29. K []byte
  30. // Host key as hashed into H.
  31. HostKey []byte
  32. // Signature of H.
  33. Signature []byte
  34. // A cryptographic hash function that matches the security
  35. // level of the key exchange algorithm. It is used for
  36. // calculating H, and for deriving keys from H and K.
  37. Hash crypto.Hash
  38. // The session ID, which is the first H computed. This is used
  39. // to signal data inside transport.
  40. SessionID []byte
  41. }
  42. // handshakeMagics contains data that is always included in the
  43. // session hash.
  44. type handshakeMagics struct {
  45. clientVersion, serverVersion []byte
  46. clientKexInit, serverKexInit []byte
  47. }
  48. func (m *handshakeMagics) write(w io.Writer) {
  49. writeString(w, m.clientVersion)
  50. writeString(w, m.serverVersion)
  51. writeString(w, m.clientKexInit)
  52. writeString(w, m.serverKexInit)
  53. }
  54. // kexAlgorithm abstracts different key exchange algorithms.
  55. type kexAlgorithm interface {
  56. // Server runs server-side key agreement, signing the result
  57. // with a hostkey.
  58. Server(p packetConn, rand io.Reader, magics *handshakeMagics, s Signer) (*kexResult, error)
  59. // Client runs the client-side key agreement. Caller is
  60. // responsible for verifying the host key signature.
  61. Client(p packetConn, rand io.Reader, magics *handshakeMagics) (*kexResult, error)
  62. }
  63. // dhGroup is a multiplicative group suitable for implementing Diffie-Hellman key agreement.
  64. type dhGroup struct {
  65. g, p *big.Int
  66. }
  67. func (group *dhGroup) diffieHellman(theirPublic, myPrivate *big.Int) (*big.Int, error) {
  68. if theirPublic.Sign() <= 0 || theirPublic.Cmp(group.p) >= 0 {
  69. return nil, errors.New("ssh: DH parameter out of bounds")
  70. }
  71. return new(big.Int).Exp(theirPublic, myPrivate, group.p), nil
  72. }
  73. func (group *dhGroup) Client(c packetConn, randSource io.Reader, magics *handshakeMagics) (*kexResult, error) {
  74. hashFunc := crypto.SHA1
  75. x, err := rand.Int(randSource, group.p)
  76. if err != nil {
  77. return nil, err
  78. }
  79. X := new(big.Int).Exp(group.g, x, group.p)
  80. kexDHInit := kexDHInitMsg{
  81. X: X,
  82. }
  83. if err := c.writePacket(Marshal(&kexDHInit)); err != nil {
  84. return nil, err
  85. }
  86. packet, err := c.readPacket()
  87. if err != nil {
  88. return nil, err
  89. }
  90. var kexDHReply kexDHReplyMsg
  91. if err = Unmarshal(packet, &kexDHReply); err != nil {
  92. return nil, err
  93. }
  94. kInt, err := group.diffieHellman(kexDHReply.Y, x)
  95. if err != nil {
  96. return nil, err
  97. }
  98. h := hashFunc.New()
  99. magics.write(h)
  100. writeString(h, kexDHReply.HostKey)
  101. writeInt(h, X)
  102. writeInt(h, kexDHReply.Y)
  103. K := make([]byte, intLength(kInt))
  104. marshalInt(K, kInt)
  105. h.Write(K)
  106. return &kexResult{
  107. H: h.Sum(nil),
  108. K: K,
  109. HostKey: kexDHReply.HostKey,
  110. Signature: kexDHReply.Signature,
  111. Hash: crypto.SHA1,
  112. }, nil
  113. }
  114. func (group *dhGroup) Server(c packetConn, randSource io.Reader, magics *handshakeMagics, priv Signer) (result *kexResult, err error) {
  115. hashFunc := crypto.SHA1
  116. packet, err := c.readPacket()
  117. if err != nil {
  118. return
  119. }
  120. var kexDHInit kexDHInitMsg
  121. if err = Unmarshal(packet, &kexDHInit); err != nil {
  122. return
  123. }
  124. y, err := rand.Int(randSource, group.p)
  125. if err != nil {
  126. return
  127. }
  128. Y := new(big.Int).Exp(group.g, y, group.p)
  129. kInt, err := group.diffieHellman(kexDHInit.X, y)
  130. if err != nil {
  131. return nil, err
  132. }
  133. hostKeyBytes := priv.PublicKey().Marshal()
  134. h := hashFunc.New()
  135. magics.write(h)
  136. writeString(h, hostKeyBytes)
  137. writeInt(h, kexDHInit.X)
  138. writeInt(h, Y)
  139. K := make([]byte, intLength(kInt))
  140. marshalInt(K, kInt)
  141. h.Write(K)
  142. H := h.Sum(nil)
  143. // H is already a hash, but the hostkey signing will apply its
  144. // own key-specific hash algorithm.
  145. sig, err := signAndMarshal(priv, randSource, H)
  146. if err != nil {
  147. return nil, err
  148. }
  149. kexDHReply := kexDHReplyMsg{
  150. HostKey: hostKeyBytes,
  151. Y: Y,
  152. Signature: sig,
  153. }
  154. packet = Marshal(&kexDHReply)
  155. err = c.writePacket(packet)
  156. return &kexResult{
  157. H: H,
  158. K: K,
  159. HostKey: hostKeyBytes,
  160. Signature: sig,
  161. Hash: crypto.SHA1,
  162. }, nil
  163. }
  164. // ecdh performs Elliptic Curve Diffie-Hellman key exchange as
  165. // described in RFC 5656, section 4.
  166. type ecdh struct {
  167. curve elliptic.Curve
  168. }
  169. func (kex *ecdh) Client(c packetConn, rand io.Reader, magics *handshakeMagics) (*kexResult, error) {
  170. ephKey, err := ecdsa.GenerateKey(kex.curve, rand)
  171. if err != nil {
  172. return nil, err
  173. }
  174. kexInit := kexECDHInitMsg{
  175. ClientPubKey: elliptic.Marshal(kex.curve, ephKey.PublicKey.X, ephKey.PublicKey.Y),
  176. }
  177. serialized := Marshal(&kexInit)
  178. if err := c.writePacket(serialized); err != nil {
  179. return nil, err
  180. }
  181. packet, err := c.readPacket()
  182. if err != nil {
  183. return nil, err
  184. }
  185. var reply kexECDHReplyMsg
  186. if err = Unmarshal(packet, &reply); err != nil {
  187. return nil, err
  188. }
  189. x, y, err := unmarshalECKey(kex.curve, reply.EphemeralPubKey)
  190. if err != nil {
  191. return nil, err
  192. }
  193. // generate shared secret
  194. secret, _ := kex.curve.ScalarMult(x, y, ephKey.D.Bytes())
  195. h := ecHash(kex.curve).New()
  196. magics.write(h)
  197. writeString(h, reply.HostKey)
  198. writeString(h, kexInit.ClientPubKey)
  199. writeString(h, reply.EphemeralPubKey)
  200. K := make([]byte, intLength(secret))
  201. marshalInt(K, secret)
  202. h.Write(K)
  203. return &kexResult{
  204. H: h.Sum(nil),
  205. K: K,
  206. HostKey: reply.HostKey,
  207. Signature: reply.Signature,
  208. Hash: ecHash(kex.curve),
  209. }, nil
  210. }
  211. // unmarshalECKey parses and checks an EC key.
  212. func unmarshalECKey(curve elliptic.Curve, pubkey []byte) (x, y *big.Int, err error) {
  213. x, y = elliptic.Unmarshal(curve, pubkey)
  214. if x == nil {
  215. return nil, nil, errors.New("ssh: elliptic.Unmarshal failure")
  216. }
  217. if !validateECPublicKey(curve, x, y) {
  218. return nil, nil, errors.New("ssh: public key not on curve")
  219. }
  220. return x, y, nil
  221. }
  222. // validateECPublicKey checks that the point is a valid public key for
  223. // the given curve. See [SEC1], 3.2.2
  224. func validateECPublicKey(curve elliptic.Curve, x, y *big.Int) bool {
  225. if x.Sign() == 0 && y.Sign() == 0 {
  226. return false
  227. }
  228. if x.Cmp(curve.Params().P) >= 0 {
  229. return false
  230. }
  231. if y.Cmp(curve.Params().P) >= 0 {
  232. return false
  233. }
  234. if !curve.IsOnCurve(x, y) {
  235. return false
  236. }
  237. // We don't check if N * PubKey == 0, since
  238. //
  239. // - the NIST curves have cofactor = 1, so this is implicit.
  240. // (We don't foresee an implementation that supports non NIST
  241. // curves)
  242. //
  243. // - for ephemeral keys, we don't need to worry about small
  244. // subgroup attacks.
  245. return true
  246. }
  247. func (kex *ecdh) Server(c packetConn, rand io.Reader, magics *handshakeMagics, priv Signer) (result *kexResult, err error) {
  248. packet, err := c.readPacket()
  249. if err != nil {
  250. return nil, err
  251. }
  252. var kexECDHInit kexECDHInitMsg
  253. if err = Unmarshal(packet, &kexECDHInit); err != nil {
  254. return nil, err
  255. }
  256. clientX, clientY, err := unmarshalECKey(kex.curve, kexECDHInit.ClientPubKey)
  257. if err != nil {
  258. return nil, err
  259. }
  260. // We could cache this key across multiple users/multiple
  261. // connection attempts, but the benefit is small. OpenSSH
  262. // generates a new key for each incoming connection.
  263. ephKey, err := ecdsa.GenerateKey(kex.curve, rand)
  264. if err != nil {
  265. return nil, err
  266. }
  267. hostKeyBytes := priv.PublicKey().Marshal()
  268. serializedEphKey := elliptic.Marshal(kex.curve, ephKey.PublicKey.X, ephKey.PublicKey.Y)
  269. // generate shared secret
  270. secret, _ := kex.curve.ScalarMult(clientX, clientY, ephKey.D.Bytes())
  271. h := ecHash(kex.curve).New()
  272. magics.write(h)
  273. writeString(h, hostKeyBytes)
  274. writeString(h, kexECDHInit.ClientPubKey)
  275. writeString(h, serializedEphKey)
  276. K := make([]byte, intLength(secret))
  277. marshalInt(K, secret)
  278. h.Write(K)
  279. H := h.Sum(nil)
  280. // H is already a hash, but the hostkey signing will apply its
  281. // own key-specific hash algorithm.
  282. sig, err := signAndMarshal(priv, rand, H)
  283. if err != nil {
  284. return nil, err
  285. }
  286. reply := kexECDHReplyMsg{
  287. EphemeralPubKey: serializedEphKey,
  288. HostKey: hostKeyBytes,
  289. Signature: sig,
  290. }
  291. serialized := Marshal(&reply)
  292. if err := c.writePacket(serialized); err != nil {
  293. return nil, err
  294. }
  295. return &kexResult{
  296. H: H,
  297. K: K,
  298. HostKey: reply.HostKey,
  299. Signature: sig,
  300. Hash: ecHash(kex.curve),
  301. }, nil
  302. }
  303. var kexAlgoMap = map[string]kexAlgorithm{}
  304. func init() {
  305. // This is the group called diffie-hellman-group1-sha1 in RFC
  306. // 4253 and Oakley Group 2 in RFC 2409.
  307. p, _ := new(big.Int).SetString("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF", 16)
  308. kexAlgoMap[kexAlgoDH1SHA1] = &dhGroup{
  309. g: new(big.Int).SetInt64(2),
  310. p: p,
  311. }
  312. // This is the group called diffie-hellman-group14-sha1 in RFC
  313. // 4253 and Oakley Group 14 in RFC 3526.
  314. p, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF", 16)
  315. kexAlgoMap[kexAlgoDH14SHA1] = &dhGroup{
  316. g: new(big.Int).SetInt64(2),
  317. p: p,
  318. }
  319. kexAlgoMap[kexAlgoECDH521] = &ecdh{elliptic.P521()}
  320. kexAlgoMap[kexAlgoECDH384] = &ecdh{elliptic.P384()}
  321. kexAlgoMap[kexAlgoECDH256] = &ecdh{elliptic.P256()}
  322. kexAlgoMap[kexAlgoCurve25519SHA256] = &curve25519sha256{}
  323. }
  324. // curve25519sha256 implements the curve25519-sha256@libssh.org key
  325. // agreement protocol, as described in
  326. // https://git.libssh.org/projects/libssh.git/tree/doc/curve25519-sha256@libssh.org.txt
  327. type curve25519sha256 struct{}
  328. type curve25519KeyPair struct {
  329. priv [32]byte
  330. pub [32]byte
  331. }
  332. func (kp *curve25519KeyPair) generate(rand io.Reader) error {
  333. if _, err := io.ReadFull(rand, kp.priv[:]); err != nil {
  334. return err
  335. }
  336. curve25519.ScalarBaseMult(&kp.pub, &kp.priv)
  337. return nil
  338. }
  339. // curve25519Zeros is just an array of 32 zero bytes so that we have something
  340. // convenient to compare against in order to reject curve25519 points with the
  341. // wrong order.
  342. var curve25519Zeros [32]byte
  343. func (kex *curve25519sha256) Client(c packetConn, rand io.Reader, magics *handshakeMagics) (*kexResult, error) {
  344. var kp curve25519KeyPair
  345. if err := kp.generate(rand); err != nil {
  346. return nil, err
  347. }
  348. if err := c.writePacket(Marshal(&kexECDHInitMsg{kp.pub[:]})); err != nil {
  349. return nil, err
  350. }
  351. packet, err := c.readPacket()
  352. if err != nil {
  353. return nil, err
  354. }
  355. var reply kexECDHReplyMsg
  356. if err = Unmarshal(packet, &reply); err != nil {
  357. return nil, err
  358. }
  359. if len(reply.EphemeralPubKey) != 32 {
  360. return nil, errors.New("ssh: peer's curve25519 public value has wrong length")
  361. }
  362. var servPub, secret [32]byte
  363. copy(servPub[:], reply.EphemeralPubKey)
  364. curve25519.ScalarMult(&secret, &kp.priv, &servPub)
  365. if subtle.ConstantTimeCompare(secret[:], curve25519Zeros[:]) == 1 {
  366. return nil, errors.New("ssh: peer's curve25519 public value has wrong order")
  367. }
  368. h := crypto.SHA256.New()
  369. magics.write(h)
  370. writeString(h, reply.HostKey)
  371. writeString(h, kp.pub[:])
  372. writeString(h, reply.EphemeralPubKey)
  373. kInt := new(big.Int).SetBytes(secret[:])
  374. K := make([]byte, intLength(kInt))
  375. marshalInt(K, kInt)
  376. h.Write(K)
  377. return &kexResult{
  378. H: h.Sum(nil),
  379. K: K,
  380. HostKey: reply.HostKey,
  381. Signature: reply.Signature,
  382. Hash: crypto.SHA256,
  383. }, nil
  384. }
  385. func (kex *curve25519sha256) Server(c packetConn, rand io.Reader, magics *handshakeMagics, priv Signer) (result *kexResult, err error) {
  386. packet, err := c.readPacket()
  387. if err != nil {
  388. return
  389. }
  390. var kexInit kexECDHInitMsg
  391. if err = Unmarshal(packet, &kexInit); err != nil {
  392. return
  393. }
  394. if len(kexInit.ClientPubKey) != 32 {
  395. return nil, errors.New("ssh: peer's curve25519 public value has wrong length")
  396. }
  397. var kp curve25519KeyPair
  398. if err := kp.generate(rand); err != nil {
  399. return nil, err
  400. }
  401. var clientPub, secret [32]byte
  402. copy(clientPub[:], kexInit.ClientPubKey)
  403. curve25519.ScalarMult(&secret, &kp.priv, &clientPub)
  404. if subtle.ConstantTimeCompare(secret[:], curve25519Zeros[:]) == 1 {
  405. return nil, errors.New("ssh: peer's curve25519 public value has wrong order")
  406. }
  407. hostKeyBytes := priv.PublicKey().Marshal()
  408. h := crypto.SHA256.New()
  409. magics.write(h)
  410. writeString(h, hostKeyBytes)
  411. writeString(h, kexInit.ClientPubKey)
  412. writeString(h, kp.pub[:])
  413. kInt := new(big.Int).SetBytes(secret[:])
  414. K := make([]byte, intLength(kInt))
  415. marshalInt(K, kInt)
  416. h.Write(K)
  417. H := h.Sum(nil)
  418. sig, err := signAndMarshal(priv, rand, H)
  419. if err != nil {
  420. return nil, err
  421. }
  422. reply := kexECDHReplyMsg{
  423. EphemeralPubKey: kp.pub[:],
  424. HostKey: hostKeyBytes,
  425. Signature: sig,
  426. }
  427. if err := c.writePacket(Marshal(&reply)); err != nil {
  428. return nil, err
  429. }
  430. return &kexResult{
  431. H: H,
  432. K: K,
  433. HostKey: hostKeyBytes,
  434. Signature: sig,
  435. Hash: crypto.SHA256,
  436. }, nil
  437. }