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.
 
 
 
 
 
 

335 lines
10 KiB

  1. package tls
  2. import (
  3. "bytes"
  4. "crypto"
  5. "crypto/ecdsa"
  6. "crypto/elliptic"
  7. "crypto/hmac"
  8. "crypto/rsa"
  9. "crypto/subtle"
  10. "errors"
  11. "io"
  12. "golang_org/x/crypto/curve25519"
  13. )
  14. func (hs *serverHandshakeState) doTLS13Handshake() error {
  15. config := hs.c.config
  16. c := hs.c
  17. hs.c.cipherSuite, hs.hello13.cipherSuite = hs.suite.id, hs.suite.id
  18. // When picking the group for the handshake, priority is given to groups
  19. // that the client provided a keyShare for, so to avoid a round-trip.
  20. // After that the order of CurvePreferences is respected.
  21. var ks keyShare
  22. for _, curveID := range config.curvePreferences() {
  23. for _, keyShare := range hs.clientHello.keyShares {
  24. if curveID == keyShare.group {
  25. ks = keyShare
  26. break
  27. }
  28. }
  29. }
  30. if ks.group == 0 {
  31. c.sendAlert(alertInternalError)
  32. return errors.New("tls: HelloRetryRequest not implemented") // TODO(filippo)
  33. }
  34. privateKey, serverKS, err := config.generateKeyShare(ks.group)
  35. if err != nil {
  36. c.sendAlert(alertInternalError)
  37. return err
  38. }
  39. hs.hello13.keyShare = serverKS
  40. hash := crypto.SHA256
  41. if hs.suite.flags&suiteSHA384 != 0 {
  42. hash = crypto.SHA384
  43. }
  44. hashSize := hash.Size()
  45. ecdheSecret := deriveECDHESecret(ks, privateKey)
  46. if ecdheSecret == nil {
  47. c.sendAlert(alertIllegalParameter)
  48. return errors.New("tls: bad ECDHE client share")
  49. }
  50. hs.finishedHash = newFinishedHash(hs.c.vers, hs.suite)
  51. hs.finishedHash.discardHandshakeBuffer()
  52. hs.finishedHash.Write(hs.clientHello.marshal())
  53. hs.finishedHash.Write(hs.hello13.marshal())
  54. if _, err := c.writeRecord(recordTypeHandshake, hs.hello13.marshal()); err != nil {
  55. return err
  56. }
  57. earlySecret := hkdfExtract(hash, nil, nil)
  58. handshakeSecret := hkdfExtract(hash, ecdheSecret, earlySecret)
  59. handshakeCtx := hs.finishedHash.Sum()
  60. cHandshakeTS := hkdfExpandLabel(hash, handshakeSecret, handshakeCtx, "client handshake traffic secret", hashSize)
  61. cKey := hkdfExpandLabel(hash, cHandshakeTS, nil, "key", hs.suite.keyLen)
  62. cIV := hkdfExpandLabel(hash, cHandshakeTS, nil, "iv", 12)
  63. sHandshakeTS := hkdfExpandLabel(hash, handshakeSecret, handshakeCtx, "server handshake traffic secret", hashSize)
  64. sKey := hkdfExpandLabel(hash, sHandshakeTS, nil, "key", hs.suite.keyLen)
  65. sIV := hkdfExpandLabel(hash, sHandshakeTS, nil, "iv", 12)
  66. clientCipher := hs.suite.aead(cKey, cIV)
  67. c.in.setCipher(c.vers, clientCipher)
  68. serverCipher := hs.suite.aead(sKey, sIV)
  69. c.out.setCipher(c.vers, serverCipher)
  70. hs.finishedHash.Write(hs.hello13Enc.marshal())
  71. if _, err := c.writeRecord(recordTypeHandshake, hs.hello13Enc.marshal()); err != nil {
  72. return err
  73. }
  74. certMsg := &certificateMsg13{
  75. certificates: hs.cert.Certificate,
  76. }
  77. hs.finishedHash.Write(certMsg.marshal())
  78. if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
  79. return err
  80. }
  81. sigScheme, err := hs.selectTLS13SignatureScheme()
  82. if err != nil {
  83. c.sendAlert(alertInternalError)
  84. return err
  85. }
  86. sigHash := hashForSignatureScheme(sigScheme)
  87. opts := crypto.SignerOpts(sigHash)
  88. if signatureSchemeIsPSS(sigScheme) {
  89. opts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
  90. }
  91. toSign := prepareDigitallySigned(sigHash, "TLS 1.3, server CertificateVerify", hs.finishedHash.Sum())
  92. signature, err := hs.cert.PrivateKey.(crypto.Signer).Sign(config.rand(), toSign[:], opts)
  93. if err != nil {
  94. c.sendAlert(alertInternalError)
  95. return err
  96. }
  97. verifyMsg := &certificateVerifyMsg{
  98. hasSignatureAndHash: true,
  99. signatureAndHash: sigSchemeToSigAndHash(sigScheme),
  100. signature: signature,
  101. }
  102. hs.finishedHash.Write(verifyMsg.marshal())
  103. if _, err := c.writeRecord(recordTypeHandshake, verifyMsg.marshal()); err != nil {
  104. return err
  105. }
  106. serverFinishedKey := hkdfExpandLabel(hash, sHandshakeTS, nil, "finished", hashSize)
  107. clientFinishedKey := hkdfExpandLabel(hash, cHandshakeTS, nil, "finished", hashSize)
  108. h := hmac.New(hash.New, serverFinishedKey)
  109. h.Write(hs.finishedHash.Sum())
  110. verifyData := h.Sum(nil)
  111. serverFinished := &finishedMsg{
  112. verifyData: verifyData,
  113. }
  114. hs.finishedHash.Write(serverFinished.marshal())
  115. if _, err := c.writeRecord(recordTypeHandshake, serverFinished.marshal()); err != nil {
  116. return err
  117. }
  118. if _, err := c.flush(); err != nil {
  119. return err
  120. }
  121. msg, err := c.readHandshake()
  122. if err != nil {
  123. return err
  124. }
  125. clientFinished, ok := msg.(*finishedMsg)
  126. if !ok {
  127. c.sendAlert(alertUnexpectedMessage)
  128. return unexpectedMessageError(clientFinished, msg)
  129. }
  130. h = hmac.New(hash.New, clientFinishedKey)
  131. h.Write(hs.finishedHash.Sum())
  132. expectedVerifyData := h.Sum(nil)
  133. if len(expectedVerifyData) != len(clientFinished.verifyData) ||
  134. subtle.ConstantTimeCompare(expectedVerifyData, clientFinished.verifyData) != 1 {
  135. c.sendAlert(alertHandshakeFailure)
  136. return errors.New("tls: client's Finished message is incorrect")
  137. }
  138. masterSecret := hkdfExtract(hash, nil, handshakeSecret)
  139. handshakeCtx = hs.finishedHash.Sum()
  140. cTrafficSecret0 := hkdfExpandLabel(hash, masterSecret, handshakeCtx, "client application traffic secret", hashSize)
  141. cKey = hkdfExpandLabel(hash, cTrafficSecret0, nil, "key", hs.suite.keyLen)
  142. cIV = hkdfExpandLabel(hash, cTrafficSecret0, nil, "iv", 12)
  143. sTrafficSecret0 := hkdfExpandLabel(hash, masterSecret, handshakeCtx, "server application traffic secret", hashSize)
  144. sKey = hkdfExpandLabel(hash, sTrafficSecret0, nil, "key", hs.suite.keyLen)
  145. sIV = hkdfExpandLabel(hash, sTrafficSecret0, nil, "iv", 12)
  146. clientCipher = hs.suite.aead(cKey, cIV)
  147. c.in.setCipher(c.vers, clientCipher)
  148. serverCipher = hs.suite.aead(sKey, sIV)
  149. c.out.setCipher(c.vers, serverCipher)
  150. return nil
  151. }
  152. // selectTLS13SignatureScheme chooses the SignatureScheme for the CertificateVerify
  153. // based on the certificate type and client supported schemes. If no overlap is found,
  154. // a fallback is selected.
  155. //
  156. // See https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.4.1.2
  157. func (hs *serverHandshakeState) selectTLS13SignatureScheme() (sigScheme SignatureScheme, err error) {
  158. var supportedSchemes []SignatureScheme
  159. signer, ok := hs.cert.PrivateKey.(crypto.Signer)
  160. if !ok {
  161. return 0, errors.New("tls: certificate private key does not implement crypto.Signer")
  162. }
  163. pk := signer.Public()
  164. if _, ok := pk.(*rsa.PublicKey); ok {
  165. sigScheme = PSSWithSHA256
  166. supportedSchemes = []SignatureScheme{PSSWithSHA256, PSSWithSHA384, PSSWithSHA512}
  167. } else if pk, ok := pk.(*ecdsa.PublicKey); ok {
  168. switch pk.Curve {
  169. case elliptic.P256():
  170. sigScheme = ECDSAWithP256AndSHA256
  171. supportedSchemes = []SignatureScheme{ECDSAWithP256AndSHA256}
  172. case elliptic.P384():
  173. sigScheme = ECDSAWithP384AndSHA384
  174. supportedSchemes = []SignatureScheme{ECDSAWithP384AndSHA384}
  175. case elliptic.P521():
  176. sigScheme = ECDSAWithP521AndSHA512
  177. supportedSchemes = []SignatureScheme{ECDSAWithP521AndSHA512}
  178. default:
  179. return 0, errors.New("tls: unknown ECDSA certificate curve")
  180. }
  181. } else {
  182. return 0, errors.New("tls: unknown certificate key type")
  183. }
  184. for _, ss := range supportedSchemes {
  185. for _, cs := range hs.clientHello.signatureAndHashes {
  186. if ss == sigAndHashToSigScheme(cs) {
  187. return ss, nil
  188. }
  189. }
  190. }
  191. return sigScheme, nil
  192. }
  193. func sigSchemeToSigAndHash(s SignatureScheme) (sah signatureAndHash) {
  194. sah.hash = byte(s >> 8)
  195. sah.signature = byte(s)
  196. return
  197. }
  198. func sigAndHashToSigScheme(sah signatureAndHash) SignatureScheme {
  199. return SignatureScheme(sah.hash)<<8 | SignatureScheme(sah.signature)
  200. }
  201. func signatureSchemeIsPSS(s SignatureScheme) bool {
  202. return s == PSSWithSHA256 || s == PSSWithSHA384 || s == PSSWithSHA512
  203. }
  204. // hashForSignatureScheme returns the Hash used by a SignatureScheme which is
  205. // supported by selectTLS13SignatureScheme.
  206. func hashForSignatureScheme(ss SignatureScheme) crypto.Hash {
  207. switch ss {
  208. case PSSWithSHA256, ECDSAWithP256AndSHA256:
  209. return crypto.SHA256
  210. case PSSWithSHA384, ECDSAWithP384AndSHA384:
  211. return crypto.SHA384
  212. case PSSWithSHA512, ECDSAWithP521AndSHA512:
  213. return crypto.SHA512
  214. default:
  215. panic("unsupported SignatureScheme passed to hashForSignatureScheme")
  216. }
  217. }
  218. func prepareDigitallySigned(hash crypto.Hash, context string, data []byte) []byte {
  219. message := bytes.Repeat([]byte{32}, 64)
  220. message = append(message, context...)
  221. message = append(message, 0)
  222. message = append(message, data...)
  223. h := hash.New()
  224. h.Write(message)
  225. return h.Sum(nil)
  226. }
  227. func (c *Config) generateKeyShare(curveID CurveID) ([]byte, keyShare, error) {
  228. if curveID == X25519 {
  229. var scalar, public [32]byte
  230. if _, err := io.ReadFull(c.rand(), scalar[:]); err != nil {
  231. return nil, keyShare{}, err
  232. }
  233. curve25519.ScalarBaseMult(&public, &scalar)
  234. return scalar[:], keyShare{group: curveID, data: public[:]}, nil
  235. }
  236. curve, ok := curveForCurveID(curveID)
  237. if !ok {
  238. return nil, keyShare{}, errors.New("tls: preferredCurves includes unsupported curve")
  239. }
  240. privateKey, x, y, err := elliptic.GenerateKey(curve, c.rand())
  241. if err != nil {
  242. return nil, keyShare{}, err
  243. }
  244. ecdhePublic := elliptic.Marshal(curve, x, y)
  245. return privateKey, keyShare{group: curveID, data: ecdhePublic}, nil
  246. }
  247. func deriveECDHESecret(ks keyShare, pk []byte) []byte {
  248. if ks.group == X25519 {
  249. if len(ks.data) != 32 {
  250. return nil
  251. }
  252. var theirPublic, sharedKey, scalar [32]byte
  253. copy(theirPublic[:], ks.data)
  254. copy(scalar[:], pk)
  255. curve25519.ScalarMult(&sharedKey, &scalar, &theirPublic)
  256. return sharedKey[:]
  257. }
  258. curve, ok := curveForCurveID(ks.group)
  259. if !ok {
  260. return nil
  261. }
  262. x, y := elliptic.Unmarshal(curve, ks.data)
  263. if x == nil {
  264. return nil
  265. }
  266. x, _ = curve.ScalarMult(x, y, pk)
  267. xBytes := x.Bytes()
  268. curveSize := (curve.Params().BitSize + 8 - 1) >> 3
  269. if len(xBytes) == curveSize {
  270. return xBytes
  271. }
  272. buf := make([]byte, curveSize)
  273. copy(buf[len(buf)-len(xBytes):], xBytes)
  274. return buf
  275. }
  276. func hkdfExpandLabel(hash crypto.Hash, secret, hashValue []byte, label string, L int) []byte {
  277. hkdfLabel := make([]byte, 4+len("TLS 1.3, ")+len(label)+len(hashValue))
  278. hkdfLabel[0] = byte(L >> 8)
  279. hkdfLabel[1] = byte(L)
  280. hkdfLabel[2] = byte(len("TLS 1.3, ") + len(label))
  281. copy(hkdfLabel[3:], "TLS 1.3, ")
  282. z := hkdfLabel[3+len("TLS 1.3, "):]
  283. copy(z, label)
  284. z = z[len(label):]
  285. z[0] = byte(len(hashValue))
  286. copy(z[1:], hashValue)
  287. return hkdfExpand(hash, secret, hkdfLabel, L)
  288. }