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.
19 // maxClientPSKIdentities is the number of client PSK identities the server will
20 // attempt to validate. It will ignore the rest not to let cheap ClientHello
21 // messages cause too much work in session ticket decryption attempts.
22 const maxClientPSKIdentities = 5
24 type serverHandshakeStateTLS13 struct {
26 clientHello *clientHelloMsg
30 suite *cipherSuiteTLS13
32 sigAlg SignatureScheme
35 handshakeSecret []byte
37 trafficSecret []byte // client_application_traffic_secret_0
42 func (hs *serverHandshakeStateTLS13) handshake() error {
46 return errors.New("tls: internal error: TLS 1.3 reached in FIPS mode")
49 // For an overview of the TLS 1.3 handshake, see RFC 8446, Section 2.
50 if err := hs.processClientHello(); err != nil {
53 if err := hs.checkForResumption(); err != nil {
56 if err := hs.pickCertificate(); err != nil {
60 if err := hs.sendServerParameters(); err != nil {
63 if err := hs.sendServerCertificate(); err != nil {
66 if err := hs.sendServerFinished(); err != nil {
69 // Note that at this point we could start sending application data without
70 // waiting for the client's second flight, but the application might not
71 // expect the lack of replay protection of the ClientHello parameters.
72 if _, err := c.flush(); err != nil {
75 if err := hs.readClientCertificate(); err != nil {
78 if err := hs.readClientFinished(); err != nil {
82 atomic.StoreUint32(&c.handshakeStatus, 1)
87 func (hs *serverHandshakeStateTLS13) processClientHello() error {
90 hs.hello = new(serverHelloMsg)
92 // TLS 1.3 froze the ServerHello.legacy_version field, and uses
93 // supported_versions instead. See RFC 8446, sections 4.1.3 and 4.2.1.
94 hs.hello.vers = VersionTLS12
95 hs.hello.supportedVersion = c.vers
97 if len(hs.clientHello.supportedVersions) == 0 {
98 c.sendAlert(alertIllegalParameter)
99 return errors.New("tls: client used the legacy version field to negotiate TLS 1.3")
102 // Abort if the client is doing a fallback and landing lower than what we
103 // support. See RFC 7507, which however does not specify the interaction
104 // with supported_versions. The only difference is that with
105 // supported_versions a client has a chance to attempt a [TLS 1.2, TLS 1.4]
106 // handshake in case TLS 1.3 is broken but 1.2 is not. Alas, in that case,
107 // it will have to drop the TLS_FALLBACK_SCSV protection if it falls back to
108 // TLS 1.2, because a TLS 1.3 server would abort here. The situation before
109 // supported_versions was not better because there was just no way to do a
110 // TLS 1.4 handshake without risking the server selecting TLS 1.3.
111 for _, id := range hs.clientHello.cipherSuites {
112 if id == TLS_FALLBACK_SCSV {
113 // Use c.vers instead of max(supported_versions) because an attacker
114 // could defeat this by adding an arbitrary high version otherwise.
115 if c.vers < c.config.maxSupportedVersion() {
116 c.sendAlert(alertInappropriateFallback)
117 return errors.New("tls: client using inappropriate protocol fallback")
123 if len(hs.clientHello.compressionMethods) != 1 ||
124 hs.clientHello.compressionMethods[0] != compressionNone {
125 c.sendAlert(alertIllegalParameter)
126 return errors.New("tls: TLS 1.3 client supports illegal compression methods")
129 hs.hello.random = make([]byte, 32)
130 if _, err := io.ReadFull(c.config.rand(), hs.hello.random); err != nil {
131 c.sendAlert(alertInternalError)
135 if len(hs.clientHello.secureRenegotiation) != 0 {
136 c.sendAlert(alertHandshakeFailure)
137 return errors.New("tls: initial handshake had non-empty renegotiation extension")
140 if hs.clientHello.earlyData {
141 // See RFC 8446, Section 4.2.10 for the complicated behavior required
142 // here. The scenario is that a different server at our address offered
143 // to accept early data in the past, which we can't handle. For now, all
144 // 0-RTT enabled session tickets need to expire before a Go server can
145 // replace a server or join a pool. That's the same requirement that
146 // applies to mixing or replacing with any TLS 1.2 server.
147 c.sendAlert(alertUnsupportedExtension)
148 return errors.New("tls: client sent unexpected early data")
151 hs.hello.sessionId = hs.clientHello.sessionId
152 hs.hello.compressionMethod = compressionNone
154 var preferenceList, supportedList []uint16
155 if c.config.PreferServerCipherSuites {
156 preferenceList = defaultCipherSuitesTLS13()
157 supportedList = hs.clientHello.cipherSuites
159 // If the client does not seem to have hardware support for AES-GCM,
160 // prefer other AEAD ciphers even if we prioritized AES-GCM ciphers
162 if !aesgcmPreferred(hs.clientHello.cipherSuites) {
163 preferenceList = deprioritizeAES(preferenceList)
166 preferenceList = hs.clientHello.cipherSuites
167 supportedList = defaultCipherSuitesTLS13()
169 // If we don't have hardware support for AES-GCM, prefer other AEAD
170 // ciphers even if the client prioritized AES-GCM.
171 // If BoringCrypto is enabled, always prioritize AES-GCM.
172 if !hasAESGCMHardwareSupport && !boringEnabled {
173 preferenceList = deprioritizeAES(preferenceList)
176 for _, suiteID := range preferenceList {
177 hs.suite = mutualCipherSuiteTLS13(supportedList, suiteID)
183 c.sendAlert(alertHandshakeFailure)
184 return errors.New("tls: no cipher suite supported by both client and server")
186 c.cipherSuite = hs.suite.id
187 hs.hello.cipherSuite = hs.suite.id
188 hs.transcript = hs.suite.hash.New()
190 // Pick the ECDHE group in server preference order, but give priority to
191 // groups with a key share, to avoid a HelloRetryRequest round-trip.
192 var selectedGroup CurveID
193 var clientKeyShare *keyShare
195 for _, preferredGroup := range c.config.curvePreferences() {
196 for _, ks := range hs.clientHello.keyShares {
197 if ks.group == preferredGroup {
198 selectedGroup = ks.group
203 if selectedGroup != 0 {
206 for _, group := range hs.clientHello.supportedCurves {
207 if group == preferredGroup {
208 selectedGroup = group
213 if selectedGroup == 0 {
214 c.sendAlert(alertHandshakeFailure)
215 return errors.New("tls: no ECDHE curve supported by both client and server")
217 if clientKeyShare == nil {
218 if err := hs.doHelloRetryRequest(selectedGroup); err != nil {
221 clientKeyShare = &hs.clientHello.keyShares[0]
224 if _, ok := curveForCurveID(selectedGroup); selectedGroup != X25519 && !ok {
225 c.sendAlert(alertInternalError)
226 return errors.New("tls: CurvePreferences includes unsupported curve")
228 params, err := generateECDHEParameters(c.config.rand(), selectedGroup)
230 c.sendAlert(alertInternalError)
233 hs.hello.serverShare = keyShare{group: selectedGroup, data: params.PublicKey()}
234 hs.sharedKey = params.SharedKey(clientKeyShare.data)
235 if hs.sharedKey == nil {
236 c.sendAlert(alertIllegalParameter)
237 return errors.New("tls: invalid client key share")
240 c.serverName = hs.clientHello.serverName
244 func (hs *serverHandshakeStateTLS13) checkForResumption() error {
247 if c.config.SessionTicketsDisabled {
252 for _, mode := range hs.clientHello.pskModes {
253 if mode == pskModeDHE {
262 if len(hs.clientHello.pskIdentities) != len(hs.clientHello.pskBinders) {
263 c.sendAlert(alertIllegalParameter)
264 return errors.New("tls: invalid or missing PSK binders")
266 if len(hs.clientHello.pskIdentities) == 0 {
270 for i, identity := range hs.clientHello.pskIdentities {
271 if i >= maxClientPSKIdentities {
275 plaintext, _ := c.decryptTicket(identity.label)
276 if plaintext == nil {
279 sessionState := new(sessionStateTLS13)
280 if ok := sessionState.unmarshal(plaintext); !ok {
284 createdAt := time.Unix(int64(sessionState.createdAt), 0)
285 if c.config.time().Sub(createdAt) > maxSessionTicketLifetime {
289 // We don't check the obfuscated ticket age because it's affected by
290 // clock skew and it's only a freshness signal useful for shrinking the
291 // window for replay attacks, which don't affect us as we don't do 0-RTT.
293 pskSuite := cipherSuiteTLS13ByID(sessionState.cipherSuite)
294 if pskSuite == nil || pskSuite.hash != hs.suite.hash {
298 // PSK connections don't re-establish client certificates, but carry
299 // them over in the session ticket. Ensure the presence of client certs
300 // in the ticket is consistent with the configured requirements.
301 sessionHasClientCerts := len(sessionState.certificate.Certificate) != 0
302 needClientCerts := requiresClientCert(c.config.ClientAuth)
303 if needClientCerts && !sessionHasClientCerts {
306 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
310 psk := hs.suite.expandLabel(sessionState.resumptionSecret, "resumption",
311 nil, hs.suite.hash.Size())
312 hs.earlySecret = hs.suite.extract(psk, nil)
313 binderKey := hs.suite.deriveSecret(hs.earlySecret, resumptionBinderLabel, nil)
314 // Clone the transcript in case a HelloRetryRequest was recorded.
315 transcript := cloneHash(hs.transcript, hs.suite.hash)
316 if transcript == nil {
317 c.sendAlert(alertInternalError)
318 return errors.New("tls: internal error: failed to clone hash")
320 transcript.Write(hs.clientHello.marshalWithoutBinders())
321 pskBinder := hs.suite.finishedHash(binderKey, transcript)
322 if !hmac.Equal(hs.clientHello.pskBinders[i], pskBinder) {
323 c.sendAlert(alertDecryptError)
324 return errors.New("tls: invalid PSK binder")
328 if err := c.processCertsFromClient(sessionState.certificate); err != nil {
332 hs.hello.selectedIdentityPresent = true
333 hs.hello.selectedIdentity = uint16(i)
341 // cloneHash uses the encoding.BinaryMarshaler and encoding.BinaryUnmarshaler
342 // interfaces implemented by standard library hashes to clone the state of in
343 // to a new instance of h. It returns nil if the operation fails.
344 func cloneHash(in hash.Hash, h crypto.Hash) hash.Hash {
345 // Recreate the interface to avoid importing encoding.
346 type binaryMarshaler interface {
347 MarshalBinary() (data []byte, err error)
348 UnmarshalBinary(data []byte) error
350 marshaler, ok := in.(binaryMarshaler)
354 state, err := marshaler.MarshalBinary()
359 unmarshaler, ok := out.(binaryMarshaler)
363 if err := unmarshaler.UnmarshalBinary(state); err != nil {
369 func (hs *serverHandshakeStateTLS13) pickCertificate() error {
372 // Only one of PSK and certificates are used at a time.
377 // signature_algorithms is required in TLS 1.3. See RFC 8446, Section 4.2.3.
378 if len(hs.clientHello.supportedSignatureAlgorithms) == 0 {
379 return c.sendAlert(alertMissingExtension)
382 certificate, err := c.config.getCertificate(clientHelloInfo(c, hs.clientHello))
384 if err == errNoCertificates {
385 c.sendAlert(alertUnrecognizedName)
387 c.sendAlert(alertInternalError)
391 hs.sigAlg, err = selectSignatureScheme(c.vers, certificate, hs.clientHello.supportedSignatureAlgorithms)
393 // getCertificate returned a certificate that is unsupported or
394 // incompatible with the client's signature algorithms.
395 c.sendAlert(alertHandshakeFailure)
398 hs.cert = certificate
403 // sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility
404 // with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4.
405 func (hs *serverHandshakeStateTLS13) sendDummyChangeCipherSpec() error {
409 hs.sentDummyCCS = true
411 _, err := hs.c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
415 func (hs *serverHandshakeStateTLS13) doHelloRetryRequest(selectedGroup CurveID) error {
418 // The first ClientHello gets double-hashed into the transcript upon a
419 // HelloRetryRequest. See RFC 8446, Section 4.4.1.
420 hs.transcript.Write(hs.clientHello.marshal())
421 chHash := hs.transcript.Sum(nil)
422 hs.transcript.Reset()
423 hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
424 hs.transcript.Write(chHash)
426 helloRetryRequest := &serverHelloMsg{
428 random: helloRetryRequestRandom,
429 sessionId: hs.hello.sessionId,
430 cipherSuite: hs.hello.cipherSuite,
431 compressionMethod: hs.hello.compressionMethod,
432 supportedVersion: hs.hello.supportedVersion,
433 selectedGroup: selectedGroup,
436 hs.transcript.Write(helloRetryRequest.marshal())
437 if _, err := c.writeRecord(recordTypeHandshake, helloRetryRequest.marshal()); err != nil {
441 if err := hs.sendDummyChangeCipherSpec(); err != nil {
445 msg, err := c.readHandshake()
450 clientHello, ok := msg.(*clientHelloMsg)
452 c.sendAlert(alertUnexpectedMessage)
453 return unexpectedMessageError(clientHello, msg)
456 if len(clientHello.keyShares) != 1 || clientHello.keyShares[0].group != selectedGroup {
457 c.sendAlert(alertIllegalParameter)
458 return errors.New("tls: client sent invalid key share in second ClientHello")
461 if clientHello.earlyData {
462 c.sendAlert(alertIllegalParameter)
463 return errors.New("tls: client indicated early data in second ClientHello")
466 if illegalClientHelloChange(clientHello, hs.clientHello) {
467 c.sendAlert(alertIllegalParameter)
468 return errors.New("tls: client illegally modified second ClientHello")
471 hs.clientHello = clientHello
475 // illegalClientHelloChange reports whether the two ClientHello messages are
476 // different, with the exception of the changes allowed before and after a
477 // HelloRetryRequest. See RFC 8446, Section 4.1.2.
478 func illegalClientHelloChange(ch, ch1 *clientHelloMsg) bool {
479 if len(ch.supportedVersions) != len(ch1.supportedVersions) ||
480 len(ch.cipherSuites) != len(ch1.cipherSuites) ||
481 len(ch.supportedCurves) != len(ch1.supportedCurves) ||
482 len(ch.supportedSignatureAlgorithms) != len(ch1.supportedSignatureAlgorithms) ||
483 len(ch.supportedSignatureAlgorithmsCert) != len(ch1.supportedSignatureAlgorithmsCert) ||
484 len(ch.alpnProtocols) != len(ch1.alpnProtocols) {
487 for i := range ch.supportedVersions {
488 if ch.supportedVersions[i] != ch1.supportedVersions[i] {
492 for i := range ch.cipherSuites {
493 if ch.cipherSuites[i] != ch1.cipherSuites[i] {
497 for i := range ch.supportedCurves {
498 if ch.supportedCurves[i] != ch1.supportedCurves[i] {
502 for i := range ch.supportedSignatureAlgorithms {
503 if ch.supportedSignatureAlgorithms[i] != ch1.supportedSignatureAlgorithms[i] {
507 for i := range ch.supportedSignatureAlgorithmsCert {
508 if ch.supportedSignatureAlgorithmsCert[i] != ch1.supportedSignatureAlgorithmsCert[i] {
512 for i := range ch.alpnProtocols {
513 if ch.alpnProtocols[i] != ch1.alpnProtocols[i] {
517 return ch.vers != ch1.vers ||
518 !bytes.Equal(ch.random, ch1.random) ||
519 !bytes.Equal(ch.sessionId, ch1.sessionId) ||
520 !bytes.Equal(ch.compressionMethods, ch1.compressionMethods) ||
521 ch.serverName != ch1.serverName ||
522 ch.ocspStapling != ch1.ocspStapling ||
523 !bytes.Equal(ch.supportedPoints, ch1.supportedPoints) ||
524 ch.ticketSupported != ch1.ticketSupported ||
525 !bytes.Equal(ch.sessionTicket, ch1.sessionTicket) ||
526 ch.secureRenegotiationSupported != ch1.secureRenegotiationSupported ||
527 !bytes.Equal(ch.secureRenegotiation, ch1.secureRenegotiation) ||
528 ch.scts != ch1.scts ||
529 !bytes.Equal(ch.cookie, ch1.cookie) ||
530 !bytes.Equal(ch.pskModes, ch1.pskModes)
533 func (hs *serverHandshakeStateTLS13) sendServerParameters() error {
536 hs.transcript.Write(hs.clientHello.marshal())
537 hs.transcript.Write(hs.hello.marshal())
538 if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
542 if err := hs.sendDummyChangeCipherSpec(); err != nil {
546 earlySecret := hs.earlySecret
547 if earlySecret == nil {
548 earlySecret = hs.suite.extract(nil, nil)
550 hs.handshakeSecret = hs.suite.extract(hs.sharedKey,
551 hs.suite.deriveSecret(earlySecret, "derived", nil))
553 clientSecret := hs.suite.deriveSecret(hs.handshakeSecret,
554 clientHandshakeTrafficLabel, hs.transcript)
555 c.in.setTrafficSecret(hs.suite, clientSecret)
556 serverSecret := hs.suite.deriveSecret(hs.handshakeSecret,
557 serverHandshakeTrafficLabel, hs.transcript)
558 c.out.setTrafficSecret(hs.suite, serverSecret)
560 err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.clientHello.random, clientSecret)
562 c.sendAlert(alertInternalError)
565 err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.clientHello.random, serverSecret)
567 c.sendAlert(alertInternalError)
571 encryptedExtensions := new(encryptedExtensionsMsg)
573 if len(hs.clientHello.alpnProtocols) > 0 {
574 if selectedProto := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); selectedProto != "" {
575 encryptedExtensions.alpnProtocol = selectedProto
576 c.clientProtocol = selectedProto
580 hs.transcript.Write(encryptedExtensions.marshal())
581 if _, err := c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal()); err != nil {
588 func (hs *serverHandshakeStateTLS13) requestClientCert() bool {
589 return hs.c.config.ClientAuth >= RequestClientCert && !hs.usingPSK
592 func (hs *serverHandshakeStateTLS13) sendServerCertificate() error {
595 // Only one of PSK and certificates are used at a time.
600 if hs.requestClientCert() {
601 // Request a client certificate
602 certReq := new(certificateRequestMsgTLS13)
603 certReq.ocspStapling = true
605 certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms()
606 if c.config.ClientCAs != nil {
607 certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
610 hs.transcript.Write(certReq.marshal())
611 if _, err := c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil {
616 certMsg := new(certificateMsgTLS13)
618 certMsg.certificate = *hs.cert
619 certMsg.scts = hs.clientHello.scts && len(hs.cert.SignedCertificateTimestamps) > 0
620 certMsg.ocspStapling = hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0
622 hs.transcript.Write(certMsg.marshal())
623 if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
627 certVerifyMsg := new(certificateVerifyMsg)
628 certVerifyMsg.hasSignatureAlgorithm = true
629 certVerifyMsg.signatureAlgorithm = hs.sigAlg
631 sigType, sigHash, err := typeAndHashFromSignatureScheme(hs.sigAlg)
633 return c.sendAlert(alertInternalError)
636 signed := signedMessage(sigHash, serverSignatureContext, hs.transcript)
637 signOpts := crypto.SignerOpts(sigHash)
638 if sigType == signatureRSAPSS {
639 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
641 sig, err := hs.cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts)
643 public := hs.cert.PrivateKey.(crypto.Signer).Public()
644 if rsaKey, ok := public.(*rsa.PublicKey); ok && sigType == signatureRSAPSS &&
645 rsaKey.N.BitLen()/8 < sigHash.Size()*2+2 { // key too small for RSA-PSS
646 c.sendAlert(alertHandshakeFailure)
648 c.sendAlert(alertInternalError)
650 return errors.New("tls: failed to sign handshake: " + err.Error())
652 certVerifyMsg.signature = sig
654 hs.transcript.Write(certVerifyMsg.marshal())
655 if _, err := c.writeRecord(recordTypeHandshake, certVerifyMsg.marshal()); err != nil {
662 func (hs *serverHandshakeStateTLS13) sendServerFinished() error {
665 finished := &finishedMsg{
666 verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
669 hs.transcript.Write(finished.marshal())
670 if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
674 // Derive secrets that take context through the server Finished.
676 hs.masterSecret = hs.suite.extract(nil,
677 hs.suite.deriveSecret(hs.handshakeSecret, "derived", nil))
679 hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret,
680 clientApplicationTrafficLabel, hs.transcript)
681 serverSecret := hs.suite.deriveSecret(hs.masterSecret,
682 serverApplicationTrafficLabel, hs.transcript)
683 c.out.setTrafficSecret(hs.suite, serverSecret)
685 err := c.config.writeKeyLog(keyLogLabelClientTraffic, hs.clientHello.random, hs.trafficSecret)
687 c.sendAlert(alertInternalError)
690 err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.clientHello.random, serverSecret)
692 c.sendAlert(alertInternalError)
696 c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript)
698 // If we did not request client certificates, at this point we can
699 // precompute the client finished and roll the transcript forward to send
700 // session tickets in our first flight.
701 if !hs.requestClientCert() {
702 if err := hs.sendSessionTickets(); err != nil {
710 func (hs *serverHandshakeStateTLS13) shouldSendSessionTickets() bool {
711 if hs.c.config.SessionTicketsDisabled {
715 // Don't send tickets the client wouldn't use. See RFC 8446, Section 4.2.9.
716 for _, pskMode := range hs.clientHello.pskModes {
717 if pskMode == pskModeDHE {
724 func (hs *serverHandshakeStateTLS13) sendSessionTickets() error {
727 hs.clientFinished = hs.suite.finishedHash(c.in.trafficSecret, hs.transcript)
728 finishedMsg := &finishedMsg{
729 verifyData: hs.clientFinished,
731 hs.transcript.Write(finishedMsg.marshal())
733 if !hs.shouldSendSessionTickets() {
737 resumptionSecret := hs.suite.deriveSecret(hs.masterSecret,
738 resumptionLabel, hs.transcript)
740 m := new(newSessionTicketMsgTLS13)
742 var certsFromClient [][]byte
743 for _, cert := range c.peerCertificates {
744 certsFromClient = append(certsFromClient, cert.Raw)
746 state := sessionStateTLS13{
747 cipherSuite: hs.suite.id,
748 createdAt: uint64(c.config.time().Unix()),
749 resumptionSecret: resumptionSecret,
750 certificate: Certificate{
751 Certificate: certsFromClient,
752 OCSPStaple: c.ocspResponse,
753 SignedCertificateTimestamps: c.scts,
757 m.label, err = c.encryptTicket(state.marshal())
761 m.lifetime = uint32(maxSessionTicketLifetime / time.Second)
763 if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
770 func (hs *serverHandshakeStateTLS13) readClientCertificate() error {
773 if !hs.requestClientCert() {
774 // Make sure the connection is still being verified whether or not
775 // the server requested a client certificate.
776 if c.config.VerifyConnection != nil {
777 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
778 c.sendAlert(alertBadCertificate)
785 // If we requested a client certificate, then the client must send a
786 // certificate message. If it's empty, no CertificateVerify is sent.
788 msg, err := c.readHandshake()
793 certMsg, ok := msg.(*certificateMsgTLS13)
795 c.sendAlert(alertUnexpectedMessage)
796 return unexpectedMessageError(certMsg, msg)
798 hs.transcript.Write(certMsg.marshal())
800 if err := c.processCertsFromClient(certMsg.certificate); err != nil {
804 if c.config.VerifyConnection != nil {
805 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
806 c.sendAlert(alertBadCertificate)
811 if len(certMsg.certificate.Certificate) != 0 {
812 msg, err = c.readHandshake()
817 certVerify, ok := msg.(*certificateVerifyMsg)
819 c.sendAlert(alertUnexpectedMessage)
820 return unexpectedMessageError(certVerify, msg)
823 // See RFC 8446, Section 4.4.3.
824 if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms()) {
825 c.sendAlert(alertIllegalParameter)
826 return errors.New("tls: client certificate used with invalid signature algorithm")
828 sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
830 return c.sendAlert(alertInternalError)
832 if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
833 c.sendAlert(alertIllegalParameter)
834 return errors.New("tls: client certificate used with invalid signature algorithm")
836 signed := signedMessage(sigHash, clientSignatureContext, hs.transcript)
837 if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey,
838 sigHash, signed, certVerify.signature); err != nil {
839 c.sendAlert(alertDecryptError)
840 return errors.New("tls: invalid signature by the client certificate: " + err.Error())
843 hs.transcript.Write(certVerify.marshal())
846 // If we waited until the client certificates to send session tickets, we
847 // are ready to do it now.
848 if err := hs.sendSessionTickets(); err != nil {
855 func (hs *serverHandshakeStateTLS13) readClientFinished() error {
858 msg, err := c.readHandshake()
863 finished, ok := msg.(*finishedMsg)
865 c.sendAlert(alertUnexpectedMessage)
866 return unexpectedMessageError(finished, msg)
869 if !hmac.Equal(hs.clientFinished, finished.verifyData) {
870 c.sendAlert(alertDecryptError)
871 return errors.New("tls: invalid client finished hash")
874 c.in.setTrafficSecret(hs.suite, hs.trafficSecret)