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(false) {
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 preferenceList = hs.clientHello.cipherSuites
160 supportedList = defaultCipherSuitesTLS13()
162 for _, suiteID := range preferenceList {
163 hs.suite = mutualCipherSuiteTLS13(supportedList, suiteID)
169 c.sendAlert(alertHandshakeFailure)
170 return errors.New("tls: no cipher suite supported by both client and server")
172 c.cipherSuite = hs.suite.id
173 hs.hello.cipherSuite = hs.suite.id
174 hs.transcript = hs.suite.hash.New()
176 // Pick the ECDHE group in server preference order, but give priority to
177 // groups with a key share, to avoid a HelloRetryRequest round-trip.
178 var selectedGroup CurveID
179 var clientKeyShare *keyShare
181 for _, preferredGroup := range c.config.curvePreferences() {
182 for _, ks := range hs.clientHello.keyShares {
183 if ks.group == preferredGroup {
184 selectedGroup = ks.group
189 if selectedGroup != 0 {
192 for _, group := range hs.clientHello.supportedCurves {
193 if group == preferredGroup {
194 selectedGroup = group
199 if selectedGroup == 0 {
200 c.sendAlert(alertHandshakeFailure)
201 return errors.New("tls: no ECDHE curve supported by both client and server")
203 if clientKeyShare == nil {
204 if err := hs.doHelloRetryRequest(selectedGroup); err != nil {
207 clientKeyShare = &hs.clientHello.keyShares[0]
210 if _, ok := curveForCurveID(selectedGroup); selectedGroup != X25519 && !ok {
211 c.sendAlert(alertInternalError)
212 return errors.New("tls: CurvePreferences includes unsupported curve")
214 params, err := generateECDHEParameters(c.config.rand(), selectedGroup)
216 c.sendAlert(alertInternalError)
219 hs.hello.serverShare = keyShare{group: selectedGroup, data: params.PublicKey()}
220 hs.sharedKey = params.SharedKey(clientKeyShare.data)
221 if hs.sharedKey == nil {
222 c.sendAlert(alertIllegalParameter)
223 return errors.New("tls: invalid client key share")
226 c.serverName = hs.clientHello.serverName
230 func (hs *serverHandshakeStateTLS13) checkForResumption() error {
233 if c.config.SessionTicketsDisabled {
238 for _, mode := range hs.clientHello.pskModes {
239 if mode == pskModeDHE {
248 if len(hs.clientHello.pskIdentities) != len(hs.clientHello.pskBinders) {
249 c.sendAlert(alertIllegalParameter)
250 return errors.New("tls: invalid or missing PSK binders")
252 if len(hs.clientHello.pskIdentities) == 0 {
256 for i, identity := range hs.clientHello.pskIdentities {
257 if i >= maxClientPSKIdentities {
261 plaintext, _ := c.decryptTicket(identity.label)
262 if plaintext == nil {
265 sessionState := new(sessionStateTLS13)
266 if ok := sessionState.unmarshal(plaintext); !ok {
270 createdAt := time.Unix(int64(sessionState.createdAt), 0)
271 if c.config.time().Sub(createdAt) > maxSessionTicketLifetime {
275 // We don't check the obfuscated ticket age because it's affected by
276 // clock skew and it's only a freshness signal useful for shrinking the
277 // window for replay attacks, which don't affect us as we don't do 0-RTT.
279 pskSuite := cipherSuiteTLS13ByID(sessionState.cipherSuite)
280 if pskSuite == nil || pskSuite.hash != hs.suite.hash {
284 // PSK connections don't re-establish client certificates, but carry
285 // them over in the session ticket. Ensure the presence of client certs
286 // in the ticket is consistent with the configured requirements.
287 sessionHasClientCerts := len(sessionState.certificate.Certificate) != 0
288 needClientCerts := requiresClientCert(c.config.ClientAuth)
289 if needClientCerts && !sessionHasClientCerts {
292 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
296 psk := hs.suite.expandLabel(sessionState.resumptionSecret, "resumption",
297 nil, hs.suite.hash.Size())
298 hs.earlySecret = hs.suite.extract(psk, nil)
299 binderKey := hs.suite.deriveSecret(hs.earlySecret, resumptionBinderLabel, nil)
300 // Clone the transcript in case a HelloRetryRequest was recorded.
301 transcript := cloneHash(hs.transcript, hs.suite.hash)
302 if transcript == nil {
303 c.sendAlert(alertInternalError)
304 return errors.New("tls: internal error: failed to clone hash")
306 transcript.Write(hs.clientHello.marshalWithoutBinders())
307 pskBinder := hs.suite.finishedHash(binderKey, transcript)
308 if !hmac.Equal(hs.clientHello.pskBinders[i], pskBinder) {
309 c.sendAlert(alertDecryptError)
310 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)
327 // cloneHash uses the encoding.BinaryMarshaler and encoding.BinaryUnmarshaler
328 // interfaces implemented by standard library hashes to clone the state of in
329 // to a new instance of h. It returns nil if the operation fails.
330 func cloneHash(in hash.Hash, h crypto.Hash) hash.Hash {
331 // Recreate the interface to avoid importing encoding.
332 type binaryMarshaler interface {
333 MarshalBinary() (data []byte, err error)
334 UnmarshalBinary(data []byte) error
336 marshaler, ok := in.(binaryMarshaler)
340 state, err := marshaler.MarshalBinary()
345 unmarshaler, ok := out.(binaryMarshaler)
349 if err := unmarshaler.UnmarshalBinary(state); err != nil {
355 func (hs *serverHandshakeStateTLS13) pickCertificate() error {
358 // Only one of PSK and certificates are used at a time.
363 // This implements a very simplistic certificate selection strategy for now:
364 // getCertificate delegates to the application Config.GetCertificate, or
365 // selects based on the server_name only. If the selected certificate's
366 // public key does not match the client signature_algorithms, the handshake
367 // is aborted. No attention is given to signature_algorithms_cert, and it is
368 // not passed to the application Config.GetCertificate. This will need to
369 // improve according to RFC 8446, sections 4.4.2.2 and 4.2.3.
370 certificate, err := c.config.getCertificate(clientHelloInfo(c, hs.clientHello))
372 c.sendAlert(alertInternalError)
375 supportedAlgs := signatureSchemesForCertificate(c.vers, certificate)
376 if supportedAlgs == nil {
377 c.sendAlert(alertInternalError)
378 return unsupportedCertificateError(certificate)
380 // Pick signature scheme in client preference order, as the server
381 // preference order is not configurable.
382 for _, preferredAlg := range hs.clientHello.supportedSignatureAlgorithms {
383 if isSupportedSignatureAlgorithm(preferredAlg, supportedAlgs) {
384 hs.sigAlg = preferredAlg
389 // getCertificate returned a certificate incompatible with the
390 // ClientHello supported signature algorithms.
391 c.sendAlert(alertHandshakeFailure)
392 return errors.New("tls: client doesn't support selected certificate")
394 hs.cert = certificate
399 // sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility
400 // with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4.
401 func (hs *serverHandshakeStateTLS13) sendDummyChangeCipherSpec() error {
405 hs.sentDummyCCS = true
407 _, err := hs.c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
411 func (hs *serverHandshakeStateTLS13) doHelloRetryRequest(selectedGroup CurveID) error {
414 // The first ClientHello gets double-hashed into the transcript upon a
415 // HelloRetryRequest. See RFC 8446, Section 4.4.1.
416 hs.transcript.Write(hs.clientHello.marshal())
417 chHash := hs.transcript.Sum(nil)
418 hs.transcript.Reset()
419 hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
420 hs.transcript.Write(chHash)
422 helloRetryRequest := &serverHelloMsg{
424 random: helloRetryRequestRandom,
425 sessionId: hs.hello.sessionId,
426 cipherSuite: hs.hello.cipherSuite,
427 compressionMethod: hs.hello.compressionMethod,
428 supportedVersion: hs.hello.supportedVersion,
429 selectedGroup: selectedGroup,
432 hs.transcript.Write(helloRetryRequest.marshal())
433 if _, err := c.writeRecord(recordTypeHandshake, helloRetryRequest.marshal()); err != nil {
437 if err := hs.sendDummyChangeCipherSpec(); err != nil {
441 msg, err := c.readHandshake()
446 clientHello, ok := msg.(*clientHelloMsg)
448 c.sendAlert(alertUnexpectedMessage)
449 return unexpectedMessageError(clientHello, msg)
452 if len(clientHello.keyShares) != 1 || clientHello.keyShares[0].group != selectedGroup {
453 c.sendAlert(alertIllegalParameter)
454 return errors.New("tls: client sent invalid key share in second ClientHello")
457 if clientHello.earlyData {
458 c.sendAlert(alertIllegalParameter)
459 return errors.New("tls: client indicated early data in second ClientHello")
462 if illegalClientHelloChange(clientHello, hs.clientHello) {
463 c.sendAlert(alertIllegalParameter)
464 return errors.New("tls: client illegally modified second ClientHello")
467 hs.clientHello = clientHello
471 // illegalClientHelloChange reports whether the two ClientHello messages are
472 // different, with the exception of the changes allowed before and after a
473 // HelloRetryRequest. See RFC 8446, Section 4.1.2.
474 func illegalClientHelloChange(ch, ch1 *clientHelloMsg) bool {
475 if len(ch.supportedVersions) != len(ch1.supportedVersions) ||
476 len(ch.cipherSuites) != len(ch1.cipherSuites) ||
477 len(ch.supportedCurves) != len(ch1.supportedCurves) ||
478 len(ch.supportedSignatureAlgorithms) != len(ch1.supportedSignatureAlgorithms) ||
479 len(ch.supportedSignatureAlgorithmsCert) != len(ch1.supportedSignatureAlgorithmsCert) ||
480 len(ch.alpnProtocols) != len(ch1.alpnProtocols) {
483 for i := range ch.supportedVersions {
484 if ch.supportedVersions[i] != ch1.supportedVersions[i] {
488 for i := range ch.cipherSuites {
489 if ch.cipherSuites[i] != ch1.cipherSuites[i] {
493 for i := range ch.supportedCurves {
494 if ch.supportedCurves[i] != ch1.supportedCurves[i] {
498 for i := range ch.supportedSignatureAlgorithms {
499 if ch.supportedSignatureAlgorithms[i] != ch1.supportedSignatureAlgorithms[i] {
503 for i := range ch.supportedSignatureAlgorithmsCert {
504 if ch.supportedSignatureAlgorithmsCert[i] != ch1.supportedSignatureAlgorithmsCert[i] {
508 for i := range ch.alpnProtocols {
509 if ch.alpnProtocols[i] != ch1.alpnProtocols[i] {
513 return ch.vers != ch1.vers ||
514 !bytes.Equal(ch.random, ch1.random) ||
515 !bytes.Equal(ch.sessionId, ch1.sessionId) ||
516 !bytes.Equal(ch.compressionMethods, ch1.compressionMethods) ||
517 ch.nextProtoNeg != ch1.nextProtoNeg ||
518 ch.serverName != ch1.serverName ||
519 ch.ocspStapling != ch1.ocspStapling ||
520 !bytes.Equal(ch.supportedPoints, ch1.supportedPoints) ||
521 ch.ticketSupported != ch1.ticketSupported ||
522 !bytes.Equal(ch.sessionTicket, ch1.sessionTicket) ||
523 ch.secureRenegotiationSupported != ch1.secureRenegotiationSupported ||
524 !bytes.Equal(ch.secureRenegotiation, ch1.secureRenegotiation) ||
525 ch.scts != ch1.scts ||
526 !bytes.Equal(ch.cookie, ch1.cookie) ||
527 !bytes.Equal(ch.pskModes, ch1.pskModes)
530 func (hs *serverHandshakeStateTLS13) sendServerParameters() error {
533 hs.transcript.Write(hs.clientHello.marshal())
534 hs.transcript.Write(hs.hello.marshal())
535 if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
539 if err := hs.sendDummyChangeCipherSpec(); err != nil {
543 earlySecret := hs.earlySecret
544 if earlySecret == nil {
545 earlySecret = hs.suite.extract(nil, nil)
547 hs.handshakeSecret = hs.suite.extract(hs.sharedKey,
548 hs.suite.deriveSecret(earlySecret, "derived", nil))
550 clientSecret := hs.suite.deriveSecret(hs.handshakeSecret,
551 clientHandshakeTrafficLabel, hs.transcript)
552 c.in.setTrafficSecret(hs.suite, clientSecret)
553 serverSecret := hs.suite.deriveSecret(hs.handshakeSecret,
554 serverHandshakeTrafficLabel, hs.transcript)
555 c.out.setTrafficSecret(hs.suite, serverSecret)
557 err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.clientHello.random, clientSecret)
559 c.sendAlert(alertInternalError)
562 err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.clientHello.random, serverSecret)
564 c.sendAlert(alertInternalError)
568 encryptedExtensions := new(encryptedExtensionsMsg)
570 if len(hs.clientHello.alpnProtocols) > 0 {
571 if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
572 encryptedExtensions.alpnProtocol = selectedProto
573 c.clientProtocol = selectedProto
577 hs.transcript.Write(encryptedExtensions.marshal())
578 if _, err := c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal()); err != nil {
585 func (hs *serverHandshakeStateTLS13) requestClientCert() bool {
586 return hs.c.config.ClientAuth >= RequestClientCert && !hs.usingPSK
589 func (hs *serverHandshakeStateTLS13) sendServerCertificate() error {
592 // Only one of PSK and certificates are used at a time.
597 if hs.requestClientCert() {
598 // Request a client certificate
599 certReq := new(certificateRequestMsgTLS13)
600 certReq.ocspStapling = true
602 certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms()
603 if c.config.ClientCAs != nil {
604 certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
607 hs.transcript.Write(certReq.marshal())
608 if _, err := c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil {
613 certMsg := new(certificateMsgTLS13)
615 certMsg.certificate = *hs.cert
616 certMsg.scts = hs.clientHello.scts && len(hs.cert.SignedCertificateTimestamps) > 0
617 certMsg.ocspStapling = hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0
619 hs.transcript.Write(certMsg.marshal())
620 if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
624 certVerifyMsg := new(certificateVerifyMsg)
625 certVerifyMsg.hasSignatureAlgorithm = true
626 certVerifyMsg.signatureAlgorithm = hs.sigAlg
628 sigType := signatureFromSignatureScheme(hs.sigAlg)
629 sigHash, err := hashFromSignatureScheme(hs.sigAlg)
630 if sigType == 0 || err != nil {
631 return c.sendAlert(alertInternalError)
634 writeSignedMessage(h, serverSignatureContext, hs.transcript)
636 signOpts := crypto.SignerOpts(sigHash)
637 if sigType == signatureRSAPSS {
638 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
640 sig, err := hs.cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), h.Sum(nil), signOpts)
642 public := hs.cert.PrivateKey.(crypto.Signer).Public()
643 if rsaKey, ok := public.(*rsa.PublicKey); ok && sigType == signatureRSAPSS &&
644 rsaKey.N.BitLen()/8 < sigHash.Size()*2+2 { // key too small for RSA-PSS
645 c.sendAlert(alertHandshakeFailure)
647 c.sendAlert(alertInternalError)
649 return errors.New("tls: failed to sign handshake: " + err.Error())
651 certVerifyMsg.signature = sig
653 hs.transcript.Write(certVerifyMsg.marshal())
654 if _, err := c.writeRecord(recordTypeHandshake, certVerifyMsg.marshal()); err != nil {
661 func (hs *serverHandshakeStateTLS13) sendServerFinished() error {
664 finished := &finishedMsg{
665 verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
668 hs.transcript.Write(finished.marshal())
669 if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
673 // Derive secrets that take context through the server Finished.
675 hs.masterSecret = hs.suite.extract(nil,
676 hs.suite.deriveSecret(hs.handshakeSecret, "derived", nil))
678 hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret,
679 clientApplicationTrafficLabel, hs.transcript)
680 serverSecret := hs.suite.deriveSecret(hs.masterSecret,
681 serverApplicationTrafficLabel, hs.transcript)
682 c.out.setTrafficSecret(hs.suite, serverSecret)
684 err := c.config.writeKeyLog(keyLogLabelClientTraffic, hs.clientHello.random, hs.trafficSecret)
686 c.sendAlert(alertInternalError)
689 err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.clientHello.random, serverSecret)
691 c.sendAlert(alertInternalError)
695 c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript)
697 // If we did not request client certificates, at this point we can
698 // precompute the client finished and roll the transcript forward to send
699 // session tickets in our first flight.
700 if !hs.requestClientCert() {
701 if err := hs.sendSessionTickets(); err != nil {
709 func (hs *serverHandshakeStateTLS13) shouldSendSessionTickets() bool {
710 if hs.c.config.SessionTicketsDisabled {
714 // Don't send tickets the client wouldn't use. See RFC 8446, Section 4.2.9.
715 for _, pskMode := range hs.clientHello.pskModes {
716 if pskMode == pskModeDHE {
723 func (hs *serverHandshakeStateTLS13) sendSessionTickets() error {
726 hs.clientFinished = hs.suite.finishedHash(c.in.trafficSecret, hs.transcript)
727 finishedMsg := &finishedMsg{
728 verifyData: hs.clientFinished,
730 hs.transcript.Write(finishedMsg.marshal())
732 if !hs.shouldSendSessionTickets() {
736 resumptionSecret := hs.suite.deriveSecret(hs.masterSecret,
737 resumptionLabel, hs.transcript)
739 m := new(newSessionTicketMsgTLS13)
741 var certsFromClient [][]byte
742 for _, cert := range c.peerCertificates {
743 certsFromClient = append(certsFromClient, cert.Raw)
745 state := sessionStateTLS13{
746 cipherSuite: hs.suite.id,
747 createdAt: uint64(c.config.time().Unix()),
748 resumptionSecret: resumptionSecret,
749 certificate: Certificate{
750 Certificate: certsFromClient,
751 OCSPStaple: c.ocspResponse,
752 SignedCertificateTimestamps: c.scts,
756 m.label, err = c.encryptTicket(state.marshal())
760 m.lifetime = uint32(maxSessionTicketLifetime / time.Second)
762 if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
769 func (hs *serverHandshakeStateTLS13) readClientCertificate() error {
772 if !hs.requestClientCert() {
776 // If we requested a client certificate, then the client must send a
777 // certificate message. If it's empty, no CertificateVerify is sent.
779 msg, err := c.readHandshake()
784 certMsg, ok := msg.(*certificateMsgTLS13)
786 c.sendAlert(alertUnexpectedMessage)
787 return unexpectedMessageError(certMsg, msg)
789 hs.transcript.Write(certMsg.marshal())
791 if err := c.processCertsFromClient(certMsg.certificate); err != nil {
795 if len(certMsg.certificate.Certificate) != 0 {
796 msg, err = c.readHandshake()
801 certVerify, ok := msg.(*certificateVerifyMsg)
803 c.sendAlert(alertUnexpectedMessage)
804 return unexpectedMessageError(certVerify, msg)
807 // See RFC 8446, Section 4.4.3.
808 if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms()) {
809 c.sendAlert(alertIllegalParameter)
810 return errors.New("tls: invalid certificate signature algorithm")
812 sigType := signatureFromSignatureScheme(certVerify.signatureAlgorithm)
813 sigHash, err := hashFromSignatureScheme(certVerify.signatureAlgorithm)
814 if sigType == 0 || err != nil {
815 c.sendAlert(alertInternalError)
818 if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
819 c.sendAlert(alertIllegalParameter)
820 return errors.New("tls: invalid certificate signature algorithm")
823 writeSignedMessage(h, clientSignatureContext, hs.transcript)
824 if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey,
825 sigHash, h.Sum(nil), certVerify.signature); err != nil {
826 c.sendAlert(alertDecryptError)
827 return errors.New("tls: invalid certificate signature")
830 hs.transcript.Write(certVerify.marshal())
833 // If we waited until the client certificates to send session tickets, we
834 // are ready to do it now.
835 if err := hs.sendSessionTickets(); err != nil {
842 func (hs *serverHandshakeStateTLS13) readClientFinished() error {
845 msg, err := c.readHandshake()
850 finished, ok := msg.(*finishedMsg)
852 c.sendAlert(alertUnexpectedMessage)
853 return unexpectedMessageError(finished, msg)
856 if !hmac.Equal(hs.clientFinished, finished.verifyData) {
857 c.sendAlert(alertDecryptError)
858 return errors.New("tls: invalid client finished hash")
861 c.in.setTrafficSecret(hs.suite, hs.trafficSecret)