xref: /aosp_15_r20/external/boringssl/src/ssl/test/runner/handshake_client.go (revision 8fb009dc861624b67b6cdb62ea21f0f22d0c584b)
1// Copyright 2009 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 runner
6
7import (
8	"bytes"
9	"crypto"
10	"crypto/ecdsa"
11	"crypto/ed25519"
12	"crypto/elliptic"
13	"crypto/rsa"
14	"crypto/subtle"
15	"crypto/x509"
16	"errors"
17	"fmt"
18	"io"
19	"math/big"
20	"net"
21	"time"
22
23	"boringssl.googlesource.com/boringssl/ssl/test/runner/hpke"
24	"golang.org/x/crypto/cryptobyte"
25)
26
27const echBadPayloadByte = 0xff
28
29type clientHandshakeState struct {
30	c              *Conn
31	serverHello    *serverHelloMsg
32	hello          *clientHelloMsg
33	innerHello     *clientHelloMsg
34	echHPKEContext *hpke.Context
35	suite          *cipherSuite
36	finishedHash   finishedHash
37	keyShares      map[CurveID]kemImplementation
38	masterSecret   []byte
39	session        *ClientSessionState
40	finishedBytes  []byte
41	peerPublicKey  crypto.PublicKey
42}
43
44func mapClientHelloVersion(vers uint16, isDTLS bool) uint16 {
45	if !isDTLS {
46		return vers
47	}
48
49	switch vers {
50	case VersionTLS12:
51		return VersionDTLS12
52	case VersionTLS10:
53		return VersionDTLS10
54	}
55
56	panic("Unknown ClientHello version.")
57}
58
59// replaceClientHello returns a new clientHelloMsg which serializes to |in|, but
60// with key shares copied from |hello|. This allows sending an exact
61// externally-specified ClientHello in tests. However, we use |hello|'s key
62// shares. This ensures we have the private keys to complete the handshake. Note
63// this function does not update internal handshake state, so the test must be
64// configured compatibly with |in|.
65func replaceClientHello(hello *clientHelloMsg, in []byte) (*clientHelloMsg, error) {
66	copied := append([]byte{}, in...)
67	newHello := new(clientHelloMsg)
68	if !newHello.unmarshal(copied) {
69		return nil, errors.New("tls: invalid ClientHello")
70	}
71
72	// Replace |newHellos|'s key shares with those of |hello|. For simplicity,
73	// we require their lengths match, which is satisfied by matching the
74	// DefaultCurves setting to the selection in the replacement ClientHello.
75	bb := cryptobyte.NewBuilder(nil)
76	hello.marshalKeyShares(bb)
77	keyShares, err := bb.Bytes()
78	if err != nil {
79		return nil, err
80	}
81	if len(keyShares) != len(newHello.keySharesRaw) {
82		return nil, errors.New("tls: ClientHello key share length is inconsistent with DefaultCurves setting")
83	}
84	// |newHello.keySharesRaw| aliases |copied|.
85	copy(newHello.keySharesRaw, keyShares)
86	newHello.keyShares = hello.keyShares
87
88	return newHello, nil
89}
90
91func (c *Conn) clientHandshake() error {
92	if c.config == nil {
93		c.config = defaultConfig()
94	}
95
96	if len(c.config.ServerName) == 0 && !c.config.InsecureSkipVerify {
97		return errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
98	}
99
100	c.sendHandshakeSeq = 0
101	c.recvHandshakeSeq = 0
102
103	hs := &clientHandshakeState{
104		c:         c,
105		keyShares: make(map[CurveID]kemImplementation),
106	}
107
108	// Pick a session to resume.
109	var session *ClientSessionState
110	var cacheKey string
111	sessionCache := c.config.ClientSessionCache
112	if sessionCache != nil {
113		// Try to resume a previously negotiated TLS session, if
114		// available.
115		cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
116		// TODO(nharper): Support storing more than one session
117		// ticket for TLS 1.3.
118		candidateSession, ok := sessionCache.Get(cacheKey)
119		if ok {
120			ticketOk := !c.config.SessionTicketsDisabled || candidateSession.sessionTicket == nil
121
122			// Check that the ciphersuite/version used for the
123			// previous session are still valid.
124			cipherSuiteOk := false
125			if candidateSession.vers <= VersionTLS12 {
126				for _, id := range c.config.cipherSuites() {
127					if id == candidateSession.cipherSuite.id {
128						cipherSuiteOk = true
129						break
130					}
131				}
132			} else {
133				// TLS 1.3 allows the cipher to change on
134				// resumption.
135				cipherSuiteOk = true
136			}
137
138			_, versOk := c.config.isSupportedVersion(candidateSession.wireVersion, c.isDTLS)
139			if ticketOk && versOk && cipherSuiteOk {
140				session = candidateSession
141				hs.session = session
142			}
143		}
144	}
145
146	// Set up ECH parameters.
147	var err error
148	var earlyHello *clientHelloMsg
149	if c.config.ClientECHConfig != nil {
150		if c.config.ClientECHConfig.KEM != hpke.X25519WithHKDFSHA256 {
151			return errors.New("tls: unsupported KEM type in ECHConfig")
152		}
153
154		echCipherSuite, ok := chooseECHCipherSuite(c.config.ClientECHConfig, c.config)
155		if !ok {
156			return errors.New("tls: did not find compatible cipher suite in ECHConfig")
157		}
158
159		info := []byte("tls ech\x00")
160		info = append(info, c.config.ClientECHConfig.Raw...)
161
162		var echEnc []byte
163		hs.echHPKEContext, echEnc, err = hpke.SetupBaseSenderX25519(echCipherSuite.KDF, echCipherSuite.AEAD, c.config.ClientECHConfig.PublicKey, info, nil)
164		if err != nil {
165			return errors.New("tls: ech: failed to set up client's HPKE sender context")
166		}
167
168		hs.innerHello, err = hs.createClientHello(nil, nil)
169		if err != nil {
170			return err
171		}
172		hs.hello, err = hs.createClientHello(hs.innerHello, echEnc)
173		if err != nil {
174			return err
175		}
176		earlyHello = hs.innerHello
177	} else {
178		hs.hello, err = hs.createClientHello(nil, nil)
179		if err != nil {
180			return err
181		}
182		earlyHello = hs.hello
183	}
184
185	if len(earlyHello.pskIdentities) == 0 || c.config.Bugs.SendEarlyData == nil {
186		earlyHello = nil
187	}
188
189	if c.config.Bugs.SendV2ClientHello {
190		hs.hello.isV2ClientHello = true
191
192		// The V2ClientHello "challenge" field is variable-length and is
193		// left-padded or truncated to become the SSL3/TLS random.
194		challengeLength := c.config.Bugs.V2ClientHelloChallengeLength
195		if challengeLength == 0 {
196			challengeLength = len(hs.hello.random)
197		}
198		if challengeLength <= len(hs.hello.random) {
199			skip := len(hs.hello.random) - challengeLength
200			for i := 0; i < skip; i++ {
201				hs.hello.random[i] = 0
202			}
203			hs.hello.v2Challenge = hs.hello.random[skip:]
204		} else {
205			hs.hello.v2Challenge = make([]byte, challengeLength)
206			copy(hs.hello.v2Challenge, hs.hello.random)
207			if _, err := io.ReadFull(c.config.rand(), hs.hello.v2Challenge[len(hs.hello.random):]); err != nil {
208				c.sendAlert(alertInternalError)
209				return fmt.Errorf("tls: short read from Rand: %s", err)
210			}
211		}
212
213		c.writeV2Record(hs.hello.marshal())
214	} else {
215		helloBytes := hs.hello.marshal()
216		var appendToHello byte
217		if c.config.Bugs.PartialClientFinishedWithClientHello {
218			appendToHello = typeFinished
219		} else if c.config.Bugs.PartialEndOfEarlyDataWithClientHello {
220			appendToHello = typeEndOfEarlyData
221		} else if c.config.Bugs.PartialSecondClientHelloAfterFirst {
222			appendToHello = typeClientHello
223		} else if c.config.Bugs.PartialClientKeyExchangeWithClientHello {
224			appendToHello = typeClientKeyExchange
225		}
226		if appendToHello != 0 {
227			c.writeRecord(recordTypeHandshake, append(helloBytes[:len(helloBytes):len(helloBytes)], appendToHello))
228		} else {
229			c.writeRecord(recordTypeHandshake, helloBytes)
230		}
231	}
232	c.flushHandshake()
233
234	if err := c.simulatePacketLoss(nil); err != nil {
235		return err
236	}
237	if c.config.Bugs.SendEarlyAlert {
238		c.sendAlert(alertHandshakeFailure)
239	}
240	if c.config.Bugs.SendFakeEarlyDataLength > 0 {
241		c.sendFakeEarlyData(c.config.Bugs.SendFakeEarlyDataLength)
242	}
243
244	// Derive early write keys and set Conn state to allow early writes.
245	if earlyHello != nil {
246		finishedHash := newFinishedHash(session.wireVersion, c.isDTLS, session.cipherSuite)
247		finishedHash.addEntropy(session.secret)
248		finishedHash.Write(earlyHello.marshal())
249
250		if !c.config.Bugs.SkipChangeCipherSpec {
251			c.wireVersion = session.wireVersion
252			c.vers = VersionTLS13
253			c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
254			c.wireVersion = 0
255			c.vers = 0
256		}
257
258		earlyTrafficSecret := finishedHash.deriveSecret(earlyTrafficLabel)
259		c.earlyExporterSecret = finishedHash.deriveSecret(earlyExporterLabel)
260
261		c.useOutTrafficSecret(encryptionEarlyData, session.wireVersion, session.cipherSuite, earlyTrafficSecret)
262		for _, earlyData := range c.config.Bugs.SendEarlyData {
263			if _, err := c.writeRecord(recordTypeApplicationData, earlyData); err != nil {
264				return err
265			}
266		}
267	}
268
269	msg, err := c.readHandshake()
270	if err != nil {
271		return err
272	}
273
274	if c.isDTLS {
275		helloVerifyRequest, ok := msg.(*helloVerifyRequestMsg)
276		if ok {
277			if helloVerifyRequest.vers != VersionDTLS10 {
278				// Per RFC 6347, the version field in
279				// HelloVerifyRequest SHOULD be always DTLS
280				// 1.0. Enforce this for testing purposes.
281				return errors.New("dtls: bad HelloVerifyRequest version")
282			}
283
284			hs.hello.raw = nil
285			hs.hello.cookie = helloVerifyRequest.cookie
286			c.writeRecord(recordTypeHandshake, hs.hello.marshal())
287			c.flushHandshake()
288
289			if err := c.simulatePacketLoss(nil); err != nil {
290				return err
291			}
292			msg, err = c.readHandshake()
293			if err != nil {
294				return err
295			}
296		}
297	}
298
299	// The first message is either ServerHello or HelloRetryRequest, either of
300	// which determines the version and cipher suite.
301	var serverWireVersion, suiteID uint16
302	switch m := msg.(type) {
303	case *helloRetryRequestMsg:
304		serverWireVersion = m.vers
305		suiteID = m.cipherSuite
306	case *serverHelloMsg:
307		serverWireVersion = m.vers
308		suiteID = m.cipherSuite
309	default:
310		c.sendAlert(alertUnexpectedMessage)
311		return fmt.Errorf("tls: received unexpected message of type %T when waiting for HelloRetryRequest or ServerHello", msg)
312	}
313
314	serverVersion, ok := c.config.isSupportedVersion(serverWireVersion, c.isDTLS)
315	if !ok {
316		c.sendAlert(alertProtocolVersion)
317		return fmt.Errorf("tls: server selected unsupported protocol version %x", c.vers)
318	}
319	c.wireVersion = serverWireVersion
320	c.vers = serverVersion
321	c.haveVers = true
322
323	// We only implement enough of SSL 3.0 to test that the server doesn't:
324	// we can send a ClientHello and attempt to read a ServerHello. The server
325	// should respond with a protocol_version alert and not get this far.
326	if c.vers == VersionSSL30 {
327		return errors.New("tls: server selected SSL 3.0")
328	}
329
330	cipherSuites := hs.hello.cipherSuites
331	if hs.innerHello != nil && c.config.Bugs.MinimalClientHelloOuter {
332		// hs.hello has a placeholder list of ciphers if testing with
333		// MinimalClientHelloOuter, so we use hs.innerHello instead. (We do not
334		// attempt to support actual different cipher suite preferences between
335		// the two.)
336		cipherSuites = hs.innerHello.cipherSuites
337	}
338	hs.suite = mutualCipherSuite(cipherSuites, suiteID)
339	if hs.suite == nil {
340		c.sendAlert(alertHandshakeFailure)
341		return fmt.Errorf("tls: server selected an unsupported cipher suite")
342	}
343
344	hs.finishedHash = newFinishedHash(c.wireVersion, c.isDTLS, hs.suite)
345	hs.finishedHash.WriteHandshake(hs.hello.marshal(), hs.c.sendHandshakeSeq-1)
346
347	if c.vers >= VersionTLS13 {
348		if err := hs.doTLS13Handshake(msg); err != nil {
349			return err
350		}
351	} else {
352		hs.serverHello, ok = msg.(*serverHelloMsg)
353		if !ok {
354			c.sendAlert(alertUnexpectedMessage)
355			return unexpectedMessageError(hs.serverHello, msg)
356		}
357		if isAllZero(hs.serverHello.random) {
358			// If the server forgets to fill in the server random, it will
359			// likely be all zero.
360			return errors.New("tls: ServerHello random was all zero")
361		}
362
363		hs.writeServerHash(hs.serverHello.marshal())
364		if c.config.Bugs.EarlyChangeCipherSpec > 0 {
365			hs.establishKeys()
366			c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
367		}
368
369		if hs.serverHello.compressionMethod != compressionNone {
370			c.sendAlert(alertUnexpectedMessage)
371			return errors.New("tls: server selected unsupported compression format")
372		}
373
374		err = hs.processServerExtensions(&hs.serverHello.extensions)
375		if err != nil {
376			return err
377		}
378
379		isResume, err := hs.processServerHello()
380		if err != nil {
381			return err
382		}
383
384		if isResume {
385			if c.config.Bugs.EarlyChangeCipherSpec == 0 {
386				if err := hs.establishKeys(); err != nil {
387					return err
388				}
389			}
390			if err := hs.readSessionTicket(); err != nil {
391				return err
392			}
393			if err := hs.readFinished(c.firstFinished[:]); err != nil {
394				return err
395			}
396			if err := hs.sendFinished(nil, isResume); err != nil {
397				return err
398			}
399		} else {
400			if err := hs.doFullHandshake(); err != nil {
401				return err
402			}
403			if err := hs.establishKeys(); err != nil {
404				return err
405			}
406			if err := hs.sendFinished(c.firstFinished[:], isResume); err != nil {
407				return err
408			}
409			// Most retransmits are triggered by a timeout, but the final
410			// leg of the handshake is retransmited upon re-receiving a
411			// Finished.
412			if err := c.simulatePacketLoss(func() {
413				c.sendHandshakeSeq--
414				c.writeRecord(recordTypeHandshake, hs.finishedBytes)
415				c.flushHandshake()
416			}); err != nil {
417				return err
418			}
419			if err := hs.readSessionTicket(); err != nil {
420				return err
421			}
422			if err := hs.readFinished(nil); err != nil {
423				return err
424			}
425		}
426
427		if sessionCache != nil && hs.session != nil && session != hs.session {
428			if c.config.Bugs.RequireSessionTickets && len(hs.session.sessionTicket) == 0 {
429				return errors.New("tls: new session used session IDs instead of tickets")
430			}
431			if c.config.Bugs.RequireSessionIDs && len(hs.session.sessionID) == 0 {
432				return errors.New("tls: new session used session tickets instead of IDs")
433			}
434			sessionCache.Put(cacheKey, hs.session)
435		}
436
437		c.didResume = isResume
438		c.exporterSecret = hs.masterSecret
439	}
440
441	c.handshakeComplete = true
442	c.cipherSuite = hs.suite
443	copy(c.clientRandom[:], hs.hello.random)
444	copy(c.serverRandom[:], hs.serverHello.random)
445
446	return nil
447}
448
449func chooseECHCipherSuite(echConfig *ECHConfig, config *Config) (HPKECipherSuite, bool) {
450	if echConfig.KEM != hpke.X25519WithHKDFSHA256 {
451		return HPKECipherSuite{}, false
452	}
453
454	for _, wantSuite := range config.echCipherSuitePreferences() {
455		if config.Bugs.IgnoreECHConfigCipherPreferences {
456			return wantSuite, true
457		}
458		for _, cipherSuite := range echConfig.CipherSuites {
459			if cipherSuite == wantSuite {
460				return cipherSuite, true
461			}
462		}
463	}
464	return HPKECipherSuite{}, false
465}
466
467// createClientHello creates a new ClientHello message. If |innerHello| is not
468// nil, this is a ClientHelloOuter that should contain an encrypted |innerHello|
469// with |echEnc| as the encapsulated public key. Otherwise, the ClientHello
470// should reflect the connection's true preferences.
471func (hs *clientHandshakeState) createClientHello(innerHello *clientHelloMsg, echEnc []byte) (*clientHelloMsg, error) {
472	c := hs.c
473	nextProtosLength := 0
474	for _, proto := range c.config.NextProtos {
475		if l := len(proto); l > 255 {
476			return nil, errors.New("tls: invalid NextProtos value")
477		} else {
478			nextProtosLength += 1 + l
479		}
480	}
481	if nextProtosLength > 0xffff {
482		return nil, errors.New("tls: NextProtos values too large")
483	}
484
485	quicTransportParams := c.config.QUICTransportParams
486	quicTransportParamsLegacy := c.config.QUICTransportParams
487	if !c.config.QUICTransportParamsUseLegacyCodepoint.IncludeStandard() {
488		quicTransportParams = nil
489	}
490	if !c.config.QUICTransportParamsUseLegacyCodepoint.IncludeLegacy() {
491		quicTransportParamsLegacy = nil
492	}
493
494	isInner := innerHello == nil && hs.echHPKEContext != nil
495
496	minVersion := c.config.minVersion(c.isDTLS)
497	maxVersion := c.config.maxVersion(c.isDTLS)
498	// The ClientHelloInner may not offer TLS 1.2 or below.
499	requireTLS13 := isInner && !c.config.Bugs.AllowTLS12InClientHelloInner
500	if requireTLS13 && minVersion < VersionTLS13 {
501		minVersion = VersionTLS13
502		if minVersion > maxVersion {
503			return nil, errors.New("tls: ECH requires TLS 1.3")
504		}
505	}
506
507	hello := &clientHelloMsg{
508		isDTLS:                    c.isDTLS,
509		compressionMethods:        []uint8{compressionNone},
510		random:                    make([]byte, 32),
511		ocspStapling:              !c.config.Bugs.NoOCSPStapling,
512		sctListSupported:          !c.config.Bugs.NoSignedCertificateTimestamps,
513		supportedCurves:           c.config.curvePreferences(),
514		supportedPoints:           []uint8{pointFormatUncompressed},
515		nextProtoNeg:              len(c.config.NextProtos) > 0,
516		secureRenegotiation:       []byte{},
517		alpnProtocols:             c.config.NextProtos,
518		quicTransportParams:       quicTransportParams,
519		quicTransportParamsLegacy: quicTransportParamsLegacy,
520		duplicateExtension:        c.config.Bugs.DuplicateExtension,
521		channelIDSupported:        c.config.ChannelID != nil,
522		extendedMasterSecret:      maxVersion >= VersionTLS10,
523		srtpProtectionProfiles:    c.config.SRTPProtectionProfiles,
524		srtpMasterKeyIdentifier:   c.config.Bugs.SRTPMasterKeyIdentifier,
525		customExtension:           c.config.Bugs.CustomExtension,
526		omitExtensions:            c.config.Bugs.OmitExtensions,
527		emptyExtensions:           c.config.Bugs.EmptyExtensions,
528		delegatedCredential:       c.config.DelegatedCredentialAlgorithms,
529	}
530
531	// Translate the bugs that modify ClientHello extension order into a
532	// list of prefix extensions. The marshal function will try these
533	// extensions before any others, followed by any remaining extensions in
534	// the default order.
535	if c.config.Bugs.PSKBinderFirst && !c.config.Bugs.OnlyCorruptSecondPSKBinder {
536		hello.prefixExtensions = append(hello.prefixExtensions, extensionPreSharedKey)
537	}
538	if c.config.Bugs.SwapNPNAndALPN {
539		hello.prefixExtensions = append(hello.prefixExtensions, extensionALPN)
540		hello.prefixExtensions = append(hello.prefixExtensions, extensionNextProtoNeg)
541	}
542
543	// Configure ech_outer_extensions.
544	if isInner {
545		hello.outerExtensions = c.config.ECHOuterExtensions
546		// If |OnlyCompressSecondClientHelloInner| is set, we still configure
547		// |hello.outerExtensions| for ordering, so that we do not introduce an
548		// unsolicited change across HelloRetryRequest.
549		hello.reorderOuterExtensionsWithoutCompressing = c.config.Bugs.OnlyCompressSecondClientHelloInner
550	} else {
551		// Compressed extensions must appear in the same relative order between
552		// ClientHelloInner and ClientHelloOuter. For simplicity, we default to
553		// forcing their order to match, but the caller can override this with
554		// either valid or invalid explicit orders.
555		if c.config.Bugs.ECHOuterExtensionOrder != nil {
556			hello.prefixExtensions = append(hello.prefixExtensions, c.config.Bugs.ECHOuterExtensionOrder...)
557		} else {
558			hello.prefixExtensions = append(hello.prefixExtensions, c.config.ECHOuterExtensions...)
559		}
560	}
561
562	if maxVersion >= VersionTLS13 {
563		hello.vers = mapClientHelloVersion(VersionTLS12, c.isDTLS)
564		if !c.config.Bugs.OmitSupportedVersions {
565			hello.supportedVersions = c.config.supportedVersions(c.isDTLS, requireTLS13)
566		}
567		hello.pskKEModes = []byte{pskDHEKEMode}
568	} else {
569		hello.vers = mapClientHelloVersion(maxVersion, c.isDTLS)
570	}
571
572	if c.config.Bugs.SendClientVersion != 0 {
573		hello.vers = c.config.Bugs.SendClientVersion
574	}
575
576	if len(c.config.Bugs.SendSupportedVersions) > 0 {
577		hello.supportedVersions = c.config.Bugs.SendSupportedVersions
578	}
579
580	if innerHello != nil {
581		hello.serverName = c.config.ClientECHConfig.PublicName
582	} else {
583		hello.serverName = c.config.ServerName
584	}
585
586	if !isInner && c.config.Bugs.OmitPublicName {
587		hello.serverName = ""
588	}
589
590	disableEMS := c.config.Bugs.NoExtendedMasterSecret
591	if c.cipherSuite != nil {
592		disableEMS = c.config.Bugs.NoExtendedMasterSecretOnRenegotiation
593	}
594
595	if disableEMS {
596		hello.extendedMasterSecret = false
597	}
598
599	if c.config.Bugs.NoSupportedCurves {
600		hello.supportedCurves = nil
601	}
602
603	if c.config.Bugs.SendPSKKeyExchangeModes != nil {
604		hello.pskKEModes = c.config.Bugs.SendPSKKeyExchangeModes
605	}
606
607	if c.config.Bugs.SendCompressionMethods != nil {
608		hello.compressionMethods = c.config.Bugs.SendCompressionMethods
609	}
610
611	if c.config.Bugs.SendSupportedPointFormats != nil {
612		hello.supportedPoints = c.config.Bugs.SendSupportedPointFormats
613	}
614
615	if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
616		if c.config.Bugs.BadRenegotiationInfo {
617			hello.secureRenegotiation = append(hello.secureRenegotiation, c.clientVerify...)
618			hello.secureRenegotiation[0] ^= 0x80
619		} else {
620			hello.secureRenegotiation = c.clientVerify
621		}
622	}
623
624	if c.config.Bugs.DuplicateCompressedCertAlgs {
625		hello.compressedCertAlgs = []uint16{1, 1}
626	} else if len(c.config.CertCompressionAlgs) > 0 {
627		hello.compressedCertAlgs = make([]uint16, 0, len(c.config.CertCompressionAlgs))
628		for id := range c.config.CertCompressionAlgs {
629			hello.compressedCertAlgs = append(hello.compressedCertAlgs, uint16(id))
630		}
631	}
632
633	if c.noRenegotiationInfo() {
634		hello.secureRenegotiation = nil
635	}
636
637	if c.config.ALPSUseNewCodepoint.IncludeNew() {
638		for protocol := range c.config.ApplicationSettings {
639			hello.alpsProtocols = append(hello.alpsProtocols, protocol)
640		}
641	}
642	if c.config.ALPSUseNewCodepoint.IncludeOld() {
643		for protocol := range c.config.ApplicationSettings {
644			hello.alpsProtocolsOld = append(hello.alpsProtocolsOld, protocol)
645		}
646	}
647
648	if maxVersion >= VersionTLS13 {
649		// Use the same key shares between ClientHelloInner and ClientHelloOuter.
650		if innerHello != nil {
651			hello.hasKeyShares = innerHello.hasKeyShares
652			hello.keyShares = innerHello.keyShares
653		} else {
654			hello.hasKeyShares = true
655			hello.trailingKeyShareData = c.config.Bugs.TrailingKeyShareData
656			curvesToSend := c.config.defaultCurves()
657			for _, curveID := range hello.supportedCurves {
658				if !curvesToSend[curveID] {
659					continue
660				}
661				kem, ok := kemForCurveID(curveID, c.config)
662				if !ok {
663					continue
664				}
665				publicKey, err := kem.generate(c.config.rand())
666				if err != nil {
667					return nil, err
668				}
669
670				if c.config.Bugs.SendCurve != 0 {
671					curveID = c.config.Bugs.SendCurve
672				}
673				if c.config.Bugs.InvalidECDHPoint {
674					publicKey[0] ^= 0xff
675				}
676
677				hello.keyShares = append(hello.keyShares, keyShareEntry{
678					group:       curveID,
679					keyExchange: publicKey,
680				})
681				hs.keyShares[curveID] = kem
682
683				if c.config.Bugs.DuplicateKeyShares {
684					hello.keyShares = append(hello.keyShares, hello.keyShares[len(hello.keyShares)-1])
685				}
686			}
687
688			if c.config.Bugs.MissingKeyShare {
689				hello.hasKeyShares = false
690			}
691		}
692	}
693
694	possibleCipherSuites := c.config.cipherSuites()
695	hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites))
696
697NextCipherSuite:
698	for _, suiteID := range possibleCipherSuites {
699		for _, suite := range cipherSuites {
700			if suite.id != suiteID {
701				continue
702			}
703			// Don't advertise TLS 1.2-only cipher suites unless
704			// we're attempting TLS 1.2.
705			if maxVersion < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
706				continue
707			}
708			hello.cipherSuites = append(hello.cipherSuites, suiteID)
709			continue NextCipherSuite
710		}
711	}
712
713	if c.config.Bugs.AdvertiseAllConfiguredCiphers {
714		hello.cipherSuites = possibleCipherSuites
715	}
716
717	if c.config.Bugs.SendRenegotiationSCSV {
718		hello.cipherSuites = append(hello.cipherSuites, renegotiationSCSV)
719	}
720
721	if c.config.Bugs.SendFallbackSCSV {
722		hello.cipherSuites = append(hello.cipherSuites, fallbackSCSV)
723	}
724
725	_, err := io.ReadFull(c.config.rand(), hello.random)
726	if err != nil {
727		c.sendAlert(alertInternalError)
728		return nil, errors.New("tls: short read from Rand: " + err.Error())
729	}
730
731	if maxVersion >= VersionTLS12 && !c.config.Bugs.NoSignatureAlgorithms {
732		hello.signatureAlgorithms = c.config.verifySignatureAlgorithms()
733	}
734
735	if c.config.ClientSessionCache != nil {
736		hello.ticketSupported = !c.config.SessionTicketsDisabled
737	}
738
739	session := hs.session
740
741	// ClientHelloOuter cannot offer sessions.
742	if innerHello != nil && !c.config.Bugs.OfferSessionInClientHelloOuter {
743		session = nil
744	}
745
746	if session != nil && c.config.time().Before(session.ticketExpiration) {
747		ticket := session.sessionTicket
748		if c.config.Bugs.FilterTicket != nil && len(ticket) > 0 {
749			// Copy the ticket so FilterTicket may act in-place.
750			ticket = make([]byte, len(session.sessionTicket))
751			copy(ticket, session.sessionTicket)
752
753			ticket, err = c.config.Bugs.FilterTicket(ticket)
754			if err != nil {
755				return nil, err
756			}
757		}
758
759		if session.vers >= VersionTLS13 || c.config.Bugs.SendBothTickets {
760			// TODO(nharper): Support sending more
761			// than one PSK identity.
762			ticketAge := uint32(c.config.time().Sub(session.ticketCreationTime) / time.Millisecond)
763			if c.config.Bugs.SendTicketAge != 0 {
764				ticketAge = uint32(c.config.Bugs.SendTicketAge / time.Millisecond)
765			}
766			psk := pskIdentity{
767				ticket:              ticket,
768				obfuscatedTicketAge: session.ticketAgeAdd + ticketAge,
769			}
770			hello.pskIdentities = []pskIdentity{psk}
771
772			if c.config.Bugs.ExtraPSKIdentity {
773				hello.pskIdentities = append(hello.pskIdentities, psk)
774			}
775		}
776
777		if session.vers < VersionTLS13 || c.config.Bugs.SendBothTickets {
778			if ticket != nil {
779				hello.sessionTicket = ticket
780				// A random session ID is used to detect when the
781				// server accepted the ticket and is resuming a session
782				// (see RFC 5077).
783				sessionIDLen := 16
784				if c.config.Bugs.TicketSessionIDLength != 0 {
785					sessionIDLen = c.config.Bugs.TicketSessionIDLength
786				}
787				if c.config.Bugs.EmptyTicketSessionID {
788					sessionIDLen = 0
789				}
790				hello.sessionID = make([]byte, sessionIDLen)
791				if _, err := io.ReadFull(c.config.rand(), hello.sessionID); err != nil {
792					c.sendAlert(alertInternalError)
793					return nil, errors.New("tls: short read from Rand: " + err.Error())
794				}
795			} else {
796				hello.sessionID = session.sessionID
797			}
798		}
799	}
800
801	if innerHello == nil {
802		// Request compatibility mode from the client by sending a fake session
803		// ID. Although BoringSSL always enables compatibility mode, other
804		// implementations make it conditional on the ClientHello. We test
805		// BoringSSL's expected behavior with SendClientHelloSessionID.
806		if len(hello.sessionID) == 0 && maxVersion >= VersionTLS13 {
807			hello.sessionID = make([]byte, 32)
808			if _, err := io.ReadFull(c.config.rand(), hello.sessionID); err != nil {
809				c.sendAlert(alertInternalError)
810				return nil, errors.New("tls: short read from Rand: " + err.Error())
811			}
812		}
813		if c.config.Bugs.MockQUICTransport != nil && !c.config.Bugs.CompatModeWithQUIC {
814			hello.sessionID = []byte{}
815		}
816		if c.config.Bugs.SendClientHelloSessionID != nil {
817			hello.sessionID = c.config.Bugs.SendClientHelloSessionID
818		}
819	} else {
820		// ClientHelloOuter's session ID is copied from ClientHelloINnner.
821		hello.sessionID = innerHello.sessionID
822	}
823
824	if c.config.Bugs.SendCipherSuites != nil {
825		hello.cipherSuites = c.config.Bugs.SendCipherSuites
826	}
827
828	if innerHello == nil {
829		if len(hello.pskIdentities) > 0 && c.config.Bugs.SendEarlyData != nil {
830			hello.hasEarlyData = true
831		}
832		if c.config.Bugs.SendFakeEarlyDataLength > 0 {
833			hello.hasEarlyData = true
834		}
835		if c.config.Bugs.OmitEarlyDataExtension {
836			hello.hasEarlyData = false
837		}
838	} else {
839		hello.hasEarlyData = innerHello.hasEarlyData
840	}
841
842	if (isInner && !c.config.Bugs.OmitECHInner) || c.config.Bugs.AlwaysSendECHInner {
843		hello.echInner = true
844		hello.invalidECHInner = c.config.Bugs.SendInvalidECHInner
845	}
846
847	if innerHello != nil {
848		if err := hs.encryptClientHello(hello, innerHello, c.config.ClientECHConfig.ConfigID, echEnc); err != nil {
849			return nil, err
850		}
851		if c.config.Bugs.CorruptEncryptedClientHello {
852			if c.config.Bugs.NullAllCiphers {
853				hello.echOuter.payload = []byte{echBadPayloadByte}
854			} else {
855				hello.echOuter.payload[0] ^= 1
856			}
857		}
858	}
859
860	// PSK binders and ECH both must be computed last because they incorporate
861	// the rest of the ClientHello and conflict. ECH resolves this by forbidding
862	// clients from offering PSKs on ClientHelloOuter, but we still need to test
863	// servers handle it correctly so they tolerate GREASE. In other cases, we
864	// expect the server to reject ECH, so we put PSK last. Note this renders
865	// ECH undecryptable.
866	if len(hello.pskIdentities) > 0 {
867		version := session.wireVersion
868		// We may have a pre-1.3 session if SendBothTickets is set.
869		if session.vers < VersionTLS13 {
870			version = VersionTLS13
871		}
872		generatePSKBinders(version, hello, session, nil, nil, c.config)
873	}
874
875	if c.config.Bugs.SendClientHelloWithFixes != nil {
876		hello, err = replaceClientHello(hello, c.config.Bugs.SendClientHelloWithFixes)
877		if err != nil {
878			return nil, err
879		}
880	}
881
882	return hello, nil
883}
884
885// encryptClientHello encrypts |innerHello| using the specified HPKE context and
886// adds the extension to |hello|.
887func (hs *clientHandshakeState) encryptClientHello(hello, innerHello *clientHelloMsg, configID uint8, enc []byte) error {
888	c := hs.c
889
890	if c.config.Bugs.MinimalClientHelloOuter {
891		*hello = clientHelloMsg{
892			vers:               VersionTLS12,
893			random:             hello.random,
894			sessionID:          hello.sessionID,
895			cipherSuites:       []uint16{0x0a0a},
896			compressionMethods: hello.compressionMethods,
897		}
898	}
899
900	if c.config.Bugs.TruncateClientECHEnc {
901		enc = enc[:1]
902	}
903
904	encodedInner := innerHello.marshalForEncodedInner()
905	padding := make([]byte, c.config.Bugs.ClientECHPadding)
906	if c.config.Bugs.BadClientECHPadding {
907		padding[0] = 1
908	}
909	encodedInner = append(encodedInner, padding...)
910
911	// Encode ClientHelloOuter with a placeholder payload string.
912	payloadLength := len(encodedInner)
913	if !c.config.Bugs.NullAllCiphers {
914		payloadLength += hs.echHPKEContext.Overhead()
915	}
916	hello.echOuter = &echClientOuter{
917		kdfID:    hs.echHPKEContext.KDF(),
918		aeadID:   hs.echHPKEContext.AEAD(),
919		configID: configID,
920		enc:      enc,
921		payload:  make([]byte, payloadLength),
922	}
923	aad := hello.marshal()[4:] // Remove message header
924
925	hello.raw = nil
926	hello.echOuter.payload = hs.echHPKEContext.Seal(encodedInner, aad)
927	if c.config.Bugs.NullAllCiphers {
928		hello.echOuter.payload = encodedInner
929	}
930
931	if c.config.Bugs.RecordClientHelloInner != nil {
932		if err := c.config.Bugs.RecordClientHelloInner(encodedInner, hello.marshal()[4:]); err != nil {
933			return err
934		}
935		// ECH is normally the last extension added to |hello|, but, when
936		// OfferSessionInClientHelloOuter is enabled, we may modify it again.
937		hello.raw = nil
938	}
939
940	return nil
941}
942
943func (hs *clientHandshakeState) checkECHConfirmation(msg any, hello *clientHelloMsg, finishedHash *finishedHash) bool {
944	var offset int
945	var raw, label []byte
946	if hrr, ok := msg.(*helloRetryRequestMsg); ok {
947		if hrr.echConfirmationOffset == 0 {
948			return false
949		}
950		raw = hrr.raw
951		label = echAcceptConfirmationHRRLabel
952		offset = hrr.echConfirmationOffset
953	} else {
954		raw = msg.(*serverHelloMsg).raw
955		label = echAcceptConfirmationLabel
956		offset = 4 + 2 + 32 - echAcceptConfirmationLength
957	}
958
959	withZeros := append(make([]byte, 0, len(raw)), raw...)
960	for i := 0; i < echAcceptConfirmationLength; i++ {
961		withZeros[i+offset] = 0
962	}
963
964	confirmation := finishedHash.echAcceptConfirmation(hello.random, label, withZeros)
965	return bytes.Equal(confirmation, raw[offset:offset+echAcceptConfirmationLength])
966}
967
968func (hs *clientHandshakeState) doTLS13Handshake(msg any) error {
969	c := hs.c
970
971	// The first message may be a ServerHello or HelloRetryRequest.
972	helloRetryRequest, haveHelloRetryRequest := msg.(*helloRetryRequestMsg)
973	if haveHelloRetryRequest {
974		hs.finishedHash.UpdateForHelloRetryRequest()
975	}
976
977	// Determine whether the server accepted ECH and drop the unnecessary
978	// transcript.
979	if hs.innerHello != nil {
980		innerFinishedHash := newFinishedHash(c.wireVersion, c.isDTLS, hs.suite)
981		innerFinishedHash.WriteHandshake(hs.innerHello.marshal(), hs.c.sendHandshakeSeq-1)
982		if haveHelloRetryRequest {
983			innerFinishedHash.UpdateForHelloRetryRequest()
984		}
985		if hs.checkECHConfirmation(msg, hs.innerHello, &innerFinishedHash) {
986			c.echAccepted = true
987			// Replace the transcript. For now, leave hs.hello and hs.innerHello
988			// as-is. HelloRetryRequest requires both be available.
989			hs.finishedHash = innerFinishedHash
990		}
991	} else {
992		// When not offering ECH, test that the backend server does not (or does)
993		// send a confirmation as expected.
994		confirmed := hs.checkECHConfirmation(msg, hs.hello, &hs.finishedHash)
995		if hs.hello.echInner && !confirmed {
996			return fmt.Errorf("tls: server did not send ECH confirmation in %T when requested", msg)
997		} else if !hs.hello.echInner && confirmed {
998			return fmt.Errorf("tls: server sent ECH confirmation in %T when not requested", msg)
999		}
1000	}
1001
1002	// Once the PRF hash is known, TLS 1.3 does not require a handshake buffer.
1003	hs.finishedHash.discardHandshakeBuffer()
1004
1005	// The first server message must be followed by a ChangeCipherSpec.
1006	c.expectTLS13ChangeCipherSpec = true
1007
1008	if haveHelloRetryRequest {
1009		hs.writeServerHash(helloRetryRequest.marshal())
1010
1011		if !bytes.Equal(hs.hello.sessionID, helloRetryRequest.sessionID) {
1012			return errors.New("tls: ClientHello and HelloRetryRequest session IDs did not match.")
1013		}
1014
1015		if c.config.Bugs.FailIfHelloRetryRequested {
1016			return errors.New("tls: unexpected HelloRetryRequest")
1017		}
1018		// Explicitly read the ChangeCipherSpec now; it should
1019		// be attached to the first flight, not the second flight.
1020		if err := c.readTLS13ChangeCipherSpec(); err != nil {
1021			return err
1022		}
1023
1024		// Reset the encryption state, in case we sent 0-RTT data.
1025		c.out.resetCipher()
1026
1027		if c.echAccepted {
1028			if err := hs.applyHelloRetryRequest(helloRetryRequest, hs.innerHello, hs.hello); err != nil {
1029				return err
1030			}
1031			hs.writeClientHash(hs.innerHello.marshal())
1032		} else {
1033			if err := hs.applyHelloRetryRequest(helloRetryRequest, hs.hello, nil); err != nil {
1034				return err
1035			}
1036			hs.writeClientHash(hs.hello.marshal())
1037		}
1038		toWrite := hs.hello.marshal()
1039
1040		if c.config.Bugs.PartialSecondClientHelloAfterFirst {
1041			// The first byte has already been sent.
1042			toWrite = toWrite[1:]
1043		}
1044
1045		if c.config.Bugs.InterleaveEarlyData {
1046			c.sendFakeEarlyData(4)
1047			c.writeRecord(recordTypeHandshake, toWrite[:16])
1048			c.sendFakeEarlyData(4)
1049			c.writeRecord(recordTypeHandshake, toWrite[16:])
1050		} else if c.config.Bugs.PartialClientFinishedWithSecondClientHello {
1051			toWrite = append(make([]byte, 0, len(toWrite)+1), toWrite...)
1052			toWrite = append(toWrite, typeFinished)
1053			c.writeRecord(recordTypeHandshake, toWrite)
1054		} else {
1055			c.writeRecord(recordTypeHandshake, toWrite)
1056		}
1057		c.flushHandshake()
1058
1059		if c.config.Bugs.SendEarlyDataOnSecondClientHello {
1060			c.sendFakeEarlyData(4)
1061		}
1062
1063		var err error
1064		msg, err = c.readHandshake()
1065		if err != nil {
1066			return err
1067		}
1068	}
1069
1070	// We no longer need to retain two ClientHellos.
1071	if c.echAccepted {
1072		hs.hello = hs.innerHello
1073	}
1074	hs.innerHello = nil
1075
1076	var ok bool
1077	hs.serverHello, ok = msg.(*serverHelloMsg)
1078	if !ok {
1079		c.sendAlert(alertUnexpectedMessage)
1080		return unexpectedMessageError(hs.serverHello, msg)
1081	}
1082
1083	if isAllZero(hs.serverHello.random) {
1084		// If the server forgets to fill in the server random, it will
1085		// likely be all zero.
1086		return errors.New("tls: ServerHello random was all zero")
1087	}
1088
1089	if c.wireVersion != hs.serverHello.vers {
1090		c.sendAlert(alertIllegalParameter)
1091		return fmt.Errorf("tls: server sent non-matching version %x vs %x", c.wireVersion, hs.serverHello.vers)
1092	}
1093
1094	if hs.suite.id != hs.serverHello.cipherSuite {
1095		c.sendAlert(alertIllegalParameter)
1096		return fmt.Errorf("tls: server sent non-matching cipher suite %04x vs %04x", hs.suite.id, hs.serverHello.cipherSuite)
1097	}
1098
1099	if haveHelloRetryRequest {
1100		if helloRetryRequest.hasSelectedGroup && helloRetryRequest.selectedGroup != hs.serverHello.keyShare.group {
1101			c.sendAlert(alertHandshakeFailure)
1102			return errors.New("tls: ServerHello parameters did not match HelloRetryRequest")
1103		}
1104
1105		// Both the ServerHello and HelloRetryRequest must have an ECH confirmation.
1106		echConfirmed := hs.checkECHConfirmation(hs.serverHello, hs.hello, &hs.finishedHash)
1107		if hs.hello.echInner && !echConfirmed {
1108			return errors.New("tls: server did not send ECH confirmation in ServerHello when requested")
1109		} else if !hs.hello.echInner && echConfirmed {
1110			return errors.New("tls: server sent ECH confirmation in ServerHello when not requested")
1111		}
1112	}
1113
1114	if !bytes.Equal(hs.hello.sessionID, hs.serverHello.sessionID) {
1115		return errors.New("tls: ClientHello and ServerHello session IDs did not match.")
1116	}
1117
1118	// Resolve PSK and compute the early secret.
1119	zeroSecret := hs.finishedHash.zeroSecret()
1120	pskSecret := zeroSecret
1121	if hs.serverHello.hasPSKIdentity {
1122		// We send at most one PSK identity.
1123		if hs.session == nil || hs.serverHello.pskIdentity != 0 {
1124			c.sendAlert(alertUnknownPSKIdentity)
1125			return errors.New("tls: server sent unknown PSK identity")
1126		}
1127		if hs.session.cipherSuite.hash() != hs.suite.hash() {
1128			c.sendAlert(alertHandshakeFailure)
1129			return errors.New("tls: server resumed an invalid session for the cipher suite")
1130		}
1131		pskSecret = hs.session.secret
1132		c.didResume = true
1133	}
1134	hs.finishedHash.addEntropy(pskSecret)
1135
1136	if !hs.serverHello.hasKeyShare {
1137		c.sendAlert(alertUnsupportedExtension)
1138		return errors.New("tls: server omitted KeyShare on resumption.")
1139	}
1140
1141	// Resolve ECDHE and compute the handshake secret.
1142	ecdheSecret := zeroSecret
1143	if !c.config.Bugs.MissingKeyShare && !c.config.Bugs.SecondClientHelloMissingKeyShare {
1144		kem, ok := hs.keyShares[hs.serverHello.keyShare.group]
1145		if !ok {
1146			c.sendAlert(alertHandshakeFailure)
1147			return errors.New("tls: server selected an unsupported group")
1148		}
1149		c.curveID = hs.serverHello.keyShare.group
1150
1151		var err error
1152		ecdheSecret, err = kem.decap(hs.serverHello.keyShare.keyExchange)
1153		if err != nil {
1154			return err
1155		}
1156	}
1157	hs.finishedHash.nextSecret()
1158	hs.finishedHash.addEntropy(ecdheSecret)
1159	hs.writeServerHash(hs.serverHello.marshal())
1160
1161	// Derive handshake traffic keys and switch read key to handshake
1162	// traffic key.
1163	clientHandshakeTrafficSecret := hs.finishedHash.deriveSecret(clientHandshakeTrafficLabel)
1164	serverHandshakeTrafficSecret := hs.finishedHash.deriveSecret(serverHandshakeTrafficLabel)
1165	if err := c.useInTrafficSecret(encryptionHandshake, c.wireVersion, hs.suite, serverHandshakeTrafficSecret); err != nil {
1166		return err
1167	}
1168
1169	msg, err := c.readHandshake()
1170	if err != nil {
1171		return err
1172	}
1173
1174	encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
1175	if !ok {
1176		c.sendAlert(alertUnexpectedMessage)
1177		return unexpectedMessageError(encryptedExtensions, msg)
1178	}
1179	hs.writeServerHash(encryptedExtensions.marshal())
1180
1181	if !bytes.Equal(encryptedExtensions.extensions.echRetryConfigs, c.config.Bugs.ExpectECHRetryConfigs) {
1182		return errors.New("tls: server sent ECH retry_configs with unexpected contents")
1183	}
1184
1185	err = hs.processServerExtensions(&encryptedExtensions.extensions)
1186	if err != nil {
1187		return err
1188	}
1189
1190	var credential *Credential
1191	var certReq *certificateRequestMsg
1192	if c.didResume {
1193		// Copy over authentication from the session.
1194		c.peerCertificates = hs.session.serverCertificates
1195		c.sctList = hs.session.sctList
1196		c.ocspResponse = hs.session.ocspResponse
1197	} else {
1198		msg, err := c.readHandshake()
1199		if err != nil {
1200			return err
1201		}
1202
1203		var ok bool
1204		certReq, ok = msg.(*certificateRequestMsg)
1205		if ok {
1206			if len(certReq.requestContext) != 0 {
1207				return errors.New("tls: non-empty certificate request context sent in handshake")
1208			}
1209
1210			if c.config.Bugs.ExpectNoCertificateAuthoritiesExtension && certReq.hasCAExtension {
1211				return errors.New("tls: expected no certificate_authorities extension")
1212			}
1213
1214			hs.writeServerHash(certReq.marshal())
1215
1216			credential = c.config.Credential
1217			if credential != nil && c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
1218				certReq.signatureAlgorithms = credential.signatureAlgorithms()
1219			}
1220
1221			msg, err = c.readHandshake()
1222			if err != nil {
1223				return err
1224			}
1225		}
1226
1227		var certMsg *certificateMsg
1228
1229		if compressedCertMsg, ok := msg.(*compressedCertificateMsg); ok {
1230			hs.writeServerHash(compressedCertMsg.marshal())
1231
1232			alg, ok := c.config.CertCompressionAlgs[compressedCertMsg.algID]
1233			if !ok {
1234				c.sendAlert(alertBadCertificate)
1235				return fmt.Errorf("tls: received certificate compressed with unknown algorithm %x", compressedCertMsg.algID)
1236			}
1237
1238			decompressed := make([]byte, 4+int(compressedCertMsg.uncompressedLength))
1239			if !alg.Decompress(decompressed[4:], compressedCertMsg.compressed) {
1240				c.sendAlert(alertBadCertificate)
1241				return fmt.Errorf("tls: failed to decompress certificate with algorithm %x", compressedCertMsg.algID)
1242			}
1243
1244			certMsg = &certificateMsg{
1245				hasRequestContext: true,
1246			}
1247
1248			if !certMsg.unmarshal(decompressed) {
1249				c.sendAlert(alertBadCertificate)
1250				return errors.New("tls: failed to parse decompressed certificate")
1251			}
1252
1253			if expected := c.config.Bugs.ExpectedCompressedCert; expected != 0 && expected != compressedCertMsg.algID {
1254				return fmt.Errorf("tls: expected certificate compressed with algorithm %x, but message used %x", expected, compressedCertMsg.algID)
1255			}
1256
1257			if c.config.Bugs.ExpectUncompressedCert {
1258				return errors.New("tls: compressed certificate received")
1259			}
1260		} else {
1261			if certMsg, ok = msg.(*certificateMsg); !ok {
1262				c.sendAlert(alertUnexpectedMessage)
1263				return unexpectedMessageError(certMsg, msg)
1264			}
1265			hs.writeServerHash(certMsg.marshal())
1266
1267			if c.config.Bugs.ExpectedCompressedCert != 0 {
1268				return errors.New("tls: uncompressed certificate received")
1269			}
1270		}
1271
1272		// Check for unsolicited extensions.
1273		for i, cert := range certMsg.certificates {
1274			if c.config.Bugs.NoOCSPStapling && cert.ocspResponse != nil {
1275				c.sendAlert(alertUnsupportedExtension)
1276				return errors.New("tls: unexpected OCSP response in the server certificate")
1277			}
1278			if c.config.Bugs.NoSignedCertificateTimestamps && cert.sctList != nil {
1279				c.sendAlert(alertUnsupportedExtension)
1280				return errors.New("tls: unexpected SCT list in the server certificate")
1281			}
1282			if i > 0 && c.config.Bugs.ExpectNoExtensionsOnIntermediate && (cert.ocspResponse != nil || cert.sctList != nil) {
1283				c.sendAlert(alertUnsupportedExtension)
1284				return errors.New("tls: unexpected extensions in the server certificate")
1285			}
1286		}
1287
1288		if err := hs.verifyCertificates(certMsg); err != nil {
1289			return err
1290		}
1291		c.ocspResponse = certMsg.certificates[0].ocspResponse
1292		c.sctList = certMsg.certificates[0].sctList
1293
1294		msg, err = c.readHandshake()
1295		if err != nil {
1296			return err
1297		}
1298		certVerifyMsg, ok := msg.(*certificateVerifyMsg)
1299		if !ok {
1300			c.sendAlert(alertUnexpectedMessage)
1301			return unexpectedMessageError(certVerifyMsg, msg)
1302		}
1303
1304		c.peerSignatureAlgorithm = certVerifyMsg.signatureAlgorithm
1305		input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13)
1306		if c.peerDelegatedCredential != nil {
1307			err = verifyMessageDC(c.isClient, c.vers, hs.peerPublicKey, c.config, certVerifyMsg.signatureAlgorithm, input, certVerifyMsg.signature)
1308		} else {
1309			err = verifyMessage(c.isClient, c.vers, hs.peerPublicKey, c.config, certVerifyMsg.signatureAlgorithm, input, certVerifyMsg.signature)
1310		}
1311		if err != nil {
1312			return err
1313		}
1314
1315		hs.writeServerHash(certVerifyMsg.marshal())
1316	}
1317
1318	msg, err = c.readHandshake()
1319	if err != nil {
1320		return err
1321	}
1322	serverFinished, ok := msg.(*finishedMsg)
1323	if !ok {
1324		c.sendAlert(alertUnexpectedMessage)
1325		return unexpectedMessageError(serverFinished, msg)
1326	}
1327
1328	verify := hs.finishedHash.serverSum(serverHandshakeTrafficSecret)
1329	if len(verify) != len(serverFinished.verifyData) ||
1330		subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
1331		c.sendAlert(alertHandshakeFailure)
1332		return errors.New("tls: server's Finished message was incorrect")
1333	}
1334
1335	hs.writeServerHash(serverFinished.marshal())
1336
1337	// The various secrets do not incorporate the client's final leg, so
1338	// derive them now before updating the handshake context.
1339	hs.finishedHash.nextSecret()
1340	hs.finishedHash.addEntropy(zeroSecret)
1341
1342	clientTrafficSecret := hs.finishedHash.deriveSecret(clientApplicationTrafficLabel)
1343	serverTrafficSecret := hs.finishedHash.deriveSecret(serverApplicationTrafficLabel)
1344	c.exporterSecret = hs.finishedHash.deriveSecret(exporterLabel)
1345
1346	// Switch to application data keys on read. In particular, any alerts
1347	// from the client certificate are read over these keys.
1348	if err := c.useInTrafficSecret(encryptionApplication, c.wireVersion, hs.suite, serverTrafficSecret); err != nil {
1349		return err
1350	}
1351
1352	// If we're expecting 0.5-RTT messages from the server, read them now.
1353	var deferredTickets []*newSessionTicketMsg
1354	if encryptedExtensions.extensions.hasEarlyData {
1355		// BoringSSL will always send two tickets half-RTT when
1356		// negotiating 0-RTT.
1357		for i := 0; i < shimConfig.HalfRTTTickets; i++ {
1358			msg, err := c.readHandshake()
1359			if err != nil {
1360				return fmt.Errorf("tls: error reading half-RTT ticket: %s", err)
1361			}
1362			newSessionTicket, ok := msg.(*newSessionTicketMsg)
1363			if !ok {
1364				return errors.New("tls: expected half-RTT ticket")
1365			}
1366			// Defer processing until the resumption secret is computed.
1367			deferredTickets = append(deferredTickets, newSessionTicket)
1368		}
1369		for _, expectedMsg := range c.config.Bugs.ExpectHalfRTTData {
1370			if err := c.readRecord(recordTypeApplicationData); err != nil {
1371				return err
1372			}
1373			if !bytes.Equal(c.input.data[c.input.off:], expectedMsg) {
1374				return errors.New("ExpectHalfRTTData: did not get expected message")
1375			}
1376			c.in.freeBlock(c.input)
1377			c.input = nil
1378		}
1379	}
1380
1381	// Send EndOfEarlyData and then switch write key to handshake
1382	// traffic key.
1383	if encryptedExtensions.extensions.hasEarlyData && !c.config.Bugs.SkipEndOfEarlyData && c.config.Bugs.MockQUICTransport == nil {
1384		if c.config.Bugs.SendStrayEarlyHandshake {
1385			helloRequest := new(helloRequestMsg)
1386			c.writeRecord(recordTypeHandshake, helloRequest.marshal())
1387		}
1388		endOfEarlyData := new(endOfEarlyDataMsg)
1389		endOfEarlyData.nonEmpty = c.config.Bugs.NonEmptyEndOfEarlyData
1390		hs.writeClientHash(endOfEarlyData.marshal())
1391		if c.config.Bugs.PartialEndOfEarlyDataWithClientHello {
1392			// The first byte has already been sent.
1393			c.writeRecord(recordTypeHandshake, endOfEarlyData.marshal()[1:])
1394		} else {
1395			c.writeRecord(recordTypeHandshake, endOfEarlyData.marshal())
1396		}
1397	}
1398
1399	if !c.config.Bugs.SkipChangeCipherSpec && !hs.hello.hasEarlyData {
1400		c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
1401	}
1402
1403	for i := 0; i < c.config.Bugs.SendExtraChangeCipherSpec; i++ {
1404		c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
1405	}
1406
1407	c.useOutTrafficSecret(encryptionHandshake, c.wireVersion, hs.suite, clientHandshakeTrafficSecret)
1408
1409	// The client EncryptedExtensions message is sent if some extension uses it.
1410	// (Currently only ALPS does.)
1411	hasEncryptedExtensions := c.config.Bugs.AlwaysSendClientEncryptedExtensions
1412	clientEncryptedExtensions := new(clientEncryptedExtensionsMsg)
1413	if encryptedExtensions.extensions.hasApplicationSettings || (c.config.Bugs.SendApplicationSettingsWithEarlyData && c.hasApplicationSettings) {
1414		hasEncryptedExtensions = true
1415		if !c.config.Bugs.OmitClientApplicationSettings {
1416			clientEncryptedExtensions.hasApplicationSettings = true
1417			clientEncryptedExtensions.applicationSettings = c.localApplicationSettings
1418		}
1419	}
1420	if encryptedExtensions.extensions.hasApplicationSettingsOld || (c.config.Bugs.SendApplicationSettingsWithEarlyData && c.hasApplicationSettingsOld) {
1421		hasEncryptedExtensions = true
1422		if !c.config.Bugs.OmitClientApplicationSettings {
1423			clientEncryptedExtensions.hasApplicationSettingsOld = true
1424			clientEncryptedExtensions.applicationSettingsOld = c.localApplicationSettingsOld
1425		}
1426	}
1427	if c.config.Bugs.SendExtraClientEncryptedExtension {
1428		hasEncryptedExtensions = true
1429		clientEncryptedExtensions.customExtension = []byte{0}
1430	}
1431	if hasEncryptedExtensions && !c.config.Bugs.OmitClientEncryptedExtensions {
1432		hs.writeClientHash(clientEncryptedExtensions.marshal())
1433		c.writeRecord(recordTypeHandshake, clientEncryptedExtensions.marshal())
1434	}
1435
1436	if certReq != nil && !c.config.Bugs.SkipClientCertificate {
1437		certMsg := &certificateMsg{
1438			hasRequestContext: true,
1439			requestContext:    certReq.requestContext,
1440		}
1441		if credential != nil {
1442			for _, certData := range credential.Certificate {
1443				certMsg.certificates = append(certMsg.certificates, certificateEntry{
1444					data:           certData,
1445					extraExtension: c.config.Bugs.SendExtensionOnCertificate,
1446				})
1447			}
1448		}
1449		hs.writeClientHash(certMsg.marshal())
1450		c.writeRecord(recordTypeHandshake, certMsg.marshal())
1451
1452		if credential != nil {
1453			certVerify := &certificateVerifyMsg{
1454				hasSignatureAlgorithm: true,
1455			}
1456
1457			// Determine the hash to sign.
1458			var err error
1459			certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.isClient, c.vers, credential, c.config, certReq.signatureAlgorithms)
1460			if err != nil {
1461				c.sendAlert(alertInternalError)
1462				return err
1463			}
1464
1465			privKey := credential.PrivateKey
1466			input := hs.finishedHash.certificateVerifyInput(clientCertificateVerifyContextTLS13)
1467			certVerify.signature, err = signMessage(c.isClient, c.vers, privKey, c.config, certVerify.signatureAlgorithm, input)
1468			if err != nil {
1469				c.sendAlert(alertInternalError)
1470				return err
1471			}
1472			if c.config.Bugs.SendSignatureAlgorithm != 0 {
1473				certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
1474			}
1475
1476			if !c.config.Bugs.SkipCertificateVerify {
1477				hs.writeClientHash(certVerify.marshal())
1478				c.writeRecord(recordTypeHandshake, certVerify.marshal())
1479			}
1480		}
1481	}
1482
1483	if encryptedExtensions.extensions.channelIDRequested {
1484		channelIDHash := crypto.SHA256.New()
1485		channelIDHash.Write(hs.finishedHash.certificateVerifyInput(channelIDContextTLS13))
1486		channelIDMsgBytes, err := hs.writeChannelIDMessage(channelIDHash.Sum(nil))
1487		if err != nil {
1488			return err
1489		}
1490		hs.writeClientHash(channelIDMsgBytes)
1491		c.writeRecord(recordTypeHandshake, channelIDMsgBytes)
1492	}
1493
1494	// Send a client Finished message.
1495	finished := new(finishedMsg)
1496	finished.verifyData = hs.finishedHash.clientSum(clientHandshakeTrafficSecret)
1497	if c.config.Bugs.BadFinished {
1498		finished.verifyData[0]++
1499	}
1500	hs.writeClientHash(finished.marshal())
1501	if c.config.Bugs.PartialClientFinishedWithClientHello {
1502		// The first byte has already been sent.
1503		c.writeRecord(recordTypeHandshake, finished.marshal()[1:])
1504	} else if c.config.Bugs.InterleaveEarlyData {
1505		finishedBytes := finished.marshal()
1506		c.sendFakeEarlyData(4)
1507		c.writeRecord(recordTypeHandshake, finishedBytes[:1])
1508		c.sendFakeEarlyData(4)
1509		c.writeRecord(recordTypeHandshake, finishedBytes[1:])
1510	} else {
1511		c.writeRecord(recordTypeHandshake, finished.marshal())
1512	}
1513	if c.config.Bugs.SendExtraFinished {
1514		c.writeRecord(recordTypeHandshake, finished.marshal())
1515	}
1516	c.flushHandshake()
1517
1518	// Switch to application data keys.
1519	c.useOutTrafficSecret(encryptionApplication, c.wireVersion, hs.suite, clientTrafficSecret)
1520	c.resumptionSecret = hs.finishedHash.deriveSecret(resumptionLabel)
1521	for _, ticket := range deferredTickets {
1522		if err := c.processTLS13NewSessionTicket(ticket, hs.suite); err != nil {
1523			return err
1524		}
1525	}
1526
1527	return nil
1528}
1529
1530// applyHelloRetryRequest updates |hello| in-place based on |helloRetryRequest|.
1531// If |outerHello| is not nil, |outerHello| will be updated to contain an
1532// encrypted copy of |hello|.
1533func (hs *clientHandshakeState) applyHelloRetryRequest(helloRetryRequest *helloRetryRequestMsg, hello, outerHello *clientHelloMsg) error {
1534	c := hs.c
1535	firstHelloBytes := hello.marshal()
1536	if len(helloRetryRequest.cookie) > 0 {
1537		hello.tls13Cookie = helloRetryRequest.cookie
1538	}
1539
1540	if c.config.Bugs.MisinterpretHelloRetryRequestCurve != 0 {
1541		helloRetryRequest.hasSelectedGroup = true
1542		helloRetryRequest.selectedGroup = c.config.Bugs.MisinterpretHelloRetryRequestCurve
1543	}
1544	if helloRetryRequest.hasSelectedGroup {
1545		var hrrCurveFound bool
1546		group := helloRetryRequest.selectedGroup
1547		for _, curveID := range hello.supportedCurves {
1548			if group == curveID {
1549				hrrCurveFound = true
1550				break
1551			}
1552		}
1553		if !hrrCurveFound || hs.keyShares[group] != nil {
1554			c.sendAlert(alertHandshakeFailure)
1555			return errors.New("tls: received invalid HelloRetryRequest")
1556		}
1557		kem, ok := kemForCurveID(group, c.config)
1558		if !ok {
1559			return errors.New("tls: Unable to get curve requested in HelloRetryRequest")
1560		}
1561		publicKey, err := kem.generate(c.config.rand())
1562		if err != nil {
1563			return err
1564		}
1565		hs.keyShares[group] = kem
1566		hello.keyShares = []keyShareEntry{{
1567			group:       group,
1568			keyExchange: publicKey,
1569		}}
1570	}
1571
1572	if c.config.Bugs.SecondClientHelloMissingKeyShare {
1573		hello.hasKeyShares = false
1574	}
1575
1576	if c.config.Bugs.OmitSecondECHInner {
1577		hello.echInner = false
1578	}
1579
1580	hello.hasEarlyData = c.config.Bugs.SendEarlyDataOnSecondClientHello
1581	// The first ClientHello may have skipped this due to OnlyCorruptSecondPSKBinder.
1582	if c.config.Bugs.PSKBinderFirst && c.config.Bugs.OnlyCorruptSecondPSKBinder {
1583		hello.prefixExtensions = append(hello.prefixExtensions, extensionPreSharedKey)
1584	}
1585	// The first ClientHello may have set this due to OnlyCompressSecondClientHelloInner.
1586	hello.reorderOuterExtensionsWithoutCompressing = false
1587	if c.config.Bugs.OmitPSKsOnSecondClientHello {
1588		hello.pskIdentities = nil
1589		hello.pskBinders = nil
1590	}
1591	hello.raw = nil
1592
1593	if len(hello.pskIdentities) > 0 {
1594		generatePSKBinders(c.wireVersion, hello, hs.session, firstHelloBytes, helloRetryRequest.marshal(), c.config)
1595	}
1596
1597	if outerHello != nil {
1598		outerHello.raw = nil
1599		// We know the server has accepted ECH, so the ClientHelloOuter's fields
1600		// are irrelevant. In the general case, the HelloRetryRequest may not
1601		// even be valid for ClientHelloOuter. However, we copy the key shares
1602		// from ClientHelloInner so they remain eligible for compression.
1603		if !c.config.Bugs.MinimalClientHelloOuter {
1604			outerHello.keyShares = hello.keyShares
1605		}
1606
1607		if c.config.Bugs.OmitSecondEncryptedClientHello {
1608			outerHello.echOuter = nil
1609		} else {
1610			configID := c.config.ClientECHConfig.ConfigID
1611			if c.config.Bugs.CorruptSecondEncryptedClientHelloConfigID {
1612				configID ^= 1
1613			}
1614			if err := hs.encryptClientHello(outerHello, hello, configID, nil); err != nil {
1615				return err
1616			}
1617			if c.config.Bugs.CorruptSecondEncryptedClientHello {
1618				if c.config.Bugs.NullAllCiphers {
1619					outerHello.echOuter.payload = []byte{echBadPayloadByte}
1620				} else {
1621					outerHello.echOuter.payload[0] ^= 1
1622				}
1623			}
1624		}
1625	}
1626
1627	return nil
1628}
1629
1630func (hs *clientHandshakeState) doFullHandshake() error {
1631	c := hs.c
1632
1633	var leaf *x509.Certificate
1634	if hs.suite.flags&suitePSK == 0 {
1635		msg, err := c.readHandshake()
1636		if err != nil {
1637			return err
1638		}
1639
1640		certMsg, ok := msg.(*certificateMsg)
1641		if !ok {
1642			c.sendAlert(alertUnexpectedMessage)
1643			return unexpectedMessageError(certMsg, msg)
1644		}
1645		hs.writeServerHash(certMsg.marshal())
1646
1647		if err := hs.verifyCertificates(certMsg); err != nil {
1648			return err
1649		}
1650		leaf = c.peerCertificates[0]
1651	}
1652
1653	if hs.serverHello.extensions.ocspStapling {
1654		msg, err := c.readHandshake()
1655		if err != nil {
1656			return err
1657		}
1658		cs, ok := msg.(*certificateStatusMsg)
1659		if !ok {
1660			c.sendAlert(alertUnexpectedMessage)
1661			return unexpectedMessageError(cs, msg)
1662		}
1663		hs.writeServerHash(cs.marshal())
1664
1665		if cs.statusType == statusTypeOCSP {
1666			c.ocspResponse = cs.response
1667		}
1668	}
1669
1670	msg, err := c.readHandshake()
1671	if err != nil {
1672		return err
1673	}
1674
1675	keyAgreement := hs.suite.ka(c.vers)
1676
1677	skx, ok := msg.(*serverKeyExchangeMsg)
1678	if ok {
1679		hs.writeServerHash(skx.marshal())
1680		err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, hs.peerPublicKey, skx)
1681		if err != nil {
1682			c.sendAlert(alertUnexpectedMessage)
1683			return err
1684		}
1685		if ecdhe, ok := keyAgreement.(*ecdheKeyAgreement); ok {
1686			c.curveID = ecdhe.curveID
1687		}
1688
1689		c.peerSignatureAlgorithm = keyAgreement.peerSignatureAlgorithm()
1690
1691		msg, err = c.readHandshake()
1692		if err != nil {
1693			return err
1694		}
1695	}
1696
1697	var credential *Credential
1698	var certRequested bool
1699	certReq, ok := msg.(*certificateRequestMsg)
1700	if ok {
1701		certRequested = true
1702		hs.writeServerHash(certReq.marshal())
1703
1704		credential = c.config.Credential
1705		if credential != nil && c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
1706			certReq.signatureAlgorithms = credential.signatureAlgorithms()
1707		}
1708
1709		msg, err = c.readHandshake()
1710		if err != nil {
1711			return err
1712		}
1713	}
1714
1715	shd, ok := msg.(*serverHelloDoneMsg)
1716	if !ok {
1717		c.sendAlert(alertUnexpectedMessage)
1718		return unexpectedMessageError(shd, msg)
1719	}
1720	hs.writeServerHash(shd.marshal())
1721
1722	// If the server requested a certificate then we have to send a
1723	// Certificate message in TLS, even if it's empty because we don't have
1724	// a certificate to send.
1725	if certRequested && !c.config.Bugs.SkipClientCertificate {
1726		certMsg := new(certificateMsg)
1727		if credential != nil {
1728			for _, certData := range credential.Certificate {
1729				certMsg.certificates = append(certMsg.certificates, certificateEntry{
1730					data: certData,
1731				})
1732			}
1733		}
1734		hs.writeClientHash(certMsg.marshal())
1735		c.writeRecord(recordTypeHandshake, certMsg.marshal())
1736	}
1737
1738	preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, leaf)
1739	if err != nil {
1740		c.sendAlert(alertInternalError)
1741		return err
1742	}
1743	if ckx != nil {
1744		if c.config.Bugs.EarlyChangeCipherSpec < 2 {
1745			hs.writeClientHash(ckx.marshal())
1746		}
1747		if c.config.Bugs.PartialClientKeyExchangeWithClientHello {
1748			// The first byte was already written.
1749			c.writeRecord(recordTypeHandshake, ckx.marshal()[1:])
1750		} else {
1751			c.writeRecord(recordTypeHandshake, ckx.marshal())
1752		}
1753	}
1754
1755	if hs.serverHello.extensions.extendedMasterSecret {
1756		hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
1757		c.extendedMasterSecret = true
1758	} else {
1759		if c.config.Bugs.RequireExtendedMasterSecret {
1760			return errors.New("tls: extended master secret required but not supported by peer")
1761		}
1762		hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
1763	}
1764
1765	if credential != nil {
1766		certVerify := &certificateVerifyMsg{
1767			hasSignatureAlgorithm: c.vers >= VersionTLS12,
1768		}
1769
1770		// Determine the hash to sign.
1771		if certVerify.hasSignatureAlgorithm {
1772			certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.isClient, c.vers, credential, c.config, certReq.signatureAlgorithms)
1773			if err != nil {
1774				c.sendAlert(alertInternalError)
1775				return err
1776			}
1777		}
1778
1779		privKey := c.config.Credential.PrivateKey
1780		certVerify.signature, err = signMessage(c.isClient, c.vers, privKey, c.config, certVerify.signatureAlgorithm, hs.finishedHash.buffer)
1781		if err == nil && c.config.Bugs.SendSignatureAlgorithm != 0 {
1782			certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
1783		}
1784		if err != nil {
1785			c.sendAlert(alertInternalError)
1786			return errors.New("tls: failed to sign handshake with client certificate: " + err.Error())
1787		}
1788
1789		if !c.config.Bugs.SkipCertificateVerify {
1790			hs.writeClientHash(certVerify.marshal())
1791			c.writeRecord(recordTypeHandshake, certVerify.marshal())
1792		}
1793	}
1794	// flushHandshake will be called in sendFinished.
1795
1796	hs.finishedHash.discardHandshakeBuffer()
1797
1798	return nil
1799}
1800
1801// delegatedCredentialSignedMessage returns the bytes that are signed in order
1802// to authenticate a delegated credential.
1803func delegatedCredentialSignedMessage(credBytes []byte, algorithm signatureAlgorithm, leafDER []byte) []byte {
1804	// https://www.rfc-editor.org/rfc/rfc9345.html#section-4
1805	ret := make([]byte, 64, 128)
1806	for i := range ret {
1807		ret[i] = 0x20
1808	}
1809
1810	ret = append(ret, []byte("TLS, server delegated credentials\x00")...)
1811	ret = append(ret, leafDER...)
1812	ret = append(ret, byte(algorithm>>8), byte(algorithm))
1813	ret = append(ret, credBytes...)
1814
1815	return ret
1816}
1817
1818func (hs *clientHandshakeState) verifyCertificates(certMsg *certificateMsg) error {
1819	c := hs.c
1820
1821	if len(certMsg.certificates) == 0 {
1822		c.sendAlert(alertIllegalParameter)
1823		return errors.New("tls: no certificates sent")
1824	}
1825
1826	var dc *delegatedCredential
1827	certs := make([]*x509.Certificate, len(certMsg.certificates))
1828	for i, certEntry := range certMsg.certificates {
1829		cert, err := x509.ParseCertificate(certEntry.data)
1830		if err != nil {
1831			c.sendAlert(alertBadCertificate)
1832			return errors.New("tls: failed to parse certificate from server: " + err.Error())
1833		}
1834		certs[i] = cert
1835
1836		if certEntry.delegatedCredential != nil {
1837			if i != 0 {
1838				c.sendAlert(alertIllegalParameter)
1839				return errors.New("tls: non-leaf certificate has a delegated credential")
1840			}
1841			if len(c.config.DelegatedCredentialAlgorithms) == 0 {
1842				c.sendAlert(alertIllegalParameter)
1843				return errors.New("tls: server sent delegated credential without it being requested")
1844			}
1845			dc = certEntry.delegatedCredential
1846		}
1847	}
1848
1849	if !c.config.InsecureSkipVerify {
1850		opts := x509.VerifyOptions{
1851			Roots:         c.config.RootCAs,
1852			CurrentTime:   c.config.time(),
1853			DNSName:       c.config.ServerName,
1854			Intermediates: x509.NewCertPool(),
1855		}
1856
1857		for i, cert := range certs {
1858			if i == 0 {
1859				continue
1860			}
1861			opts.Intermediates.AddCert(cert)
1862		}
1863		var err error
1864		c.verifiedChains, err = certs[0].Verify(opts)
1865		if err != nil {
1866			c.sendAlert(alertBadCertificate)
1867			return err
1868		}
1869	}
1870
1871	leafPublicKey := certs[0].PublicKey
1872	switch leafPublicKey.(type) {
1873	case *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey:
1874		break
1875	default:
1876		c.sendAlert(alertUnsupportedCertificate)
1877		return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", leafPublicKey)
1878	}
1879
1880	c.peerCertificates = certs
1881
1882	if dc != nil {
1883		// Note that this doesn't check a) the delegated credential temporal
1884		// validity nor b) that the certificate has the special OID asserted.
1885		var err error
1886		if hs.peerPublicKey, err = x509.ParsePKIXPublicKey(dc.pkixPublicKey); err != nil {
1887			c.sendAlert(alertBadCertificate)
1888			return errors.New("tls: failed to parse public key from delegated credential: " + err.Error())
1889		}
1890
1891		signedMsg := delegatedCredentialSignedMessage(dc.signedBytes, dc.algorithm, certs[0].Raw)
1892		if err := verifyMessage(c.isClient, c.vers, leafPublicKey, c.config, dc.algorithm, signedMsg, dc.signature); err != nil {
1893			c.sendAlert(alertBadCertificate)
1894			return errors.New("tls: failed to verify delegated credential: " + err.Error())
1895		}
1896		c.peerDelegatedCredential = dc.raw
1897	} else {
1898		hs.peerPublicKey = leafPublicKey
1899	}
1900
1901	return nil
1902}
1903
1904func (hs *clientHandshakeState) establishKeys() error {
1905	c := hs.c
1906
1907	clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
1908		keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen(c.vers))
1909	var clientCipher, serverCipher any
1910	var clientHash, serverHash macFunction
1911	if hs.suite.cipher != nil {
1912		clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
1913		clientHash = hs.suite.mac(c.vers, clientMAC)
1914		serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
1915		serverHash = hs.suite.mac(c.vers, serverMAC)
1916	} else {
1917		clientCipher = hs.suite.aead(c.vers, clientKey, clientIV)
1918		serverCipher = hs.suite.aead(c.vers, serverKey, serverIV)
1919	}
1920
1921	c.in.prepareCipherSpec(c.wireVersion, serverCipher, serverHash)
1922	c.out.prepareCipherSpec(c.wireVersion, clientCipher, clientHash)
1923	return nil
1924}
1925
1926func (hs *clientHandshakeState) processServerExtensions(serverExtensions *serverExtensions) error {
1927	c := hs.c
1928
1929	if c.vers < VersionTLS13 {
1930		if c.config.Bugs.RequireRenegotiationInfo && serverExtensions.secureRenegotiation == nil {
1931			return errors.New("tls: renegotiation extension missing")
1932		}
1933
1934		if len(c.clientVerify) > 0 && !c.noRenegotiationInfo() {
1935			var expectedRenegInfo []byte
1936			expectedRenegInfo = append(expectedRenegInfo, c.clientVerify...)
1937			expectedRenegInfo = append(expectedRenegInfo, c.serverVerify...)
1938			if !bytes.Equal(serverExtensions.secureRenegotiation, expectedRenegInfo) {
1939				c.sendAlert(alertHandshakeFailure)
1940				return fmt.Errorf("tls: renegotiation mismatch")
1941			}
1942		}
1943	} else if serverExtensions.secureRenegotiation != nil {
1944		return errors.New("tls: renegotiation info sent in TLS 1.3")
1945	}
1946
1947	if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
1948		if serverExtensions.customExtension != *expected {
1949			return fmt.Errorf("tls: bad custom extension contents %q", serverExtensions.customExtension)
1950		}
1951	}
1952
1953	clientDidNPN := hs.hello.nextProtoNeg
1954	clientDidALPN := len(hs.hello.alpnProtocols) > 0
1955	serverHasNPN := serverExtensions.nextProtoNeg
1956	serverHasALPN := len(serverExtensions.alpnProtocol) > 0
1957
1958	if !clientDidNPN && serverHasNPN {
1959		c.sendAlert(alertHandshakeFailure)
1960		return errors.New("server advertised unrequested NPN extension")
1961	}
1962
1963	if !clientDidALPN && serverHasALPN {
1964		c.sendAlert(alertHandshakeFailure)
1965		return errors.New("server advertised unrequested ALPN extension")
1966	}
1967
1968	if serverHasNPN && serverHasALPN {
1969		c.sendAlert(alertHandshakeFailure)
1970		return errors.New("server advertised both NPN and ALPN extensions")
1971	}
1972
1973	if serverHasALPN {
1974		c.clientProtocol = serverExtensions.alpnProtocol
1975		c.clientProtocolFallback = false
1976		c.usedALPN = true
1977	}
1978
1979	if serverHasNPN && c.vers >= VersionTLS13 {
1980		c.sendAlert(alertHandshakeFailure)
1981		return errors.New("server advertised NPN over TLS 1.3")
1982	}
1983
1984	if !hs.hello.channelIDSupported && serverExtensions.channelIDRequested {
1985		c.sendAlert(alertHandshakeFailure)
1986		return errors.New("server advertised unrequested Channel ID extension")
1987	}
1988
1989	if serverExtensions.extendedMasterSecret && c.vers >= VersionTLS13 {
1990		return errors.New("tls: server advertised extended master secret over TLS 1.3")
1991	}
1992
1993	if serverExtensions.ticketSupported && c.vers >= VersionTLS13 {
1994		return errors.New("tls: server advertised ticket extension over TLS 1.3")
1995	}
1996
1997	if serverExtensions.ocspStapling && c.vers >= VersionTLS13 {
1998		return errors.New("tls: server advertised OCSP in ServerHello over TLS 1.3")
1999	}
2000
2001	if serverExtensions.ocspStapling && c.config.Bugs.NoOCSPStapling {
2002		return errors.New("tls: server advertised unrequested OCSP extension")
2003	}
2004
2005	if len(serverExtensions.sctList) > 0 && c.vers >= VersionTLS13 {
2006		return errors.New("tls: server advertised SCTs in ServerHello over TLS 1.3")
2007	}
2008
2009	if len(serverExtensions.sctList) > 0 && c.config.Bugs.NoSignedCertificateTimestamps {
2010		return errors.New("tls: server advertised unrequested SCTs")
2011	}
2012
2013	if serverExtensions.srtpProtectionProfile != 0 {
2014		if serverExtensions.srtpMasterKeyIdentifier != "" {
2015			return errors.New("tls: server selected SRTP MKI value")
2016		}
2017
2018		found := false
2019		for _, p := range c.config.SRTPProtectionProfiles {
2020			if p == serverExtensions.srtpProtectionProfile {
2021				found = true
2022				break
2023			}
2024		}
2025		if !found {
2026			return errors.New("tls: server advertised unsupported SRTP profile")
2027		}
2028
2029		c.srtpProtectionProfile = serverExtensions.srtpProtectionProfile
2030	}
2031
2032	if c.vers >= VersionTLS13 && c.didResume {
2033		if c.config.Bugs.ExpectEarlyDataAccepted && !serverExtensions.hasEarlyData {
2034			c.sendAlert(alertHandshakeFailure)
2035			return errors.New("tls: server did not accept early data when expected")
2036		}
2037
2038		if !c.config.Bugs.ExpectEarlyDataAccepted && serverExtensions.hasEarlyData {
2039			c.sendAlert(alertHandshakeFailure)
2040			return errors.New("tls: server accepted early data when not expected")
2041		}
2042	} else if serverExtensions.hasEarlyData {
2043		return errors.New("tls: server accepted early data when not resuming")
2044	}
2045
2046	if len(serverExtensions.quicTransportParams) > 0 {
2047		if c.vers < VersionTLS13 {
2048			c.sendAlert(alertHandshakeFailure)
2049			return errors.New("tls: server sent QUIC transport params for TLS version less than 1.3")
2050		}
2051		c.quicTransportParams = serverExtensions.quicTransportParams
2052	}
2053
2054	if len(serverExtensions.quicTransportParamsLegacy) > 0 {
2055		if c.vers < VersionTLS13 {
2056			c.sendAlert(alertHandshakeFailure)
2057			return errors.New("tls: server sent QUIC transport params for TLS version less than 1.3")
2058		}
2059		c.quicTransportParamsLegacy = serverExtensions.quicTransportParamsLegacy
2060	}
2061
2062	if serverExtensions.hasApplicationSettings && serverExtensions.hasApplicationSettingsOld {
2063		return errors.New("tls: server negotiated both old and new application settings together")
2064	}
2065
2066	if serverExtensions.hasApplicationSettings || serverExtensions.hasApplicationSettingsOld {
2067		if c.vers < VersionTLS13 {
2068			return errors.New("tls: server sent application settings at invalid version")
2069		}
2070		if serverExtensions.hasEarlyData {
2071			return errors.New("tls: server sent application settings with 0-RTT")
2072		}
2073		if !serverHasALPN {
2074			return errors.New("tls: server sent application settings without ALPN")
2075		}
2076		settings, ok := c.config.ApplicationSettings[serverExtensions.alpnProtocol]
2077		if !ok {
2078			return errors.New("tls: server sent application settings for invalid protocol")
2079		}
2080
2081		if serverExtensions.hasApplicationSettings {
2082			c.hasApplicationSettings = true
2083			c.localApplicationSettings = settings
2084			c.peerApplicationSettings = serverExtensions.applicationSettings
2085		}
2086
2087		if serverExtensions.hasApplicationSettingsOld {
2088			c.hasApplicationSettingsOld = true
2089			c.localApplicationSettingsOld = settings
2090			c.peerApplicationSettingsOld = serverExtensions.applicationSettingsOld
2091		}
2092	} else if serverExtensions.hasEarlyData {
2093		// 0-RTT connections inherit application settings from the session.
2094		c.hasApplicationSettings = hs.session.hasApplicationSettings
2095		c.localApplicationSettings = hs.session.localApplicationSettings
2096		c.peerApplicationSettings = hs.session.peerApplicationSettings
2097		c.hasApplicationSettingsOld = hs.session.hasApplicationSettingsOld
2098		c.localApplicationSettingsOld = hs.session.localApplicationSettingsOld
2099		c.peerApplicationSettingsOld = hs.session.peerApplicationSettingsOld
2100	}
2101
2102	return nil
2103}
2104
2105func (hs *clientHandshakeState) serverResumedSession() bool {
2106	// If the server responded with the same sessionID then it means the
2107	// sessionTicket is being used to resume a TLS session.
2108	//
2109	// Note that, if hs.hello.sessionID is a non-nil empty array, this will
2110	// accept an empty session ID from the server as resumption. See
2111	// EmptyTicketSessionID.
2112	return hs.session != nil && hs.hello.sessionID != nil &&
2113		bytes.Equal(hs.serverHello.sessionID, hs.hello.sessionID)
2114}
2115
2116func (hs *clientHandshakeState) processServerHello() (bool, error) {
2117	c := hs.c
2118
2119	// Check for downgrade signals in the server random, per RFC 8446, section 4.1.3.
2120	gotDowngrade := hs.serverHello.random[len(hs.serverHello.random)-8:]
2121	if !c.config.Bugs.IgnoreTLS13DowngradeRandom {
2122		if c.config.maxVersion(c.isDTLS) >= VersionTLS13 {
2123			if bytes.Equal(gotDowngrade, downgradeTLS13) {
2124				c.sendAlert(alertProtocolVersion)
2125				return false, errors.New("tls: downgrade from TLS 1.3 detected")
2126			}
2127		}
2128		if c.vers <= VersionTLS11 && c.config.maxVersion(c.isDTLS) >= VersionTLS12 {
2129			if bytes.Equal(gotDowngrade, downgradeTLS12) {
2130				c.sendAlert(alertProtocolVersion)
2131				return false, errors.New("tls: downgrade from TLS 1.2 detected")
2132			}
2133		}
2134	}
2135
2136	if bytes.Equal(gotDowngrade, downgradeJDK11) != c.config.Bugs.ExpectJDK11DowngradeRandom {
2137		c.sendAlert(alertProtocolVersion)
2138		if c.config.Bugs.ExpectJDK11DowngradeRandom {
2139			return false, errors.New("tls: server did not send a JDK 11 downgrade signal")
2140		}
2141		return false, errors.New("tls: server sent an unexpected JDK 11 downgrade signal")
2142	}
2143
2144	if c.config.Bugs.ExpectOmitExtensions && !hs.serverHello.omitExtensions {
2145		return false, errors.New("tls: ServerHello did not omit extensions")
2146	}
2147
2148	if hs.serverResumedSession() {
2149		// For test purposes, assert that the server never accepts the
2150		// resumption offer on renegotiation.
2151		if c.cipherSuite != nil && c.config.Bugs.FailIfResumeOnRenego {
2152			return false, errors.New("tls: server resumed session on renegotiation")
2153		}
2154
2155		if hs.serverHello.extensions.sctList != nil {
2156			return false, errors.New("tls: server sent SCT extension on session resumption")
2157		}
2158
2159		if hs.serverHello.extensions.ocspStapling {
2160			return false, errors.New("tls: server sent OCSP extension on session resumption")
2161		}
2162
2163		// Restore masterSecret and peerCerts from previous state
2164		hs.masterSecret = hs.session.secret
2165		c.peerCertificates = hs.session.serverCertificates
2166		c.peerDelegatedCredential = hs.session.serverDelegatedCredential
2167		c.extendedMasterSecret = hs.session.extendedMasterSecret
2168		c.sctList = hs.session.sctList
2169		c.ocspResponse = hs.session.ocspResponse
2170		hs.finishedHash.discardHandshakeBuffer()
2171		return true, nil
2172	}
2173
2174	if hs.serverHello.extensions.sctList != nil {
2175		c.sctList = hs.serverHello.extensions.sctList
2176	}
2177
2178	return false, nil
2179}
2180
2181func (hs *clientHandshakeState) readFinished(out []byte) error {
2182	c := hs.c
2183
2184	c.readRecord(recordTypeChangeCipherSpec)
2185	if err := c.in.error(); err != nil {
2186		return err
2187	}
2188
2189	msg, err := c.readHandshake()
2190	if err != nil {
2191		return err
2192	}
2193	serverFinished, ok := msg.(*finishedMsg)
2194	if !ok {
2195		c.sendAlert(alertUnexpectedMessage)
2196		return unexpectedMessageError(serverFinished, msg)
2197	}
2198
2199	if c.config.Bugs.EarlyChangeCipherSpec == 0 {
2200		verify := hs.finishedHash.serverSum(hs.masterSecret)
2201		if len(verify) != len(serverFinished.verifyData) ||
2202			subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
2203			c.sendAlert(alertHandshakeFailure)
2204			return errors.New("tls: server's Finished message was incorrect")
2205		}
2206	}
2207	c.serverVerify = append(c.serverVerify[:0], serverFinished.verifyData...)
2208	copy(out, serverFinished.verifyData)
2209	hs.writeServerHash(serverFinished.marshal())
2210	return nil
2211}
2212
2213func (hs *clientHandshakeState) readSessionTicket() error {
2214	c := hs.c
2215
2216	// Create a session with no server identifier. Either a
2217	// session ID or session ticket will be attached.
2218	session := &ClientSessionState{
2219		vers:                      c.vers,
2220		wireVersion:               c.wireVersion,
2221		cipherSuite:               hs.suite,
2222		secret:                    hs.masterSecret,
2223		handshakeHash:             hs.finishedHash.Sum(),
2224		serverCertificates:        c.peerCertificates,
2225		serverDelegatedCredential: c.peerDelegatedCredential,
2226		sctList:                   c.sctList,
2227		ocspResponse:              c.ocspResponse,
2228		ticketExpiration:          c.config.time().Add(time.Duration(7 * 24 * time.Hour)),
2229	}
2230
2231	if !hs.serverHello.extensions.ticketSupported {
2232		if c.config.Bugs.ExpectNewTicket {
2233			return errors.New("tls: expected new ticket")
2234		}
2235		if hs.session == nil && len(hs.serverHello.sessionID) > 0 {
2236			session.sessionID = hs.serverHello.sessionID
2237			hs.session = session
2238		}
2239		return nil
2240	}
2241
2242	if c.config.Bugs.ExpectNoNewSessionTicket {
2243		return errors.New("tls: received unexpected NewSessionTicket")
2244	}
2245
2246	msg, err := c.readHandshake()
2247	if err != nil {
2248		return err
2249	}
2250	sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
2251	if !ok {
2252		c.sendAlert(alertUnexpectedMessage)
2253		return unexpectedMessageError(sessionTicketMsg, msg)
2254	}
2255
2256	session.sessionTicket = sessionTicketMsg.ticket
2257	hs.session = session
2258
2259	hs.writeServerHash(sessionTicketMsg.marshal())
2260
2261	return nil
2262}
2263
2264func (hs *clientHandshakeState) sendFinished(out []byte, isResume bool) error {
2265	c := hs.c
2266
2267	var postCCSMsgs [][]byte
2268	seqno := hs.c.sendHandshakeSeq
2269	if hs.serverHello.extensions.nextProtoNeg {
2270		nextProto := new(nextProtoMsg)
2271		proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.extensions.nextProtos)
2272		if fallback && c.config.NoFallbackNextProto {
2273			proto = ""
2274			fallback = false
2275		}
2276		nextProto.proto = proto
2277		c.clientProtocol = proto
2278		c.clientProtocolFallback = fallback
2279
2280		nextProtoBytes := nextProto.marshal()
2281		hs.finishedHash.WriteHandshake(nextProtoBytes, seqno)
2282		seqno++
2283		postCCSMsgs = append(postCCSMsgs, nextProtoBytes)
2284	}
2285
2286	if hs.serverHello.extensions.channelIDRequested {
2287		var resumeHash []byte
2288		if isResume {
2289			resumeHash = hs.session.handshakeHash
2290		}
2291		channelIDMsgBytes, err := hs.writeChannelIDMessage(hs.finishedHash.hashForChannelID(resumeHash))
2292		if err != nil {
2293			return err
2294		}
2295		hs.finishedHash.WriteHandshake(channelIDMsgBytes, seqno)
2296		seqno++
2297		postCCSMsgs = append(postCCSMsgs, channelIDMsgBytes)
2298	}
2299
2300	finished := new(finishedMsg)
2301	if c.config.Bugs.EarlyChangeCipherSpec == 2 {
2302		finished.verifyData = hs.finishedHash.clientSum(nil)
2303	} else {
2304		finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
2305	}
2306	copy(out, finished.verifyData)
2307	if c.config.Bugs.BadFinished {
2308		finished.verifyData[0]++
2309	}
2310	c.clientVerify = append(c.clientVerify[:0], finished.verifyData...)
2311	hs.finishedBytes = finished.marshal()
2312	hs.finishedHash.WriteHandshake(hs.finishedBytes, seqno)
2313	if c.config.Bugs.PartialClientFinishedWithClientHello {
2314		// The first byte has already been written.
2315		postCCSMsgs = append(postCCSMsgs, hs.finishedBytes[1:])
2316	} else {
2317		postCCSMsgs = append(postCCSMsgs, hs.finishedBytes)
2318	}
2319
2320	if c.config.Bugs.FragmentAcrossChangeCipherSpec {
2321		c.writeRecord(recordTypeHandshake, postCCSMsgs[0][:5])
2322		postCCSMsgs[0] = postCCSMsgs[0][5:]
2323	} else if c.config.Bugs.SendUnencryptedFinished {
2324		c.writeRecord(recordTypeHandshake, postCCSMsgs[0])
2325		postCCSMsgs = postCCSMsgs[1:]
2326	}
2327
2328	if !c.config.Bugs.SkipChangeCipherSpec &&
2329		c.config.Bugs.EarlyChangeCipherSpec == 0 {
2330		ccs := []byte{1}
2331		if c.config.Bugs.BadChangeCipherSpec != nil {
2332			ccs = c.config.Bugs.BadChangeCipherSpec
2333		}
2334		c.writeRecord(recordTypeChangeCipherSpec, ccs)
2335	}
2336
2337	if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
2338		c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
2339	}
2340	if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
2341		c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
2342		return errors.New("tls: simulating post-CCS alert")
2343	}
2344
2345	if !c.config.Bugs.SkipFinished {
2346		for _, msg := range postCCSMsgs {
2347			c.writeRecord(recordTypeHandshake, msg)
2348		}
2349
2350		if c.config.Bugs.SendExtraFinished {
2351			c.writeRecord(recordTypeHandshake, finished.marshal())
2352		}
2353	}
2354
2355	if !isResume || !c.config.Bugs.PackAppDataWithHandshake {
2356		c.flushHandshake()
2357	}
2358	return nil
2359}
2360
2361func (hs *clientHandshakeState) writeChannelIDMessage(channelIDHash []byte) ([]byte, error) {
2362	c := hs.c
2363	channelIDMsg := new(channelIDMsg)
2364	if c.config.ChannelID.Curve != elliptic.P256() {
2365		return nil, fmt.Errorf("tls: Channel ID is not on P-256.")
2366	}
2367	r, s, err := ecdsa.Sign(c.config.rand(), c.config.ChannelID, channelIDHash)
2368	if err != nil {
2369		return nil, err
2370	}
2371	channelID := make([]byte, 128)
2372	writeIntPadded(channelID[0:32], c.config.ChannelID.X)
2373	writeIntPadded(channelID[32:64], c.config.ChannelID.Y)
2374	writeIntPadded(channelID[64:96], r)
2375	writeIntPadded(channelID[96:128], s)
2376	if c.config.Bugs.InvalidChannelIDSignature {
2377		channelID[64] ^= 1
2378	}
2379	channelIDMsg.channelID = channelID
2380
2381	c.channelID = &c.config.ChannelID.PublicKey
2382
2383	return channelIDMsg.marshal(), nil
2384}
2385
2386func (hs *clientHandshakeState) writeClientHash(msg []byte) {
2387	// writeClientHash is called before writeRecord.
2388	hs.finishedHash.WriteHandshake(msg, hs.c.sendHandshakeSeq)
2389}
2390
2391func (hs *clientHandshakeState) writeServerHash(msg []byte) {
2392	// writeServerHash is called after readHandshake.
2393	hs.finishedHash.WriteHandshake(msg, hs.c.recvHandshakeSeq-1)
2394}
2395
2396// clientSessionCacheKey returns a key used to cache sessionTickets that could
2397// be used to resume previously negotiated TLS sessions with a server.
2398func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
2399	if len(config.ServerName) > 0 {
2400		return config.ServerName
2401	}
2402	return serverAddr.String()
2403}
2404
2405// mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
2406// given list of possible protocols and a list of the preference order. The
2407// first list must not be empty. It returns the resulting protocol and flag
2408// indicating if the fallback case was reached.
2409func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
2410	for _, s := range preferenceProtos {
2411		for _, c := range protos {
2412			if s == c {
2413				return s, false
2414			}
2415		}
2416	}
2417
2418	return protos[0], true
2419}
2420
2421// writeIntPadded writes x into b, padded up with leading zeros as
2422// needed.
2423func writeIntPadded(b []byte, x *big.Int) {
2424	for i := range b {
2425		b[i] = 0
2426	}
2427	xb := x.Bytes()
2428	copy(b[len(b)-len(xb):], xb)
2429}
2430
2431func generatePSKBinders(version uint16, hello *clientHelloMsg, session *ClientSessionState, firstClientHello, helloRetryRequest []byte, config *Config) {
2432	maybeCorruptBinder := !config.Bugs.OnlyCorruptSecondPSKBinder || len(firstClientHello) > 0
2433	binderLen := session.cipherSuite.hash().Size()
2434	numBinders := 1
2435	if maybeCorruptBinder {
2436		if config.Bugs.SendNoPSKBinder {
2437			// The binders may have been set from the previous
2438			// ClientHello.
2439			hello.pskBinders = nil
2440			return
2441		}
2442
2443		if config.Bugs.SendShortPSKBinder {
2444			binderLen--
2445		}
2446
2447		if config.Bugs.SendExtraPSKBinder {
2448			numBinders++
2449		}
2450	}
2451
2452	// Fill hello.pskBinders with appropriate length arrays of zeros so the
2453	// length prefixes are correct when computing the binder over the truncated
2454	// ClientHello message.
2455	hello.pskBinders = make([][]byte, numBinders)
2456	for i := range hello.pskBinders {
2457		hello.pskBinders[i] = make([]byte, binderLen)
2458	}
2459
2460	helloBytes := hello.marshal()
2461	binderSize := len(hello.pskBinders)*(binderLen+1) + 2
2462	truncatedHello := helloBytes[:len(helloBytes)-binderSize]
2463	binder := computePSKBinder(session.secret, version, resumptionPSKBinderLabel, session.cipherSuite, firstClientHello, helloRetryRequest, truncatedHello)
2464	if maybeCorruptBinder {
2465		if config.Bugs.SendShortPSKBinder {
2466			binder = binder[:binderLen]
2467		}
2468		if config.Bugs.SendInvalidPSKBinder {
2469			binder[0] ^= 1
2470		}
2471	}
2472
2473	for i := range hello.pskBinders {
2474		hello.pskBinders[i] = binder
2475	}
2476
2477	hello.raw = nil
2478}
2479