You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

474 regels
14 KiB

  1. // Copyright 2010 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 tls
  5. import (
  6. "crypto"
  7. "crypto/ecdsa"
  8. "crypto/elliptic"
  9. "crypto/md5"
  10. "crypto/rsa"
  11. "crypto/sha1"
  12. "crypto/x509"
  13. "encoding/asn1"
  14. "errors"
  15. "io"
  16. "math/big"
  17. "golang_org/x/crypto/curve25519"
  18. )
  19. var errClientKeyExchange = errors.New("tls: invalid ClientKeyExchange message")
  20. var errServerKeyExchange = errors.New("tls: invalid ServerKeyExchange message")
  21. // rsaKeyAgreement implements the standard TLS key agreement where the client
  22. // encrypts the pre-master secret to the server's public key.
  23. type rsaKeyAgreement struct{}
  24. func (ka rsaKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
  25. return nil, nil
  26. }
  27. func (ka rsaKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
  28. if len(ckx.ciphertext) < 2 {
  29. return nil, errClientKeyExchange
  30. }
  31. ciphertext := ckx.ciphertext
  32. if version != VersionSSL30 {
  33. ciphertextLen := int(ckx.ciphertext[0])<<8 | int(ckx.ciphertext[1])
  34. if ciphertextLen != len(ckx.ciphertext)-2 {
  35. return nil, errClientKeyExchange
  36. }
  37. ciphertext = ckx.ciphertext[2:]
  38. }
  39. priv, ok := cert.PrivateKey.(crypto.Decrypter)
  40. if !ok {
  41. return nil, errors.New("tls: certificate private key does not implement crypto.Decrypter")
  42. }
  43. // Perform constant time RSA PKCS#1 v1.5 decryption
  44. preMasterSecret, err := priv.Decrypt(config.rand(), ciphertext, &rsa.PKCS1v15DecryptOptions{SessionKeyLen: 48})
  45. if err != nil {
  46. return nil, err
  47. }
  48. // We don't check the version number in the premaster secret. For one,
  49. // by checking it, we would leak information about the validity of the
  50. // encrypted pre-master secret. Secondly, it provides only a small
  51. // benefit against a downgrade attack and some implementations send the
  52. // wrong version anyway. See the discussion at the end of section
  53. // 7.4.7.1 of RFC 4346.
  54. return preMasterSecret, nil
  55. }
  56. func (ka rsaKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
  57. return errors.New("tls: unexpected ServerKeyExchange")
  58. }
  59. func (ka rsaKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
  60. preMasterSecret := make([]byte, 48)
  61. preMasterSecret[0] = byte(clientHello.vers >> 8)
  62. preMasterSecret[1] = byte(clientHello.vers)
  63. _, err := io.ReadFull(config.rand(), preMasterSecret[2:])
  64. if err != nil {
  65. return nil, nil, err
  66. }
  67. encrypted, err := rsa.EncryptPKCS1v15(config.rand(), cert.PublicKey.(*rsa.PublicKey), preMasterSecret)
  68. if err != nil {
  69. return nil, nil, err
  70. }
  71. ckx := new(clientKeyExchangeMsg)
  72. ckx.ciphertext = make([]byte, len(encrypted)+2)
  73. ckx.ciphertext[0] = byte(len(encrypted) >> 8)
  74. ckx.ciphertext[1] = byte(len(encrypted))
  75. copy(ckx.ciphertext[2:], encrypted)
  76. return preMasterSecret, ckx, nil
  77. }
  78. // sha1Hash calculates a SHA1 hash over the given byte slices.
  79. func sha1Hash(slices [][]byte) []byte {
  80. hsha1 := sha1.New()
  81. for _, slice := range slices {
  82. hsha1.Write(slice)
  83. }
  84. return hsha1.Sum(nil)
  85. }
  86. // md5SHA1Hash implements TLS 1.0's hybrid hash function which consists of the
  87. // concatenation of an MD5 and SHA1 hash.
  88. func md5SHA1Hash(slices [][]byte) []byte {
  89. md5sha1 := make([]byte, md5.Size+sha1.Size)
  90. hmd5 := md5.New()
  91. for _, slice := range slices {
  92. hmd5.Write(slice)
  93. }
  94. copy(md5sha1, hmd5.Sum(nil))
  95. copy(md5sha1[md5.Size:], sha1Hash(slices))
  96. return md5sha1
  97. }
  98. // hashForServerKeyExchange hashes the given slices and returns their digest
  99. // and the identifier of the hash function used. The sigAndHash argument is
  100. // only used for >= TLS 1.2 and precisely identifies the hash function to use.
  101. func hashForServerKeyExchange(sigAndHash signatureAndHash, version uint16, slices ...[]byte) ([]byte, crypto.Hash, error) {
  102. if version >= VersionTLS12 {
  103. if !isSupportedSignatureAndHash(sigAndHash, supportedSignatureAlgorithms) {
  104. return nil, crypto.Hash(0), errors.New("tls: unsupported hash function used by peer")
  105. }
  106. hashFunc, err := lookupTLSHash(sigAndHash.hash)
  107. if err != nil {
  108. return nil, crypto.Hash(0), err
  109. }
  110. h := hashFunc.New()
  111. for _, slice := range slices {
  112. h.Write(slice)
  113. }
  114. digest := h.Sum(nil)
  115. return digest, hashFunc, nil
  116. }
  117. if sigAndHash.signature == signatureECDSA {
  118. return sha1Hash(slices), crypto.SHA1, nil
  119. }
  120. return md5SHA1Hash(slices), crypto.MD5SHA1, nil
  121. }
  122. // pickTLS12HashForSignature returns a TLS 1.2 hash identifier for signing a
  123. // ServerKeyExchange given the signature type being used and the client's
  124. // advertised list of supported signature and hash combinations.
  125. func pickTLS12HashForSignature(sigType uint8, clientList []signatureAndHash) (uint8, error) {
  126. if len(clientList) == 0 {
  127. // If the client didn't specify any signature_algorithms
  128. // extension then we can assume that it supports SHA1. See
  129. // http://tools.ietf.org/html/rfc5246#section-7.4.1.4.1
  130. return hashSHA1, nil
  131. }
  132. for _, sigAndHash := range clientList {
  133. if sigAndHash.signature != sigType {
  134. continue
  135. }
  136. if isSupportedSignatureAndHash(sigAndHash, supportedSignatureAlgorithms) {
  137. return sigAndHash.hash, nil
  138. }
  139. }
  140. return 0, errors.New("tls: client doesn't support any common hash functions")
  141. }
  142. func curveForCurveID(id CurveID) (elliptic.Curve, bool) {
  143. switch id {
  144. case CurveP256:
  145. return elliptic.P256(), true
  146. case CurveP384:
  147. return elliptic.P384(), true
  148. case CurveP521:
  149. return elliptic.P521(), true
  150. default:
  151. return nil, false
  152. }
  153. }
  154. // ecdheRSAKeyAgreement implements a TLS key agreement where the server
  155. // generates a ephemeral EC public/private key pair and signs it. The
  156. // pre-master secret is then calculated using ECDH. The signature may
  157. // either be ECDSA or RSA.
  158. type ecdheKeyAgreement struct {
  159. version uint16
  160. sigType uint8
  161. privateKey []byte
  162. curveid CurveID
  163. // publicKey is used to store the peer's public value when X25519 is
  164. // being used.
  165. publicKey []byte
  166. // x and y are used to store the peer's public value when one of the
  167. // NIST curves is being used.
  168. x, y *big.Int
  169. }
  170. func (ka *ecdheKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
  171. preferredCurves := config.curvePreferences()
  172. NextCandidate:
  173. for _, candidate := range preferredCurves {
  174. for _, c := range clientHello.supportedCurves {
  175. if candidate == c {
  176. ka.curveid = c
  177. break NextCandidate
  178. }
  179. }
  180. }
  181. if ka.curveid == 0 {
  182. return nil, errors.New("tls: no supported elliptic curves offered")
  183. }
  184. var ecdhePublic []byte
  185. if ka.curveid == X25519 {
  186. var scalar, public [32]byte
  187. if _, err := io.ReadFull(config.rand(), scalar[:]); err != nil {
  188. return nil, err
  189. }
  190. curve25519.ScalarBaseMult(&public, &scalar)
  191. ka.privateKey = scalar[:]
  192. ecdhePublic = public[:]
  193. } else {
  194. curve, ok := curveForCurveID(ka.curveid)
  195. if !ok {
  196. return nil, errors.New("tls: preferredCurves includes unsupported curve")
  197. }
  198. var x, y *big.Int
  199. var err error
  200. ka.privateKey, x, y, err = elliptic.GenerateKey(curve, config.rand())
  201. if err != nil {
  202. return nil, err
  203. }
  204. ecdhePublic = elliptic.Marshal(curve, x, y)
  205. }
  206. // http://tools.ietf.org/html/rfc4492#section-5.4
  207. serverECDHParams := make([]byte, 1+2+1+len(ecdhePublic))
  208. serverECDHParams[0] = 3 // named curve
  209. serverECDHParams[1] = byte(ka.curveid >> 8)
  210. serverECDHParams[2] = byte(ka.curveid)
  211. serverECDHParams[3] = byte(len(ecdhePublic))
  212. copy(serverECDHParams[4:], ecdhePublic)
  213. sigAndHash := signatureAndHash{signature: ka.sigType}
  214. if ka.version >= VersionTLS12 {
  215. var err error
  216. if sigAndHash.hash, err = pickTLS12HashForSignature(ka.sigType, clientHello.signatureAndHashes); err != nil {
  217. return nil, err
  218. }
  219. }
  220. digest, hashFunc, err := hashForServerKeyExchange(sigAndHash, ka.version, clientHello.random, hello.random, serverECDHParams)
  221. if err != nil {
  222. return nil, err
  223. }
  224. priv, ok := cert.PrivateKey.(crypto.Signer)
  225. if !ok {
  226. return nil, errors.New("tls: certificate private key does not implement crypto.Signer")
  227. }
  228. var sig []byte
  229. switch ka.sigType {
  230. case signatureECDSA:
  231. _, ok := priv.Public().(*ecdsa.PublicKey)
  232. if !ok {
  233. return nil, errors.New("tls: ECDHE ECDSA requires an ECDSA server key")
  234. }
  235. case signatureRSA:
  236. _, ok := priv.Public().(*rsa.PublicKey)
  237. if !ok {
  238. return nil, errors.New("tls: ECDHE RSA requires a RSA server key")
  239. }
  240. default:
  241. return nil, errors.New("tls: unknown ECDHE signature algorithm")
  242. }
  243. sig, err = priv.Sign(config.rand(), digest, hashFunc)
  244. if err != nil {
  245. return nil, errors.New("tls: failed to sign ECDHE parameters: " + err.Error())
  246. }
  247. skx := new(serverKeyExchangeMsg)
  248. sigAndHashLen := 0
  249. if ka.version >= VersionTLS12 {
  250. sigAndHashLen = 2
  251. }
  252. skx.key = make([]byte, len(serverECDHParams)+sigAndHashLen+2+len(sig))
  253. copy(skx.key, serverECDHParams)
  254. k := skx.key[len(serverECDHParams):]
  255. if ka.version >= VersionTLS12 {
  256. k[0] = sigAndHash.hash
  257. k[1] = sigAndHash.signature
  258. k = k[2:]
  259. }
  260. k[0] = byte(len(sig) >> 8)
  261. k[1] = byte(len(sig))
  262. copy(k[2:], sig)
  263. return skx, nil
  264. }
  265. func (ka *ecdheKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
  266. if len(ckx.ciphertext) == 0 || int(ckx.ciphertext[0]) != len(ckx.ciphertext)-1 {
  267. return nil, errClientKeyExchange
  268. }
  269. if ka.curveid == X25519 {
  270. if len(ckx.ciphertext) != 1+32 {
  271. return nil, errClientKeyExchange
  272. }
  273. var theirPublic, sharedKey, scalar [32]byte
  274. copy(theirPublic[:], ckx.ciphertext[1:])
  275. copy(scalar[:], ka.privateKey)
  276. curve25519.ScalarMult(&sharedKey, &scalar, &theirPublic)
  277. return sharedKey[:], nil
  278. }
  279. curve, ok := curveForCurveID(ka.curveid)
  280. if !ok {
  281. panic("internal error")
  282. }
  283. x, y := elliptic.Unmarshal(curve, ckx.ciphertext[1:])
  284. if x == nil {
  285. return nil, errClientKeyExchange
  286. }
  287. x, _ = curve.ScalarMult(x, y, ka.privateKey)
  288. curveSize := (curve.Params().BitSize + 7) >> 3
  289. xBytes := x.Bytes()
  290. if len(xBytes) == curveSize {
  291. return xBytes, nil
  292. }
  293. preMasterSecret := make([]byte, curveSize)
  294. copy(preMasterSecret[len(preMasterSecret)-len(xBytes):], xBytes)
  295. return preMasterSecret, nil
  296. }
  297. func (ka *ecdheKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
  298. if len(skx.key) < 4 {
  299. return errServerKeyExchange
  300. }
  301. if skx.key[0] != 3 { // named curve
  302. return errors.New("tls: server selected unsupported curve")
  303. }
  304. ka.curveid = CurveID(skx.key[1])<<8 | CurveID(skx.key[2])
  305. publicLen := int(skx.key[3])
  306. if publicLen+4 > len(skx.key) {
  307. return errServerKeyExchange
  308. }
  309. serverECDHParams := skx.key[:4+publicLen]
  310. publicKey := serverECDHParams[4:]
  311. sig := skx.key[4+publicLen:]
  312. if len(sig) < 2 {
  313. return errServerKeyExchange
  314. }
  315. if ka.curveid == X25519 {
  316. if len(publicKey) != 32 {
  317. return errors.New("tls: bad X25519 public value")
  318. }
  319. ka.publicKey = publicKey
  320. } else {
  321. curve, ok := curveForCurveID(ka.curveid)
  322. if !ok {
  323. return errors.New("tls: server selected unsupported curve")
  324. }
  325. ka.x, ka.y = elliptic.Unmarshal(curve, publicKey)
  326. if ka.x == nil {
  327. return errServerKeyExchange
  328. }
  329. if !curve.IsOnCurve(ka.x, ka.y) {
  330. return errServerKeyExchange
  331. }
  332. }
  333. sigAndHash := signatureAndHash{signature: ka.sigType}
  334. if ka.version >= VersionTLS12 {
  335. // handle SignatureAndHashAlgorithm
  336. sigAndHash = signatureAndHash{hash: sig[0], signature: sig[1]}
  337. if sigAndHash.signature != ka.sigType {
  338. return errServerKeyExchange
  339. }
  340. sig = sig[2:]
  341. if len(sig) < 2 {
  342. return errServerKeyExchange
  343. }
  344. }
  345. sigLen := int(sig[0])<<8 | int(sig[1])
  346. if sigLen+2 != len(sig) {
  347. return errServerKeyExchange
  348. }
  349. sig = sig[2:]
  350. digest, hashFunc, err := hashForServerKeyExchange(sigAndHash, ka.version, clientHello.random, serverHello.random, serverECDHParams)
  351. if err != nil {
  352. return err
  353. }
  354. switch ka.sigType {
  355. case signatureECDSA:
  356. pubKey, ok := cert.PublicKey.(*ecdsa.PublicKey)
  357. if !ok {
  358. return errors.New("tls: ECDHE ECDSA requires a ECDSA server public key")
  359. }
  360. ecdsaSig := new(ecdsaSignature)
  361. if _, err := asn1.Unmarshal(sig, ecdsaSig); err != nil {
  362. return err
  363. }
  364. if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
  365. return errors.New("tls: ECDSA signature contained zero or negative values")
  366. }
  367. if !ecdsa.Verify(pubKey, digest, ecdsaSig.R, ecdsaSig.S) {
  368. return errors.New("tls: ECDSA verification failure")
  369. }
  370. case signatureRSA:
  371. pubKey, ok := cert.PublicKey.(*rsa.PublicKey)
  372. if !ok {
  373. return errors.New("tls: ECDHE RSA requires a RSA server public key")
  374. }
  375. if err := rsa.VerifyPKCS1v15(pubKey, hashFunc, digest, sig); err != nil {
  376. return err
  377. }
  378. default:
  379. return errors.New("tls: unknown ECDHE signature algorithm")
  380. }
  381. return nil
  382. }
  383. func (ka *ecdheKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
  384. if ka.curveid == 0 {
  385. return nil, nil, errors.New("tls: missing ServerKeyExchange message")
  386. }
  387. var serialized, preMasterSecret []byte
  388. if ka.curveid == X25519 {
  389. var ourPublic, theirPublic, sharedKey, scalar [32]byte
  390. if _, err := io.ReadFull(config.rand(), scalar[:]); err != nil {
  391. return nil, nil, err
  392. }
  393. copy(theirPublic[:], ka.publicKey)
  394. curve25519.ScalarBaseMult(&ourPublic, &scalar)
  395. curve25519.ScalarMult(&sharedKey, &scalar, &theirPublic)
  396. serialized = ourPublic[:]
  397. preMasterSecret = sharedKey[:]
  398. } else {
  399. curve, ok := curveForCurveID(ka.curveid)
  400. if !ok {
  401. panic("internal error")
  402. }
  403. priv, mx, my, err := elliptic.GenerateKey(curve, config.rand())
  404. if err != nil {
  405. return nil, nil, err
  406. }
  407. x, _ := curve.ScalarMult(ka.x, ka.y, priv)
  408. preMasterSecret = make([]byte, (curve.Params().BitSize+7)>>3)
  409. xBytes := x.Bytes()
  410. copy(preMasterSecret[len(preMasterSecret)-len(xBytes):], xBytes)
  411. serialized = elliptic.Marshal(curve, mx, my)
  412. }
  413. ckx := new(clientKeyExchangeMsg)
  414. ckx.ciphertext = make([]byte, 1+len(serialized))
  415. ckx.ciphertext[0] = byte(len(serialized))
  416. copy(ckx.ciphertext[1:], serialized)
  417. return preMasterSecret, ckx, nil
  418. }