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.
4
5package tls
6
7import (
8	"bytes"
9	"context"
10	"crypto"
11	"crypto/hmac"
12	"crypto/internal/mlkem768"
13	"crypto/rsa"
14	"errors"
15	"hash"
16	"internal/byteorder"
17	"io"
18	"slices"
19	"time"
20)
21
22// maxClientPSKIdentities is the number of client PSK identities the server will
23// attempt to validate. It will ignore the rest not to let cheap ClientHello
24// messages cause too much work in session ticket decryption attempts.
25const maxClientPSKIdentities = 5
26
27type serverHandshakeStateTLS13 struct {
28	c               *Conn
29	ctx             context.Context
30	clientHello     *clientHelloMsg
31	hello           *serverHelloMsg
32	sentDummyCCS    bool
33	usingPSK        bool
34	earlyData       bool
35	suite           *cipherSuiteTLS13
36	cert            *Certificate
37	sigAlg          SignatureScheme
38	earlySecret     []byte
39	sharedKey       []byte
40	handshakeSecret []byte
41	masterSecret    []byte
42	trafficSecret   []byte // client_application_traffic_secret_0
43	transcript      hash.Hash
44	clientFinished  []byte
45}
46
47func (hs *serverHandshakeStateTLS13) handshake() error {
48	c := hs.c
49
50	if needFIPS() {
51		return errors.New("tls: internal error: TLS 1.3 reached in FIPS mode")
52	}
53
54	// For an overview of the TLS 1.3 handshake, see RFC 8446, Section 2.
55	if err := hs.processClientHello(); err != nil {
56		return err
57	}
58	if err := hs.checkForResumption(); err != nil {
59		return err
60	}
61	if err := hs.pickCertificate(); err != nil {
62		return err
63	}
64	c.buffering = true
65	if err := hs.sendServerParameters(); err != nil {
66		return err
67	}
68	if err := hs.sendServerCertificate(); err != nil {
69		return err
70	}
71	if err := hs.sendServerFinished(); err != nil {
72		return err
73	}
74	// Note that at this point we could start sending application data without
75	// waiting for the client's second flight, but the application might not
76	// expect the lack of replay protection of the ClientHello parameters.
77	if _, err := c.flush(); err != nil {
78		return err
79	}
80	if err := hs.readClientCertificate(); err != nil {
81		return err
82	}
83	if err := hs.readClientFinished(); err != nil {
84		return err
85	}
86
87	c.isHandshakeComplete.Store(true)
88
89	return nil
90}
91
92func (hs *serverHandshakeStateTLS13) processClientHello() error {
93	c := hs.c
94
95	hs.hello = new(serverHelloMsg)
96
97	// TLS 1.3 froze the ServerHello.legacy_version field, and uses
98	// supported_versions instead. See RFC 8446, sections 4.1.3 and 4.2.1.
99	hs.hello.vers = VersionTLS12
100	hs.hello.supportedVersion = c.vers
101
102	if len(hs.clientHello.supportedVersions) == 0 {
103		c.sendAlert(alertIllegalParameter)
104		return errors.New("tls: client used the legacy version field to negotiate TLS 1.3")
105	}
106
107	// Abort if the client is doing a fallback and landing lower than what we
108	// support. See RFC 7507, which however does not specify the interaction
109	// with supported_versions. The only difference is that with
110	// supported_versions a client has a chance to attempt a [TLS 1.2, TLS 1.4]
111	// handshake in case TLS 1.3 is broken but 1.2 is not. Alas, in that case,
112	// it will have to drop the TLS_FALLBACK_SCSV protection if it falls back to
113	// TLS 1.2, because a TLS 1.3 server would abort here. The situation before
114	// supported_versions was not better because there was just no way to do a
115	// TLS 1.4 handshake without risking the server selecting TLS 1.3.
116	for _, id := range hs.clientHello.cipherSuites {
117		if id == TLS_FALLBACK_SCSV {
118			// Use c.vers instead of max(supported_versions) because an attacker
119			// could defeat this by adding an arbitrary high version otherwise.
120			if c.vers < c.config.maxSupportedVersion(roleServer) {
121				c.sendAlert(alertInappropriateFallback)
122				return errors.New("tls: client using inappropriate protocol fallback")
123			}
124			break
125		}
126	}
127
128	if len(hs.clientHello.compressionMethods) != 1 ||
129		hs.clientHello.compressionMethods[0] != compressionNone {
130		c.sendAlert(alertIllegalParameter)
131		return errors.New("tls: TLS 1.3 client supports illegal compression methods")
132	}
133
134	hs.hello.random = make([]byte, 32)
135	if _, err := io.ReadFull(c.config.rand(), hs.hello.random); err != nil {
136		c.sendAlert(alertInternalError)
137		return err
138	}
139
140	if len(hs.clientHello.secureRenegotiation) != 0 {
141		c.sendAlert(alertHandshakeFailure)
142		return errors.New("tls: initial handshake had non-empty renegotiation extension")
143	}
144
145	if hs.clientHello.earlyData && c.quic != nil {
146		if len(hs.clientHello.pskIdentities) == 0 {
147			c.sendAlert(alertIllegalParameter)
148			return errors.New("tls: early_data without pre_shared_key")
149		}
150	} else if hs.clientHello.earlyData {
151		// See RFC 8446, Section 4.2.10 for the complicated behavior required
152		// here. The scenario is that a different server at our address offered
153		// to accept early data in the past, which we can't handle. For now, all
154		// 0-RTT enabled session tickets need to expire before a Go server can
155		// replace a server or join a pool. That's the same requirement that
156		// applies to mixing or replacing with any TLS 1.2 server.
157		c.sendAlert(alertUnsupportedExtension)
158		return errors.New("tls: client sent unexpected early data")
159	}
160
161	hs.hello.sessionId = hs.clientHello.sessionId
162	hs.hello.compressionMethod = compressionNone
163
164	preferenceList := defaultCipherSuitesTLS13
165	if !hasAESGCMHardwareSupport || !aesgcmPreferred(hs.clientHello.cipherSuites) {
166		preferenceList = defaultCipherSuitesTLS13NoAES
167	}
168	for _, suiteID := range preferenceList {
169		hs.suite = mutualCipherSuiteTLS13(hs.clientHello.cipherSuites, suiteID)
170		if hs.suite != nil {
171			break
172		}
173	}
174	if hs.suite == nil {
175		c.sendAlert(alertHandshakeFailure)
176		return errors.New("tls: no cipher suite supported by both client and server")
177	}
178	c.cipherSuite = hs.suite.id
179	hs.hello.cipherSuite = hs.suite.id
180	hs.transcript = hs.suite.hash.New()
181
182	// Pick the key exchange method in server preference order, but give
183	// priority to key shares, to avoid a HelloRetryRequest round-trip.
184	var selectedGroup CurveID
185	var clientKeyShare *keyShare
186	preferredGroups := c.config.curvePreferences(c.vers)
187	for _, preferredGroup := range preferredGroups {
188		ki := slices.IndexFunc(hs.clientHello.keyShares, func(ks keyShare) bool {
189			return ks.group == preferredGroup
190		})
191		if ki != -1 {
192			clientKeyShare = &hs.clientHello.keyShares[ki]
193			selectedGroup = clientKeyShare.group
194			if !slices.Contains(hs.clientHello.supportedCurves, selectedGroup) {
195				c.sendAlert(alertIllegalParameter)
196				return errors.New("tls: client sent key share for group it does not support")
197			}
198			break
199		}
200	}
201	if selectedGroup == 0 {
202		for _, preferredGroup := range preferredGroups {
203			if slices.Contains(hs.clientHello.supportedCurves, preferredGroup) {
204				selectedGroup = preferredGroup
205				break
206			}
207		}
208	}
209	if selectedGroup == 0 {
210		c.sendAlert(alertHandshakeFailure)
211		return errors.New("tls: no ECDHE curve supported by both client and server")
212	}
213	if clientKeyShare == nil {
214		ks, err := hs.doHelloRetryRequest(selectedGroup)
215		if err != nil {
216			return err
217		}
218		clientKeyShare = ks
219	}
220	c.curveID = selectedGroup
221
222	ecdhGroup := selectedGroup
223	ecdhData := clientKeyShare.data
224	if selectedGroup == x25519Kyber768Draft00 {
225		ecdhGroup = X25519
226		if len(ecdhData) != x25519PublicKeySize+mlkem768.EncapsulationKeySize {
227			c.sendAlert(alertIllegalParameter)
228			return errors.New("tls: invalid Kyber client key share")
229		}
230		ecdhData = ecdhData[:x25519PublicKeySize]
231	}
232	if _, ok := curveForCurveID(ecdhGroup); !ok {
233		c.sendAlert(alertInternalError)
234		return errors.New("tls: CurvePreferences includes unsupported curve")
235	}
236	key, err := generateECDHEKey(c.config.rand(), ecdhGroup)
237	if err != nil {
238		c.sendAlert(alertInternalError)
239		return err
240	}
241	hs.hello.serverShare = keyShare{group: selectedGroup, data: key.PublicKey().Bytes()}
242	peerKey, err := key.Curve().NewPublicKey(ecdhData)
243	if err != nil {
244		c.sendAlert(alertIllegalParameter)
245		return errors.New("tls: invalid client key share")
246	}
247	hs.sharedKey, err = key.ECDH(peerKey)
248	if err != nil {
249		c.sendAlert(alertIllegalParameter)
250		return errors.New("tls: invalid client key share")
251	}
252	if selectedGroup == x25519Kyber768Draft00 {
253		ciphertext, kyberShared, err := kyberEncapsulate(clientKeyShare.data[x25519PublicKeySize:])
254		if err != nil {
255			c.sendAlert(alertIllegalParameter)
256			return errors.New("tls: invalid Kyber client key share")
257		}
258		hs.sharedKey = append(hs.sharedKey, kyberShared...)
259		hs.hello.serverShare.data = append(hs.hello.serverShare.data, ciphertext...)
260	}
261
262	selectedProto, err := negotiateALPN(c.config.NextProtos, hs.clientHello.alpnProtocols, c.quic != nil)
263	if err != nil {
264		c.sendAlert(alertNoApplicationProtocol)
265		return err
266	}
267	c.clientProtocol = selectedProto
268
269	if c.quic != nil {
270		// RFC 9001 Section 4.2: Clients MUST NOT offer TLS versions older than 1.3.
271		for _, v := range hs.clientHello.supportedVersions {
272			if v < VersionTLS13 {
273				c.sendAlert(alertProtocolVersion)
274				return errors.New("tls: client offered TLS version older than TLS 1.3")
275			}
276		}
277		// RFC 9001 Section 8.2.
278		if hs.clientHello.quicTransportParameters == nil {
279			c.sendAlert(alertMissingExtension)
280			return errors.New("tls: client did not send a quic_transport_parameters extension")
281		}
282		c.quicSetTransportParameters(hs.clientHello.quicTransportParameters)
283	} else {
284		if hs.clientHello.quicTransportParameters != nil {
285			c.sendAlert(alertUnsupportedExtension)
286			return errors.New("tls: client sent an unexpected quic_transport_parameters extension")
287		}
288	}
289
290	c.serverName = hs.clientHello.serverName
291	return nil
292}
293
294func (hs *serverHandshakeStateTLS13) checkForResumption() error {
295	c := hs.c
296
297	if c.config.SessionTicketsDisabled {
298		return nil
299	}
300
301	modeOK := false
302	for _, mode := range hs.clientHello.pskModes {
303		if mode == pskModeDHE {
304			modeOK = true
305			break
306		}
307	}
308	if !modeOK {
309		return nil
310	}
311
312	if len(hs.clientHello.pskIdentities) != len(hs.clientHello.pskBinders) {
313		c.sendAlert(alertIllegalParameter)
314		return errors.New("tls: invalid or missing PSK binders")
315	}
316	if len(hs.clientHello.pskIdentities) == 0 {
317		return nil
318	}
319
320	for i, identity := range hs.clientHello.pskIdentities {
321		if i >= maxClientPSKIdentities {
322			break
323		}
324
325		var sessionState *SessionState
326		if c.config.UnwrapSession != nil {
327			var err error
328			sessionState, err = c.config.UnwrapSession(identity.label, c.connectionStateLocked())
329			if err != nil {
330				return err
331			}
332			if sessionState == nil {
333				continue
334			}
335		} else {
336			plaintext := c.config.decryptTicket(identity.label, c.ticketKeys)
337			if plaintext == nil {
338				continue
339			}
340			var err error
341			sessionState, err = ParseSessionState(plaintext)
342			if err != nil {
343				continue
344			}
345		}
346
347		if sessionState.version != VersionTLS13 {
348			continue
349		}
350
351		createdAt := time.Unix(int64(sessionState.createdAt), 0)
352		if c.config.time().Sub(createdAt) > maxSessionTicketLifetime {
353			continue
354		}
355
356		pskSuite := cipherSuiteTLS13ByID(sessionState.cipherSuite)
357		if pskSuite == nil || pskSuite.hash != hs.suite.hash {
358			continue
359		}
360
361		// PSK connections don't re-establish client certificates, but carry
362		// them over in the session ticket. Ensure the presence of client certs
363		// in the ticket is consistent with the configured requirements.
364		sessionHasClientCerts := len(sessionState.peerCertificates) != 0
365		needClientCerts := requiresClientCert(c.config.ClientAuth)
366		if needClientCerts && !sessionHasClientCerts {
367			continue
368		}
369		if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
370			continue
371		}
372		if sessionHasClientCerts && c.config.time().After(sessionState.peerCertificates[0].NotAfter) {
373			continue
374		}
375		if sessionHasClientCerts && c.config.ClientAuth >= VerifyClientCertIfGiven &&
376			len(sessionState.verifiedChains) == 0 {
377			continue
378		}
379
380		if c.quic != nil && c.quic.enableSessionEvents {
381			if err := c.quicResumeSession(sessionState); err != nil {
382				return err
383			}
384		}
385
386		hs.earlySecret = hs.suite.extract(sessionState.secret, nil)
387		binderKey := hs.suite.deriveSecret(hs.earlySecret, resumptionBinderLabel, nil)
388		// Clone the transcript in case a HelloRetryRequest was recorded.
389		transcript := cloneHash(hs.transcript, hs.suite.hash)
390		if transcript == nil {
391			c.sendAlert(alertInternalError)
392			return errors.New("tls: internal error: failed to clone hash")
393		}
394		clientHelloBytes, err := hs.clientHello.marshalWithoutBinders()
395		if err != nil {
396			c.sendAlert(alertInternalError)
397			return err
398		}
399		transcript.Write(clientHelloBytes)
400		pskBinder := hs.suite.finishedHash(binderKey, transcript)
401		if !hmac.Equal(hs.clientHello.pskBinders[i], pskBinder) {
402			c.sendAlert(alertDecryptError)
403			return errors.New("tls: invalid PSK binder")
404		}
405
406		if c.quic != nil && hs.clientHello.earlyData && i == 0 &&
407			sessionState.EarlyData && sessionState.cipherSuite == hs.suite.id &&
408			sessionState.alpnProtocol == c.clientProtocol {
409			hs.earlyData = true
410
411			transcript := hs.suite.hash.New()
412			if err := transcriptMsg(hs.clientHello, transcript); err != nil {
413				return err
414			}
415			earlyTrafficSecret := hs.suite.deriveSecret(hs.earlySecret, clientEarlyTrafficLabel, transcript)
416			c.quicSetReadSecret(QUICEncryptionLevelEarly, hs.suite.id, earlyTrafficSecret)
417		}
418
419		c.didResume = true
420		c.peerCertificates = sessionState.peerCertificates
421		c.ocspResponse = sessionState.ocspResponse
422		c.scts = sessionState.scts
423		c.verifiedChains = sessionState.verifiedChains
424
425		hs.hello.selectedIdentityPresent = true
426		hs.hello.selectedIdentity = uint16(i)
427		hs.usingPSK = true
428		return nil
429	}
430
431	return nil
432}
433
434// cloneHash uses the encoding.BinaryMarshaler and encoding.BinaryUnmarshaler
435// interfaces implemented by standard library hashes to clone the state of in
436// to a new instance of h. It returns nil if the operation fails.
437func cloneHash(in hash.Hash, h crypto.Hash) hash.Hash {
438	// Recreate the interface to avoid importing encoding.
439	type binaryMarshaler interface {
440		MarshalBinary() (data []byte, err error)
441		UnmarshalBinary(data []byte) error
442	}
443	marshaler, ok := in.(binaryMarshaler)
444	if !ok {
445		return nil
446	}
447	state, err := marshaler.MarshalBinary()
448	if err != nil {
449		return nil
450	}
451	out := h.New()
452	unmarshaler, ok := out.(binaryMarshaler)
453	if !ok {
454		return nil
455	}
456	if err := unmarshaler.UnmarshalBinary(state); err != nil {
457		return nil
458	}
459	return out
460}
461
462func (hs *serverHandshakeStateTLS13) pickCertificate() error {
463	c := hs.c
464
465	// Only one of PSK and certificates are used at a time.
466	if hs.usingPSK {
467		return nil
468	}
469
470	// signature_algorithms is required in TLS 1.3. See RFC 8446, Section 4.2.3.
471	if len(hs.clientHello.supportedSignatureAlgorithms) == 0 {
472		return c.sendAlert(alertMissingExtension)
473	}
474
475	certificate, err := c.config.getCertificate(clientHelloInfo(hs.ctx, c, hs.clientHello))
476	if err != nil {
477		if err == errNoCertificates {
478			c.sendAlert(alertUnrecognizedName)
479		} else {
480			c.sendAlert(alertInternalError)
481		}
482		return err
483	}
484	hs.sigAlg, err = selectSignatureScheme(c.vers, certificate, hs.clientHello.supportedSignatureAlgorithms)
485	if err != nil {
486		// getCertificate returned a certificate that is unsupported or
487		// incompatible with the client's signature algorithms.
488		c.sendAlert(alertHandshakeFailure)
489		return err
490	}
491	hs.cert = certificate
492
493	return nil
494}
495
496// sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility
497// with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4.
498func (hs *serverHandshakeStateTLS13) sendDummyChangeCipherSpec() error {
499	if hs.c.quic != nil {
500		return nil
501	}
502	if hs.sentDummyCCS {
503		return nil
504	}
505	hs.sentDummyCCS = true
506
507	return hs.c.writeChangeCipherRecord()
508}
509
510func (hs *serverHandshakeStateTLS13) doHelloRetryRequest(selectedGroup CurveID) (*keyShare, error) {
511	c := hs.c
512
513	// The first ClientHello gets double-hashed into the transcript upon a
514	// HelloRetryRequest. See RFC 8446, Section 4.4.1.
515	if err := transcriptMsg(hs.clientHello, hs.transcript); err != nil {
516		return nil, err
517	}
518	chHash := hs.transcript.Sum(nil)
519	hs.transcript.Reset()
520	hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
521	hs.transcript.Write(chHash)
522
523	helloRetryRequest := &serverHelloMsg{
524		vers:              hs.hello.vers,
525		random:            helloRetryRequestRandom,
526		sessionId:         hs.hello.sessionId,
527		cipherSuite:       hs.hello.cipherSuite,
528		compressionMethod: hs.hello.compressionMethod,
529		supportedVersion:  hs.hello.supportedVersion,
530		selectedGroup:     selectedGroup,
531	}
532
533	if _, err := hs.c.writeHandshakeRecord(helloRetryRequest, hs.transcript); err != nil {
534		return nil, err
535	}
536
537	if err := hs.sendDummyChangeCipherSpec(); err != nil {
538		return nil, err
539	}
540
541	// clientHelloMsg is not included in the transcript.
542	msg, err := c.readHandshake(nil)
543	if err != nil {
544		return nil, err
545	}
546
547	clientHello, ok := msg.(*clientHelloMsg)
548	if !ok {
549		c.sendAlert(alertUnexpectedMessage)
550		return nil, unexpectedMessageError(clientHello, msg)
551	}
552
553	if len(clientHello.keyShares) != 1 {
554		c.sendAlert(alertIllegalParameter)
555		return nil, errors.New("tls: client didn't send one key share in second ClientHello")
556	}
557	ks := &clientHello.keyShares[0]
558
559	if ks.group != selectedGroup {
560		c.sendAlert(alertIllegalParameter)
561		return nil, errors.New("tls: client sent unexpected key share in second ClientHello")
562	}
563
564	if clientHello.earlyData {
565		c.sendAlert(alertIllegalParameter)
566		return nil, errors.New("tls: client indicated early data in second ClientHello")
567	}
568
569	if illegalClientHelloChange(clientHello, hs.clientHello) {
570		c.sendAlert(alertIllegalParameter)
571		return nil, errors.New("tls: client illegally modified second ClientHello")
572	}
573
574	c.didHRR = true
575	hs.clientHello = clientHello
576	return ks, nil
577}
578
579// illegalClientHelloChange reports whether the two ClientHello messages are
580// different, with the exception of the changes allowed before and after a
581// HelloRetryRequest. See RFC 8446, Section 4.1.2.
582func illegalClientHelloChange(ch, ch1 *clientHelloMsg) bool {
583	if len(ch.supportedVersions) != len(ch1.supportedVersions) ||
584		len(ch.cipherSuites) != len(ch1.cipherSuites) ||
585		len(ch.supportedCurves) != len(ch1.supportedCurves) ||
586		len(ch.supportedSignatureAlgorithms) != len(ch1.supportedSignatureAlgorithms) ||
587		len(ch.supportedSignatureAlgorithmsCert) != len(ch1.supportedSignatureAlgorithmsCert) ||
588		len(ch.alpnProtocols) != len(ch1.alpnProtocols) {
589		return true
590	}
591	for i := range ch.supportedVersions {
592		if ch.supportedVersions[i] != ch1.supportedVersions[i] {
593			return true
594		}
595	}
596	for i := range ch.cipherSuites {
597		if ch.cipherSuites[i] != ch1.cipherSuites[i] {
598			return true
599		}
600	}
601	for i := range ch.supportedCurves {
602		if ch.supportedCurves[i] != ch1.supportedCurves[i] {
603			return true
604		}
605	}
606	for i := range ch.supportedSignatureAlgorithms {
607		if ch.supportedSignatureAlgorithms[i] != ch1.supportedSignatureAlgorithms[i] {
608			return true
609		}
610	}
611	for i := range ch.supportedSignatureAlgorithmsCert {
612		if ch.supportedSignatureAlgorithmsCert[i] != ch1.supportedSignatureAlgorithmsCert[i] {
613			return true
614		}
615	}
616	for i := range ch.alpnProtocols {
617		if ch.alpnProtocols[i] != ch1.alpnProtocols[i] {
618			return true
619		}
620	}
621	return ch.vers != ch1.vers ||
622		!bytes.Equal(ch.random, ch1.random) ||
623		!bytes.Equal(ch.sessionId, ch1.sessionId) ||
624		!bytes.Equal(ch.compressionMethods, ch1.compressionMethods) ||
625		ch.serverName != ch1.serverName ||
626		ch.ocspStapling != ch1.ocspStapling ||
627		!bytes.Equal(ch.supportedPoints, ch1.supportedPoints) ||
628		ch.ticketSupported != ch1.ticketSupported ||
629		!bytes.Equal(ch.sessionTicket, ch1.sessionTicket) ||
630		ch.secureRenegotiationSupported != ch1.secureRenegotiationSupported ||
631		!bytes.Equal(ch.secureRenegotiation, ch1.secureRenegotiation) ||
632		ch.scts != ch1.scts ||
633		!bytes.Equal(ch.cookie, ch1.cookie) ||
634		!bytes.Equal(ch.pskModes, ch1.pskModes)
635}
636
637func (hs *serverHandshakeStateTLS13) sendServerParameters() error {
638	c := hs.c
639
640	if err := transcriptMsg(hs.clientHello, hs.transcript); err != nil {
641		return err
642	}
643	if _, err := hs.c.writeHandshakeRecord(hs.hello, hs.transcript); err != nil {
644		return err
645	}
646
647	if err := hs.sendDummyChangeCipherSpec(); err != nil {
648		return err
649	}
650
651	earlySecret := hs.earlySecret
652	if earlySecret == nil {
653		earlySecret = hs.suite.extract(nil, nil)
654	}
655	hs.handshakeSecret = hs.suite.extract(hs.sharedKey,
656		hs.suite.deriveSecret(earlySecret, "derived", nil))
657
658	clientSecret := hs.suite.deriveSecret(hs.handshakeSecret,
659		clientHandshakeTrafficLabel, hs.transcript)
660	c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, clientSecret)
661	serverSecret := hs.suite.deriveSecret(hs.handshakeSecret,
662		serverHandshakeTrafficLabel, hs.transcript)
663	c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, serverSecret)
664
665	if c.quic != nil {
666		if c.hand.Len() != 0 {
667			c.sendAlert(alertUnexpectedMessage)
668		}
669		c.quicSetWriteSecret(QUICEncryptionLevelHandshake, hs.suite.id, serverSecret)
670		c.quicSetReadSecret(QUICEncryptionLevelHandshake, hs.suite.id, clientSecret)
671	}
672
673	err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.clientHello.random, clientSecret)
674	if err != nil {
675		c.sendAlert(alertInternalError)
676		return err
677	}
678	err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.clientHello.random, serverSecret)
679	if err != nil {
680		c.sendAlert(alertInternalError)
681		return err
682	}
683
684	encryptedExtensions := new(encryptedExtensionsMsg)
685	encryptedExtensions.alpnProtocol = c.clientProtocol
686
687	if c.quic != nil {
688		p, err := c.quicGetTransportParameters()
689		if err != nil {
690			return err
691		}
692		encryptedExtensions.quicTransportParameters = p
693		encryptedExtensions.earlyData = hs.earlyData
694	}
695
696	if _, err := hs.c.writeHandshakeRecord(encryptedExtensions, hs.transcript); err != nil {
697		return err
698	}
699
700	return nil
701}
702
703func (hs *serverHandshakeStateTLS13) requestClientCert() bool {
704	return hs.c.config.ClientAuth >= RequestClientCert && !hs.usingPSK
705}
706
707func (hs *serverHandshakeStateTLS13) sendServerCertificate() error {
708	c := hs.c
709
710	// Only one of PSK and certificates are used at a time.
711	if hs.usingPSK {
712		return nil
713	}
714
715	if hs.requestClientCert() {
716		// Request a client certificate
717		certReq := new(certificateRequestMsgTLS13)
718		certReq.ocspStapling = true
719		certReq.scts = true
720		certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms()
721		if c.config.ClientCAs != nil {
722			certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
723		}
724
725		if _, err := hs.c.writeHandshakeRecord(certReq, hs.transcript); err != nil {
726			return err
727		}
728	}
729
730	certMsg := new(certificateMsgTLS13)
731
732	certMsg.certificate = *hs.cert
733	certMsg.scts = hs.clientHello.scts && len(hs.cert.SignedCertificateTimestamps) > 0
734	certMsg.ocspStapling = hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0
735
736	if _, err := hs.c.writeHandshakeRecord(certMsg, hs.transcript); err != nil {
737		return err
738	}
739
740	certVerifyMsg := new(certificateVerifyMsg)
741	certVerifyMsg.hasSignatureAlgorithm = true
742	certVerifyMsg.signatureAlgorithm = hs.sigAlg
743
744	sigType, sigHash, err := typeAndHashFromSignatureScheme(hs.sigAlg)
745	if err != nil {
746		return c.sendAlert(alertInternalError)
747	}
748
749	signed := signedMessage(sigHash, serverSignatureContext, hs.transcript)
750	signOpts := crypto.SignerOpts(sigHash)
751	if sigType == signatureRSAPSS {
752		signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
753	}
754	sig, err := hs.cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts)
755	if err != nil {
756		public := hs.cert.PrivateKey.(crypto.Signer).Public()
757		if rsaKey, ok := public.(*rsa.PublicKey); ok && sigType == signatureRSAPSS &&
758			rsaKey.N.BitLen()/8 < sigHash.Size()*2+2 { // key too small for RSA-PSS
759			c.sendAlert(alertHandshakeFailure)
760		} else {
761			c.sendAlert(alertInternalError)
762		}
763		return errors.New("tls: failed to sign handshake: " + err.Error())
764	}
765	certVerifyMsg.signature = sig
766
767	if _, err := hs.c.writeHandshakeRecord(certVerifyMsg, hs.transcript); err != nil {
768		return err
769	}
770
771	return nil
772}
773
774func (hs *serverHandshakeStateTLS13) sendServerFinished() error {
775	c := hs.c
776
777	finished := &finishedMsg{
778		verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
779	}
780
781	if _, err := hs.c.writeHandshakeRecord(finished, hs.transcript); err != nil {
782		return err
783	}
784
785	// Derive secrets that take context through the server Finished.
786
787	hs.masterSecret = hs.suite.extract(nil,
788		hs.suite.deriveSecret(hs.handshakeSecret, "derived", nil))
789
790	hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret,
791		clientApplicationTrafficLabel, hs.transcript)
792	serverSecret := hs.suite.deriveSecret(hs.masterSecret,
793		serverApplicationTrafficLabel, hs.transcript)
794	c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, serverSecret)
795
796	if c.quic != nil {
797		if c.hand.Len() != 0 {
798			// TODO: Handle this in setTrafficSecret?
799			c.sendAlert(alertUnexpectedMessage)
800		}
801		c.quicSetWriteSecret(QUICEncryptionLevelApplication, hs.suite.id, serverSecret)
802	}
803
804	err := c.config.writeKeyLog(keyLogLabelClientTraffic, hs.clientHello.random, hs.trafficSecret)
805	if err != nil {
806		c.sendAlert(alertInternalError)
807		return err
808	}
809	err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.clientHello.random, serverSecret)
810	if err != nil {
811		c.sendAlert(alertInternalError)
812		return err
813	}
814
815	c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript)
816
817	// If we did not request client certificates, at this point we can
818	// precompute the client finished and roll the transcript forward to send
819	// session tickets in our first flight.
820	if !hs.requestClientCert() {
821		if err := hs.sendSessionTickets(); err != nil {
822			return err
823		}
824	}
825
826	return nil
827}
828
829func (hs *serverHandshakeStateTLS13) shouldSendSessionTickets() bool {
830	if hs.c.config.SessionTicketsDisabled {
831		return false
832	}
833
834	// QUIC tickets are sent by QUICConn.SendSessionTicket, not automatically.
835	if hs.c.quic != nil {
836		return false
837	}
838
839	// Don't send tickets the client wouldn't use. See RFC 8446, Section 4.2.9.
840	for _, pskMode := range hs.clientHello.pskModes {
841		if pskMode == pskModeDHE {
842			return true
843		}
844	}
845	return false
846}
847
848func (hs *serverHandshakeStateTLS13) sendSessionTickets() error {
849	c := hs.c
850
851	hs.clientFinished = hs.suite.finishedHash(c.in.trafficSecret, hs.transcript)
852	finishedMsg := &finishedMsg{
853		verifyData: hs.clientFinished,
854	}
855	if err := transcriptMsg(finishedMsg, hs.transcript); err != nil {
856		return err
857	}
858
859	c.resumptionSecret = hs.suite.deriveSecret(hs.masterSecret,
860		resumptionLabel, hs.transcript)
861
862	if !hs.shouldSendSessionTickets() {
863		return nil
864	}
865	return c.sendSessionTicket(false, nil)
866}
867
868func (c *Conn) sendSessionTicket(earlyData bool, extra [][]byte) error {
869	suite := cipherSuiteTLS13ByID(c.cipherSuite)
870	if suite == nil {
871		return errors.New("tls: internal error: unknown cipher suite")
872	}
873	// ticket_nonce, which must be unique per connection, is always left at
874	// zero because we only ever send one ticket per connection.
875	psk := suite.expandLabel(c.resumptionSecret, "resumption",
876		nil, suite.hash.Size())
877
878	m := new(newSessionTicketMsgTLS13)
879
880	state := c.sessionState()
881	state.secret = psk
882	state.EarlyData = earlyData
883	state.Extra = extra
884	if c.config.WrapSession != nil {
885		var err error
886		m.label, err = c.config.WrapSession(c.connectionStateLocked(), state)
887		if err != nil {
888			return err
889		}
890	} else {
891		stateBytes, err := state.Bytes()
892		if err != nil {
893			c.sendAlert(alertInternalError)
894			return err
895		}
896		m.label, err = c.config.encryptTicket(stateBytes, c.ticketKeys)
897		if err != nil {
898			return err
899		}
900	}
901	m.lifetime = uint32(maxSessionTicketLifetime / time.Second)
902
903	// ticket_age_add is a random 32-bit value. See RFC 8446, section 4.6.1
904	// The value is not stored anywhere; we never need to check the ticket age
905	// because 0-RTT is not supported.
906	ageAdd := make([]byte, 4)
907	if _, err := c.config.rand().Read(ageAdd); err != nil {
908		return err
909	}
910	m.ageAdd = byteorder.LeUint32(ageAdd)
911
912	if earlyData {
913		// RFC 9001, Section 4.6.1
914		m.maxEarlyData = 0xffffffff
915	}
916
917	if _, err := c.writeHandshakeRecord(m, nil); err != nil {
918		return err
919	}
920
921	return nil
922}
923
924func (hs *serverHandshakeStateTLS13) readClientCertificate() error {
925	c := hs.c
926
927	if !hs.requestClientCert() {
928		// Make sure the connection is still being verified whether or not
929		// the server requested a client certificate.
930		if c.config.VerifyConnection != nil {
931			if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
932				c.sendAlert(alertBadCertificate)
933				return err
934			}
935		}
936		return nil
937	}
938
939	// If we requested a client certificate, then the client must send a
940	// certificate message. If it's empty, no CertificateVerify is sent.
941
942	msg, err := c.readHandshake(hs.transcript)
943	if err != nil {
944		return err
945	}
946
947	certMsg, ok := msg.(*certificateMsgTLS13)
948	if !ok {
949		c.sendAlert(alertUnexpectedMessage)
950		return unexpectedMessageError(certMsg, msg)
951	}
952
953	if err := c.processCertsFromClient(certMsg.certificate); err != nil {
954		return err
955	}
956
957	if c.config.VerifyConnection != nil {
958		if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
959			c.sendAlert(alertBadCertificate)
960			return err
961		}
962	}
963
964	if len(certMsg.certificate.Certificate) != 0 {
965		// certificateVerifyMsg is included in the transcript, but not until
966		// after we verify the handshake signature, since the state before
967		// this message was sent is used.
968		msg, err = c.readHandshake(nil)
969		if err != nil {
970			return err
971		}
972
973		certVerify, ok := msg.(*certificateVerifyMsg)
974		if !ok {
975			c.sendAlert(alertUnexpectedMessage)
976			return unexpectedMessageError(certVerify, msg)
977		}
978
979		// See RFC 8446, Section 4.4.3.
980		if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms()) {
981			c.sendAlert(alertIllegalParameter)
982			return errors.New("tls: client certificate used with invalid signature algorithm")
983		}
984		sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
985		if err != nil {
986			return c.sendAlert(alertInternalError)
987		}
988		if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
989			c.sendAlert(alertIllegalParameter)
990			return errors.New("tls: client certificate used with invalid signature algorithm")
991		}
992		signed := signedMessage(sigHash, clientSignatureContext, hs.transcript)
993		if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey,
994			sigHash, signed, certVerify.signature); err != nil {
995			c.sendAlert(alertDecryptError)
996			return errors.New("tls: invalid signature by the client certificate: " + err.Error())
997		}
998
999		if err := transcriptMsg(certVerify, hs.transcript); err != nil {
1000			return err
1001		}
1002	}
1003
1004	// If we waited until the client certificates to send session tickets, we
1005	// are ready to do it now.
1006	if err := hs.sendSessionTickets(); err != nil {
1007		return err
1008	}
1009
1010	return nil
1011}
1012
1013func (hs *serverHandshakeStateTLS13) readClientFinished() error {
1014	c := hs.c
1015
1016	// finishedMsg is not included in the transcript.
1017	msg, err := c.readHandshake(nil)
1018	if err != nil {
1019		return err
1020	}
1021
1022	finished, ok := msg.(*finishedMsg)
1023	if !ok {
1024		c.sendAlert(alertUnexpectedMessage)
1025		return unexpectedMessageError(finished, msg)
1026	}
1027
1028	if !hmac.Equal(hs.clientFinished, finished.verifyData) {
1029		c.sendAlert(alertDecryptError)
1030		return errors.New("tls: invalid client finished hash")
1031	}
1032
1033	c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, hs.trafficSecret)
1034
1035	return nil
1036}
1037