Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 
 
 

467 Zeilen
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 an 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:]) // Unmarshal also checks whether the given point is on the curve
  284. if x == nil {
  285. return nil, errClientKeyExchange
  286. }
  287. x, _ = curve.ScalarMult(x, y, ka.privateKey)
  288. preMasterSecret := make([]byte, (curve.Params().BitSize+7)>>3)
  289. xBytes := x.Bytes()
  290. copy(preMasterSecret[len(preMasterSecret)-len(xBytes):], xBytes)
  291. return preMasterSecret, nil
  292. }
  293. func (ka *ecdheKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
  294. if len(skx.key) < 4 {
  295. return errServerKeyExchange
  296. }
  297. if skx.key[0] != 3 { // named curve
  298. return errors.New("tls: server selected unsupported curve")
  299. }
  300. ka.curveid = CurveID(skx.key[1])<<8 | CurveID(skx.key[2])
  301. publicLen := int(skx.key[3])
  302. if publicLen+4 > len(skx.key) {
  303. return errServerKeyExchange
  304. }
  305. serverECDHParams := skx.key[:4+publicLen]
  306. publicKey := serverECDHParams[4:]
  307. sig := skx.key[4+publicLen:]
  308. if len(sig) < 2 {
  309. return errServerKeyExchange
  310. }
  311. if ka.curveid == X25519 {
  312. if len(publicKey) != 32 {
  313. return errors.New("tls: bad X25519 public value")
  314. }
  315. ka.publicKey = publicKey
  316. } else {
  317. curve, ok := curveForCurveID(ka.curveid)
  318. if !ok {
  319. return errors.New("tls: server selected unsupported curve")
  320. }
  321. ka.x, ka.y = elliptic.Unmarshal(curve, publicKey) // Unmarshal also checks whether the given point is on the curve
  322. if ka.x == nil {
  323. return errServerKeyExchange
  324. }
  325. }
  326. sigAndHash := signatureAndHash{signature: ka.sigType}
  327. if ka.version >= VersionTLS12 {
  328. // handle SignatureAndHashAlgorithm
  329. sigAndHash = signatureAndHash{hash: sig[0], signature: sig[1]}
  330. if sigAndHash.signature != ka.sigType {
  331. return errServerKeyExchange
  332. }
  333. sig = sig[2:]
  334. if len(sig) < 2 {
  335. return errServerKeyExchange
  336. }
  337. }
  338. sigLen := int(sig[0])<<8 | int(sig[1])
  339. if sigLen+2 != len(sig) {
  340. return errServerKeyExchange
  341. }
  342. sig = sig[2:]
  343. digest, hashFunc, err := hashForServerKeyExchange(sigAndHash, ka.version, clientHello.random, serverHello.random, serverECDHParams)
  344. if err != nil {
  345. return err
  346. }
  347. switch ka.sigType {
  348. case signatureECDSA:
  349. pubKey, ok := cert.PublicKey.(*ecdsa.PublicKey)
  350. if !ok {
  351. return errors.New("tls: ECDHE ECDSA requires a ECDSA server public key")
  352. }
  353. ecdsaSig := new(ecdsaSignature)
  354. if _, err := asn1.Unmarshal(sig, ecdsaSig); err != nil {
  355. return err
  356. }
  357. if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
  358. return errors.New("tls: ECDSA signature contained zero or negative values")
  359. }
  360. if !ecdsa.Verify(pubKey, digest, ecdsaSig.R, ecdsaSig.S) {
  361. return errors.New("tls: ECDSA verification failure")
  362. }
  363. case signatureRSA:
  364. pubKey, ok := cert.PublicKey.(*rsa.PublicKey)
  365. if !ok {
  366. return errors.New("tls: ECDHE RSA requires a RSA server public key")
  367. }
  368. if err := rsa.VerifyPKCS1v15(pubKey, hashFunc, digest, sig); err != nil {
  369. return err
  370. }
  371. default:
  372. return errors.New("tls: unknown ECDHE signature algorithm")
  373. }
  374. return nil
  375. }
  376. func (ka *ecdheKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
  377. if ka.curveid == 0 {
  378. return nil, nil, errors.New("tls: missing ServerKeyExchange message")
  379. }
  380. var serialized, preMasterSecret []byte
  381. if ka.curveid == X25519 {
  382. var ourPublic, theirPublic, sharedKey, scalar [32]byte
  383. if _, err := io.ReadFull(config.rand(), scalar[:]); err != nil {
  384. return nil, nil, err
  385. }
  386. copy(theirPublic[:], ka.publicKey)
  387. curve25519.ScalarBaseMult(&ourPublic, &scalar)
  388. curve25519.ScalarMult(&sharedKey, &scalar, &theirPublic)
  389. serialized = ourPublic[:]
  390. preMasterSecret = sharedKey[:]
  391. } else {
  392. curve, ok := curveForCurveID(ka.curveid)
  393. if !ok {
  394. panic("internal error")
  395. }
  396. priv, mx, my, err := elliptic.GenerateKey(curve, config.rand())
  397. if err != nil {
  398. return nil, nil, err
  399. }
  400. x, _ := curve.ScalarMult(ka.x, ka.y, priv)
  401. preMasterSecret = make([]byte, (curve.Params().BitSize+7)>>3)
  402. xBytes := x.Bytes()
  403. copy(preMasterSecret[len(preMasterSecret)-len(xBytes):], xBytes)
  404. serialized = elliptic.Marshal(curve, mx, my)
  405. }
  406. ckx := new(clientKeyExchangeMsg)
  407. ckx.ciphertext = make([]byte, 1+len(serialized))
  408. ckx.ciphertext[0] = byte(len(serialized))
  409. copy(ckx.ciphertext[1:], serialized)
  410. return preMasterSecret, ckx, nil
  411. }