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.
21 // maxClientPSKIdentities is the number of client PSK identities the server will
22 // attempt to validate. It will ignore the rest not to let cheap ClientHello
23 // messages cause too much work in session ticket decryption attempts.
24 const maxClientPSKIdentities = 5
26 type serverHandshakeStateTLS13 struct {
29 clientHello *clientHelloMsg
33 suite *cipherSuiteTLS13
35 sigAlg SignatureScheme
38 handshakeSecret []byte
40 trafficSecret []byte // client_application_traffic_secret_0
45 func (hs *serverHandshakeStateTLS13) handshake() error {
49 return errors.New("tls: internal error: TLS 1.3 reached in FIPS mode")
52 // For an overview of the TLS 1.3 handshake, see RFC 8446, Section 2.
53 if err := hs.processClientHello(); err != nil {
56 if err := hs.checkForResumption(); err != nil {
59 if err := hs.pickCertificate(); err != nil {
63 if err := hs.sendServerParameters(); err != nil {
66 if err := hs.sendServerCertificate(); err != nil {
69 if err := hs.sendServerFinished(); err != nil {
72 // Note that at this point we could start sending application data without
73 // waiting for the client's second flight, but the application might not
74 // expect the lack of replay protection of the ClientHello parameters.
75 if _, err := c.flush(); err != nil {
78 if err := hs.readClientCertificate(); err != nil {
81 if err := hs.readClientFinished(); err != nil {
85 atomic.StoreUint32(&c.handshakeStatus, 1)
90 func (hs *serverHandshakeStateTLS13) processClientHello() error {
93 hs.hello = new(serverHelloMsg)
95 // TLS 1.3 froze the ServerHello.legacy_version field, and uses
96 // supported_versions instead. See RFC 8446, sections 4.1.3 and 4.2.1.
97 hs.hello.vers = VersionTLS12
98 hs.hello.supportedVersion = c.vers
100 if len(hs.clientHello.supportedVersions) == 0 {
101 c.sendAlert(alertIllegalParameter)
102 return errors.New("tls: client used the legacy version field to negotiate TLS 1.3")
105 // Abort if the client is doing a fallback and landing lower than what we
106 // support. See RFC 7507, which however does not specify the interaction
107 // with supported_versions. The only difference is that with
108 // supported_versions a client has a chance to attempt a [TLS 1.2, TLS 1.4]
109 // handshake in case TLS 1.3 is broken but 1.2 is not. Alas, in that case,
110 // it will have to drop the TLS_FALLBACK_SCSV protection if it falls back to
111 // TLS 1.2, because a TLS 1.3 server would abort here. The situation before
112 // supported_versions was not better because there was just no way to do a
113 // TLS 1.4 handshake without risking the server selecting TLS 1.3.
114 for _, id := range hs.clientHello.cipherSuites {
115 if id == TLS_FALLBACK_SCSV {
116 // Use c.vers instead of max(supported_versions) because an attacker
117 // could defeat this by adding an arbitrary high version otherwise.
118 if c.vers < c.config.maxSupportedVersion() {
119 c.sendAlert(alertInappropriateFallback)
120 return errors.New("tls: client using inappropriate protocol fallback")
126 if len(hs.clientHello.compressionMethods) != 1 ||
127 hs.clientHello.compressionMethods[0] != compressionNone {
128 c.sendAlert(alertIllegalParameter)
129 return errors.New("tls: TLS 1.3 client supports illegal compression methods")
132 hs.hello.random = make([]byte, 32)
133 if _, err := io.ReadFull(c.config.rand(), hs.hello.random); err != nil {
134 c.sendAlert(alertInternalError)
138 if len(hs.clientHello.secureRenegotiation) != 0 {
139 c.sendAlert(alertHandshakeFailure)
140 return errors.New("tls: initial handshake had non-empty renegotiation extension")
143 if hs.clientHello.earlyData {
144 // See RFC 8446, Section 4.2.10 for the complicated behavior required
145 // here. The scenario is that a different server at our address offered
146 // to accept early data in the past, which we can't handle. For now, all
147 // 0-RTT enabled session tickets need to expire before a Go server can
148 // replace a server or join a pool. That's the same requirement that
149 // applies to mixing or replacing with any TLS 1.2 server.
150 c.sendAlert(alertUnsupportedExtension)
151 return errors.New("tls: client sent unexpected early data")
154 hs.hello.sessionId = hs.clientHello.sessionId
155 hs.hello.compressionMethod = compressionNone
157 preferenceList := defaultCipherSuitesTLS13
158 if !hasAESGCMHardwareSupport || !aesgcmPreferred(hs.clientHello.cipherSuites) {
159 preferenceList = defaultCipherSuitesTLS13NoAES
161 for _, suiteID := range preferenceList {
162 hs.suite = mutualCipherSuiteTLS13(hs.clientHello.cipherSuites, suiteID)
168 c.sendAlert(alertHandshakeFailure)
169 return errors.New("tls: no cipher suite supported by both client and server")
171 c.cipherSuite = hs.suite.id
172 hs.hello.cipherSuite = hs.suite.id
173 hs.transcript = hs.suite.hash.New()
175 // Pick the ECDHE group in server preference order, but give priority to
176 // groups with a key share, to avoid a HelloRetryRequest round-trip.
177 var selectedGroup CurveID
178 var clientKeyShare *keyShare
180 for _, preferredGroup := range c.config.curvePreferences() {
181 for _, ks := range hs.clientHello.keyShares {
182 if ks.group == preferredGroup {
183 selectedGroup = ks.group
188 if selectedGroup != 0 {
191 for _, group := range hs.clientHello.supportedCurves {
192 if group == preferredGroup {
193 selectedGroup = group
198 if selectedGroup == 0 {
199 c.sendAlert(alertHandshakeFailure)
200 return errors.New("tls: no ECDHE curve supported by both client and server")
202 if clientKeyShare == nil {
203 if err := hs.doHelloRetryRequest(selectedGroup); err != nil {
206 clientKeyShare = &hs.clientHello.keyShares[0]
209 if _, ok := curveForCurveID(selectedGroup); selectedGroup != X25519 && !ok {
210 c.sendAlert(alertInternalError)
211 return errors.New("tls: CurvePreferences includes unsupported curve")
213 params, err := generateECDHEParameters(c.config.rand(), selectedGroup)
215 c.sendAlert(alertInternalError)
218 hs.hello.serverShare = keyShare{group: selectedGroup, data: params.PublicKey()}
219 hs.sharedKey = params.SharedKey(clientKeyShare.data)
220 if hs.sharedKey == nil {
221 c.sendAlert(alertIllegalParameter)
222 return errors.New("tls: invalid client key share")
225 c.serverName = hs.clientHello.serverName
229 func (hs *serverHandshakeStateTLS13) checkForResumption() error {
232 if c.config.SessionTicketsDisabled {
237 for _, mode := range hs.clientHello.pskModes {
238 if mode == pskModeDHE {
247 if len(hs.clientHello.pskIdentities) != len(hs.clientHello.pskBinders) {
248 c.sendAlert(alertIllegalParameter)
249 return errors.New("tls: invalid or missing PSK binders")
251 if len(hs.clientHello.pskIdentities) == 0 {
255 for i, identity := range hs.clientHello.pskIdentities {
256 if i >= maxClientPSKIdentities {
260 plaintext, _ := c.decryptTicket(identity.label)
261 if plaintext == nil {
264 sessionState := new(sessionStateTLS13)
265 if ok := sessionState.unmarshal(plaintext); !ok {
269 createdAt := time.Unix(int64(sessionState.createdAt), 0)
270 if c.config.time().Sub(createdAt) > maxSessionTicketLifetime {
274 // We don't check the obfuscated ticket age because it's affected by
275 // clock skew and it's only a freshness signal useful for shrinking the
276 // window for replay attacks, which don't affect us as we don't do 0-RTT.
278 pskSuite := cipherSuiteTLS13ByID(sessionState.cipherSuite)
279 if pskSuite == nil || pskSuite.hash != hs.suite.hash {
283 // PSK connections don't re-establish client certificates, but carry
284 // them over in the session ticket. Ensure the presence of client certs
285 // in the ticket is consistent with the configured requirements.
286 sessionHasClientCerts := len(sessionState.certificate.Certificate) != 0
287 needClientCerts := requiresClientCert(c.config.ClientAuth)
288 if needClientCerts && !sessionHasClientCerts {
291 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
295 psk := hs.suite.expandLabel(sessionState.resumptionSecret, "resumption",
296 nil, hs.suite.hash.Size())
297 hs.earlySecret = hs.suite.extract(psk, nil)
298 binderKey := hs.suite.deriveSecret(hs.earlySecret, resumptionBinderLabel, nil)
299 // Clone the transcript in case a HelloRetryRequest was recorded.
300 transcript := cloneHash(hs.transcript, hs.suite.hash)
301 if transcript == nil {
302 c.sendAlert(alertInternalError)
303 return errors.New("tls: internal error: failed to clone hash")
305 transcript.Write(hs.clientHello.marshalWithoutBinders())
306 pskBinder := hs.suite.finishedHash(binderKey, transcript)
307 if !hmac.Equal(hs.clientHello.pskBinders[i], pskBinder) {
308 c.sendAlert(alertDecryptError)
309 return errors.New("tls: invalid PSK binder")
313 if err := c.processCertsFromClient(sessionState.certificate); err != nil {
317 hs.hello.selectedIdentityPresent = true
318 hs.hello.selectedIdentity = uint16(i)
326 // cloneHash uses the encoding.BinaryMarshaler and encoding.BinaryUnmarshaler
327 // interfaces implemented by standard library hashes to clone the state of in
328 // to a new instance of h. It returns nil if the operation fails.
329 func cloneHash(in hash.Hash, h crypto.Hash) hash.Hash {
330 // Recreate the interface to avoid importing encoding.
331 type binaryMarshaler interface {
332 MarshalBinary() (data []byte, err error)
333 UnmarshalBinary(data []byte) error
335 marshaler, ok := in.(binaryMarshaler)
339 state, err := marshaler.MarshalBinary()
344 unmarshaler, ok := out.(binaryMarshaler)
348 if err := unmarshaler.UnmarshalBinary(state); err != nil {
354 func (hs *serverHandshakeStateTLS13) pickCertificate() error {
357 // Only one of PSK and certificates are used at a time.
362 // signature_algorithms is required in TLS 1.3. See RFC 8446, Section 4.2.3.
363 if len(hs.clientHello.supportedSignatureAlgorithms) == 0 {
364 return c.sendAlert(alertMissingExtension)
367 certificate, err := c.config.getCertificate(clientHelloInfo(hs.ctx, c, hs.clientHello))
369 if err == errNoCertificates {
370 c.sendAlert(alertUnrecognizedName)
372 c.sendAlert(alertInternalError)
376 hs.sigAlg, err = selectSignatureScheme(c.vers, certificate, hs.clientHello.supportedSignatureAlgorithms)
378 // getCertificate returned a certificate that is unsupported or
379 // incompatible with the client's signature algorithms.
380 c.sendAlert(alertHandshakeFailure)
383 hs.cert = certificate
388 // sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility
389 // with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4.
390 func (hs *serverHandshakeStateTLS13) sendDummyChangeCipherSpec() error {
394 hs.sentDummyCCS = true
396 _, err := hs.c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
400 func (hs *serverHandshakeStateTLS13) doHelloRetryRequest(selectedGroup CurveID) error {
403 // The first ClientHello gets double-hashed into the transcript upon a
404 // HelloRetryRequest. See RFC 8446, Section 4.4.1.
405 hs.transcript.Write(hs.clientHello.marshal())
406 chHash := hs.transcript.Sum(nil)
407 hs.transcript.Reset()
408 hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
409 hs.transcript.Write(chHash)
411 helloRetryRequest := &serverHelloMsg{
413 random: helloRetryRequestRandom,
414 sessionId: hs.hello.sessionId,
415 cipherSuite: hs.hello.cipherSuite,
416 compressionMethod: hs.hello.compressionMethod,
417 supportedVersion: hs.hello.supportedVersion,
418 selectedGroup: selectedGroup,
421 hs.transcript.Write(helloRetryRequest.marshal())
422 if _, err := c.writeRecord(recordTypeHandshake, helloRetryRequest.marshal()); err != nil {
426 if err := hs.sendDummyChangeCipherSpec(); err != nil {
430 msg, err := c.readHandshake()
435 clientHello, ok := msg.(*clientHelloMsg)
437 c.sendAlert(alertUnexpectedMessage)
438 return unexpectedMessageError(clientHello, msg)
441 if len(clientHello.keyShares) != 1 || clientHello.keyShares[0].group != selectedGroup {
442 c.sendAlert(alertIllegalParameter)
443 return errors.New("tls: client sent invalid key share in second ClientHello")
446 if clientHello.earlyData {
447 c.sendAlert(alertIllegalParameter)
448 return errors.New("tls: client indicated early data in second ClientHello")
451 if illegalClientHelloChange(clientHello, hs.clientHello) {
452 c.sendAlert(alertIllegalParameter)
453 return errors.New("tls: client illegally modified second ClientHello")
456 hs.clientHello = clientHello
460 // illegalClientHelloChange reports whether the two ClientHello messages are
461 // different, with the exception of the changes allowed before and after a
462 // HelloRetryRequest. See RFC 8446, Section 4.1.2.
463 func illegalClientHelloChange(ch, ch1 *clientHelloMsg) bool {
464 if len(ch.supportedVersions) != len(ch1.supportedVersions) ||
465 len(ch.cipherSuites) != len(ch1.cipherSuites) ||
466 len(ch.supportedCurves) != len(ch1.supportedCurves) ||
467 len(ch.supportedSignatureAlgorithms) != len(ch1.supportedSignatureAlgorithms) ||
468 len(ch.supportedSignatureAlgorithmsCert) != len(ch1.supportedSignatureAlgorithmsCert) ||
469 len(ch.alpnProtocols) != len(ch1.alpnProtocols) {
472 for i := range ch.supportedVersions {
473 if ch.supportedVersions[i] != ch1.supportedVersions[i] {
477 for i := range ch.cipherSuites {
478 if ch.cipherSuites[i] != ch1.cipherSuites[i] {
482 for i := range ch.supportedCurves {
483 if ch.supportedCurves[i] != ch1.supportedCurves[i] {
487 for i := range ch.supportedSignatureAlgorithms {
488 if ch.supportedSignatureAlgorithms[i] != ch1.supportedSignatureAlgorithms[i] {
492 for i := range ch.supportedSignatureAlgorithmsCert {
493 if ch.supportedSignatureAlgorithmsCert[i] != ch1.supportedSignatureAlgorithmsCert[i] {
497 for i := range ch.alpnProtocols {
498 if ch.alpnProtocols[i] != ch1.alpnProtocols[i] {
502 return ch.vers != ch1.vers ||
503 !bytes.Equal(ch.random, ch1.random) ||
504 !bytes.Equal(ch.sessionId, ch1.sessionId) ||
505 !bytes.Equal(ch.compressionMethods, ch1.compressionMethods) ||
506 ch.serverName != ch1.serverName ||
507 ch.ocspStapling != ch1.ocspStapling ||
508 !bytes.Equal(ch.supportedPoints, ch1.supportedPoints) ||
509 ch.ticketSupported != ch1.ticketSupported ||
510 !bytes.Equal(ch.sessionTicket, ch1.sessionTicket) ||
511 ch.secureRenegotiationSupported != ch1.secureRenegotiationSupported ||
512 !bytes.Equal(ch.secureRenegotiation, ch1.secureRenegotiation) ||
513 ch.scts != ch1.scts ||
514 !bytes.Equal(ch.cookie, ch1.cookie) ||
515 !bytes.Equal(ch.pskModes, ch1.pskModes)
518 func (hs *serverHandshakeStateTLS13) sendServerParameters() error {
521 hs.transcript.Write(hs.clientHello.marshal())
522 hs.transcript.Write(hs.hello.marshal())
523 if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
527 if err := hs.sendDummyChangeCipherSpec(); err != nil {
531 earlySecret := hs.earlySecret
532 if earlySecret == nil {
533 earlySecret = hs.suite.extract(nil, nil)
535 hs.handshakeSecret = hs.suite.extract(hs.sharedKey,
536 hs.suite.deriveSecret(earlySecret, "derived", nil))
538 clientSecret := hs.suite.deriveSecret(hs.handshakeSecret,
539 clientHandshakeTrafficLabel, hs.transcript)
540 c.in.setTrafficSecret(hs.suite, clientSecret)
541 serverSecret := hs.suite.deriveSecret(hs.handshakeSecret,
542 serverHandshakeTrafficLabel, hs.transcript)
543 c.out.setTrafficSecret(hs.suite, serverSecret)
545 err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.clientHello.random, clientSecret)
547 c.sendAlert(alertInternalError)
550 err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.clientHello.random, serverSecret)
552 c.sendAlert(alertInternalError)
556 encryptedExtensions := new(encryptedExtensionsMsg)
558 if len(c.config.NextProtos) > 0 && len(hs.clientHello.alpnProtocols) > 0 {
559 selectedProto := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos)
560 if selectedProto == "" {
561 c.sendAlert(alertNoApplicationProtocol)
562 return fmt.Errorf("tls: client requested unsupported application protocols (%s)", hs.clientHello.alpnProtocols)
564 encryptedExtensions.alpnProtocol = selectedProto
565 c.clientProtocol = selectedProto
568 hs.transcript.Write(encryptedExtensions.marshal())
569 if _, err := c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal()); err != nil {
576 func (hs *serverHandshakeStateTLS13) requestClientCert() bool {
577 return hs.c.config.ClientAuth >= RequestClientCert && !hs.usingPSK
580 func (hs *serverHandshakeStateTLS13) sendServerCertificate() error {
583 // Only one of PSK and certificates are used at a time.
588 if hs.requestClientCert() {
589 // Request a client certificate
590 certReq := new(certificateRequestMsgTLS13)
591 certReq.ocspStapling = true
593 certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms()
594 if c.config.ClientCAs != nil {
595 certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
598 hs.transcript.Write(certReq.marshal())
599 if _, err := c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil {
604 certMsg := new(certificateMsgTLS13)
606 certMsg.certificate = *hs.cert
607 certMsg.scts = hs.clientHello.scts && len(hs.cert.SignedCertificateTimestamps) > 0
608 certMsg.ocspStapling = hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0
610 hs.transcript.Write(certMsg.marshal())
611 if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
615 certVerifyMsg := new(certificateVerifyMsg)
616 certVerifyMsg.hasSignatureAlgorithm = true
617 certVerifyMsg.signatureAlgorithm = hs.sigAlg
619 sigType, sigHash, err := typeAndHashFromSignatureScheme(hs.sigAlg)
621 return c.sendAlert(alertInternalError)
624 signed := signedMessage(sigHash, serverSignatureContext, hs.transcript)
625 signOpts := crypto.SignerOpts(sigHash)
626 if sigType == signatureRSAPSS {
627 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
629 sig, err := hs.cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts)
631 public := hs.cert.PrivateKey.(crypto.Signer).Public()
632 if rsaKey, ok := public.(*rsa.PublicKey); ok && sigType == signatureRSAPSS &&
633 rsaKey.N.BitLen()/8 < sigHash.Size()*2+2 { // key too small for RSA-PSS
634 c.sendAlert(alertHandshakeFailure)
636 c.sendAlert(alertInternalError)
638 return errors.New("tls: failed to sign handshake: " + err.Error())
640 certVerifyMsg.signature = sig
642 hs.transcript.Write(certVerifyMsg.marshal())
643 if _, err := c.writeRecord(recordTypeHandshake, certVerifyMsg.marshal()); err != nil {
650 func (hs *serverHandshakeStateTLS13) sendServerFinished() error {
653 finished := &finishedMsg{
654 verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
657 hs.transcript.Write(finished.marshal())
658 if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
662 // Derive secrets that take context through the server Finished.
664 hs.masterSecret = hs.suite.extract(nil,
665 hs.suite.deriveSecret(hs.handshakeSecret, "derived", nil))
667 hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret,
668 clientApplicationTrafficLabel, hs.transcript)
669 serverSecret := hs.suite.deriveSecret(hs.masterSecret,
670 serverApplicationTrafficLabel, hs.transcript)
671 c.out.setTrafficSecret(hs.suite, serverSecret)
673 err := c.config.writeKeyLog(keyLogLabelClientTraffic, hs.clientHello.random, hs.trafficSecret)
675 c.sendAlert(alertInternalError)
678 err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.clientHello.random, serverSecret)
680 c.sendAlert(alertInternalError)
684 c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript)
686 // If we did not request client certificates, at this point we can
687 // precompute the client finished and roll the transcript forward to send
688 // session tickets in our first flight.
689 if !hs.requestClientCert() {
690 if err := hs.sendSessionTickets(); err != nil {
698 func (hs *serverHandshakeStateTLS13) shouldSendSessionTickets() bool {
699 if hs.c.config.SessionTicketsDisabled {
703 // Don't send tickets the client wouldn't use. See RFC 8446, Section 4.2.9.
704 for _, pskMode := range hs.clientHello.pskModes {
705 if pskMode == pskModeDHE {
712 func (hs *serverHandshakeStateTLS13) sendSessionTickets() error {
715 hs.clientFinished = hs.suite.finishedHash(c.in.trafficSecret, hs.transcript)
716 finishedMsg := &finishedMsg{
717 verifyData: hs.clientFinished,
719 hs.transcript.Write(finishedMsg.marshal())
721 if !hs.shouldSendSessionTickets() {
725 resumptionSecret := hs.suite.deriveSecret(hs.masterSecret,
726 resumptionLabel, hs.transcript)
728 m := new(newSessionTicketMsgTLS13)
730 var certsFromClient [][]byte
731 for _, cert := range c.peerCertificates {
732 certsFromClient = append(certsFromClient, cert.Raw)
734 state := sessionStateTLS13{
735 cipherSuite: hs.suite.id,
736 createdAt: uint64(c.config.time().Unix()),
737 resumptionSecret: resumptionSecret,
738 certificate: Certificate{
739 Certificate: certsFromClient,
740 OCSPStaple: c.ocspResponse,
741 SignedCertificateTimestamps: c.scts,
745 m.label, err = c.encryptTicket(state.marshal())
749 m.lifetime = uint32(maxSessionTicketLifetime / time.Second)
751 if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
758 func (hs *serverHandshakeStateTLS13) readClientCertificate() error {
761 if !hs.requestClientCert() {
762 // Make sure the connection is still being verified whether or not
763 // the server requested a client certificate.
764 if c.config.VerifyConnection != nil {
765 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
766 c.sendAlert(alertBadCertificate)
773 // If we requested a client certificate, then the client must send a
774 // certificate message. If it's empty, no CertificateVerify is sent.
776 msg, err := c.readHandshake()
781 certMsg, ok := msg.(*certificateMsgTLS13)
783 c.sendAlert(alertUnexpectedMessage)
784 return unexpectedMessageError(certMsg, msg)
786 hs.transcript.Write(certMsg.marshal())
788 if err := c.processCertsFromClient(certMsg.certificate); err != nil {
792 if c.config.VerifyConnection != nil {
793 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
794 c.sendAlert(alertBadCertificate)
799 if len(certMsg.certificate.Certificate) != 0 {
800 msg, err = c.readHandshake()
805 certVerify, ok := msg.(*certificateVerifyMsg)
807 c.sendAlert(alertUnexpectedMessage)
808 return unexpectedMessageError(certVerify, msg)
811 // See RFC 8446, Section 4.4.3.
812 if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms()) {
813 c.sendAlert(alertIllegalParameter)
814 return errors.New("tls: client certificate used with invalid signature algorithm")
816 sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
818 return c.sendAlert(alertInternalError)
820 if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
821 c.sendAlert(alertIllegalParameter)
822 return errors.New("tls: client certificate used with invalid signature algorithm")
824 signed := signedMessage(sigHash, clientSignatureContext, hs.transcript)
825 if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey,
826 sigHash, signed, certVerify.signature); err != nil {
827 c.sendAlert(alertDecryptError)
828 return errors.New("tls: invalid signature by the client certificate: " + err.Error())
831 hs.transcript.Write(certVerify.marshal())
834 // If we waited until the client certificates to send session tickets, we
835 // are ready to do it now.
836 if err := hs.sendSessionTickets(); err != nil {
843 func (hs *serverHandshakeStateTLS13) readClientFinished() error {
846 msg, err := c.readHandshake()
851 finished, ok := msg.(*finishedMsg)
853 c.sendAlert(alertUnexpectedMessage)
854 return unexpectedMessageError(finished, msg)
857 if !hmac.Equal(hs.clientFinished, finished.verifyData) {
858 c.sendAlert(alertDecryptError)
859 return errors.New("tls: invalid client finished hash")
862 c.in.setTrafficSecret(hs.suite, hs.trafficSecret)