kex.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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. "errors"
  11. "io"
  12. "math/big"
  13. )
  14. const (
  15. kexAlgoDH1SHA1 = "diffie-hellman-group1-sha1"
  16. kexAlgoDH14SHA1 = "diffie-hellman-group14-sha1"
  17. kexAlgoECDH256 = "ecdh-sha2-nistp256"
  18. kexAlgoECDH384 = "ecdh-sha2-nistp384"
  19. kexAlgoECDH521 = "ecdh-sha2-nistp521"
  20. )
  21. // kexResult captures the outcome of a key exchange.
  22. type kexResult struct {
  23. // Session hash. See also RFC 4253, section 8.
  24. H []byte
  25. // Shared secret. See also RFC 4253, section 8.
  26. K []byte
  27. // Host key as hashed into H
  28. HostKey []byte
  29. // Signature of H
  30. Signature []byte
  31. }
  32. // handshakeMagics contains data that is always included in the
  33. // session hash.
  34. type handshakeMagics struct {
  35. clientVersion, serverVersion []byte
  36. clientKexInit, serverKexInit []byte
  37. }
  38. func (m *handshakeMagics) write(w io.Writer) {
  39. writeString(w, m.clientVersion)
  40. writeString(w, m.serverVersion)
  41. writeString(w, m.clientKexInit)
  42. writeString(w, m.serverKexInit)
  43. }
  44. // kexAlgorithm abstracts different key exchange algorithms.
  45. type kexAlgorithm interface {
  46. // Server runs server-side key agreement, signing the result
  47. // with a hostkey.
  48. Server(p packetConn, rand io.Reader, magics *handshakeMagics, s Signer) (*kexResult, error)
  49. // Client runs the client-side key agreement. Caller is
  50. // responsible for verifying the host key signature.
  51. Client(p packetConn, rand io.Reader, magics *handshakeMagics) (*kexResult, error)
  52. // Hash returns a cryptographic hash function that matches the
  53. // security level of the key exchange algorithm. It is used
  54. // for calculating kexResult.H, and for deriving keys from
  55. // data in kexResult.
  56. Hash() crypto.Hash
  57. }
  58. // dhGroup is a multiplicative group suitable for implementing Diffie-Hellman key agreement.
  59. type dhGroup struct {
  60. g, p *big.Int
  61. }
  62. func (group *dhGroup) Hash() crypto.Hash {
  63. return crypto.SHA1
  64. }
  65. func (group *dhGroup) diffieHellman(theirPublic, myPrivate *big.Int) (*big.Int, error) {
  66. if theirPublic.Sign() <= 0 || theirPublic.Cmp(group.p) >= 0 {
  67. return nil, errors.New("ssh: DH parameter out of bounds")
  68. }
  69. return new(big.Int).Exp(theirPublic, myPrivate, group.p), nil
  70. }
  71. func (group *dhGroup) Client(c packetConn, randSource io.Reader, magics *handshakeMagics) (*kexResult, error) {
  72. hashFunc := crypto.SHA1
  73. x, err := rand.Int(randSource, group.p)
  74. if err != nil {
  75. return nil, err
  76. }
  77. X := new(big.Int).Exp(group.g, x, group.p)
  78. kexDHInit := kexDHInitMsg{
  79. X: X,
  80. }
  81. if err := c.writePacket(marshal(msgKexDHInit, kexDHInit)); err != nil {
  82. return nil, err
  83. }
  84. packet, err := c.readPacket()
  85. if err != nil {
  86. return nil, err
  87. }
  88. var kexDHReply kexDHReplyMsg
  89. if err = unmarshal(&kexDHReply, packet, msgKexDHReply); err != nil {
  90. return nil, err
  91. }
  92. kInt, err := group.diffieHellman(kexDHReply.Y, x)
  93. if err != nil {
  94. return nil, err
  95. }
  96. h := hashFunc.New()
  97. magics.write(h)
  98. writeString(h, kexDHReply.HostKey)
  99. writeInt(h, X)
  100. writeInt(h, kexDHReply.Y)
  101. K := make([]byte, intLength(kInt))
  102. marshalInt(K, kInt)
  103. h.Write(K)
  104. return &kexResult{
  105. H: h.Sum(nil),
  106. K: K,
  107. HostKey: kexDHReply.HostKey,
  108. Signature: kexDHReply.Signature,
  109. }, nil
  110. }
  111. func (group *dhGroup) Server(c packetConn, randSource io.Reader, magics *handshakeMagics, priv Signer) (result *kexResult, err error) {
  112. hashFunc := crypto.SHA1
  113. packet, err := c.readPacket()
  114. if err != nil {
  115. return
  116. }
  117. var kexDHInit kexDHInitMsg
  118. if err = unmarshal(&kexDHInit, packet, msgKexDHInit); err != nil {
  119. return
  120. }
  121. y, err := rand.Int(randSource, group.p)
  122. if err != nil {
  123. return
  124. }
  125. Y := new(big.Int).Exp(group.g, y, group.p)
  126. kInt, err := group.diffieHellman(kexDHInit.X, y)
  127. if err != nil {
  128. return nil, err
  129. }
  130. hostKeyBytes := MarshalPublicKey(priv.PublicKey())
  131. h := hashFunc.New()
  132. magics.write(h)
  133. writeString(h, hostKeyBytes)
  134. writeInt(h, kexDHInit.X)
  135. writeInt(h, Y)
  136. K := make([]byte, intLength(kInt))
  137. marshalInt(K, kInt)
  138. h.Write(K)
  139. H := h.Sum(nil)
  140. // H is already a hash, but the hostkey signing will apply its
  141. // own key-specific hash algorithm.
  142. sig, err := signAndMarshal(priv, randSource, H)
  143. if err != nil {
  144. return nil, err
  145. }
  146. kexDHReply := kexDHReplyMsg{
  147. HostKey: hostKeyBytes,
  148. Y: Y,
  149. Signature: sig,
  150. }
  151. packet = marshal(msgKexDHReply, kexDHReply)
  152. err = c.writePacket(packet)
  153. return &kexResult{
  154. H: H,
  155. K: K,
  156. HostKey: hostKeyBytes,
  157. Signature: sig,
  158. }, nil
  159. }
  160. // ecdh performs Elliptic Curve Diffie-Hellman key exchange as
  161. // described in RFC 5656, section 4.
  162. type ecdh struct {
  163. curve elliptic.Curve
  164. }
  165. func (kex *ecdh) Client(c packetConn, rand io.Reader, magics *handshakeMagics) (*kexResult, error) {
  166. ephKey, err := ecdsa.GenerateKey(kex.curve, rand)
  167. if err != nil {
  168. return nil, err
  169. }
  170. kexInit := kexECDHInitMsg{
  171. ClientPubKey: elliptic.Marshal(kex.curve, ephKey.PublicKey.X, ephKey.PublicKey.Y),
  172. }
  173. serialized := marshal(msgKexECDHInit, kexInit)
  174. if err := c.writePacket(serialized); err != nil {
  175. return nil, err
  176. }
  177. packet, err := c.readPacket()
  178. if err != nil {
  179. return nil, err
  180. }
  181. var reply kexECDHReplyMsg
  182. if err = unmarshal(&reply, packet, msgKexECDHReply); err != nil {
  183. return nil, err
  184. }
  185. x, y, err := unmarshalECKey(kex.curve, reply.EphemeralPubKey)
  186. if err != nil {
  187. return nil, err
  188. }
  189. // generate shared secret
  190. secret, _ := kex.curve.ScalarMult(x, y, ephKey.D.Bytes())
  191. h := ecHash(kex.curve).New()
  192. magics.write(h)
  193. writeString(h, reply.HostKey)
  194. writeString(h, kexInit.ClientPubKey)
  195. writeString(h, reply.EphemeralPubKey)
  196. K := make([]byte, intLength(secret))
  197. marshalInt(K, secret)
  198. h.Write(K)
  199. return &kexResult{
  200. H: h.Sum(nil),
  201. K: K,
  202. HostKey: reply.HostKey,
  203. Signature: reply.Signature,
  204. }, nil
  205. }
  206. // unmarshalECKey parses and checks an EC key.
  207. func unmarshalECKey(curve elliptic.Curve, pubkey []byte) (x, y *big.Int, err error) {
  208. x, y = elliptic.Unmarshal(curve, pubkey)
  209. if x == nil {
  210. return nil, nil, errors.New("ssh: elliptic.Unmarshal failure")
  211. }
  212. if !validateECPublicKey(curve, x, y) {
  213. return nil, nil, errors.New("ssh: public key not on curve")
  214. }
  215. return x, y, nil
  216. }
  217. // validateECPublicKey checks that the point is a valid public key for
  218. // the given curve. See [SEC1], 3.2.2
  219. func validateECPublicKey(curve elliptic.Curve, x, y *big.Int) bool {
  220. if x.Sign() == 0 && y.Sign() == 0 {
  221. return false
  222. }
  223. if x.Cmp(curve.Params().P) >= 0 {
  224. return false
  225. }
  226. if y.Cmp(curve.Params().P) >= 0 {
  227. return false
  228. }
  229. if !curve.IsOnCurve(x, y) {
  230. return false
  231. }
  232. // We don't check if N * PubKey == 0, since
  233. //
  234. // - the NIST curves have cofactor = 1, so this is implicit.
  235. // (We don't forsee an implementation that supports non NIST
  236. // curves)
  237. //
  238. // - for ephemeral keys, we don't need to worry about small
  239. // subgroup attacks.
  240. return true
  241. }
  242. func (kex *ecdh) Server(c packetConn, rand io.Reader, magics *handshakeMagics, priv Signer) (result *kexResult, err error) {
  243. packet, err := c.readPacket()
  244. if err != nil {
  245. return nil, err
  246. }
  247. var kexECDHInit kexECDHInitMsg
  248. if err = unmarshal(&kexECDHInit, packet, msgKexECDHInit); err != nil {
  249. return nil, err
  250. }
  251. clientX, clientY, err := unmarshalECKey(kex.curve, kexECDHInit.ClientPubKey)
  252. if err != nil {
  253. return nil, err
  254. }
  255. // We could cache this key across multiple users/multiple
  256. // connection attempts, but the benefit is small. OpenSSH
  257. // generates a new key for each incoming connection.
  258. ephKey, err := ecdsa.GenerateKey(kex.curve, rand)
  259. if err != nil {
  260. return nil, err
  261. }
  262. hostKeyBytes := MarshalPublicKey(priv.PublicKey())
  263. serializedEphKey := elliptic.Marshal(kex.curve, ephKey.PublicKey.X, ephKey.PublicKey.Y)
  264. // generate shared secret
  265. secret, _ := kex.curve.ScalarMult(clientX, clientY, ephKey.D.Bytes())
  266. h := ecHash(kex.curve).New()
  267. magics.write(h)
  268. writeString(h, hostKeyBytes)
  269. writeString(h, kexECDHInit.ClientPubKey)
  270. writeString(h, serializedEphKey)
  271. K := make([]byte, intLength(secret))
  272. marshalInt(K, secret)
  273. h.Write(K)
  274. H := h.Sum(nil)
  275. // H is already a hash, but the hostkey signing will apply its
  276. // own key-specific hash algorithm.
  277. sig, err := signAndMarshal(priv, rand, H)
  278. if err != nil {
  279. return nil, err
  280. }
  281. reply := kexECDHReplyMsg{
  282. EphemeralPubKey: serializedEphKey,
  283. HostKey: hostKeyBytes,
  284. Signature: sig,
  285. }
  286. serialized := marshal(msgKexECDHReply, reply)
  287. if err := c.writePacket(serialized); err != nil {
  288. return nil, err
  289. }
  290. return &kexResult{
  291. H: H,
  292. K: K,
  293. HostKey: reply.HostKey,
  294. Signature: sig,
  295. }, nil
  296. }
  297. func (kex *ecdh) Hash() crypto.Hash {
  298. return ecHash(kex.curve)
  299. }
  300. var kexAlgoMap = map[string]kexAlgorithm{}
  301. func init() {
  302. // This is the group called diffie-hellman-group1-sha1 in RFC
  303. // 4253 and Oakley Group 2 in RFC 2409.
  304. p, _ := new(big.Int).SetString("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF", 16)
  305. kexAlgoMap[kexAlgoDH1SHA1] = &dhGroup{
  306. g: new(big.Int).SetInt64(2),
  307. p: p,
  308. }
  309. // This is the group called diffie-hellman-group14-sha1 in RFC
  310. // 4253 and Oakley Group 14 in RFC 3526.
  311. p, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF", 16)
  312. kexAlgoMap[kexAlgoDH14SHA1] = &dhGroup{
  313. g: new(big.Int).SetInt64(2),
  314. p: p,
  315. }
  316. kexAlgoMap[kexAlgoECDH521] = &ecdh{elliptic.P521()}
  317. kexAlgoMap[kexAlgoECDH384] = &ecdh{elliptic.P384()}
  318. kexAlgoMap[kexAlgoECDH256] = &ecdh{elliptic.P256()}
  319. }