25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

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