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 tls
6
7import (
8	"bytes"
9	"context"
10	"crypto"
11	"crypto/ecdsa"
12	"crypto/ed25519"
13	"crypto/internal/hpke"
14	"crypto/internal/mlkem768"
15	"crypto/rsa"
16	"crypto/subtle"
17	"crypto/x509"
18	"errors"
19	"fmt"
20	"hash"
21	"internal/byteorder"
22	"internal/godebug"
23	"io"
24	"net"
25	"strconv"
26	"strings"
27	"time"
28)
29
30type clientHandshakeState struct {
31	c            *Conn
32	ctx          context.Context
33	serverHello  *serverHelloMsg
34	hello        *clientHelloMsg
35	suite        *cipherSuite
36	finishedHash finishedHash
37	masterSecret []byte
38	session      *SessionState // the session being resumed
39	ticket       []byte        // a fresh ticket received during this handshake
40}
41
42var testingOnlyForceClientHelloSignatureAlgorithms []SignatureScheme
43
44func (c *Conn) makeClientHello() (*clientHelloMsg, *keySharePrivateKeys, *echContext, error) {
45	config := c.config
46	if len(config.ServerName) == 0 && !config.InsecureSkipVerify {
47		return nil, nil, nil, errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
48	}
49
50	nextProtosLength := 0
51	for _, proto := range config.NextProtos {
52		if l := len(proto); l == 0 || l > 255 {
53			return nil, nil, nil, errors.New("tls: invalid NextProtos value")
54		} else {
55			nextProtosLength += 1 + l
56		}
57	}
58	if nextProtosLength > 0xffff {
59		return nil, nil, nil, errors.New("tls: NextProtos values too large")
60	}
61
62	supportedVersions := config.supportedVersions(roleClient)
63	if len(supportedVersions) == 0 {
64		return nil, nil, nil, errors.New("tls: no supported versions satisfy MinVersion and MaxVersion")
65	}
66	maxVersion := config.maxSupportedVersion(roleClient)
67
68	hello := &clientHelloMsg{
69		vers:                         maxVersion,
70		compressionMethods:           []uint8{compressionNone},
71		random:                       make([]byte, 32),
72		extendedMasterSecret:         true,
73		ocspStapling:                 true,
74		scts:                         true,
75		serverName:                   hostnameInSNI(config.ServerName),
76		supportedCurves:              config.curvePreferences(maxVersion),
77		supportedPoints:              []uint8{pointFormatUncompressed},
78		secureRenegotiationSupported: true,
79		alpnProtocols:                config.NextProtos,
80		supportedVersions:            supportedVersions,
81	}
82
83	// The version at the beginning of the ClientHello was capped at TLS 1.2
84	// for compatibility reasons. The supported_versions extension is used
85	// to negotiate versions now. See RFC 8446, Section 4.2.1.
86	if hello.vers > VersionTLS12 {
87		hello.vers = VersionTLS12
88	}
89
90	if c.handshakes > 0 {
91		hello.secureRenegotiation = c.clientFinished[:]
92	}
93
94	preferenceOrder := cipherSuitesPreferenceOrder
95	if !hasAESGCMHardwareSupport {
96		preferenceOrder = cipherSuitesPreferenceOrderNoAES
97	}
98	configCipherSuites := config.cipherSuites()
99	hello.cipherSuites = make([]uint16, 0, len(configCipherSuites))
100
101	for _, suiteId := range preferenceOrder {
102		suite := mutualCipherSuite(configCipherSuites, suiteId)
103		if suite == nil {
104			continue
105		}
106		// Don't advertise TLS 1.2-only cipher suites unless
107		// we're attempting TLS 1.2.
108		if maxVersion < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
109			continue
110		}
111		hello.cipherSuites = append(hello.cipherSuites, suiteId)
112	}
113
114	_, err := io.ReadFull(config.rand(), hello.random)
115	if err != nil {
116		return nil, nil, nil, errors.New("tls: short read from Rand: " + err.Error())
117	}
118
119	// A random session ID is used to detect when the server accepted a ticket
120	// and is resuming a session (see RFC 5077). In TLS 1.3, it's always set as
121	// a compatibility measure (see RFC 8446, Section 4.1.2).
122	//
123	// The session ID is not set for QUIC connections (see RFC 9001, Section 8.4).
124	if c.quic == nil {
125		hello.sessionId = make([]byte, 32)
126		if _, err := io.ReadFull(config.rand(), hello.sessionId); err != nil {
127			return nil, nil, nil, errors.New("tls: short read from Rand: " + err.Error())
128		}
129	}
130
131	if maxVersion >= VersionTLS12 {
132		hello.supportedSignatureAlgorithms = supportedSignatureAlgorithms()
133	}
134	if testingOnlyForceClientHelloSignatureAlgorithms != nil {
135		hello.supportedSignatureAlgorithms = testingOnlyForceClientHelloSignatureAlgorithms
136	}
137
138	var keyShareKeys *keySharePrivateKeys
139	if hello.supportedVersions[0] == VersionTLS13 {
140		// Reset the list of ciphers when the client only supports TLS 1.3.
141		if len(hello.supportedVersions) == 1 {
142			hello.cipherSuites = nil
143		}
144		if hasAESGCMHardwareSupport {
145			hello.cipherSuites = append(hello.cipherSuites, defaultCipherSuitesTLS13...)
146		} else {
147			hello.cipherSuites = append(hello.cipherSuites, defaultCipherSuitesTLS13NoAES...)
148		}
149
150		curveID := config.curvePreferences(maxVersion)[0]
151		keyShareKeys = &keySharePrivateKeys{curveID: curveID}
152		if curveID == x25519Kyber768Draft00 {
153			keyShareKeys.ecdhe, err = generateECDHEKey(config.rand(), X25519)
154			if err != nil {
155				return nil, nil, nil, err
156			}
157			seed := make([]byte, mlkem768.SeedSize)
158			if _, err := io.ReadFull(config.rand(), seed); err != nil {
159				return nil, nil, nil, err
160			}
161			keyShareKeys.kyber, err = mlkem768.NewKeyFromSeed(seed)
162			if err != nil {
163				return nil, nil, nil, err
164			}
165			// For draft-tls-westerbaan-xyber768d00-03, we send both a hybrid
166			// and a standard X25519 key share, since most servers will only
167			// support the latter. We reuse the same X25519 ephemeral key for
168			// both, as allowed by draft-ietf-tls-hybrid-design-09, Section 3.2.
169			hello.keyShares = []keyShare{
170				{group: x25519Kyber768Draft00, data: append(keyShareKeys.ecdhe.PublicKey().Bytes(),
171					keyShareKeys.kyber.EncapsulationKey()...)},
172				{group: X25519, data: keyShareKeys.ecdhe.PublicKey().Bytes()},
173			}
174		} else {
175			if _, ok := curveForCurveID(curveID); !ok {
176				return nil, nil, nil, errors.New("tls: CurvePreferences includes unsupported curve")
177			}
178			keyShareKeys.ecdhe, err = generateECDHEKey(config.rand(), curveID)
179			if err != nil {
180				return nil, nil, nil, err
181			}
182			hello.keyShares = []keyShare{{group: curveID, data: keyShareKeys.ecdhe.PublicKey().Bytes()}}
183		}
184	}
185
186	if c.quic != nil {
187		p, err := c.quicGetTransportParameters()
188		if err != nil {
189			return nil, nil, nil, err
190		}
191		if p == nil {
192			p = []byte{}
193		}
194		hello.quicTransportParameters = p
195	}
196
197	var ech *echContext
198	if c.config.EncryptedClientHelloConfigList != nil {
199		if c.config.MinVersion != 0 && c.config.MinVersion < VersionTLS13 {
200			return nil, nil, nil, errors.New("tls: MinVersion must be >= VersionTLS13 if EncryptedClientHelloConfigList is populated")
201		}
202		if c.config.MaxVersion != 0 && c.config.MaxVersion <= VersionTLS12 {
203			return nil, nil, nil, errors.New("tls: MaxVersion must be >= VersionTLS13 if EncryptedClientHelloConfigList is populated")
204		}
205		echConfigs, err := parseECHConfigList(c.config.EncryptedClientHelloConfigList)
206		if err != nil {
207			return nil, nil, nil, err
208		}
209		echConfig := pickECHConfig(echConfigs)
210		if echConfig == nil {
211			return nil, nil, nil, errors.New("tls: EncryptedClientHelloConfigList contains no valid configs")
212		}
213		ech = &echContext{config: echConfig}
214		hello.encryptedClientHello = []byte{1} // indicate inner hello
215		// We need to explicitly set these 1.2 fields to nil, as we do not
216		// marshal them when encoding the inner hello, otherwise transcripts
217		// will later mismatch.
218		hello.supportedPoints = nil
219		hello.ticketSupported = false
220		hello.secureRenegotiationSupported = false
221		hello.extendedMasterSecret = false
222
223		echPK, err := hpke.ParseHPKEPublicKey(ech.config.KemID, ech.config.PublicKey)
224		if err != nil {
225			return nil, nil, nil, err
226		}
227		suite, err := pickECHCipherSuite(ech.config.SymmetricCipherSuite)
228		if err != nil {
229			return nil, nil, nil, err
230		}
231		ech.kdfID, ech.aeadID = suite.KDFID, suite.AEADID
232		info := append([]byte("tls ech\x00"), ech.config.raw...)
233		ech.encapsulatedKey, ech.hpkeContext, err = hpke.SetupSender(ech.config.KemID, suite.KDFID, suite.AEADID, echPK, info)
234		if err != nil {
235			return nil, nil, nil, err
236		}
237	}
238
239	return hello, keyShareKeys, ech, nil
240}
241
242type echContext struct {
243	config          *echConfig
244	hpkeContext     *hpke.Sender
245	encapsulatedKey []byte
246	innerHello      *clientHelloMsg
247	innerTranscript hash.Hash
248	kdfID           uint16
249	aeadID          uint16
250	echRejected     bool
251}
252
253func (c *Conn) clientHandshake(ctx context.Context) (err error) {
254	if c.config == nil {
255		c.config = defaultConfig()
256	}
257
258	// This may be a renegotiation handshake, in which case some fields
259	// need to be reset.
260	c.didResume = false
261
262	hello, keyShareKeys, ech, err := c.makeClientHello()
263	if err != nil {
264		return err
265	}
266
267	session, earlySecret, binderKey, err := c.loadSession(hello)
268	if err != nil {
269		return err
270	}
271	if session != nil {
272		defer func() {
273			// If we got a handshake failure when resuming a session, throw away
274			// the session ticket. See RFC 5077, Section 3.2.
275			//
276			// RFC 8446 makes no mention of dropping tickets on failure, but it
277			// does require servers to abort on invalid binders, so we need to
278			// delete tickets to recover from a corrupted PSK.
279			if err != nil {
280				if cacheKey := c.clientSessionCacheKey(); cacheKey != "" {
281					c.config.ClientSessionCache.Put(cacheKey, nil)
282				}
283			}
284		}()
285	}
286
287	if ech != nil {
288		// Split hello into inner and outer
289		ech.innerHello = hello.clone()
290
291		// Overwrite the server name in the outer hello with the public facing
292		// name.
293		hello.serverName = string(ech.config.PublicName)
294		// Generate a new random for the outer hello.
295		hello.random = make([]byte, 32)
296		_, err = io.ReadFull(c.config.rand(), hello.random)
297		if err != nil {
298			return errors.New("tls: short read from Rand: " + err.Error())
299		}
300
301		// NOTE: we don't do PSK GREASE, in line with boringssl, it's meant to
302		// work around _possibly_ broken middleboxes, but there is little-to-no
303		// evidence that this is actually a problem.
304
305		if err := computeAndUpdateOuterECHExtension(hello, ech.innerHello, ech, true); err != nil {
306			return err
307		}
308	}
309
310	c.serverName = hello.serverName
311
312	if _, err := c.writeHandshakeRecord(hello, nil); err != nil {
313		return err
314	}
315
316	if hello.earlyData {
317		suite := cipherSuiteTLS13ByID(session.cipherSuite)
318		transcript := suite.hash.New()
319		if err := transcriptMsg(hello, transcript); err != nil {
320			return err
321		}
322		earlyTrafficSecret := suite.deriveSecret(earlySecret, clientEarlyTrafficLabel, transcript)
323		c.quicSetWriteSecret(QUICEncryptionLevelEarly, suite.id, earlyTrafficSecret)
324	}
325
326	// serverHelloMsg is not included in the transcript
327	msg, err := c.readHandshake(nil)
328	if err != nil {
329		return err
330	}
331
332	serverHello, ok := msg.(*serverHelloMsg)
333	if !ok {
334		c.sendAlert(alertUnexpectedMessage)
335		return unexpectedMessageError(serverHello, msg)
336	}
337
338	if err := c.pickTLSVersion(serverHello); err != nil {
339		return err
340	}
341
342	// If we are negotiating a protocol version that's lower than what we
343	// support, check for the server downgrade canaries.
344	// See RFC 8446, Section 4.1.3.
345	maxVers := c.config.maxSupportedVersion(roleClient)
346	tls12Downgrade := string(serverHello.random[24:]) == downgradeCanaryTLS12
347	tls11Downgrade := string(serverHello.random[24:]) == downgradeCanaryTLS11
348	if maxVers == VersionTLS13 && c.vers <= VersionTLS12 && (tls12Downgrade || tls11Downgrade) ||
349		maxVers == VersionTLS12 && c.vers <= VersionTLS11 && tls11Downgrade {
350		c.sendAlert(alertIllegalParameter)
351		return errors.New("tls: downgrade attempt detected, possibly due to a MitM attack or a broken middlebox")
352	}
353
354	if c.vers == VersionTLS13 {
355		hs := &clientHandshakeStateTLS13{
356			c:            c,
357			ctx:          ctx,
358			serverHello:  serverHello,
359			hello:        hello,
360			keyShareKeys: keyShareKeys,
361			session:      session,
362			earlySecret:  earlySecret,
363			binderKey:    binderKey,
364			echContext:   ech,
365		}
366		return hs.handshake()
367	}
368
369	hs := &clientHandshakeState{
370		c:           c,
371		ctx:         ctx,
372		serverHello: serverHello,
373		hello:       hello,
374		session:     session,
375	}
376	return hs.handshake()
377}
378
379func (c *Conn) loadSession(hello *clientHelloMsg) (
380	session *SessionState, earlySecret, binderKey []byte, err error) {
381	if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil {
382		return nil, nil, nil, nil
383	}
384
385	echInner := bytes.Equal(hello.encryptedClientHello, []byte{1})
386
387	// ticketSupported is a TLS 1.2 extension (as TLS 1.3 replaced tickets with PSK
388	// identities) and ECH requires and forces TLS 1.3.
389	hello.ticketSupported = true && !echInner
390
391	if hello.supportedVersions[0] == VersionTLS13 {
392		// Require DHE on resumption as it guarantees forward secrecy against
393		// compromise of the session ticket key. See RFC 8446, Section 4.2.9.
394		hello.pskModes = []uint8{pskModeDHE}
395	}
396
397	// Session resumption is not allowed if renegotiating because
398	// renegotiation is primarily used to allow a client to send a client
399	// certificate, which would be skipped if session resumption occurred.
400	if c.handshakes != 0 {
401		return nil, nil, nil, nil
402	}
403
404	// Try to resume a previously negotiated TLS session, if available.
405	cacheKey := c.clientSessionCacheKey()
406	if cacheKey == "" {
407		return nil, nil, nil, nil
408	}
409	cs, ok := c.config.ClientSessionCache.Get(cacheKey)
410	if !ok || cs == nil {
411		return nil, nil, nil, nil
412	}
413	session = cs.session
414
415	// Check that version used for the previous session is still valid.
416	versOk := false
417	for _, v := range hello.supportedVersions {
418		if v == session.version {
419			versOk = true
420			break
421		}
422	}
423	if !versOk {
424		return nil, nil, nil, nil
425	}
426
427	// Check that the cached server certificate is not expired, and that it's
428	// valid for the ServerName. This should be ensured by the cache key, but
429	// protect the application from a faulty ClientSessionCache implementation.
430	if c.config.time().After(session.peerCertificates[0].NotAfter) {
431		// Expired certificate, delete the entry.
432		c.config.ClientSessionCache.Put(cacheKey, nil)
433		return nil, nil, nil, nil
434	}
435	if !c.config.InsecureSkipVerify {
436		if len(session.verifiedChains) == 0 {
437			// The original connection had InsecureSkipVerify, while this doesn't.
438			return nil, nil, nil, nil
439		}
440		if err := session.peerCertificates[0].VerifyHostname(c.config.ServerName); err != nil {
441			return nil, nil, nil, nil
442		}
443	}
444
445	if session.version != VersionTLS13 {
446		// In TLS 1.2 the cipher suite must match the resumed session. Ensure we
447		// are still offering it.
448		if mutualCipherSuite(hello.cipherSuites, session.cipherSuite) == nil {
449			return nil, nil, nil, nil
450		}
451
452		hello.sessionTicket = session.ticket
453		return
454	}
455
456	// Check that the session ticket is not expired.
457	if c.config.time().After(time.Unix(int64(session.useBy), 0)) {
458		c.config.ClientSessionCache.Put(cacheKey, nil)
459		return nil, nil, nil, nil
460	}
461
462	// In TLS 1.3 the KDF hash must match the resumed session. Ensure we
463	// offer at least one cipher suite with that hash.
464	cipherSuite := cipherSuiteTLS13ByID(session.cipherSuite)
465	if cipherSuite == nil {
466		return nil, nil, nil, nil
467	}
468	cipherSuiteOk := false
469	for _, offeredID := range hello.cipherSuites {
470		offeredSuite := cipherSuiteTLS13ByID(offeredID)
471		if offeredSuite != nil && offeredSuite.hash == cipherSuite.hash {
472			cipherSuiteOk = true
473			break
474		}
475	}
476	if !cipherSuiteOk {
477		return nil, nil, nil, nil
478	}
479
480	if c.quic != nil {
481		if c.quic.enableSessionEvents {
482			c.quicResumeSession(session)
483		}
484
485		// For 0-RTT, the cipher suite has to match exactly, and we need to be
486		// offering the same ALPN.
487		if session.EarlyData && mutualCipherSuiteTLS13(hello.cipherSuites, session.cipherSuite) != nil {
488			for _, alpn := range hello.alpnProtocols {
489				if alpn == session.alpnProtocol {
490					hello.earlyData = true
491					break
492				}
493			}
494		}
495	}
496
497	// Set the pre_shared_key extension. See RFC 8446, Section 4.2.11.1.
498	ticketAge := c.config.time().Sub(time.Unix(int64(session.createdAt), 0))
499	identity := pskIdentity{
500		label:               session.ticket,
501		obfuscatedTicketAge: uint32(ticketAge/time.Millisecond) + session.ageAdd,
502	}
503	hello.pskIdentities = []pskIdentity{identity}
504	hello.pskBinders = [][]byte{make([]byte, cipherSuite.hash.Size())}
505
506	// Compute the PSK binders. See RFC 8446, Section 4.2.11.2.
507	earlySecret = cipherSuite.extract(session.secret, nil)
508	binderKey = cipherSuite.deriveSecret(earlySecret, resumptionBinderLabel, nil)
509	transcript := cipherSuite.hash.New()
510	if err := computeAndUpdatePSK(hello, binderKey, transcript, cipherSuite.finishedHash); err != nil {
511		return nil, nil, nil, err
512	}
513
514	return
515}
516
517func (c *Conn) pickTLSVersion(serverHello *serverHelloMsg) error {
518	peerVersion := serverHello.vers
519	if serverHello.supportedVersion != 0 {
520		peerVersion = serverHello.supportedVersion
521	}
522
523	vers, ok := c.config.mutualVersion(roleClient, []uint16{peerVersion})
524	if !ok {
525		c.sendAlert(alertProtocolVersion)
526		return fmt.Errorf("tls: server selected unsupported protocol version %x", peerVersion)
527	}
528
529	c.vers = vers
530	c.haveVers = true
531	c.in.version = vers
532	c.out.version = vers
533
534	return nil
535}
536
537// Does the handshake, either a full one or resumes old session. Requires hs.c,
538// hs.hello, hs.serverHello, and, optionally, hs.session to be set.
539func (hs *clientHandshakeState) handshake() error {
540	c := hs.c
541
542	isResume, err := hs.processServerHello()
543	if err != nil {
544		return err
545	}
546
547	hs.finishedHash = newFinishedHash(c.vers, hs.suite)
548
549	// No signatures of the handshake are needed in a resumption.
550	// Otherwise, in a full handshake, if we don't have any certificates
551	// configured then we will never send a CertificateVerify message and
552	// thus no signatures are needed in that case either.
553	if isResume || (len(c.config.Certificates) == 0 && c.config.GetClientCertificate == nil) {
554		hs.finishedHash.discardHandshakeBuffer()
555	}
556
557	if err := transcriptMsg(hs.hello, &hs.finishedHash); err != nil {
558		return err
559	}
560	if err := transcriptMsg(hs.serverHello, &hs.finishedHash); err != nil {
561		return err
562	}
563
564	c.buffering = true
565	c.didResume = isResume
566	if isResume {
567		if err := hs.establishKeys(); err != nil {
568			return err
569		}
570		if err := hs.readSessionTicket(); err != nil {
571			return err
572		}
573		if err := hs.readFinished(c.serverFinished[:]); err != nil {
574			return err
575		}
576		c.clientFinishedIsFirst = false
577		// Make sure the connection is still being verified whether or not this
578		// is a resumption. Resumptions currently don't reverify certificates so
579		// they don't call verifyServerCertificate. See Issue 31641.
580		if c.config.VerifyConnection != nil {
581			if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
582				c.sendAlert(alertBadCertificate)
583				return err
584			}
585		}
586		if err := hs.sendFinished(c.clientFinished[:]); err != nil {
587			return err
588		}
589		if _, err := c.flush(); err != nil {
590			return err
591		}
592	} else {
593		if err := hs.doFullHandshake(); err != nil {
594			return err
595		}
596		if err := hs.establishKeys(); err != nil {
597			return err
598		}
599		if err := hs.sendFinished(c.clientFinished[:]); err != nil {
600			return err
601		}
602		if _, err := c.flush(); err != nil {
603			return err
604		}
605		c.clientFinishedIsFirst = true
606		if err := hs.readSessionTicket(); err != nil {
607			return err
608		}
609		if err := hs.readFinished(c.serverFinished[:]); err != nil {
610			return err
611		}
612	}
613	if err := hs.saveSessionTicket(); err != nil {
614		return err
615	}
616
617	c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random)
618	c.isHandshakeComplete.Store(true)
619
620	return nil
621}
622
623func (hs *clientHandshakeState) pickCipherSuite() error {
624	if hs.suite = mutualCipherSuite(hs.hello.cipherSuites, hs.serverHello.cipherSuite); hs.suite == nil {
625		hs.c.sendAlert(alertHandshakeFailure)
626		return errors.New("tls: server chose an unconfigured cipher suite")
627	}
628
629	if hs.c.config.CipherSuites == nil && !needFIPS() && rsaKexCiphers[hs.suite.id] {
630		tlsrsakex.Value() // ensure godebug is initialized
631		tlsrsakex.IncNonDefault()
632	}
633	if hs.c.config.CipherSuites == nil && !needFIPS() && tdesCiphers[hs.suite.id] {
634		tls3des.Value() // ensure godebug is initialized
635		tls3des.IncNonDefault()
636	}
637
638	hs.c.cipherSuite = hs.suite.id
639	return nil
640}
641
642func (hs *clientHandshakeState) doFullHandshake() error {
643	c := hs.c
644
645	msg, err := c.readHandshake(&hs.finishedHash)
646	if err != nil {
647		return err
648	}
649	certMsg, ok := msg.(*certificateMsg)
650	if !ok || len(certMsg.certificates) == 0 {
651		c.sendAlert(alertUnexpectedMessage)
652		return unexpectedMessageError(certMsg, msg)
653	}
654
655	msg, err = c.readHandshake(&hs.finishedHash)
656	if err != nil {
657		return err
658	}
659
660	cs, ok := msg.(*certificateStatusMsg)
661	if ok {
662		// RFC4366 on Certificate Status Request:
663		// The server MAY return a "certificate_status" message.
664
665		if !hs.serverHello.ocspStapling {
666			// If a server returns a "CertificateStatus" message, then the
667			// server MUST have included an extension of type "status_request"
668			// with empty "extension_data" in the extended server hello.
669
670			c.sendAlert(alertUnexpectedMessage)
671			return errors.New("tls: received unexpected CertificateStatus message")
672		}
673
674		c.ocspResponse = cs.response
675
676		msg, err = c.readHandshake(&hs.finishedHash)
677		if err != nil {
678			return err
679		}
680	}
681
682	if c.handshakes == 0 {
683		// If this is the first handshake on a connection, process and
684		// (optionally) verify the server's certificates.
685		if err := c.verifyServerCertificate(certMsg.certificates); err != nil {
686			return err
687		}
688	} else {
689		// This is a renegotiation handshake. We require that the
690		// server's identity (i.e. leaf certificate) is unchanged and
691		// thus any previous trust decision is still valid.
692		//
693		// See https://mitls.org/pages/attacks/3SHAKE for the
694		// motivation behind this requirement.
695		if !bytes.Equal(c.peerCertificates[0].Raw, certMsg.certificates[0]) {
696			c.sendAlert(alertBadCertificate)
697			return errors.New("tls: server's identity changed during renegotiation")
698		}
699	}
700
701	keyAgreement := hs.suite.ka(c.vers)
702
703	skx, ok := msg.(*serverKeyExchangeMsg)
704	if ok {
705		err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, c.peerCertificates[0], skx)
706		if err != nil {
707			c.sendAlert(alertUnexpectedMessage)
708			return err
709		}
710		if len(skx.key) >= 3 && skx.key[0] == 3 /* named curve */ {
711			c.curveID = CurveID(byteorder.BeUint16(skx.key[1:]))
712		}
713
714		msg, err = c.readHandshake(&hs.finishedHash)
715		if err != nil {
716			return err
717		}
718	}
719
720	var chainToSend *Certificate
721	var certRequested bool
722	certReq, ok := msg.(*certificateRequestMsg)
723	if ok {
724		certRequested = true
725
726		cri := certificateRequestInfoFromMsg(hs.ctx, c.vers, certReq)
727		if chainToSend, err = c.getClientCertificate(cri); err != nil {
728			c.sendAlert(alertInternalError)
729			return err
730		}
731
732		msg, err = c.readHandshake(&hs.finishedHash)
733		if err != nil {
734			return err
735		}
736	}
737
738	shd, ok := msg.(*serverHelloDoneMsg)
739	if !ok {
740		c.sendAlert(alertUnexpectedMessage)
741		return unexpectedMessageError(shd, msg)
742	}
743
744	// If the server requested a certificate then we have to send a
745	// Certificate message, even if it's empty because we don't have a
746	// certificate to send.
747	if certRequested {
748		certMsg = new(certificateMsg)
749		certMsg.certificates = chainToSend.Certificate
750		if _, err := hs.c.writeHandshakeRecord(certMsg, &hs.finishedHash); err != nil {
751			return err
752		}
753	}
754
755	preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, c.peerCertificates[0])
756	if err != nil {
757		c.sendAlert(alertInternalError)
758		return err
759	}
760	if ckx != nil {
761		if _, err := hs.c.writeHandshakeRecord(ckx, &hs.finishedHash); err != nil {
762			return err
763		}
764	}
765
766	if hs.serverHello.extendedMasterSecret {
767		c.extMasterSecret = true
768		hs.masterSecret = extMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret,
769			hs.finishedHash.Sum())
770	} else {
771		hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret,
772			hs.hello.random, hs.serverHello.random)
773	}
774	if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.hello.random, hs.masterSecret); err != nil {
775		c.sendAlert(alertInternalError)
776		return errors.New("tls: failed to write to key log: " + err.Error())
777	}
778
779	if chainToSend != nil && len(chainToSend.Certificate) > 0 {
780		certVerify := &certificateVerifyMsg{}
781
782		key, ok := chainToSend.PrivateKey.(crypto.Signer)
783		if !ok {
784			c.sendAlert(alertInternalError)
785			return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey)
786		}
787
788		var sigType uint8
789		var sigHash crypto.Hash
790		if c.vers >= VersionTLS12 {
791			signatureAlgorithm, err := selectSignatureScheme(c.vers, chainToSend, certReq.supportedSignatureAlgorithms)
792			if err != nil {
793				c.sendAlert(alertIllegalParameter)
794				return err
795			}
796			sigType, sigHash, err = typeAndHashFromSignatureScheme(signatureAlgorithm)
797			if err != nil {
798				return c.sendAlert(alertInternalError)
799			}
800			certVerify.hasSignatureAlgorithm = true
801			certVerify.signatureAlgorithm = signatureAlgorithm
802		} else {
803			sigType, sigHash, err = legacyTypeAndHashFromPublicKey(key.Public())
804			if err != nil {
805				c.sendAlert(alertIllegalParameter)
806				return err
807			}
808		}
809
810		signed := hs.finishedHash.hashForClientCertificate(sigType, sigHash)
811		signOpts := crypto.SignerOpts(sigHash)
812		if sigType == signatureRSAPSS {
813			signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
814		}
815		certVerify.signature, err = key.Sign(c.config.rand(), signed, signOpts)
816		if err != nil {
817			c.sendAlert(alertInternalError)
818			return err
819		}
820
821		if _, err := hs.c.writeHandshakeRecord(certVerify, &hs.finishedHash); err != nil {
822			return err
823		}
824	}
825
826	hs.finishedHash.discardHandshakeBuffer()
827
828	return nil
829}
830
831func (hs *clientHandshakeState) establishKeys() error {
832	c := hs.c
833
834	clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
835		keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
836	var clientCipher, serverCipher any
837	var clientHash, serverHash hash.Hash
838	if hs.suite.cipher != nil {
839		clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
840		clientHash = hs.suite.mac(clientMAC)
841		serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
842		serverHash = hs.suite.mac(serverMAC)
843	} else {
844		clientCipher = hs.suite.aead(clientKey, clientIV)
845		serverCipher = hs.suite.aead(serverKey, serverIV)
846	}
847
848	c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
849	c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
850	return nil
851}
852
853func (hs *clientHandshakeState) serverResumedSession() bool {
854	// If the server responded with the same sessionId then it means the
855	// sessionTicket is being used to resume a TLS session.
856	return hs.session != nil && hs.hello.sessionId != nil &&
857		bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
858}
859
860func (hs *clientHandshakeState) processServerHello() (bool, error) {
861	c := hs.c
862
863	if err := hs.pickCipherSuite(); err != nil {
864		return false, err
865	}
866
867	if hs.serverHello.compressionMethod != compressionNone {
868		c.sendAlert(alertUnexpectedMessage)
869		return false, errors.New("tls: server selected unsupported compression format")
870	}
871
872	if c.handshakes == 0 && hs.serverHello.secureRenegotiationSupported {
873		c.secureRenegotiation = true
874		if len(hs.serverHello.secureRenegotiation) != 0 {
875			c.sendAlert(alertHandshakeFailure)
876			return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
877		}
878	}
879
880	if c.handshakes > 0 && c.secureRenegotiation {
881		var expectedSecureRenegotiation [24]byte
882		copy(expectedSecureRenegotiation[:], c.clientFinished[:])
883		copy(expectedSecureRenegotiation[12:], c.serverFinished[:])
884		if !bytes.Equal(hs.serverHello.secureRenegotiation, expectedSecureRenegotiation[:]) {
885			c.sendAlert(alertHandshakeFailure)
886			return false, errors.New("tls: incorrect renegotiation extension contents")
887		}
888	}
889
890	if err := checkALPN(hs.hello.alpnProtocols, hs.serverHello.alpnProtocol, false); err != nil {
891		c.sendAlert(alertUnsupportedExtension)
892		return false, err
893	}
894	c.clientProtocol = hs.serverHello.alpnProtocol
895
896	c.scts = hs.serverHello.scts
897
898	if !hs.serverResumedSession() {
899		return false, nil
900	}
901
902	if hs.session.version != c.vers {
903		c.sendAlert(alertHandshakeFailure)
904		return false, errors.New("tls: server resumed a session with a different version")
905	}
906
907	if hs.session.cipherSuite != hs.suite.id {
908		c.sendAlert(alertHandshakeFailure)
909		return false, errors.New("tls: server resumed a session with a different cipher suite")
910	}
911
912	// RFC 7627, Section 5.3
913	if hs.session.extMasterSecret != hs.serverHello.extendedMasterSecret {
914		c.sendAlert(alertHandshakeFailure)
915		return false, errors.New("tls: server resumed a session with a different EMS extension")
916	}
917
918	// Restore master secret and certificates from previous state
919	hs.masterSecret = hs.session.secret
920	c.extMasterSecret = hs.session.extMasterSecret
921	c.peerCertificates = hs.session.peerCertificates
922	c.activeCertHandles = hs.c.activeCertHandles
923	c.verifiedChains = hs.session.verifiedChains
924	c.ocspResponse = hs.session.ocspResponse
925	// Let the ServerHello SCTs override the session SCTs from the original
926	// connection, if any are provided
927	if len(c.scts) == 0 && len(hs.session.scts) != 0 {
928		c.scts = hs.session.scts
929	}
930
931	return true, nil
932}
933
934// checkALPN ensure that the server's choice of ALPN protocol is compatible with
935// the protocols that we advertised in the Client Hello.
936func checkALPN(clientProtos []string, serverProto string, quic bool) error {
937	if serverProto == "" {
938		if quic && len(clientProtos) > 0 {
939			// RFC 9001, Section 8.1
940			return errors.New("tls: server did not select an ALPN protocol")
941		}
942		return nil
943	}
944	if len(clientProtos) == 0 {
945		return errors.New("tls: server advertised unrequested ALPN extension")
946	}
947	for _, proto := range clientProtos {
948		if proto == serverProto {
949			return nil
950		}
951	}
952	return errors.New("tls: server selected unadvertised ALPN protocol")
953}
954
955func (hs *clientHandshakeState) readFinished(out []byte) error {
956	c := hs.c
957
958	if err := c.readChangeCipherSpec(); err != nil {
959		return err
960	}
961
962	// finishedMsg is included in the transcript, but not until after we
963	// check the client version, since the state before this message was
964	// sent is used during verification.
965	msg, err := c.readHandshake(nil)
966	if err != nil {
967		return err
968	}
969	serverFinished, ok := msg.(*finishedMsg)
970	if !ok {
971		c.sendAlert(alertUnexpectedMessage)
972		return unexpectedMessageError(serverFinished, msg)
973	}
974
975	verify := hs.finishedHash.serverSum(hs.masterSecret)
976	if len(verify) != len(serverFinished.verifyData) ||
977		subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
978		c.sendAlert(alertHandshakeFailure)
979		return errors.New("tls: server's Finished message was incorrect")
980	}
981
982	if err := transcriptMsg(serverFinished, &hs.finishedHash); err != nil {
983		return err
984	}
985
986	copy(out, verify)
987	return nil
988}
989
990func (hs *clientHandshakeState) readSessionTicket() error {
991	if !hs.serverHello.ticketSupported {
992		return nil
993	}
994	c := hs.c
995
996	if !hs.hello.ticketSupported {
997		c.sendAlert(alertIllegalParameter)
998		return errors.New("tls: server sent unrequested session ticket")
999	}
1000
1001	msg, err := c.readHandshake(&hs.finishedHash)
1002	if err != nil {
1003		return err
1004	}
1005	sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
1006	if !ok {
1007		c.sendAlert(alertUnexpectedMessage)
1008		return unexpectedMessageError(sessionTicketMsg, msg)
1009	}
1010
1011	hs.ticket = sessionTicketMsg.ticket
1012	return nil
1013}
1014
1015func (hs *clientHandshakeState) saveSessionTicket() error {
1016	if hs.ticket == nil {
1017		return nil
1018	}
1019	c := hs.c
1020
1021	cacheKey := c.clientSessionCacheKey()
1022	if cacheKey == "" {
1023		return nil
1024	}
1025
1026	session := c.sessionState()
1027	session.secret = hs.masterSecret
1028	session.ticket = hs.ticket
1029
1030	cs := &ClientSessionState{session: session}
1031	c.config.ClientSessionCache.Put(cacheKey, cs)
1032	return nil
1033}
1034
1035func (hs *clientHandshakeState) sendFinished(out []byte) error {
1036	c := hs.c
1037
1038	if err := c.writeChangeCipherRecord(); err != nil {
1039		return err
1040	}
1041
1042	finished := new(finishedMsg)
1043	finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
1044	if _, err := hs.c.writeHandshakeRecord(finished, &hs.finishedHash); err != nil {
1045		return err
1046	}
1047	copy(out, finished.verifyData)
1048	return nil
1049}
1050
1051// defaultMaxRSAKeySize is the maximum RSA key size in bits that we are willing
1052// to verify the signatures of during a TLS handshake.
1053const defaultMaxRSAKeySize = 8192
1054
1055var tlsmaxrsasize = godebug.New("tlsmaxrsasize")
1056
1057func checkKeySize(n int) (max int, ok bool) {
1058	if v := tlsmaxrsasize.Value(); v != "" {
1059		if max, err := strconv.Atoi(v); err == nil {
1060			if (n <= max) != (n <= defaultMaxRSAKeySize) {
1061				tlsmaxrsasize.IncNonDefault()
1062			}
1063			return max, n <= max
1064		}
1065	}
1066	return defaultMaxRSAKeySize, n <= defaultMaxRSAKeySize
1067}
1068
1069// verifyServerCertificate parses and verifies the provided chain, setting
1070// c.verifiedChains and c.peerCertificates or sending the appropriate alert.
1071func (c *Conn) verifyServerCertificate(certificates [][]byte) error {
1072	activeHandles := make([]*activeCert, len(certificates))
1073	certs := make([]*x509.Certificate, len(certificates))
1074	for i, asn1Data := range certificates {
1075		cert, err := globalCertCache.newCert(asn1Data)
1076		if err != nil {
1077			c.sendAlert(alertBadCertificate)
1078			return errors.New("tls: failed to parse certificate from server: " + err.Error())
1079		}
1080		if cert.cert.PublicKeyAlgorithm == x509.RSA {
1081			n := cert.cert.PublicKey.(*rsa.PublicKey).N.BitLen()
1082			if max, ok := checkKeySize(n); !ok {
1083				c.sendAlert(alertBadCertificate)
1084				return fmt.Errorf("tls: server sent certificate containing RSA key larger than %d bits", max)
1085			}
1086		}
1087		activeHandles[i] = cert
1088		certs[i] = cert.cert
1089	}
1090
1091	echRejected := c.config.EncryptedClientHelloConfigList != nil && !c.echAccepted
1092	if echRejected {
1093		if c.config.EncryptedClientHelloRejectionVerify != nil {
1094			if err := c.config.EncryptedClientHelloRejectionVerify(c.connectionStateLocked()); err != nil {
1095				c.sendAlert(alertBadCertificate)
1096				return err
1097			}
1098		} else {
1099			opts := x509.VerifyOptions{
1100				Roots:         c.config.RootCAs,
1101				CurrentTime:   c.config.time(),
1102				DNSName:       c.serverName,
1103				Intermediates: x509.NewCertPool(),
1104			}
1105
1106			for _, cert := range certs[1:] {
1107				opts.Intermediates.AddCert(cert)
1108			}
1109			var err error
1110			c.verifiedChains, err = certs[0].Verify(opts)
1111			if err != nil {
1112				c.sendAlert(alertBadCertificate)
1113				return &CertificateVerificationError{UnverifiedCertificates: certs, Err: err}
1114			}
1115		}
1116	} else if !c.config.InsecureSkipVerify {
1117		opts := x509.VerifyOptions{
1118			Roots:         c.config.RootCAs,
1119			CurrentTime:   c.config.time(),
1120			DNSName:       c.config.ServerName,
1121			Intermediates: x509.NewCertPool(),
1122		}
1123
1124		for _, cert := range certs[1:] {
1125			opts.Intermediates.AddCert(cert)
1126		}
1127		var err error
1128		c.verifiedChains, err = certs[0].Verify(opts)
1129		if err != nil {
1130			c.sendAlert(alertBadCertificate)
1131			return &CertificateVerificationError{UnverifiedCertificates: certs, Err: err}
1132		}
1133	}
1134
1135	switch certs[0].PublicKey.(type) {
1136	case *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey:
1137		break
1138	default:
1139		c.sendAlert(alertUnsupportedCertificate)
1140		return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
1141	}
1142
1143	c.activeCertHandles = activeHandles
1144	c.peerCertificates = certs
1145
1146	if c.config.VerifyPeerCertificate != nil && !echRejected {
1147		if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
1148			c.sendAlert(alertBadCertificate)
1149			return err
1150		}
1151	}
1152
1153	if c.config.VerifyConnection != nil && !echRejected {
1154		if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
1155			c.sendAlert(alertBadCertificate)
1156			return err
1157		}
1158	}
1159
1160	return nil
1161}
1162
1163// certificateRequestInfoFromMsg generates a CertificateRequestInfo from a TLS
1164// <= 1.2 CertificateRequest, making an effort to fill in missing information.
1165func certificateRequestInfoFromMsg(ctx context.Context, vers uint16, certReq *certificateRequestMsg) *CertificateRequestInfo {
1166	cri := &CertificateRequestInfo{
1167		AcceptableCAs: certReq.certificateAuthorities,
1168		Version:       vers,
1169		ctx:           ctx,
1170	}
1171
1172	var rsaAvail, ecAvail bool
1173	for _, certType := range certReq.certificateTypes {
1174		switch certType {
1175		case certTypeRSASign:
1176			rsaAvail = true
1177		case certTypeECDSASign:
1178			ecAvail = true
1179		}
1180	}
1181
1182	if !certReq.hasSignatureAlgorithm {
1183		// Prior to TLS 1.2, signature schemes did not exist. In this case we
1184		// make up a list based on the acceptable certificate types, to help
1185		// GetClientCertificate and SupportsCertificate select the right certificate.
1186		// The hash part of the SignatureScheme is a lie here, because
1187		// TLS 1.0 and 1.1 always use MD5+SHA1 for RSA and SHA1 for ECDSA.
1188		switch {
1189		case rsaAvail && ecAvail:
1190			cri.SignatureSchemes = []SignatureScheme{
1191				ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512,
1192				PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1,
1193			}
1194		case rsaAvail:
1195			cri.SignatureSchemes = []SignatureScheme{
1196				PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1,
1197			}
1198		case ecAvail:
1199			cri.SignatureSchemes = []SignatureScheme{
1200				ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512,
1201			}
1202		}
1203		return cri
1204	}
1205
1206	// Filter the signature schemes based on the certificate types.
1207	// See RFC 5246, Section 7.4.4 (where it calls this "somewhat complicated").
1208	cri.SignatureSchemes = make([]SignatureScheme, 0, len(certReq.supportedSignatureAlgorithms))
1209	for _, sigScheme := range certReq.supportedSignatureAlgorithms {
1210		sigType, _, err := typeAndHashFromSignatureScheme(sigScheme)
1211		if err != nil {
1212			continue
1213		}
1214		switch sigType {
1215		case signatureECDSA, signatureEd25519:
1216			if ecAvail {
1217				cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme)
1218			}
1219		case signatureRSAPSS, signaturePKCS1v15:
1220			if rsaAvail {
1221				cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme)
1222			}
1223		}
1224	}
1225
1226	return cri
1227}
1228
1229func (c *Conn) getClientCertificate(cri *CertificateRequestInfo) (*Certificate, error) {
1230	if c.config.GetClientCertificate != nil {
1231		return c.config.GetClientCertificate(cri)
1232	}
1233
1234	for _, chain := range c.config.Certificates {
1235		if err := cri.SupportsCertificate(&chain); err != nil {
1236			continue
1237		}
1238		return &chain, nil
1239	}
1240
1241	// No acceptable certificate found. Don't send a certificate.
1242	return new(Certificate), nil
1243}
1244
1245// clientSessionCacheKey returns a key used to cache sessionTickets that could
1246// be used to resume previously negotiated TLS sessions with a server.
1247func (c *Conn) clientSessionCacheKey() string {
1248	if len(c.config.ServerName) > 0 {
1249		return c.config.ServerName
1250	}
1251	if c.conn != nil {
1252		return c.conn.RemoteAddr().String()
1253	}
1254	return ""
1255}
1256
1257// hostnameInSNI converts name into an appropriate hostname for SNI.
1258// Literal IP addresses and absolute FQDNs are not permitted as SNI values.
1259// See RFC 6066, Section 3.
1260func hostnameInSNI(name string) string {
1261	host := name
1262	if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' {
1263		host = host[1 : len(host)-1]
1264	}
1265	if i := strings.LastIndex(host, "%"); i > 0 {
1266		host = host[:i]
1267	}
1268	if net.ParseIP(host) != nil {
1269		return ""
1270	}
1271	for len(name) > 0 && name[len(name)-1] == '.' {
1272		name = name[:len(name)-1]
1273	}
1274	return name
1275}
1276
1277func computeAndUpdatePSK(m *clientHelloMsg, binderKey []byte, transcript hash.Hash, finishedHash func([]byte, hash.Hash) []byte) error {
1278	helloBytes, err := m.marshalWithoutBinders()
1279	if err != nil {
1280		return err
1281	}
1282	transcript.Write(helloBytes)
1283	pskBinders := [][]byte{finishedHash(binderKey, transcript)}
1284	return m.updateBinders(pskBinders)
1285}
1286