1 // Copyright 2018 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.
20 // maxClientPSKIdentities is the number of client PSK identities the server will
21 // attempt to validate. It will ignore the rest not to let cheap ClientHello
22 // messages cause too much work in session ticket decryption attempts.
23 const maxClientPSKIdentities = 5
25 type serverHandshakeStateTLS13 struct {
27 clientHello *clientHelloMsg
31 suite *cipherSuiteTLS13
33 sigAlg SignatureScheme
36 handshakeSecret []byte
38 trafficSecret []byte // client_application_traffic_secret_0
43 func (hs *serverHandshakeStateTLS13) handshake() error {
47 return errors.New("tls: internal error: TLS 1.3 reached in FIPS mode")
50 // For an overview of the TLS 1.3 handshake, see RFC 8446, Section 2.
51 if err := hs.processClientHello(); err != nil {
54 if err := hs.checkForResumption(); err != nil {
57 if err := hs.pickCertificate(); err != nil {
61 if err := hs.sendServerParameters(); err != nil {
64 if err := hs.sendServerCertificate(); err != nil {
67 if err := hs.sendServerFinished(); err != nil {
70 // Note that at this point we could start sending application data without
71 // waiting for the client's second flight, but the application might not
72 // expect the lack of replay protection of the ClientHello parameters.
73 if _, err := c.flush(); err != nil {
76 if err := hs.readClientCertificate(); err != nil {
79 if err := hs.readClientFinished(); err != nil {
83 atomic.StoreUint32(&c.handshakeStatus, 1)
88 func (hs *serverHandshakeStateTLS13) processClientHello() error {
91 hs.hello = new(serverHelloMsg)
93 // TLS 1.3 froze the ServerHello.legacy_version field, and uses
94 // supported_versions instead. See RFC 8446, sections 4.1.3 and 4.2.1.
95 hs.hello.vers = VersionTLS12
96 hs.hello.supportedVersion = c.vers
98 if len(hs.clientHello.supportedVersions) == 0 {
99 c.sendAlert(alertIllegalParameter)
100 return errors.New("tls: client used the legacy version field to negotiate TLS 1.3")
103 // Abort if the client is doing a fallback and landing lower than what we
104 // support. See RFC 7507, which however does not specify the interaction
105 // with supported_versions. The only difference is that with
106 // supported_versions a client has a chance to attempt a [TLS 1.2, TLS 1.4]
107 // handshake in case TLS 1.3 is broken but 1.2 is not. Alas, in that case,
108 // it will have to drop the TLS_FALLBACK_SCSV protection if it falls back to
109 // TLS 1.2, because a TLS 1.3 server would abort here. The situation before
110 // supported_versions was not better because there was just no way to do a
111 // TLS 1.4 handshake without risking the server selecting TLS 1.3.
112 for _, id := range hs.clientHello.cipherSuites {
113 if id == TLS_FALLBACK_SCSV {
114 // Use c.vers instead of max(supported_versions) because an attacker
115 // could defeat this by adding an arbitrary high version otherwise.
116 if c.vers < c.config.maxSupportedVersion(false) {
117 c.sendAlert(alertInappropriateFallback)
118 return errors.New("tls: client using inappropriate protocol fallback")
124 if len(hs.clientHello.compressionMethods) != 1 ||
125 hs.clientHello.compressionMethods[0] != compressionNone {
126 c.sendAlert(alertIllegalParameter)
127 return errors.New("tls: TLS 1.3 client supports illegal compression methods")
130 hs.hello.random = make([]byte, 32)
131 if _, err := io.ReadFull(c.config.rand(), hs.hello.random); err != nil {
132 c.sendAlert(alertInternalError)
136 if len(hs.clientHello.secureRenegotiation) != 0 {
137 c.sendAlert(alertHandshakeFailure)
138 return errors.New("tls: initial handshake had non-empty renegotiation extension")
141 if hs.clientHello.earlyData {
142 // See RFC 8446, Section 4.2.10 for the complicated behavior required
143 // here. The scenario is that a different server at our address offered
144 // to accept early data in the past, which we can't handle. For now, all
145 // 0-RTT enabled session tickets need to expire before a Go server can
146 // replace a server or join a pool. That's the same requirement that
147 // applies to mixing or replacing with any TLS 1.2 server.
148 c.sendAlert(alertUnsupportedExtension)
149 return errors.New("tls: client sent unexpected early data")
152 hs.hello.sessionId = hs.clientHello.sessionId
153 hs.hello.compressionMethod = compressionNone
155 var preferenceList, supportedList []uint16
156 if c.config.PreferServerCipherSuites {
157 preferenceList = defaultCipherSuitesTLS13()
158 supportedList = hs.clientHello.cipherSuites
160 preferenceList = hs.clientHello.cipherSuites
161 supportedList = defaultCipherSuitesTLS13()
163 for _, suiteID := range preferenceList {
164 hs.suite = mutualCipherSuiteTLS13(supportedList, suiteID)
170 c.sendAlert(alertHandshakeFailure)
171 return errors.New("tls: no cipher suite supported by both client and server")
173 c.cipherSuite = hs.suite.id
174 hs.hello.cipherSuite = hs.suite.id
175 hs.transcript = hs.suite.hash.New()
177 // Pick the ECDHE group in server preference order, but give priority to
178 // groups with a key share, to avoid a HelloRetryRequest round-trip.
179 var selectedGroup CurveID
180 var clientKeyShare *keyShare
182 for _, preferredGroup := range c.config.curvePreferences() {
183 for _, ks := range hs.clientHello.keyShares {
184 if ks.group == preferredGroup {
185 selectedGroup = ks.group
190 if selectedGroup != 0 {
193 for _, group := range hs.clientHello.supportedCurves {
194 if group == preferredGroup {
195 selectedGroup = group
200 if selectedGroup == 0 {
201 c.sendAlert(alertHandshakeFailure)
202 return errors.New("tls: no ECDHE curve supported by both client and server")
204 if clientKeyShare == nil {
205 if err := hs.doHelloRetryRequest(selectedGroup); err != nil {
208 clientKeyShare = &hs.clientHello.keyShares[0]
211 if _, ok := curveForCurveID(selectedGroup); selectedGroup != X25519 && !ok {
212 c.sendAlert(alertInternalError)
213 return errors.New("tls: CurvePreferences includes unsupported curve")
215 params, err := generateECDHEParameters(c.config.rand(), selectedGroup)
217 c.sendAlert(alertInternalError)
220 hs.hello.serverShare = keyShare{group: selectedGroup, data: params.PublicKey()}
221 hs.sharedKey = params.SharedKey(clientKeyShare.data)
222 if hs.sharedKey == nil {
223 c.sendAlert(alertIllegalParameter)
224 return errors.New("tls: invalid client key share")
227 c.serverName = hs.clientHello.serverName
231 func (hs *serverHandshakeStateTLS13) checkForResumption() error {
234 if c.config.SessionTicketsDisabled {
239 for _, mode := range hs.clientHello.pskModes {
240 if mode == pskModeDHE {
249 if len(hs.clientHello.pskIdentities) != len(hs.clientHello.pskBinders) {
250 c.sendAlert(alertIllegalParameter)
251 return errors.New("tls: invalid or missing PSK binders")
253 if len(hs.clientHello.pskIdentities) == 0 {
257 for i, identity := range hs.clientHello.pskIdentities {
258 if i >= maxClientPSKIdentities {
262 plaintext, _ := c.decryptTicket(identity.label)
263 if plaintext == nil {
266 sessionState := new(sessionStateTLS13)
267 if ok := sessionState.unmarshal(plaintext); !ok {
271 createdAt := time.Unix(int64(sessionState.createdAt), 0)
272 if c.config.time().Sub(createdAt) > maxSessionTicketLifetime {
276 // We don't check the obfuscated ticket age because it's affected by
277 // clock skew and it's only a freshness signal useful for shrinking the
278 // window for replay attacks, which don't affect us as we don't do 0-RTT.
280 pskSuite := cipherSuiteTLS13ByID(sessionState.cipherSuite)
281 if pskSuite == nil || pskSuite.hash != hs.suite.hash {
285 // PSK connections don't re-establish client certificates, but carry
286 // them over in the session ticket. Ensure the presence of client certs
287 // in the ticket is consistent with the configured requirements.
288 sessionHasClientCerts := len(sessionState.certificate.Certificate) != 0
289 needClientCerts := requiresClientCert(c.config.ClientAuth)
290 if needClientCerts && !sessionHasClientCerts {
293 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
297 psk := hs.suite.expandLabel(sessionState.resumptionSecret, "resumption",
298 nil, hs.suite.hash.Size())
299 hs.earlySecret = hs.suite.extract(psk, nil)
300 binderKey := hs.suite.deriveSecret(hs.earlySecret, resumptionBinderLabel, nil)
301 // Clone the transcript in case a HelloRetryRequest was recorded.
302 transcript := cloneHash(hs.transcript, hs.suite.hash)
303 if transcript == nil {
304 c.sendAlert(alertInternalError)
305 return errors.New("tls: internal error: failed to clone hash")
307 transcript.Write(hs.clientHello.marshalWithoutBinders())
308 pskBinder := hs.suite.finishedHash(binderKey, transcript)
309 if !hmac.Equal(hs.clientHello.pskBinders[i], pskBinder) {
310 c.sendAlert(alertDecryptError)
311 return errors.New("tls: invalid PSK binder")
314 if err := c.processCertsFromClient(sessionState.certificate); err != nil {
318 hs.hello.selectedIdentityPresent = true
319 hs.hello.selectedIdentity = uint16(i)
328 // cloneHash uses the encoding.BinaryMarshaler and encoding.BinaryUnmarshaler
329 // interfaces implemented by standard library hashes to clone the state of in
330 // to a new instance of h. It returns nil if the operation fails.
331 func cloneHash(in hash.Hash, h crypto.Hash) hash.Hash {
332 // Recreate the interface to avoid importing encoding.
333 type binaryMarshaler interface {
334 MarshalBinary() (data []byte, err error)
335 UnmarshalBinary(data []byte) error
337 marshaler, ok := in.(binaryMarshaler)
341 state, err := marshaler.MarshalBinary()
346 unmarshaler, ok := out.(binaryMarshaler)
350 if err := unmarshaler.UnmarshalBinary(state); err != nil {
356 func (hs *serverHandshakeStateTLS13) pickCertificate() error {
359 // Only one of PSK and certificates are used at a time.
364 // This implements a very simplistic certificate selection strategy for now:
365 // getCertificate delegates to the application Config.GetCertificate, or
366 // selects based on the server_name only. If the selected certificate's
367 // public key does not match the client signature_algorithms, the handshake
368 // is aborted. No attention is given to signature_algorithms_cert, and it is
369 // not passed to the application Config.GetCertificate. This will need to
370 // improve according to RFC 8446, sections 4.4.2.2 and 4.2.3.
371 certificate, err := c.config.getCertificate(clientHelloInfo(c, hs.clientHello))
373 c.sendAlert(alertInternalError)
376 supportedAlgs := signatureSchemesForCertificate(certificate)
377 if supportedAlgs == nil {
378 c.sendAlert(alertInternalError)
379 return fmt.Errorf("tls: unsupported certificate key (%T)", certificate.PrivateKey)
381 // Pick signature scheme in client preference order, as the server
382 // preference order is not configurable.
383 for _, preferredAlg := range hs.clientHello.supportedSignatureAlgorithms {
384 if isSupportedSignatureAlgorithm(preferredAlg, supportedAlgs) {
385 hs.sigAlg = preferredAlg
390 c.sendAlert(alertHandshakeFailure)
391 return errors.New("tls: client doesn't support selected certificate")
393 hs.cert = certificate
398 // sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility
399 // with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4.
400 func (hs *serverHandshakeStateTLS13) sendDummyChangeCipherSpec() error {
404 hs.sentDummyCCS = true
406 _, err := hs.c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
410 func (hs *serverHandshakeStateTLS13) doHelloRetryRequest(selectedGroup CurveID) error {
413 // The first ClientHello gets double-hashed into the transcript upon a
414 // HelloRetryRequest. See RFC 8446, Section 4.4.1.
415 hs.transcript.Write(hs.clientHello.marshal())
416 chHash := hs.transcript.Sum(nil)
417 hs.transcript.Reset()
418 hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
419 hs.transcript.Write(chHash)
421 helloRetryRequest := &serverHelloMsg{
423 random: helloRetryRequestRandom,
424 sessionId: hs.hello.sessionId,
425 cipherSuite: hs.hello.cipherSuite,
426 compressionMethod: hs.hello.compressionMethod,
427 supportedVersion: hs.hello.supportedVersion,
428 selectedGroup: selectedGroup,
431 hs.transcript.Write(helloRetryRequest.marshal())
432 if _, err := c.writeRecord(recordTypeHandshake, helloRetryRequest.marshal()); err != nil {
436 if err := hs.sendDummyChangeCipherSpec(); err != nil {
440 msg, err := c.readHandshake()
445 clientHello, ok := msg.(*clientHelloMsg)
447 c.sendAlert(alertUnexpectedMessage)
448 return unexpectedMessageError(clientHello, msg)
451 if len(clientHello.keyShares) != 1 || clientHello.keyShares[0].group != selectedGroup {
452 c.sendAlert(alertIllegalParameter)
453 return errors.New("tls: client sent invalid key share in second ClientHello")
456 if clientHello.earlyData {
457 c.sendAlert(alertIllegalParameter)
458 return errors.New("tls: client indicated early data in second ClientHello")
461 if illegalClientHelloChange(clientHello, hs.clientHello) {
462 c.sendAlert(alertIllegalParameter)
463 return errors.New("tls: client illegally modified second ClientHello")
466 hs.clientHello = clientHello
470 // illegalClientHelloChange returns whether the two ClientHello messages are
471 // different, with the exception of the changes allowed before and after a
472 // HelloRetryRequest. See RFC 8446, Section 4.1.2.
473 func illegalClientHelloChange(ch, ch1 *clientHelloMsg) bool {
474 if len(ch.supportedVersions) != len(ch1.supportedVersions) ||
475 len(ch.cipherSuites) != len(ch1.cipherSuites) ||
476 len(ch.supportedCurves) != len(ch1.supportedCurves) ||
477 len(ch.supportedSignatureAlgorithms) != len(ch1.supportedSignatureAlgorithms) ||
478 len(ch.supportedSignatureAlgorithmsCert) != len(ch1.supportedSignatureAlgorithmsCert) ||
479 len(ch.alpnProtocols) != len(ch1.alpnProtocols) {
482 for i := range ch.supportedVersions {
483 if ch.supportedVersions[i] != ch1.supportedVersions[i] {
487 for i := range ch.cipherSuites {
488 if ch.cipherSuites[i] != ch1.cipherSuites[i] {
492 for i := range ch.supportedCurves {
493 if ch.supportedCurves[i] != ch1.supportedCurves[i] {
497 for i := range ch.supportedSignatureAlgorithms {
498 if ch.supportedSignatureAlgorithms[i] != ch1.supportedSignatureAlgorithms[i] {
502 for i := range ch.supportedSignatureAlgorithmsCert {
503 if ch.supportedSignatureAlgorithmsCert[i] != ch1.supportedSignatureAlgorithmsCert[i] {
507 for i := range ch.alpnProtocols {
508 if ch.alpnProtocols[i] != ch1.alpnProtocols[i] {
512 return ch.vers != ch1.vers ||
513 !bytes.Equal(ch.random, ch1.random) ||
514 !bytes.Equal(ch.sessionId, ch1.sessionId) ||
515 !bytes.Equal(ch.compressionMethods, ch1.compressionMethods) ||
516 ch.nextProtoNeg != ch1.nextProtoNeg ||
517 ch.serverName != ch1.serverName ||
518 ch.ocspStapling != ch1.ocspStapling ||
519 !bytes.Equal(ch.supportedPoints, ch1.supportedPoints) ||
520 ch.ticketSupported != ch1.ticketSupported ||
521 !bytes.Equal(ch.sessionTicket, ch1.sessionTicket) ||
522 ch.secureRenegotiationSupported != ch1.secureRenegotiationSupported ||
523 !bytes.Equal(ch.secureRenegotiation, ch1.secureRenegotiation) ||
524 ch.scts != ch1.scts ||
525 !bytes.Equal(ch.cookie, ch1.cookie) ||
526 !bytes.Equal(ch.pskModes, ch1.pskModes)
529 func (hs *serverHandshakeStateTLS13) sendServerParameters() error {
532 hs.transcript.Write(hs.clientHello.marshal())
533 hs.transcript.Write(hs.hello.marshal())
534 if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
538 if err := hs.sendDummyChangeCipherSpec(); err != nil {
542 earlySecret := hs.earlySecret
543 if earlySecret == nil {
544 earlySecret = hs.suite.extract(nil, nil)
546 hs.handshakeSecret = hs.suite.extract(hs.sharedKey,
547 hs.suite.deriveSecret(earlySecret, "derived", nil))
549 clientSecret := hs.suite.deriveSecret(hs.handshakeSecret,
550 clientHandshakeTrafficLabel, hs.transcript)
551 c.in.setTrafficSecret(hs.suite, clientSecret)
552 serverSecret := hs.suite.deriveSecret(hs.handshakeSecret,
553 serverHandshakeTrafficLabel, hs.transcript)
554 c.out.setTrafficSecret(hs.suite, serverSecret)
556 err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.clientHello.random, clientSecret)
558 c.sendAlert(alertInternalError)
561 err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.clientHello.random, serverSecret)
563 c.sendAlert(alertInternalError)
567 encryptedExtensions := new(encryptedExtensionsMsg)
569 if len(hs.clientHello.alpnProtocols) > 0 {
570 if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
571 encryptedExtensions.alpnProtocol = selectedProto
572 c.clientProtocol = selectedProto
576 hs.transcript.Write(encryptedExtensions.marshal())
577 if _, err := c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal()); err != nil {
584 func (hs *serverHandshakeStateTLS13) requestClientCert() bool {
585 return hs.c.config.ClientAuth >= RequestClientCert && !hs.usingPSK
588 func (hs *serverHandshakeStateTLS13) sendServerCertificate() error {
591 // Only one of PSK and certificates are used at a time.
596 if hs.requestClientCert() {
597 // Request a client certificate
598 certReq := new(certificateRequestMsgTLS13)
599 certReq.ocspStapling = true
601 certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms()
602 if c.config.ClientCAs != nil {
603 certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
606 hs.transcript.Write(certReq.marshal())
607 if _, err := c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil {
612 certMsg := new(certificateMsgTLS13)
614 certMsg.certificate = *hs.cert
615 certMsg.scts = hs.clientHello.scts && len(hs.cert.SignedCertificateTimestamps) > 0
616 certMsg.ocspStapling = hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0
618 hs.transcript.Write(certMsg.marshal())
619 if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
623 certVerifyMsg := new(certificateVerifyMsg)
624 certVerifyMsg.hasSignatureAlgorithm = true
625 certVerifyMsg.signatureAlgorithm = hs.sigAlg
627 sigType := signatureFromSignatureScheme(hs.sigAlg)
628 sigHash, err := hashFromSignatureScheme(hs.sigAlg)
629 if sigType == 0 || err != nil {
630 // getCertificate returned a certificate incompatible with the
631 // ClientHello supported signature algorithms.
632 c.sendAlert(alertInternalError)
636 writeSignedMessage(h, serverSignatureContext, hs.transcript)
638 signOpts := crypto.SignerOpts(sigHash)
639 if sigType == signatureRSAPSS {
640 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
642 sig, err := hs.cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), h.Sum(nil), signOpts)
644 c.sendAlert(alertInternalError)
645 return errors.New("tls: failed to sign handshake: " + err.Error())
647 certVerifyMsg.signature = sig
649 hs.transcript.Write(certVerifyMsg.marshal())
650 if _, err := c.writeRecord(recordTypeHandshake, certVerifyMsg.marshal()); err != nil {
657 func (hs *serverHandshakeStateTLS13) sendServerFinished() error {
660 finished := &finishedMsg{
661 verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
664 hs.transcript.Write(finished.marshal())
665 if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
669 // Derive secrets that take context through the server Finished.
671 hs.masterSecret = hs.suite.extract(nil,
672 hs.suite.deriveSecret(hs.handshakeSecret, "derived", nil))
674 hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret,
675 clientApplicationTrafficLabel, hs.transcript)
676 serverSecret := hs.suite.deriveSecret(hs.masterSecret,
677 serverApplicationTrafficLabel, hs.transcript)
678 c.out.setTrafficSecret(hs.suite, serverSecret)
680 err := c.config.writeKeyLog(keyLogLabelClientTraffic, hs.clientHello.random, hs.trafficSecret)
682 c.sendAlert(alertInternalError)
685 err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.clientHello.random, serverSecret)
687 c.sendAlert(alertInternalError)
691 c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript)
693 // If we did not request client certificates, at this point we can
694 // precompute the client finished and roll the transcript forward to send
695 // session tickets in our first flight.
696 if !hs.requestClientCert() {
697 if err := hs.sendSessionTickets(); err != nil {
705 func (hs *serverHandshakeStateTLS13) shouldSendSessionTickets() bool {
706 if hs.c.config.SessionTicketsDisabled {
710 // Don't send tickets the client wouldn't use. See RFC 8446, Section 4.2.9.
711 for _, pskMode := range hs.clientHello.pskModes {
712 if pskMode == pskModeDHE {
719 func (hs *serverHandshakeStateTLS13) sendSessionTickets() error {
722 hs.clientFinished = hs.suite.finishedHash(c.in.trafficSecret, hs.transcript)
723 finishedMsg := &finishedMsg{
724 verifyData: hs.clientFinished,
726 hs.transcript.Write(finishedMsg.marshal())
728 if !hs.shouldSendSessionTickets() {
732 resumptionSecret := hs.suite.deriveSecret(hs.masterSecret,
733 resumptionLabel, hs.transcript)
735 m := new(newSessionTicketMsgTLS13)
737 var certsFromClient [][]byte
738 for _, cert := range c.peerCertificates {
739 certsFromClient = append(certsFromClient, cert.Raw)
741 state := sessionStateTLS13{
742 cipherSuite: hs.suite.id,
743 createdAt: uint64(c.config.time().Unix()),
744 resumptionSecret: resumptionSecret,
745 certificate: Certificate{
746 Certificate: certsFromClient,
747 OCSPStaple: c.ocspResponse,
748 SignedCertificateTimestamps: c.scts,
752 m.label, err = c.encryptTicket(state.marshal())
756 m.lifetime = uint32(maxSessionTicketLifetime / time.Second)
758 if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
765 func (hs *serverHandshakeStateTLS13) readClientCertificate() error {
768 if !hs.requestClientCert() {
772 // If we requested a client certificate, then the client must send a
773 // certificate message. If it's empty, no CertificateVerify is sent.
775 msg, err := c.readHandshake()
780 certMsg, ok := msg.(*certificateMsgTLS13)
782 c.sendAlert(alertUnexpectedMessage)
783 return unexpectedMessageError(certMsg, msg)
785 hs.transcript.Write(certMsg.marshal())
787 if err := c.processCertsFromClient(certMsg.certificate); err != nil {
791 if len(certMsg.certificate.Certificate) != 0 {
792 msg, err = c.readHandshake()
797 certVerify, ok := msg.(*certificateVerifyMsg)
799 c.sendAlert(alertUnexpectedMessage)
800 return unexpectedMessageError(certVerify, msg)
803 // See RFC 8446, Section 4.4.3.
804 if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms()) {
805 c.sendAlert(alertIllegalParameter)
806 return errors.New("tls: invalid certificate signature algorithm")
808 sigType := signatureFromSignatureScheme(certVerify.signatureAlgorithm)
809 sigHash, err := hashFromSignatureScheme(certVerify.signatureAlgorithm)
810 if sigType == 0 || err != nil {
811 c.sendAlert(alertInternalError)
814 if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
815 c.sendAlert(alertIllegalParameter)
816 return errors.New("tls: invalid certificate signature algorithm")
819 writeSignedMessage(h, clientSignatureContext, hs.transcript)
820 if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey,
821 sigHash, h.Sum(nil), certVerify.signature); err != nil {
822 c.sendAlert(alertDecryptError)
823 return errors.New("tls: invalid certificate signature")
826 hs.transcript.Write(certVerify.marshal())
829 // If we waited until the client certificates to send session tickets, we
830 // are ready to do it now.
831 if err := hs.sendSessionTickets(); err != nil {
838 func (hs *serverHandshakeStateTLS13) readClientFinished() error {
841 msg, err := c.readHandshake()
846 finished, ok := msg.(*finishedMsg)
848 c.sendAlert(alertUnexpectedMessage)
849 return unexpectedMessageError(finished, msg)
852 if !hmac.Equal(hs.clientFinished, finished.verifyData) {
853 c.sendAlert(alertDecryptError)
854 return errors.New("tls: invalid client finished hash")
857 c.in.setTrafficSecret(hs.suite, hs.trafficSecret)