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 {
28 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 c.isHandshakeComplete.Store(true)
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(roleServer) {
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 && c.quic != nil {
144 if len(hs.clientHello.pskIdentities) == 0 {
145 c.sendAlert(alertIllegalParameter)
146 return errors.New("tls: early_data without pre_shared_key")
148 } else if hs.clientHello.earlyData {
149 // See RFC 8446, Section 4.2.10 for the complicated behavior required
150 // here. The scenario is that a different server at our address offered
151 // to accept early data in the past, which we can't handle. For now, all
152 // 0-RTT enabled session tickets need to expire before a Go server can
153 // replace a server or join a pool. That's the same requirement that
154 // applies to mixing or replacing with any TLS 1.2 server.
155 c.sendAlert(alertUnsupportedExtension)
156 return errors.New("tls: client sent unexpected early data")
159 hs.hello.sessionId = hs.clientHello.sessionId
160 hs.hello.compressionMethod = compressionNone
162 preferenceList := defaultCipherSuitesTLS13
163 if !hasAESGCMHardwareSupport || !aesgcmPreferred(hs.clientHello.cipherSuites) {
164 preferenceList = defaultCipherSuitesTLS13NoAES
166 for _, suiteID := range preferenceList {
167 hs.suite = mutualCipherSuiteTLS13(hs.clientHello.cipherSuites, suiteID)
173 c.sendAlert(alertHandshakeFailure)
174 return errors.New("tls: no cipher suite supported by both client and server")
176 c.cipherSuite = hs.suite.id
177 hs.hello.cipherSuite = hs.suite.id
178 hs.transcript = hs.suite.hash.New()
180 // Pick the ECDHE group in server preference order, but give priority to
181 // groups with a key share, to avoid a HelloRetryRequest round-trip.
182 var selectedGroup CurveID
183 var clientKeyShare *keyShare
185 for _, preferredGroup := range c.config.curvePreferences() {
186 for _, ks := range hs.clientHello.keyShares {
187 if ks.group == preferredGroup {
188 selectedGroup = ks.group
193 if selectedGroup != 0 {
196 for _, group := range hs.clientHello.supportedCurves {
197 if group == preferredGroup {
198 selectedGroup = group
203 if selectedGroup == 0 {
204 c.sendAlert(alertHandshakeFailure)
205 return errors.New("tls: no ECDHE curve supported by both client and server")
207 if clientKeyShare == nil {
208 if err := hs.doHelloRetryRequest(selectedGroup); err != nil {
211 clientKeyShare = &hs.clientHello.keyShares[0]
214 if _, ok := curveForCurveID(selectedGroup); !ok {
215 c.sendAlert(alertInternalError)
216 return errors.New("tls: CurvePreferences includes unsupported curve")
218 key, err := generateECDHEKey(c.config.rand(), selectedGroup)
220 c.sendAlert(alertInternalError)
223 hs.hello.serverShare = keyShare{group: selectedGroup, data: key.PublicKey().Bytes()}
224 peerKey, err := key.Curve().NewPublicKey(clientKeyShare.data)
226 c.sendAlert(alertIllegalParameter)
227 return errors.New("tls: invalid client key share")
229 hs.sharedKey, err = key.ECDH(peerKey)
231 c.sendAlert(alertIllegalParameter)
232 return errors.New("tls: invalid client key share")
235 selectedProto, err := negotiateALPN(c.config.NextProtos, hs.clientHello.alpnProtocols, c.quic != nil)
237 c.sendAlert(alertNoApplicationProtocol)
240 c.clientProtocol = selectedProto
243 if hs.clientHello.quicTransportParameters == nil {
244 // RFC 9001 Section 8.2.
245 c.sendAlert(alertMissingExtension)
246 return errors.New("tls: client did not send a quic_transport_parameters extension")
248 c.quicSetTransportParameters(hs.clientHello.quicTransportParameters)
250 if hs.clientHello.quicTransportParameters != nil {
251 c.sendAlert(alertUnsupportedExtension)
252 return errors.New("tls: client sent an unexpected quic_transport_parameters extension")
256 c.serverName = hs.clientHello.serverName
260 func (hs *serverHandshakeStateTLS13) checkForResumption() error {
263 if c.config.SessionTicketsDisabled {
268 for _, mode := range hs.clientHello.pskModes {
269 if mode == pskModeDHE {
278 if len(hs.clientHello.pskIdentities) != len(hs.clientHello.pskBinders) {
279 c.sendAlert(alertIllegalParameter)
280 return errors.New("tls: invalid or missing PSK binders")
282 if len(hs.clientHello.pskIdentities) == 0 {
286 for i, identity := range hs.clientHello.pskIdentities {
287 if i >= maxClientPSKIdentities {
291 var sessionState *SessionState
292 if c.config.UnwrapSession != nil {
294 sessionState, err = c.config.UnwrapSession(identity.label, c.connectionStateLocked())
298 if sessionState == nil {
302 plaintext := c.config.decryptTicket(identity.label, c.ticketKeys)
303 if plaintext == nil {
307 sessionState, err = ParseSessionState(plaintext)
313 if sessionState.version != VersionTLS13 {
317 createdAt := time.Unix(int64(sessionState.createdAt), 0)
318 if c.config.time().Sub(createdAt) > maxSessionTicketLifetime {
322 pskSuite := cipherSuiteTLS13ByID(sessionState.cipherSuite)
323 if pskSuite == nil || pskSuite.hash != hs.suite.hash {
327 // PSK connections don't re-establish client certificates, but carry
328 // them over in the session ticket. Ensure the presence of client certs
329 // in the ticket is consistent with the configured requirements.
330 sessionHasClientCerts := len(sessionState.peerCertificates) != 0
331 needClientCerts := requiresClientCert(c.config.ClientAuth)
332 if needClientCerts && !sessionHasClientCerts {
335 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
339 hs.earlySecret = hs.suite.extract(sessionState.secret, nil)
340 binderKey := hs.suite.deriveSecret(hs.earlySecret, resumptionBinderLabel, nil)
341 // Clone the transcript in case a HelloRetryRequest was recorded.
342 transcript := cloneHash(hs.transcript, hs.suite.hash)
343 if transcript == nil {
344 c.sendAlert(alertInternalError)
345 return errors.New("tls: internal error: failed to clone hash")
347 clientHelloBytes, err := hs.clientHello.marshalWithoutBinders()
349 c.sendAlert(alertInternalError)
352 transcript.Write(clientHelloBytes)
353 pskBinder := hs.suite.finishedHash(binderKey, transcript)
354 if !hmac.Equal(hs.clientHello.pskBinders[i], pskBinder) {
355 c.sendAlert(alertDecryptError)
356 return errors.New("tls: invalid PSK binder")
359 if c.quic != nil && hs.clientHello.earlyData && i == 0 &&
360 sessionState.EarlyData && sessionState.cipherSuite == hs.suite.id &&
361 sessionState.alpnProtocol == c.clientProtocol {
364 transcript := hs.suite.hash.New()
365 if err := transcriptMsg(hs.clientHello, transcript); err != nil {
368 earlyTrafficSecret := hs.suite.deriveSecret(hs.earlySecret, clientEarlyTrafficLabel, transcript)
369 c.quicSetReadSecret(QUICEncryptionLevelEarly, hs.suite.id, earlyTrafficSecret)
373 if err := c.processCertsFromClient(sessionState.certificate()); err != nil {
377 hs.hello.selectedIdentityPresent = true
378 hs.hello.selectedIdentity = uint16(i)
386 // cloneHash uses the encoding.BinaryMarshaler and encoding.BinaryUnmarshaler
387 // interfaces implemented by standard library hashes to clone the state of in
388 // to a new instance of h. It returns nil if the operation fails.
389 func cloneHash(in hash.Hash, h crypto.Hash) hash.Hash {
390 // Recreate the interface to avoid importing encoding.
391 type binaryMarshaler interface {
392 MarshalBinary() (data []byte, err error)
393 UnmarshalBinary(data []byte) error
395 marshaler, ok := in.(binaryMarshaler)
399 state, err := marshaler.MarshalBinary()
404 unmarshaler, ok := out.(binaryMarshaler)
408 if err := unmarshaler.UnmarshalBinary(state); err != nil {
414 func (hs *serverHandshakeStateTLS13) pickCertificate() error {
417 // Only one of PSK and certificates are used at a time.
422 // signature_algorithms is required in TLS 1.3. See RFC 8446, Section 4.2.3.
423 if len(hs.clientHello.supportedSignatureAlgorithms) == 0 {
424 return c.sendAlert(alertMissingExtension)
427 certificate, err := c.config.getCertificate(clientHelloInfo(hs.ctx, c, hs.clientHello))
429 if err == errNoCertificates {
430 c.sendAlert(alertUnrecognizedName)
432 c.sendAlert(alertInternalError)
436 hs.sigAlg, err = selectSignatureScheme(c.vers, certificate, hs.clientHello.supportedSignatureAlgorithms)
438 // getCertificate returned a certificate that is unsupported or
439 // incompatible with the client's signature algorithms.
440 c.sendAlert(alertHandshakeFailure)
443 hs.cert = certificate
448 // sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility
449 // with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4.
450 func (hs *serverHandshakeStateTLS13) sendDummyChangeCipherSpec() error {
451 if hs.c.quic != nil {
457 hs.sentDummyCCS = true
459 return hs.c.writeChangeCipherRecord()
462 func (hs *serverHandshakeStateTLS13) doHelloRetryRequest(selectedGroup CurveID) error {
465 // The first ClientHello gets double-hashed into the transcript upon a
466 // HelloRetryRequest. See RFC 8446, Section 4.4.1.
467 if err := transcriptMsg(hs.clientHello, hs.transcript); err != nil {
470 chHash := hs.transcript.Sum(nil)
471 hs.transcript.Reset()
472 hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
473 hs.transcript.Write(chHash)
475 helloRetryRequest := &serverHelloMsg{
477 random: helloRetryRequestRandom,
478 sessionId: hs.hello.sessionId,
479 cipherSuite: hs.hello.cipherSuite,
480 compressionMethod: hs.hello.compressionMethod,
481 supportedVersion: hs.hello.supportedVersion,
482 selectedGroup: selectedGroup,
485 if _, err := hs.c.writeHandshakeRecord(helloRetryRequest, hs.transcript); err != nil {
489 if err := hs.sendDummyChangeCipherSpec(); err != nil {
493 // clientHelloMsg is not included in the transcript.
494 msg, err := c.readHandshake(nil)
499 clientHello, ok := msg.(*clientHelloMsg)
501 c.sendAlert(alertUnexpectedMessage)
502 return unexpectedMessageError(clientHello, msg)
505 if len(clientHello.keyShares) != 1 || clientHello.keyShares[0].group != selectedGroup {
506 c.sendAlert(alertIllegalParameter)
507 return errors.New("tls: client sent invalid key share in second ClientHello")
510 if clientHello.earlyData {
511 c.sendAlert(alertIllegalParameter)
512 return errors.New("tls: client indicated early data in second ClientHello")
515 if illegalClientHelloChange(clientHello, hs.clientHello) {
516 c.sendAlert(alertIllegalParameter)
517 return errors.New("tls: client illegally modified second ClientHello")
520 hs.clientHello = clientHello
524 // illegalClientHelloChange reports whether the two ClientHello messages are
525 // different, with the exception of the changes allowed before and after a
526 // HelloRetryRequest. See RFC 8446, Section 4.1.2.
527 func illegalClientHelloChange(ch, ch1 *clientHelloMsg) bool {
528 if len(ch.supportedVersions) != len(ch1.supportedVersions) ||
529 len(ch.cipherSuites) != len(ch1.cipherSuites) ||
530 len(ch.supportedCurves) != len(ch1.supportedCurves) ||
531 len(ch.supportedSignatureAlgorithms) != len(ch1.supportedSignatureAlgorithms) ||
532 len(ch.supportedSignatureAlgorithmsCert) != len(ch1.supportedSignatureAlgorithmsCert) ||
533 len(ch.alpnProtocols) != len(ch1.alpnProtocols) {
536 for i := range ch.supportedVersions {
537 if ch.supportedVersions[i] != ch1.supportedVersions[i] {
541 for i := range ch.cipherSuites {
542 if ch.cipherSuites[i] != ch1.cipherSuites[i] {
546 for i := range ch.supportedCurves {
547 if ch.supportedCurves[i] != ch1.supportedCurves[i] {
551 for i := range ch.supportedSignatureAlgorithms {
552 if ch.supportedSignatureAlgorithms[i] != ch1.supportedSignatureAlgorithms[i] {
556 for i := range ch.supportedSignatureAlgorithmsCert {
557 if ch.supportedSignatureAlgorithmsCert[i] != ch1.supportedSignatureAlgorithmsCert[i] {
561 for i := range ch.alpnProtocols {
562 if ch.alpnProtocols[i] != ch1.alpnProtocols[i] {
566 return ch.vers != ch1.vers ||
567 !bytes.Equal(ch.random, ch1.random) ||
568 !bytes.Equal(ch.sessionId, ch1.sessionId) ||
569 !bytes.Equal(ch.compressionMethods, ch1.compressionMethods) ||
570 ch.serverName != ch1.serverName ||
571 ch.ocspStapling != ch1.ocspStapling ||
572 !bytes.Equal(ch.supportedPoints, ch1.supportedPoints) ||
573 ch.ticketSupported != ch1.ticketSupported ||
574 !bytes.Equal(ch.sessionTicket, ch1.sessionTicket) ||
575 ch.secureRenegotiationSupported != ch1.secureRenegotiationSupported ||
576 !bytes.Equal(ch.secureRenegotiation, ch1.secureRenegotiation) ||
577 ch.scts != ch1.scts ||
578 !bytes.Equal(ch.cookie, ch1.cookie) ||
579 !bytes.Equal(ch.pskModes, ch1.pskModes)
582 func (hs *serverHandshakeStateTLS13) sendServerParameters() error {
585 if err := transcriptMsg(hs.clientHello, hs.transcript); err != nil {
588 if _, err := hs.c.writeHandshakeRecord(hs.hello, hs.transcript); err != nil {
592 if err := hs.sendDummyChangeCipherSpec(); err != nil {
596 earlySecret := hs.earlySecret
597 if earlySecret == nil {
598 earlySecret = hs.suite.extract(nil, nil)
600 hs.handshakeSecret = hs.suite.extract(hs.sharedKey,
601 hs.suite.deriveSecret(earlySecret, "derived", nil))
603 clientSecret := hs.suite.deriveSecret(hs.handshakeSecret,
604 clientHandshakeTrafficLabel, hs.transcript)
605 c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, clientSecret)
606 serverSecret := hs.suite.deriveSecret(hs.handshakeSecret,
607 serverHandshakeTrafficLabel, hs.transcript)
608 c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, serverSecret)
611 if c.hand.Len() != 0 {
612 c.sendAlert(alertUnexpectedMessage)
614 c.quicSetWriteSecret(QUICEncryptionLevelHandshake, hs.suite.id, serverSecret)
615 c.quicSetReadSecret(QUICEncryptionLevelHandshake, hs.suite.id, clientSecret)
618 err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.clientHello.random, clientSecret)
620 c.sendAlert(alertInternalError)
623 err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.clientHello.random, serverSecret)
625 c.sendAlert(alertInternalError)
629 encryptedExtensions := new(encryptedExtensionsMsg)
630 encryptedExtensions.alpnProtocol = c.clientProtocol
633 p, err := c.quicGetTransportParameters()
637 encryptedExtensions.quicTransportParameters = p
638 encryptedExtensions.earlyData = hs.earlyData
641 if _, err := hs.c.writeHandshakeRecord(encryptedExtensions, hs.transcript); err != nil {
648 func (hs *serverHandshakeStateTLS13) requestClientCert() bool {
649 return hs.c.config.ClientAuth >= RequestClientCert && !hs.usingPSK
652 func (hs *serverHandshakeStateTLS13) sendServerCertificate() error {
655 // Only one of PSK and certificates are used at a time.
660 if hs.requestClientCert() {
661 // Request a client certificate
662 certReq := new(certificateRequestMsgTLS13)
663 certReq.ocspStapling = true
665 certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms()
666 if c.config.ClientCAs != nil {
667 certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
670 if _, err := hs.c.writeHandshakeRecord(certReq, hs.transcript); err != nil {
675 certMsg := new(certificateMsgTLS13)
677 certMsg.certificate = *hs.cert
678 certMsg.scts = hs.clientHello.scts && len(hs.cert.SignedCertificateTimestamps) > 0
679 certMsg.ocspStapling = hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0
681 if _, err := hs.c.writeHandshakeRecord(certMsg, hs.transcript); err != nil {
685 certVerifyMsg := new(certificateVerifyMsg)
686 certVerifyMsg.hasSignatureAlgorithm = true
687 certVerifyMsg.signatureAlgorithm = hs.sigAlg
689 sigType, sigHash, err := typeAndHashFromSignatureScheme(hs.sigAlg)
691 return c.sendAlert(alertInternalError)
694 signed := signedMessage(sigHash, serverSignatureContext, hs.transcript)
695 signOpts := crypto.SignerOpts(sigHash)
696 if sigType == signatureRSAPSS {
697 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
699 sig, err := hs.cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts)
701 public := hs.cert.PrivateKey.(crypto.Signer).Public()
702 if rsaKey, ok := public.(*rsa.PublicKey); ok && sigType == signatureRSAPSS &&
703 rsaKey.N.BitLen()/8 < sigHash.Size()*2+2 { // key too small for RSA-PSS
704 c.sendAlert(alertHandshakeFailure)
706 c.sendAlert(alertInternalError)
708 return errors.New("tls: failed to sign handshake: " + err.Error())
710 certVerifyMsg.signature = sig
712 if _, err := hs.c.writeHandshakeRecord(certVerifyMsg, hs.transcript); err != nil {
719 func (hs *serverHandshakeStateTLS13) sendServerFinished() error {
722 finished := &finishedMsg{
723 verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
726 if _, err := hs.c.writeHandshakeRecord(finished, hs.transcript); err != nil {
730 // Derive secrets that take context through the server Finished.
732 hs.masterSecret = hs.suite.extract(nil,
733 hs.suite.deriveSecret(hs.handshakeSecret, "derived", nil))
735 hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret,
736 clientApplicationTrafficLabel, hs.transcript)
737 serverSecret := hs.suite.deriveSecret(hs.masterSecret,
738 serverApplicationTrafficLabel, hs.transcript)
739 c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, serverSecret)
742 if c.hand.Len() != 0 {
743 // TODO: Handle this in setTrafficSecret?
744 c.sendAlert(alertUnexpectedMessage)
746 c.quicSetWriteSecret(QUICEncryptionLevelApplication, hs.suite.id, serverSecret)
749 err := c.config.writeKeyLog(keyLogLabelClientTraffic, hs.clientHello.random, hs.trafficSecret)
751 c.sendAlert(alertInternalError)
754 err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.clientHello.random, serverSecret)
756 c.sendAlert(alertInternalError)
760 c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript)
762 // If we did not request client certificates, at this point we can
763 // precompute the client finished and roll the transcript forward to send
764 // session tickets in our first flight.
765 if !hs.requestClientCert() {
766 if err := hs.sendSessionTickets(); err != nil {
774 func (hs *serverHandshakeStateTLS13) shouldSendSessionTickets() bool {
775 if hs.c.config.SessionTicketsDisabled {
779 // QUIC tickets are sent by QUICConn.SendSessionTicket, not automatically.
780 if hs.c.quic != nil {
784 // Don't send tickets the client wouldn't use. See RFC 8446, Section 4.2.9.
785 for _, pskMode := range hs.clientHello.pskModes {
786 if pskMode == pskModeDHE {
793 func (hs *serverHandshakeStateTLS13) sendSessionTickets() error {
796 hs.clientFinished = hs.suite.finishedHash(c.in.trafficSecret, hs.transcript)
797 finishedMsg := &finishedMsg{
798 verifyData: hs.clientFinished,
800 if err := transcriptMsg(finishedMsg, hs.transcript); err != nil {
804 c.resumptionSecret = hs.suite.deriveSecret(hs.masterSecret,
805 resumptionLabel, hs.transcript)
807 if !hs.shouldSendSessionTickets() {
810 return c.sendSessionTicket(false)
813 func (c *Conn) sendSessionTicket(earlyData bool) error {
814 suite := cipherSuiteTLS13ByID(c.cipherSuite)
816 return errors.New("tls: internal error: unknown cipher suite")
818 // ticket_nonce, which must be unique per connection, is always left at
819 // zero because we only ever send one ticket per connection.
820 psk := suite.expandLabel(c.resumptionSecret, "resumption",
821 nil, suite.hash.Size())
823 m := new(newSessionTicketMsgTLS13)
825 state, err := c.sessionState()
830 state.EarlyData = earlyData
831 if c.config.WrapSession != nil {
832 m.label, err = c.config.WrapSession(c.connectionStateLocked(), state)
837 stateBytes, err := state.Bytes()
839 c.sendAlert(alertInternalError)
842 m.label, err = c.config.encryptTicket(stateBytes, c.ticketKeys)
847 m.lifetime = uint32(maxSessionTicketLifetime / time.Second)
849 // ticket_age_add is a random 32-bit value. See RFC 8446, section 4.6.1
850 // The value is not stored anywhere; we never need to check the ticket age
851 // because 0-RTT is not supported.
852 ageAdd := make([]byte, 4)
853 _, err = c.config.rand().Read(ageAdd)
857 m.ageAdd = binary.LittleEndian.Uint32(ageAdd)
860 // RFC 9001, Section 4.6.1
861 m.maxEarlyData = 0xffffffff
864 if _, err := c.writeHandshakeRecord(m, nil); err != nil {
871 func (hs *serverHandshakeStateTLS13) readClientCertificate() error {
874 if !hs.requestClientCert() {
875 // Make sure the connection is still being verified whether or not
876 // the server requested a client certificate.
877 if c.config.VerifyConnection != nil {
878 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
879 c.sendAlert(alertBadCertificate)
886 // If we requested a client certificate, then the client must send a
887 // certificate message. If it's empty, no CertificateVerify is sent.
889 msg, err := c.readHandshake(hs.transcript)
894 certMsg, ok := msg.(*certificateMsgTLS13)
896 c.sendAlert(alertUnexpectedMessage)
897 return unexpectedMessageError(certMsg, msg)
900 if err := c.processCertsFromClient(certMsg.certificate); err != nil {
904 if c.config.VerifyConnection != nil {
905 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
906 c.sendAlert(alertBadCertificate)
911 if len(certMsg.certificate.Certificate) != 0 {
912 // certificateVerifyMsg is included in the transcript, but not until
913 // after we verify the handshake signature, since the state before
914 // this message was sent is used.
915 msg, err = c.readHandshake(nil)
920 certVerify, ok := msg.(*certificateVerifyMsg)
922 c.sendAlert(alertUnexpectedMessage)
923 return unexpectedMessageError(certVerify, msg)
926 // See RFC 8446, Section 4.4.3.
927 if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms()) {
928 c.sendAlert(alertIllegalParameter)
929 return errors.New("tls: client certificate used with invalid signature algorithm")
931 sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
933 return c.sendAlert(alertInternalError)
935 if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
936 c.sendAlert(alertIllegalParameter)
937 return errors.New("tls: client certificate used with invalid signature algorithm")
939 signed := signedMessage(sigHash, clientSignatureContext, hs.transcript)
940 if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey,
941 sigHash, signed, certVerify.signature); err != nil {
942 c.sendAlert(alertDecryptError)
943 return errors.New("tls: invalid signature by the client certificate: " + err.Error())
946 if err := transcriptMsg(certVerify, hs.transcript); err != nil {
951 // If we waited until the client certificates to send session tickets, we
952 // are ready to do it now.
953 if err := hs.sendSessionTickets(); err != nil {
960 func (hs *serverHandshakeStateTLS13) readClientFinished() error {
963 // finishedMsg is not included in the transcript.
964 msg, err := c.readHandshake(nil)
969 finished, ok := msg.(*finishedMsg)
971 c.sendAlert(alertUnexpectedMessage)
972 return unexpectedMessageError(finished, msg)
975 if !hmac.Equal(hs.clientFinished, finished.verifyData) {
976 c.sendAlert(alertDecryptError)
977 return errors.New("tls: invalid client finished hash")
980 c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, hs.trafficSecret)