kex.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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. // A cryptographic hash function that matches the security
  32. // level of the key exchange algorithm. It is used for
  33. // calculating H, and for deriving keys from H and K.
  34. Hash crypto.Hash
  35. // The session ID, which is the first H computed. This is used
  36. // to signal data inside transport.
  37. SessionID []byte
  38. }
  39. // handshakeMagics contains data that is always included in the
  40. // session hash.
  41. type handshakeMagics struct {
  42. clientVersion, serverVersion []byte
  43. clientKexInit, serverKexInit []byte
  44. }
  45. func (m *handshakeMagics) write(w io.Writer) {
  46. writeString(w, m.clientVersion)
  47. writeString(w, m.serverVersion)
  48. writeString(w, m.clientKexInit)
  49. writeString(w, m.serverKexInit)
  50. }
  51. // kexAlgorithm abstracts different key exchange algorithms.
  52. type kexAlgorithm interface {
  53. // Server runs server-side key agreement, signing the result
  54. // with a hostkey.
  55. Server(p packetConn, rand io.Reader, magics *handshakeMagics, s Signer) (*kexResult, error)
  56. // Client runs the client-side key agreement. Caller is
  57. // responsible for verifying the host key signature.
  58. Client(p packetConn, rand io.Reader, magics *handshakeMagics) (*kexResult, error)
  59. }
  60. // dhGroup is a multiplicative group suitable for implementing Diffie-Hellman key agreement.
  61. type dhGroup struct {
  62. g, p *big.Int
  63. }
  64. func (group *dhGroup) diffieHellman(theirPublic, myPrivate *big.Int) (*big.Int, error) {
  65. if theirPublic.Sign() <= 0 || theirPublic.Cmp(group.p) >= 0 {
  66. return nil, errors.New("ssh: DH parameter out of bounds")
  67. }
  68. return new(big.Int).Exp(theirPublic, myPrivate, group.p), nil
  69. }
  70. func (group *dhGroup) Client(c packetConn, randSource io.Reader, magics *handshakeMagics) (*kexResult, error) {
  71. hashFunc := crypto.SHA1
  72. x, err := rand.Int(randSource, group.p)
  73. if err != nil {
  74. return nil, err
  75. }
  76. X := new(big.Int).Exp(group.g, x, group.p)
  77. kexDHInit := kexDHInitMsg{
  78. X: X,
  79. }
  80. if err := c.writePacket(Marshal(&kexDHInit)); err != nil {
  81. return nil, err
  82. }
  83. packet, err := c.readPacket()
  84. if err != nil {
  85. return nil, err
  86. }
  87. var kexDHReply kexDHReplyMsg
  88. if err = Unmarshal(packet, &kexDHReply); err != nil {
  89. return nil, err
  90. }
  91. kInt, err := group.diffieHellman(kexDHReply.Y, x)
  92. if err != nil {
  93. return nil, err
  94. }
  95. h := hashFunc.New()
  96. magics.write(h)
  97. writeString(h, kexDHReply.HostKey)
  98. writeInt(h, X)
  99. writeInt(h, kexDHReply.Y)
  100. K := make([]byte, intLength(kInt))
  101. marshalInt(K, kInt)
  102. h.Write(K)
  103. return &kexResult{
  104. H: h.Sum(nil),
  105. K: K,
  106. HostKey: kexDHReply.HostKey,
  107. Signature: kexDHReply.Signature,
  108. Hash: crypto.SHA1,
  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(packet, &kexDHInit); 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 := priv.PublicKey().Marshal()
  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(&kexDHReply)
  152. err = c.writePacket(packet)
  153. return &kexResult{
  154. H: H,
  155. K: K,
  156. HostKey: hostKeyBytes,
  157. Signature: sig,
  158. Hash: crypto.SHA1,
  159. }, nil
  160. }
  161. // ecdh performs Elliptic Curve Diffie-Hellman key exchange as
  162. // described in RFC 5656, section 4.
  163. type ecdh struct {
  164. curve elliptic.Curve
  165. }
  166. func (kex *ecdh) Client(c packetConn, rand io.Reader, magics *handshakeMagics) (*kexResult, error) {
  167. ephKey, err := ecdsa.GenerateKey(kex.curve, rand)
  168. if err != nil {
  169. return nil, err
  170. }
  171. kexInit := kexECDHInitMsg{
  172. ClientPubKey: elliptic.Marshal(kex.curve, ephKey.PublicKey.X, ephKey.PublicKey.Y),
  173. }
  174. serialized := Marshal(&kexInit)
  175. if err := c.writePacket(serialized); err != nil {
  176. return nil, err
  177. }
  178. packet, err := c.readPacket()
  179. if err != nil {
  180. return nil, err
  181. }
  182. var reply kexECDHReplyMsg
  183. if err = Unmarshal(packet, &reply); err != nil {
  184. return nil, err
  185. }
  186. x, y, err := unmarshalECKey(kex.curve, reply.EphemeralPubKey)
  187. if err != nil {
  188. return nil, err
  189. }
  190. // generate shared secret
  191. secret, _ := kex.curve.ScalarMult(x, y, ephKey.D.Bytes())
  192. h := ecHash(kex.curve).New()
  193. magics.write(h)
  194. writeString(h, reply.HostKey)
  195. writeString(h, kexInit.ClientPubKey)
  196. writeString(h, reply.EphemeralPubKey)
  197. K := make([]byte, intLength(secret))
  198. marshalInt(K, secret)
  199. h.Write(K)
  200. return &kexResult{
  201. H: h.Sum(nil),
  202. K: K,
  203. HostKey: reply.HostKey,
  204. Signature: reply.Signature,
  205. Hash: ecHash(kex.curve),
  206. }, nil
  207. }
  208. // unmarshalECKey parses and checks an EC key.
  209. func unmarshalECKey(curve elliptic.Curve, pubkey []byte) (x, y *big.Int, err error) {
  210. x, y = elliptic.Unmarshal(curve, pubkey)
  211. if x == nil {
  212. return nil, nil, errors.New("ssh: elliptic.Unmarshal failure")
  213. }
  214. if !validateECPublicKey(curve, x, y) {
  215. return nil, nil, errors.New("ssh: public key not on curve")
  216. }
  217. return x, y, nil
  218. }
  219. // validateECPublicKey checks that the point is a valid public key for
  220. // the given curve. See [SEC1], 3.2.2
  221. func validateECPublicKey(curve elliptic.Curve, x, y *big.Int) bool {
  222. if x.Sign() == 0 && y.Sign() == 0 {
  223. return false
  224. }
  225. if x.Cmp(curve.Params().P) >= 0 {
  226. return false
  227. }
  228. if y.Cmp(curve.Params().P) >= 0 {
  229. return false
  230. }
  231. if !curve.IsOnCurve(x, y) {
  232. return false
  233. }
  234. // We don't check if N * PubKey == 0, since
  235. //
  236. // - the NIST curves have cofactor = 1, so this is implicit.
  237. // (We don't foresee an implementation that supports non NIST
  238. // curves)
  239. //
  240. // - for ephemeral keys, we don't need to worry about small
  241. // subgroup attacks.
  242. return true
  243. }
  244. func (kex *ecdh) Server(c packetConn, rand io.Reader, magics *handshakeMagics, priv Signer) (result *kexResult, err error) {
  245. packet, err := c.readPacket()
  246. if err != nil {
  247. return nil, err
  248. }
  249. var kexECDHInit kexECDHInitMsg
  250. if err = Unmarshal(packet, &kexECDHInit); err != nil {
  251. return nil, err
  252. }
  253. clientX, clientY, err := unmarshalECKey(kex.curve, kexECDHInit.ClientPubKey)
  254. if err != nil {
  255. return nil, err
  256. }
  257. // We could cache this key across multiple users/multiple
  258. // connection attempts, but the benefit is small. OpenSSH
  259. // generates a new key for each incoming connection.
  260. ephKey, err := ecdsa.GenerateKey(kex.curve, rand)
  261. if err != nil {
  262. return nil, err
  263. }
  264. hostKeyBytes := priv.PublicKey().Marshal()
  265. serializedEphKey := elliptic.Marshal(kex.curve, ephKey.PublicKey.X, ephKey.PublicKey.Y)
  266. // generate shared secret
  267. secret, _ := kex.curve.ScalarMult(clientX, clientY, ephKey.D.Bytes())
  268. h := ecHash(kex.curve).New()
  269. magics.write(h)
  270. writeString(h, hostKeyBytes)
  271. writeString(h, kexECDHInit.ClientPubKey)
  272. writeString(h, serializedEphKey)
  273. K := make([]byte, intLength(secret))
  274. marshalInt(K, secret)
  275. h.Write(K)
  276. H := h.Sum(nil)
  277. // H is already a hash, but the hostkey signing will apply its
  278. // own key-specific hash algorithm.
  279. sig, err := signAndMarshal(priv, rand, H)
  280. if err != nil {
  281. return nil, err
  282. }
  283. reply := kexECDHReplyMsg{
  284. EphemeralPubKey: serializedEphKey,
  285. HostKey: hostKeyBytes,
  286. Signature: sig,
  287. }
  288. serialized := Marshal(&reply)
  289. if err := c.writePacket(serialized); err != nil {
  290. return nil, err
  291. }
  292. return &kexResult{
  293. H: H,
  294. K: K,
  295. HostKey: reply.HostKey,
  296. Signature: sig,
  297. Hash: ecHash(kex.curve),
  298. }, nil
  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. }