Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

475 рядки
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 signatureAlgorithm argument
  100. // is only used for >= TLS 1.2 and identifies the hash function to use.
  101. func hashForServerKeyExchange(sigType uint8, signatureAlgorithm SignatureScheme, version uint16, slices ...[]byte) ([]byte, crypto.Hash, error) {
  102. if version >= VersionTLS12 {
  103. if !isSupportedSignatureAlgorithm(signatureAlgorithm, supportedSignatureAlgorithms) {
  104. return nil, crypto.Hash(0), errors.New("tls: unsupported hash function used by peer")
  105. }
  106. hashFunc, err := lookupTLSHash(signatureAlgorithm)
  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 sigType == 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 []SignatureScheme) (SignatureScheme, 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. switch sigType {
  131. case signatureRSA:
  132. return PKCS1WithSHA1, nil
  133. case signatureECDSA:
  134. return ECDSAWithSHA1, nil
  135. default:
  136. return 0, errors.New("tls: unknown signature algorithm")
  137. }
  138. }
  139. for _, sigAlg := range clientList {
  140. if signatureFromSignatureScheme(sigAlg) != sigType {
  141. continue
  142. }
  143. if isSupportedSignatureAlgorithm(sigAlg, supportedSignatureAlgorithms) {
  144. return sigAlg, nil
  145. }
  146. }
  147. return 0, errors.New("tls: client doesn't support any common hash functions")
  148. }
  149. func curveForCurveID(id CurveID) (elliptic.Curve, bool) {
  150. switch id {
  151. case CurveP256:
  152. return elliptic.P256(), true
  153. case CurveP384:
  154. return elliptic.P384(), true
  155. case CurveP521:
  156. return elliptic.P521(), true
  157. default:
  158. return nil, false
  159. }
  160. }
  161. // ecdheRSAKeyAgreement implements a TLS key agreement where the server
  162. // generates an ephemeral EC public/private key pair and signs it. The
  163. // pre-master secret is then calculated using ECDH. The signature may
  164. // either be ECDSA or RSA.
  165. type ecdheKeyAgreement struct {
  166. version uint16
  167. sigType uint8
  168. privateKey []byte
  169. curveid CurveID
  170. // publicKey is used to store the peer's public value when X25519 is
  171. // being used.
  172. publicKey []byte
  173. // x and y are used to store the peer's public value when one of the
  174. // NIST curves is being used.
  175. x, y *big.Int
  176. }
  177. func (ka *ecdheKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
  178. preferredCurves := config.curvePreferences()
  179. NextCandidate:
  180. for _, candidate := range preferredCurves {
  181. for _, c := range clientHello.supportedCurves {
  182. if candidate == c {
  183. ka.curveid = c
  184. break NextCandidate
  185. }
  186. }
  187. }
  188. if ka.curveid == 0 {
  189. return nil, errors.New("tls: no supported elliptic curves offered")
  190. }
  191. var ecdhePublic []byte
  192. if ka.curveid == X25519 {
  193. var scalar, public [32]byte
  194. if _, err := io.ReadFull(config.rand(), scalar[:]); err != nil {
  195. return nil, err
  196. }
  197. curve25519.ScalarBaseMult(&public, &scalar)
  198. ka.privateKey = scalar[:]
  199. ecdhePublic = public[:]
  200. } else {
  201. curve, ok := curveForCurveID(ka.curveid)
  202. if !ok {
  203. return nil, errors.New("tls: preferredCurves includes unsupported curve")
  204. }
  205. var x, y *big.Int
  206. var err error
  207. ka.privateKey, x, y, err = elliptic.GenerateKey(curve, config.rand())
  208. if err != nil {
  209. return nil, err
  210. }
  211. ecdhePublic = elliptic.Marshal(curve, x, y)
  212. }
  213. // http://tools.ietf.org/html/rfc4492#section-5.4
  214. serverECDHParams := make([]byte, 1+2+1+len(ecdhePublic))
  215. serverECDHParams[0] = 3 // named curve
  216. serverECDHParams[1] = byte(ka.curveid >> 8)
  217. serverECDHParams[2] = byte(ka.curveid)
  218. serverECDHParams[3] = byte(len(ecdhePublic))
  219. copy(serverECDHParams[4:], ecdhePublic)
  220. var signatureAlgorithm SignatureScheme
  221. if ka.version >= VersionTLS12 {
  222. var err error
  223. signatureAlgorithm, err = pickTLS12HashForSignature(ka.sigType, clientHello.supportedSignatureAlgorithms)
  224. if err != nil {
  225. return nil, err
  226. }
  227. }
  228. digest, hashFunc, err := hashForServerKeyExchange(ka.sigType, signatureAlgorithm, ka.version, clientHello.random, hello.random, serverECDHParams)
  229. if err != nil {
  230. return nil, err
  231. }
  232. priv, ok := cert.PrivateKey.(crypto.Signer)
  233. if !ok {
  234. return nil, errors.New("tls: certificate private key does not implement crypto.Signer")
  235. }
  236. var sig []byte
  237. switch ka.sigType {
  238. case signatureECDSA:
  239. _, ok := priv.Public().(*ecdsa.PublicKey)
  240. if !ok {
  241. return nil, errors.New("tls: ECDHE ECDSA requires an ECDSA server key")
  242. }
  243. case signatureRSA:
  244. _, ok := priv.Public().(*rsa.PublicKey)
  245. if !ok {
  246. return nil, errors.New("tls: ECDHE RSA requires a RSA server key")
  247. }
  248. default:
  249. return nil, errors.New("tls: unknown ECDHE signature algorithm")
  250. }
  251. sig, err = priv.Sign(config.rand(), digest, hashFunc)
  252. if err != nil {
  253. return nil, errors.New("tls: failed to sign ECDHE parameters: " + err.Error())
  254. }
  255. skx := new(serverKeyExchangeMsg)
  256. sigAndHashLen := 0
  257. if ka.version >= VersionTLS12 {
  258. sigAndHashLen = 2
  259. }
  260. skx.key = make([]byte, len(serverECDHParams)+sigAndHashLen+2+len(sig))
  261. copy(skx.key, serverECDHParams)
  262. k := skx.key[len(serverECDHParams):]
  263. if ka.version >= VersionTLS12 {
  264. k[0] = byte(signatureAlgorithm >> 8)
  265. k[1] = byte(signatureAlgorithm)
  266. k = k[2:]
  267. }
  268. k[0] = byte(len(sig) >> 8)
  269. k[1] = byte(len(sig))
  270. copy(k[2:], sig)
  271. return skx, nil
  272. }
  273. func (ka *ecdheKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
  274. if len(ckx.ciphertext) == 0 || int(ckx.ciphertext[0]) != len(ckx.ciphertext)-1 {
  275. return nil, errClientKeyExchange
  276. }
  277. if ka.curveid == X25519 {
  278. if len(ckx.ciphertext) != 1+32 {
  279. return nil, errClientKeyExchange
  280. }
  281. var theirPublic, sharedKey, scalar [32]byte
  282. copy(theirPublic[:], ckx.ciphertext[1:])
  283. copy(scalar[:], ka.privateKey)
  284. curve25519.ScalarMult(&sharedKey, &scalar, &theirPublic)
  285. return sharedKey[:], nil
  286. }
  287. curve, ok := curveForCurveID(ka.curveid)
  288. if !ok {
  289. panic("internal error")
  290. }
  291. x, y := elliptic.Unmarshal(curve, ckx.ciphertext[1:]) // Unmarshal also checks whether the given point is on the curve
  292. if x == nil {
  293. return nil, errClientKeyExchange
  294. }
  295. x, _ = curve.ScalarMult(x, y, ka.privateKey)
  296. preMasterSecret := make([]byte, (curve.Params().BitSize+7)>>3)
  297. xBytes := x.Bytes()
  298. copy(preMasterSecret[len(preMasterSecret)-len(xBytes):], xBytes)
  299. return preMasterSecret, nil
  300. }
  301. func (ka *ecdheKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
  302. if len(skx.key) < 4 {
  303. return errServerKeyExchange
  304. }
  305. if skx.key[0] != 3 { // named curve
  306. return errors.New("tls: server selected unsupported curve")
  307. }
  308. ka.curveid = CurveID(skx.key[1])<<8 | CurveID(skx.key[2])
  309. publicLen := int(skx.key[3])
  310. if publicLen+4 > len(skx.key) {
  311. return errServerKeyExchange
  312. }
  313. serverECDHParams := skx.key[:4+publicLen]
  314. publicKey := serverECDHParams[4:]
  315. sig := skx.key[4+publicLen:]
  316. if len(sig) < 2 {
  317. return errServerKeyExchange
  318. }
  319. if ka.curveid == X25519 {
  320. if len(publicKey) != 32 {
  321. return errors.New("tls: bad X25519 public value")
  322. }
  323. ka.publicKey = publicKey
  324. } else {
  325. curve, ok := curveForCurveID(ka.curveid)
  326. if !ok {
  327. return errors.New("tls: server selected unsupported curve")
  328. }
  329. ka.x, ka.y = elliptic.Unmarshal(curve, publicKey) // Unmarshal also checks whether the given point is on the curve
  330. if ka.x == nil {
  331. return errServerKeyExchange
  332. }
  333. }
  334. var signatureAlgorithm SignatureScheme
  335. if ka.version >= VersionTLS12 {
  336. // handle SignatureAndHashAlgorithm
  337. signatureAlgorithm = SignatureScheme(sig[0])<<8 | SignatureScheme(sig[1])
  338. if signatureFromSignatureScheme(signatureAlgorithm) != ka.sigType {
  339. return errServerKeyExchange
  340. }
  341. sig = sig[2:]
  342. if len(sig) < 2 {
  343. return errServerKeyExchange
  344. }
  345. }
  346. sigLen := int(sig[0])<<8 | int(sig[1])
  347. if sigLen+2 != len(sig) {
  348. return errServerKeyExchange
  349. }
  350. sig = sig[2:]
  351. digest, hashFunc, err := hashForServerKeyExchange(ka.sigType, signatureAlgorithm, ka.version, clientHello.random, serverHello.random, serverECDHParams)
  352. if err != nil {
  353. return err
  354. }
  355. switch ka.sigType {
  356. case signatureECDSA:
  357. pubKey, ok := cert.PublicKey.(*ecdsa.PublicKey)
  358. if !ok {
  359. return errors.New("tls: ECDHE ECDSA requires a ECDSA server public key")
  360. }
  361. ecdsaSig := new(ecdsaSignature)
  362. if _, err := asn1.Unmarshal(sig, ecdsaSig); err != nil {
  363. return err
  364. }
  365. if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
  366. return errors.New("tls: ECDSA signature contained zero or negative values")
  367. }
  368. if !ecdsa.Verify(pubKey, digest, ecdsaSig.R, ecdsaSig.S) {
  369. return errors.New("tls: ECDSA verification failure")
  370. }
  371. case signatureRSA:
  372. pubKey, ok := cert.PublicKey.(*rsa.PublicKey)
  373. if !ok {
  374. return errors.New("tls: ECDHE RSA requires a RSA server public key")
  375. }
  376. if err := rsa.VerifyPKCS1v15(pubKey, hashFunc, digest, sig); err != nil {
  377. return err
  378. }
  379. default:
  380. return errors.New("tls: unknown ECDHE signature algorithm")
  381. }
  382. return nil
  383. }
  384. func (ka *ecdheKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
  385. if ka.curveid == 0 {
  386. return nil, nil, errors.New("tls: missing ServerKeyExchange message")
  387. }
  388. var serialized, preMasterSecret []byte
  389. if ka.curveid == X25519 {
  390. var ourPublic, theirPublic, sharedKey, scalar [32]byte
  391. if _, err := io.ReadFull(config.rand(), scalar[:]); err != nil {
  392. return nil, nil, err
  393. }
  394. copy(theirPublic[:], ka.publicKey)
  395. curve25519.ScalarBaseMult(&ourPublic, &scalar)
  396. curve25519.ScalarMult(&sharedKey, &scalar, &theirPublic)
  397. serialized = ourPublic[:]
  398. preMasterSecret = sharedKey[:]
  399. } else {
  400. curve, ok := curveForCurveID(ka.curveid)
  401. if !ok {
  402. panic("internal error")
  403. }
  404. priv, mx, my, err := elliptic.GenerateKey(curve, config.rand())
  405. if err != nil {
  406. return nil, nil, err
  407. }
  408. x, _ := curve.ScalarMult(ka.x, ka.y, priv)
  409. preMasterSecret = make([]byte, (curve.Params().BitSize+7)>>3)
  410. xBytes := x.Bytes()
  411. copy(preMasterSecret[len(preMasterSecret)-len(xBytes):], xBytes)
  412. serialized = elliptic.Marshal(curve, mx, my)
  413. }
  414. ckx := new(clientKeyExchangeMsg)
  415. ckx.ciphertext = make([]byte, 1+len(serialized))
  416. ckx.ciphertext[0] = byte(len(serialized))
  417. copy(ckx.ciphertext[1:], serialized)
  418. return preMasterSecret, ckx, nil
  419. }