• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/elliptic"
12	"crypto/rsa"
13	"crypto/subtle"
14	"crypto/x509"
15	"errors"
16	"fmt"
17	"io"
18	"math/big"
19	"net"
20	"strconv"
21	"time"
22
23	"./ed25519"
24)
25
26type clientHandshakeState struct {
27	c             *Conn
28	serverHello   *serverHelloMsg
29	hello         *clientHelloMsg
30	suite         *cipherSuite
31	finishedHash  finishedHash
32	keyShares     map[CurveID]ecdhCurve
33	masterSecret  []byte
34	session       *ClientSessionState
35	finishedBytes []byte
36}
37
38func mapClientHelloVersion(vers uint16, isDTLS bool) uint16 {
39	if !isDTLS {
40		return vers
41	}
42
43	switch vers {
44	case VersionTLS12:
45		return VersionDTLS12
46	case VersionTLS10:
47		return VersionDTLS10
48	}
49
50	panic("Unknown ClientHello version.")
51}
52
53func (c *Conn) clientHandshake() error {
54	if c.config == nil {
55		c.config = defaultConfig()
56	}
57
58	if len(c.config.ServerName) == 0 && !c.config.InsecureSkipVerify {
59		return errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
60	}
61
62	c.sendHandshakeSeq = 0
63	c.recvHandshakeSeq = 0
64
65	nextProtosLength := 0
66	for _, proto := range c.config.NextProtos {
67		if l := len(proto); l > 255 {
68			return errors.New("tls: invalid NextProtos value")
69		} else {
70			nextProtosLength += 1 + l
71		}
72	}
73	if nextProtosLength > 0xffff {
74		return errors.New("tls: NextProtos values too large")
75	}
76
77	minVersion := c.config.minVersion(c.isDTLS)
78	maxVersion := c.config.maxVersion(c.isDTLS)
79	hello := &clientHelloMsg{
80		isDTLS:                  c.isDTLS,
81		compressionMethods:      []uint8{compressionNone},
82		random:                  make([]byte, 32),
83		ocspStapling:            !c.config.Bugs.NoOCSPStapling,
84		sctListSupported:        !c.config.Bugs.NoSignedCertificateTimestamps,
85		serverName:              c.config.ServerName,
86		supportedCurves:         c.config.curvePreferences(),
87		supportedPoints:         []uint8{pointFormatUncompressed},
88		nextProtoNeg:            len(c.config.NextProtos) > 0,
89		secureRenegotiation:     []byte{},
90		alpnProtocols:           c.config.NextProtos,
91		duplicateExtension:      c.config.Bugs.DuplicateExtension,
92		channelIDSupported:      c.config.ChannelID != nil,
93		npnAfterAlpn:            c.config.Bugs.SwapNPNAndALPN,
94		extendedMasterSecret:    maxVersion >= VersionTLS10,
95		srtpProtectionProfiles:  c.config.SRTPProtectionProfiles,
96		srtpMasterKeyIdentifier: c.config.Bugs.SRTPMasterKeyIdentifer,
97		customExtension:         c.config.Bugs.CustomExtension,
98		pskBinderFirst:          c.config.Bugs.PSKBinderFirst,
99		omitExtensions:          c.config.Bugs.OmitExtensions,
100		emptyExtensions:         c.config.Bugs.EmptyExtensions,
101	}
102
103	if maxVersion >= VersionTLS13 {
104		hello.vers = mapClientHelloVersion(VersionTLS12, c.isDTLS)
105		if !c.config.Bugs.OmitSupportedVersions {
106			hello.supportedVersions = c.config.supportedVersions(c.isDTLS)
107		}
108		hello.pskKEModes = []byte{pskDHEKEMode}
109	} else {
110		hello.vers = mapClientHelloVersion(maxVersion, c.isDTLS)
111	}
112
113	if c.config.Bugs.SendClientVersion != 0 {
114		hello.vers = c.config.Bugs.SendClientVersion
115	}
116
117	if len(c.config.Bugs.SendSupportedVersions) > 0 {
118		hello.supportedVersions = c.config.Bugs.SendSupportedVersions
119	}
120
121	disableEMS := c.config.Bugs.NoExtendedMasterSecret
122	if c.cipherSuite != nil {
123		disableEMS = c.config.Bugs.NoExtendedMasterSecretOnRenegotiation
124	}
125
126	if disableEMS {
127		hello.extendedMasterSecret = false
128	}
129
130	if c.config.Bugs.NoSupportedCurves {
131		hello.supportedCurves = nil
132	}
133
134	if len(c.config.Bugs.SendPSKKeyExchangeModes) != 0 {
135		hello.pskKEModes = c.config.Bugs.SendPSKKeyExchangeModes
136	}
137
138	if c.config.Bugs.SendCompressionMethods != nil {
139		hello.compressionMethods = c.config.Bugs.SendCompressionMethods
140	}
141
142	if c.config.Bugs.SendSupportedPointFormats != nil {
143		hello.supportedPoints = c.config.Bugs.SendSupportedPointFormats
144	}
145
146	if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
147		if c.config.Bugs.BadRenegotiationInfo {
148			hello.secureRenegotiation = append(hello.secureRenegotiation, c.clientVerify...)
149			hello.secureRenegotiation[0] ^= 0x80
150		} else {
151			hello.secureRenegotiation = c.clientVerify
152		}
153	}
154
155	if c.noRenegotiationInfo() {
156		hello.secureRenegotiation = nil
157	}
158
159	var keyShares map[CurveID]ecdhCurve
160	if maxVersion >= VersionTLS13 {
161		keyShares = make(map[CurveID]ecdhCurve)
162		hello.hasKeyShares = true
163		hello.trailingKeyShareData = c.config.Bugs.TrailingKeyShareData
164		curvesToSend := c.config.defaultCurves()
165		for _, curveID := range hello.supportedCurves {
166			if !curvesToSend[curveID] {
167				continue
168			}
169			curve, ok := curveForCurveID(curveID)
170			if !ok {
171				continue
172			}
173			publicKey, err := curve.offer(c.config.rand())
174			if err != nil {
175				return err
176			}
177
178			if c.config.Bugs.SendCurve != 0 {
179				curveID = c.config.Bugs.SendCurve
180			}
181			if c.config.Bugs.InvalidECDHPoint {
182				publicKey[0] ^= 0xff
183			}
184
185			hello.keyShares = append(hello.keyShares, keyShareEntry{
186				group:       curveID,
187				keyExchange: publicKey,
188			})
189			keyShares[curveID] = curve
190
191			if c.config.Bugs.DuplicateKeyShares {
192				hello.keyShares = append(hello.keyShares, hello.keyShares[len(hello.keyShares)-1])
193			}
194		}
195
196		if c.config.Bugs.MissingKeyShare {
197			hello.hasKeyShares = false
198		}
199	}
200
201	possibleCipherSuites := c.config.cipherSuites()
202	hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites))
203
204NextCipherSuite:
205	for _, suiteId := range possibleCipherSuites {
206		for _, suite := range cipherSuites {
207			if suite.id != suiteId {
208				continue
209			}
210			// Don't advertise TLS 1.2-only cipher suites unless
211			// we're attempting TLS 1.2.
212			if maxVersion < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
213				continue
214			}
215			// Don't advertise non-DTLS cipher suites in DTLS.
216			if c.isDTLS && suite.flags&suiteNoDTLS != 0 {
217				continue
218			}
219			hello.cipherSuites = append(hello.cipherSuites, suiteId)
220			continue NextCipherSuite
221		}
222	}
223
224	if c.config.Bugs.AdvertiseAllConfiguredCiphers {
225		hello.cipherSuites = possibleCipherSuites
226	}
227
228	if c.config.Bugs.SendRenegotiationSCSV {
229		hello.cipherSuites = append(hello.cipherSuites, renegotiationSCSV)
230	}
231
232	if c.config.Bugs.SendFallbackSCSV {
233		hello.cipherSuites = append(hello.cipherSuites, fallbackSCSV)
234	}
235
236	_, err := io.ReadFull(c.config.rand(), hello.random)
237	if err != nil {
238		c.sendAlert(alertInternalError)
239		return errors.New("tls: short read from Rand: " + err.Error())
240	}
241
242	if maxVersion >= VersionTLS12 && !c.config.Bugs.NoSignatureAlgorithms {
243		hello.signatureAlgorithms = c.config.verifySignatureAlgorithms()
244	}
245
246	var session *ClientSessionState
247	var cacheKey string
248	sessionCache := c.config.ClientSessionCache
249
250	if sessionCache != nil {
251		hello.ticketSupported = !c.config.SessionTicketsDisabled
252
253		// Try to resume a previously negotiated TLS session, if
254		// available.
255		cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
256		// TODO(nharper): Support storing more than one session
257		// ticket for TLS 1.3.
258		candidateSession, ok := sessionCache.Get(cacheKey)
259		if ok {
260			ticketOk := !c.config.SessionTicketsDisabled || candidateSession.sessionTicket == nil
261
262			// Check that the ciphersuite/version used for the
263			// previous session are still valid.
264			cipherSuiteOk := false
265			if candidateSession.vers <= VersionTLS12 {
266				for _, id := range hello.cipherSuites {
267					if id == candidateSession.cipherSuite {
268						cipherSuiteOk = true
269						break
270					}
271				}
272			} else {
273				// TLS 1.3 allows the cipher to change on
274				// resumption.
275				cipherSuiteOk = true
276			}
277
278			versOk := candidateSession.vers >= minVersion &&
279				candidateSession.vers <= maxVersion
280			if ticketOk && versOk && cipherSuiteOk {
281				session = candidateSession
282			}
283		}
284	}
285
286	var pskCipherSuite *cipherSuite
287	if session != nil && c.config.time().Before(session.ticketExpiration) {
288		ticket := session.sessionTicket
289		if c.config.Bugs.FilterTicket != nil && len(ticket) > 0 {
290			// Copy the ticket so FilterTicket may act in-place.
291			ticket = make([]byte, len(session.sessionTicket))
292			copy(ticket, session.sessionTicket)
293
294			ticket, err = c.config.Bugs.FilterTicket(ticket)
295			if err != nil {
296				return err
297			}
298		}
299
300		if session.vers >= VersionTLS13 || c.config.Bugs.SendBothTickets {
301			pskCipherSuite = cipherSuiteFromID(session.cipherSuite)
302			if pskCipherSuite == nil {
303				return errors.New("tls: client session cache has invalid cipher suite")
304			}
305			// TODO(nharper): Support sending more
306			// than one PSK identity.
307			ticketAge := uint32(c.config.time().Sub(session.ticketCreationTime) / time.Millisecond)
308			if c.config.Bugs.SendTicketAge != 0 {
309				ticketAge = uint32(c.config.Bugs.SendTicketAge / time.Millisecond)
310			}
311			psk := pskIdentity{
312				ticket:              ticket,
313				obfuscatedTicketAge: session.ticketAgeAdd + ticketAge,
314			}
315			hello.pskIdentities = []pskIdentity{psk}
316
317			if c.config.Bugs.ExtraPSKIdentity {
318				hello.pskIdentities = append(hello.pskIdentities, psk)
319			}
320		}
321
322		if session.vers < VersionTLS13 || c.config.Bugs.SendBothTickets {
323			if ticket != nil {
324				hello.sessionTicket = ticket
325				// A random session ID is used to detect when the
326				// server accepted the ticket and is resuming a session
327				// (see RFC 5077).
328				sessionIdLen := 16
329				if c.config.Bugs.TicketSessionIDLength != 0 {
330					sessionIdLen = c.config.Bugs.TicketSessionIDLength
331				}
332				if c.config.Bugs.EmptyTicketSessionID {
333					sessionIdLen = 0
334				}
335				hello.sessionId = make([]byte, sessionIdLen)
336				if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil {
337					c.sendAlert(alertInternalError)
338					return errors.New("tls: short read from Rand: " + err.Error())
339				}
340			} else {
341				hello.sessionId = session.sessionId
342			}
343		}
344	}
345
346	if c.config.Bugs.SendCipherSuites != nil {
347		hello.cipherSuites = c.config.Bugs.SendCipherSuites
348	}
349
350	var sendEarlyData bool
351	if len(hello.pskIdentities) > 0 && c.config.Bugs.SendEarlyData != nil {
352		hello.hasEarlyData = true
353		sendEarlyData = true
354	}
355	if c.config.Bugs.SendFakeEarlyDataLength > 0 {
356		hello.hasEarlyData = true
357	}
358	if c.config.Bugs.OmitEarlyDataExtension {
359		hello.hasEarlyData = false
360	}
361
362	var helloBytes []byte
363	if c.config.Bugs.SendV2ClientHello {
364		// Test that the peer left-pads random.
365		hello.random[0] = 0
366		v2Hello := &v2ClientHelloMsg{
367			vers:         hello.vers,
368			cipherSuites: hello.cipherSuites,
369			// No session resumption for V2ClientHello.
370			sessionId: nil,
371			challenge: hello.random[1:],
372		}
373		helloBytes = v2Hello.marshal()
374		c.writeV2Record(helloBytes)
375	} else {
376		if len(hello.pskIdentities) > 0 {
377			generatePSKBinders(hello, pskCipherSuite, session.masterSecret, []byte{}, c.config)
378		}
379		helloBytes = hello.marshal()
380
381		if c.config.Bugs.PartialClientFinishedWithClientHello {
382			// Include one byte of Finished. We can compute it
383			// without completing the handshake. This assumes we
384			// negotiate TLS 1.3 with no HelloRetryRequest or
385			// CertificateRequest.
386			toWrite := make([]byte, 0, len(helloBytes)+1)
387			toWrite = append(toWrite, helloBytes...)
388			toWrite = append(toWrite, typeFinished)
389			c.writeRecord(recordTypeHandshake, toWrite)
390		} else {
391			c.writeRecord(recordTypeHandshake, helloBytes)
392		}
393	}
394	c.flushHandshake()
395
396	if err := c.simulatePacketLoss(nil); err != nil {
397		return err
398	}
399	if c.config.Bugs.SendEarlyAlert {
400		c.sendAlert(alertHandshakeFailure)
401	}
402	if c.config.Bugs.SendFakeEarlyDataLength > 0 {
403		c.sendFakeEarlyData(c.config.Bugs.SendFakeEarlyDataLength)
404	}
405
406	// Derive early write keys and set Conn state to allow early writes.
407	if sendEarlyData {
408		finishedHash := newFinishedHash(session.vers, pskCipherSuite)
409		finishedHash.addEntropy(session.masterSecret)
410		finishedHash.Write(helloBytes)
411		earlyTrafficSecret := finishedHash.deriveSecret(earlyTrafficLabel)
412		c.out.useTrafficSecret(session.vers, pskCipherSuite, earlyTrafficSecret, clientWrite)
413		for _, earlyData := range c.config.Bugs.SendEarlyData {
414			if _, err := c.writeRecord(recordTypeApplicationData, earlyData); err != nil {
415				return err
416			}
417		}
418	}
419
420	msg, err := c.readHandshake()
421	if err != nil {
422		return err
423	}
424
425	if c.isDTLS {
426		helloVerifyRequest, ok := msg.(*helloVerifyRequestMsg)
427		if ok {
428			if helloVerifyRequest.vers != VersionDTLS10 {
429				// Per RFC 6347, the version field in
430				// HelloVerifyRequest SHOULD be always DTLS
431				// 1.0. Enforce this for testing purposes.
432				return errors.New("dtls: bad HelloVerifyRequest version")
433			}
434
435			hello.raw = nil
436			hello.cookie = helloVerifyRequest.cookie
437			helloBytes = hello.marshal()
438			c.writeRecord(recordTypeHandshake, helloBytes)
439			c.flushHandshake()
440
441			if err := c.simulatePacketLoss(nil); err != nil {
442				return err
443			}
444			msg, err = c.readHandshake()
445			if err != nil {
446				return err
447			}
448		}
449	}
450
451	var serverWireVersion uint16
452	switch m := msg.(type) {
453	case *helloRetryRequestMsg:
454		serverWireVersion = m.vers
455	case *serverHelloMsg:
456		serverWireVersion = m.vers
457	default:
458		c.sendAlert(alertUnexpectedMessage)
459		return fmt.Errorf("tls: received unexpected message of type %T when waiting for HelloRetryRequest or ServerHello", msg)
460	}
461
462	serverVersion, ok := c.config.isSupportedVersion(serverWireVersion, c.isDTLS)
463	if !ok {
464		c.sendAlert(alertProtocolVersion)
465		return fmt.Errorf("tls: server selected unsupported protocol version %x", c.vers)
466	}
467	c.wireVersion = serverWireVersion
468	c.vers = serverVersion
469	c.haveVers = true
470
471	helloRetryRequest, haveHelloRetryRequest := msg.(*helloRetryRequestMsg)
472	var secondHelloBytes []byte
473	if haveHelloRetryRequest {
474		c.out.resetCipher()
475		if len(helloRetryRequest.cookie) > 0 {
476			hello.tls13Cookie = helloRetryRequest.cookie
477		}
478
479		if c.config.Bugs.MisinterpretHelloRetryRequestCurve != 0 {
480			helloRetryRequest.hasSelectedGroup = true
481			helloRetryRequest.selectedGroup = c.config.Bugs.MisinterpretHelloRetryRequestCurve
482		}
483		if helloRetryRequest.hasSelectedGroup {
484			var hrrCurveFound bool
485			group := helloRetryRequest.selectedGroup
486			for _, curveID := range hello.supportedCurves {
487				if group == curveID {
488					hrrCurveFound = true
489					break
490				}
491			}
492			if !hrrCurveFound || keyShares[group] != nil {
493				c.sendAlert(alertHandshakeFailure)
494				return errors.New("tls: received invalid HelloRetryRequest")
495			}
496			curve, ok := curveForCurveID(group)
497			if !ok {
498				return errors.New("tls: Unable to get curve requested in HelloRetryRequest")
499			}
500			publicKey, err := curve.offer(c.config.rand())
501			if err != nil {
502				return err
503			}
504			keyShares[group] = curve
505			hello.keyShares = []keyShareEntry{{
506				group:       group,
507				keyExchange: publicKey,
508			}}
509		}
510
511		if c.config.Bugs.SecondClientHelloMissingKeyShare {
512			hello.hasKeyShares = false
513		}
514
515		hello.hasEarlyData = c.config.Bugs.SendEarlyDataOnSecondClientHello
516		hello.raw = nil
517
518		if len(hello.pskIdentities) > 0 {
519			generatePSKBinders(hello, pskCipherSuite, session.masterSecret, append(helloBytes, helloRetryRequest.marshal()...), c.config)
520		}
521		secondHelloBytes = hello.marshal()
522
523		if c.config.Bugs.InterleaveEarlyData {
524			c.sendFakeEarlyData(4)
525			c.writeRecord(recordTypeHandshake, secondHelloBytes[:16])
526			c.sendFakeEarlyData(4)
527			c.writeRecord(recordTypeHandshake, secondHelloBytes[16:])
528		} else {
529			c.writeRecord(recordTypeHandshake, secondHelloBytes)
530		}
531		c.flushHandshake()
532
533		if c.config.Bugs.SendEarlyDataOnSecondClientHello {
534			c.sendFakeEarlyData(4)
535		}
536
537		msg, err = c.readHandshake()
538		if err != nil {
539			return err
540		}
541	}
542
543	serverHello, ok := msg.(*serverHelloMsg)
544	if !ok {
545		c.sendAlert(alertUnexpectedMessage)
546		return unexpectedMessageError(serverHello, msg)
547	}
548
549	if serverWireVersion != serverHello.vers {
550		c.sendAlert(alertProtocolVersion)
551		return fmt.Errorf("tls: server sent non-matching version %x vs %x", serverWireVersion, serverHello.vers)
552	}
553
554	// Check for downgrade signals in the server random, per
555	// draft-ietf-tls-tls13-16, section 4.1.3.
556	if c.vers <= VersionTLS12 && c.config.maxVersion(c.isDTLS) >= VersionTLS13 {
557		if bytes.Equal(serverHello.random[len(serverHello.random)-8:], downgradeTLS13) {
558			c.sendAlert(alertProtocolVersion)
559			return errors.New("tls: downgrade from TLS 1.3 detected")
560		}
561	}
562	if c.vers <= VersionTLS11 && c.config.maxVersion(c.isDTLS) >= VersionTLS12 {
563		if bytes.Equal(serverHello.random[len(serverHello.random)-8:], downgradeTLS12) {
564			c.sendAlert(alertProtocolVersion)
565			return errors.New("tls: downgrade from TLS 1.2 detected")
566		}
567	}
568
569	suite := mutualCipherSuite(hello.cipherSuites, serverHello.cipherSuite)
570	if suite == nil {
571		c.sendAlert(alertHandshakeFailure)
572		return fmt.Errorf("tls: server selected an unsupported cipher suite")
573	}
574
575	if haveHelloRetryRequest && helloRetryRequest.hasSelectedGroup && helloRetryRequest.selectedGroup != serverHello.keyShare.group {
576		c.sendAlert(alertHandshakeFailure)
577		return errors.New("tls: ServerHello parameters did not match HelloRetryRequest")
578	}
579
580	hs := &clientHandshakeState{
581		c:            c,
582		serverHello:  serverHello,
583		hello:        hello,
584		suite:        suite,
585		finishedHash: newFinishedHash(c.vers, suite),
586		keyShares:    keyShares,
587		session:      session,
588	}
589
590	hs.writeHash(helloBytes, hs.c.sendHandshakeSeq-1)
591	if haveHelloRetryRequest {
592		hs.writeServerHash(helloRetryRequest.marshal())
593		hs.writeClientHash(secondHelloBytes)
594	}
595	hs.writeServerHash(hs.serverHello.marshal())
596
597	if c.vers >= VersionTLS13 {
598		if err := hs.doTLS13Handshake(); err != nil {
599			return err
600		}
601	} else {
602		if c.config.Bugs.EarlyChangeCipherSpec > 0 {
603			hs.establishKeys()
604			c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
605		}
606
607		if hs.serverHello.compressionMethod != compressionNone {
608			c.sendAlert(alertUnexpectedMessage)
609			return errors.New("tls: server selected unsupported compression format")
610		}
611
612		err = hs.processServerExtensions(&serverHello.extensions)
613		if err != nil {
614			return err
615		}
616
617		isResume, err := hs.processServerHello()
618		if err != nil {
619			return err
620		}
621
622		if isResume {
623			if c.config.Bugs.EarlyChangeCipherSpec == 0 {
624				if err := hs.establishKeys(); err != nil {
625					return err
626				}
627			}
628			if err := hs.readSessionTicket(); err != nil {
629				return err
630			}
631			if err := hs.readFinished(c.firstFinished[:]); err != nil {
632				return err
633			}
634			if err := hs.sendFinished(nil, isResume); err != nil {
635				return err
636			}
637		} else {
638			if err := hs.doFullHandshake(); err != nil {
639				return err
640			}
641			if err := hs.establishKeys(); err != nil {
642				return err
643			}
644			if err := hs.sendFinished(c.firstFinished[:], isResume); err != nil {
645				return err
646			}
647			// Most retransmits are triggered by a timeout, but the final
648			// leg of the handshake is retransmited upon re-receiving a
649			// Finished.
650			if err := c.simulatePacketLoss(func() {
651				c.sendHandshakeSeq--
652				c.writeRecord(recordTypeHandshake, hs.finishedBytes)
653				c.flushHandshake()
654			}); err != nil {
655				return err
656			}
657			if err := hs.readSessionTicket(); err != nil {
658				return err
659			}
660			if err := hs.readFinished(nil); err != nil {
661				return err
662			}
663		}
664
665		if sessionCache != nil && hs.session != nil && session != hs.session {
666			if c.config.Bugs.RequireSessionTickets && len(hs.session.sessionTicket) == 0 {
667				return errors.New("tls: new session used session IDs instead of tickets")
668			}
669			sessionCache.Put(cacheKey, hs.session)
670		}
671
672		c.didResume = isResume
673		c.exporterSecret = hs.masterSecret
674	}
675
676	c.handshakeComplete = true
677	c.cipherSuite = suite
678	copy(c.clientRandom[:], hs.hello.random)
679	copy(c.serverRandom[:], hs.serverHello.random)
680
681	return nil
682}
683
684func (hs *clientHandshakeState) doTLS13Handshake() error {
685	c := hs.c
686
687	// Once the PRF hash is known, TLS 1.3 does not require a handshake
688	// buffer.
689	hs.finishedHash.discardHandshakeBuffer()
690
691	zeroSecret := hs.finishedHash.zeroSecret()
692
693	// Resolve PSK and compute the early secret.
694	//
695	// TODO(davidben): This will need to be handled slightly earlier once
696	// 0-RTT is implemented.
697	if hs.serverHello.hasPSKIdentity {
698		// We send at most one PSK identity.
699		if hs.session == nil || hs.serverHello.pskIdentity != 0 {
700			c.sendAlert(alertUnknownPSKIdentity)
701			return errors.New("tls: server sent unknown PSK identity")
702		}
703		sessionCipher := cipherSuiteFromID(hs.session.cipherSuite)
704		if sessionCipher == nil || sessionCipher.hash() != hs.suite.hash() {
705			c.sendAlert(alertHandshakeFailure)
706			return errors.New("tls: server resumed an invalid session for the cipher suite")
707		}
708		hs.finishedHash.addEntropy(hs.session.masterSecret)
709		c.didResume = true
710	} else {
711		hs.finishedHash.addEntropy(zeroSecret)
712	}
713
714	if !hs.serverHello.hasKeyShare {
715		c.sendAlert(alertUnsupportedExtension)
716		return errors.New("tls: server omitted KeyShare on resumption.")
717	}
718
719	// Resolve ECDHE and compute the handshake secret.
720	if !c.config.Bugs.MissingKeyShare && !c.config.Bugs.SecondClientHelloMissingKeyShare {
721		curve, ok := hs.keyShares[hs.serverHello.keyShare.group]
722		if !ok {
723			c.sendAlert(alertHandshakeFailure)
724			return errors.New("tls: server selected an unsupported group")
725		}
726		c.curveID = hs.serverHello.keyShare.group
727
728		ecdheSecret, err := curve.finish(hs.serverHello.keyShare.keyExchange)
729		if err != nil {
730			return err
731		}
732		hs.finishedHash.addEntropy(ecdheSecret)
733	} else {
734		hs.finishedHash.addEntropy(zeroSecret)
735	}
736
737	if c.wireVersion == tls13ExperimentVersion {
738		if err := c.readRecord(recordTypeChangeCipherSpec); err != nil {
739			return err
740		}
741	}
742
743	// Derive handshake traffic keys and switch read key to handshake
744	// traffic key.
745	clientHandshakeTrafficSecret := hs.finishedHash.deriveSecret(clientHandshakeTrafficLabel)
746	serverHandshakeTrafficSecret := hs.finishedHash.deriveSecret(serverHandshakeTrafficLabel)
747	c.in.useTrafficSecret(c.vers, hs.suite, serverHandshakeTrafficSecret, serverWrite)
748
749	msg, err := c.readHandshake()
750	if err != nil {
751		return err
752	}
753
754	encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
755	if !ok {
756		c.sendAlert(alertUnexpectedMessage)
757		return unexpectedMessageError(encryptedExtensions, msg)
758	}
759	hs.writeServerHash(encryptedExtensions.marshal())
760
761	err = hs.processServerExtensions(&encryptedExtensions.extensions)
762	if err != nil {
763		return err
764	}
765
766	var chainToSend *Certificate
767	var certReq *certificateRequestMsg
768	if c.didResume {
769		// Copy over authentication from the session.
770		c.peerCertificates = hs.session.serverCertificates
771		c.sctList = hs.session.sctList
772		c.ocspResponse = hs.session.ocspResponse
773	} else {
774		msg, err := c.readHandshake()
775		if err != nil {
776			return err
777		}
778
779		var ok bool
780		certReq, ok = msg.(*certificateRequestMsg)
781		if ok {
782			if len(certReq.requestContext) != 0 {
783				return errors.New("tls: non-empty certificate request context sent in handshake")
784			}
785
786			if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
787				certReq.signatureAlgorithms = c.config.signSignatureAlgorithms()
788			}
789
790			hs.writeServerHash(certReq.marshal())
791
792			chainToSend, err = selectClientCertificate(c, certReq)
793			if err != nil {
794				return err
795			}
796
797			msg, err = c.readHandshake()
798			if err != nil {
799				return err
800			}
801		}
802
803		certMsg, ok := msg.(*certificateMsg)
804		if !ok {
805			c.sendAlert(alertUnexpectedMessage)
806			return unexpectedMessageError(certMsg, msg)
807		}
808		hs.writeServerHash(certMsg.marshal())
809
810		// Check for unsolicited extensions.
811		for i, cert := range certMsg.certificates {
812			if c.config.Bugs.NoOCSPStapling && cert.ocspResponse != nil {
813				c.sendAlert(alertUnsupportedExtension)
814				return errors.New("tls: unexpected OCSP response in the server certificate")
815			}
816			if c.config.Bugs.NoSignedCertificateTimestamps && cert.sctList != nil {
817				c.sendAlert(alertUnsupportedExtension)
818				return errors.New("tls: unexpected SCT list in the server certificate")
819			}
820			if i > 0 && c.config.Bugs.ExpectNoExtensionsOnIntermediate && (cert.ocspResponse != nil || cert.sctList != nil) {
821				c.sendAlert(alertUnsupportedExtension)
822				return errors.New("tls: unexpected extensions in the server certificate")
823			}
824		}
825
826		if err := hs.verifyCertificates(certMsg); err != nil {
827			return err
828		}
829		leaf := c.peerCertificates[0]
830		c.ocspResponse = certMsg.certificates[0].ocspResponse
831		c.sctList = certMsg.certificates[0].sctList
832
833		msg, err = c.readHandshake()
834		if err != nil {
835			return err
836		}
837		certVerifyMsg, ok := msg.(*certificateVerifyMsg)
838		if !ok {
839			c.sendAlert(alertUnexpectedMessage)
840			return unexpectedMessageError(certVerifyMsg, msg)
841		}
842
843		c.peerSignatureAlgorithm = certVerifyMsg.signatureAlgorithm
844		input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13)
845		err = verifyMessage(c.vers, getCertificatePublicKey(leaf), c.config, certVerifyMsg.signatureAlgorithm, input, certVerifyMsg.signature)
846		if err != nil {
847			return err
848		}
849
850		hs.writeServerHash(certVerifyMsg.marshal())
851	}
852
853	msg, err = c.readHandshake()
854	if err != nil {
855		return err
856	}
857	serverFinished, ok := msg.(*finishedMsg)
858	if !ok {
859		c.sendAlert(alertUnexpectedMessage)
860		return unexpectedMessageError(serverFinished, msg)
861	}
862
863	verify := hs.finishedHash.serverSum(serverHandshakeTrafficSecret)
864	if len(verify) != len(serverFinished.verifyData) ||
865		subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
866		c.sendAlert(alertHandshakeFailure)
867		return errors.New("tls: server's Finished message was incorrect")
868	}
869
870	hs.writeServerHash(serverFinished.marshal())
871
872	// The various secrets do not incorporate the client's final leg, so
873	// derive them now before updating the handshake context.
874	hs.finishedHash.addEntropy(zeroSecret)
875	clientTrafficSecret := hs.finishedHash.deriveSecret(clientApplicationTrafficLabel)
876	serverTrafficSecret := hs.finishedHash.deriveSecret(serverApplicationTrafficLabel)
877	c.exporterSecret = hs.finishedHash.deriveSecret(exporterLabel)
878
879	// Switch to application data keys on read. In particular, any alerts
880	// from the client certificate are read over these keys.
881	c.in.useTrafficSecret(c.vers, hs.suite, serverTrafficSecret, serverWrite)
882
883	// If we're expecting 0.5-RTT messages from the server, read them
884	// now.
885	if encryptedExtensions.extensions.hasEarlyData {
886		// BoringSSL will always send two tickets half-RTT when
887		// negotiating 0-RTT.
888		for i := 0; i < shimConfig.HalfRTTTickets; i++ {
889			msg, err := c.readHandshake()
890			if err != nil {
891				return fmt.Errorf("tls: error reading half-RTT ticket: %s", err)
892			}
893			newSessionTicket, ok := msg.(*newSessionTicketMsg)
894			if !ok {
895				return errors.New("tls: expected half-RTT ticket")
896			}
897			if err := c.processTLS13NewSessionTicket(newSessionTicket, hs.suite); err != nil {
898				return err
899			}
900		}
901		for _, expectedMsg := range c.config.Bugs.ExpectHalfRTTData {
902			if err := c.readRecord(recordTypeApplicationData); err != nil {
903				return err
904			}
905			if !bytes.Equal(c.input.data[c.input.off:], expectedMsg) {
906				return errors.New("ExpectHalfRTTData: did not get expected message")
907			}
908			c.in.freeBlock(c.input)
909			c.input = nil
910		}
911	}
912
913	// Send EndOfEarlyData and then switch write key to handshake
914	// traffic key.
915	if c.out.cipher != nil && !c.config.Bugs.SkipEndOfEarlyData {
916		if c.config.Bugs.SendStrayEarlyHandshake {
917			helloRequest := new(helloRequestMsg)
918			c.writeRecord(recordTypeHandshake, helloRequest.marshal())
919		}
920		c.sendAlert(alertEndOfEarlyData)
921	}
922
923	if c.wireVersion == tls13ExperimentVersion {
924		c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
925	}
926
927	c.out.useTrafficSecret(c.vers, hs.suite, clientHandshakeTrafficSecret, clientWrite)
928
929	if certReq != nil && !c.config.Bugs.SkipClientCertificate {
930		certMsg := &certificateMsg{
931			hasRequestContext: true,
932			requestContext:    certReq.requestContext,
933		}
934		if chainToSend != nil {
935			for _, certData := range chainToSend.Certificate {
936				certMsg.certificates = append(certMsg.certificates, certificateEntry{
937					data:           certData,
938					extraExtension: c.config.Bugs.SendExtensionOnCertificate,
939				})
940			}
941		}
942		hs.writeClientHash(certMsg.marshal())
943		c.writeRecord(recordTypeHandshake, certMsg.marshal())
944
945		if chainToSend != nil {
946			certVerify := &certificateVerifyMsg{
947				hasSignatureAlgorithm: true,
948			}
949
950			// Determine the hash to sign.
951			privKey := chainToSend.PrivateKey
952
953			var err error
954			certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms)
955			if err != nil {
956				c.sendAlert(alertInternalError)
957				return err
958			}
959
960			input := hs.finishedHash.certificateVerifyInput(clientCertificateVerifyContextTLS13)
961			certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, input)
962			if err != nil {
963				c.sendAlert(alertInternalError)
964				return err
965			}
966			if c.config.Bugs.SendSignatureAlgorithm != 0 {
967				certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
968			}
969
970			hs.writeClientHash(certVerify.marshal())
971			c.writeRecord(recordTypeHandshake, certVerify.marshal())
972		}
973	}
974
975	if encryptedExtensions.extensions.channelIDRequested {
976		channelIDHash := crypto.SHA256.New()
977		channelIDHash.Write(hs.finishedHash.certificateVerifyInput(channelIDContextTLS13))
978		channelIDMsgBytes, err := hs.writeChannelIDMessage(channelIDHash.Sum(nil))
979		if err != nil {
980			return err
981		}
982		hs.writeClientHash(channelIDMsgBytes)
983		c.writeRecord(recordTypeHandshake, channelIDMsgBytes)
984	}
985
986	// Send a client Finished message.
987	finished := new(finishedMsg)
988	finished.verifyData = hs.finishedHash.clientSum(clientHandshakeTrafficSecret)
989	if c.config.Bugs.BadFinished {
990		finished.verifyData[0]++
991	}
992	hs.writeClientHash(finished.marshal())
993	if c.config.Bugs.PartialClientFinishedWithClientHello {
994		// The first byte has already been sent.
995		c.writeRecord(recordTypeHandshake, finished.marshal()[1:])
996	} else if c.config.Bugs.InterleaveEarlyData {
997		finishedBytes := finished.marshal()
998		c.sendFakeEarlyData(4)
999		c.writeRecord(recordTypeHandshake, finishedBytes[:1])
1000		c.sendFakeEarlyData(4)
1001		c.writeRecord(recordTypeHandshake, finishedBytes[1:])
1002	} else {
1003		c.writeRecord(recordTypeHandshake, finished.marshal())
1004	}
1005	if c.config.Bugs.SendExtraFinished {
1006		c.writeRecord(recordTypeHandshake, finished.marshal())
1007	}
1008	c.flushHandshake()
1009
1010	// Switch to application data keys.
1011	c.out.useTrafficSecret(c.vers, hs.suite, clientTrafficSecret, clientWrite)
1012
1013	c.resumptionSecret = hs.finishedHash.deriveSecret(resumptionLabel)
1014	return nil
1015}
1016
1017func (hs *clientHandshakeState) doFullHandshake() error {
1018	c := hs.c
1019
1020	var leaf *x509.Certificate
1021	if hs.suite.flags&suitePSK == 0 {
1022		msg, err := c.readHandshake()
1023		if err != nil {
1024			return err
1025		}
1026
1027		certMsg, ok := msg.(*certificateMsg)
1028		if !ok {
1029			c.sendAlert(alertUnexpectedMessage)
1030			return unexpectedMessageError(certMsg, msg)
1031		}
1032		hs.writeServerHash(certMsg.marshal())
1033
1034		if err := hs.verifyCertificates(certMsg); err != nil {
1035			return err
1036		}
1037		leaf = c.peerCertificates[0]
1038	}
1039
1040	if hs.serverHello.extensions.ocspStapling {
1041		msg, err := c.readHandshake()
1042		if err != nil {
1043			return err
1044		}
1045		cs, ok := msg.(*certificateStatusMsg)
1046		if !ok {
1047			c.sendAlert(alertUnexpectedMessage)
1048			return unexpectedMessageError(cs, msg)
1049		}
1050		hs.writeServerHash(cs.marshal())
1051
1052		if cs.statusType == statusTypeOCSP {
1053			c.ocspResponse = cs.response
1054		}
1055	}
1056
1057	msg, err := c.readHandshake()
1058	if err != nil {
1059		return err
1060	}
1061
1062	keyAgreement := hs.suite.ka(c.vers)
1063
1064	skx, ok := msg.(*serverKeyExchangeMsg)
1065	if ok {
1066		hs.writeServerHash(skx.marshal())
1067		err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, leaf, skx)
1068		if err != nil {
1069			c.sendAlert(alertUnexpectedMessage)
1070			return err
1071		}
1072		if ecdhe, ok := keyAgreement.(*ecdheKeyAgreement); ok {
1073			c.curveID = ecdhe.curveID
1074		}
1075
1076		c.peerSignatureAlgorithm = keyAgreement.peerSignatureAlgorithm()
1077
1078		msg, err = c.readHandshake()
1079		if err != nil {
1080			return err
1081		}
1082	}
1083
1084	var chainToSend *Certificate
1085	var certRequested bool
1086	certReq, ok := msg.(*certificateRequestMsg)
1087	if ok {
1088		certRequested = true
1089		if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
1090			certReq.signatureAlgorithms = c.config.signSignatureAlgorithms()
1091		}
1092
1093		hs.writeServerHash(certReq.marshal())
1094
1095		chainToSend, err = selectClientCertificate(c, certReq)
1096		if err != nil {
1097			return err
1098		}
1099
1100		msg, err = c.readHandshake()
1101		if err != nil {
1102			return err
1103		}
1104	}
1105
1106	shd, ok := msg.(*serverHelloDoneMsg)
1107	if !ok {
1108		c.sendAlert(alertUnexpectedMessage)
1109		return unexpectedMessageError(shd, msg)
1110	}
1111	hs.writeServerHash(shd.marshal())
1112
1113	// If the server requested a certificate then we have to send a
1114	// Certificate message in TLS, even if it's empty because we don't have
1115	// a certificate to send. In SSL 3.0, skip the message and send a
1116	// no_certificate warning alert.
1117	if certRequested {
1118		if c.vers == VersionSSL30 && chainToSend == nil {
1119			c.sendAlert(alertNoCertificate)
1120		} else if !c.config.Bugs.SkipClientCertificate {
1121			certMsg := new(certificateMsg)
1122			if chainToSend != nil {
1123				for _, certData := range chainToSend.Certificate {
1124					certMsg.certificates = append(certMsg.certificates, certificateEntry{
1125						data: certData,
1126					})
1127				}
1128			}
1129			hs.writeClientHash(certMsg.marshal())
1130			c.writeRecord(recordTypeHandshake, certMsg.marshal())
1131		}
1132	}
1133
1134	preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, leaf)
1135	if err != nil {
1136		c.sendAlert(alertInternalError)
1137		return err
1138	}
1139	if ckx != nil {
1140		if c.config.Bugs.EarlyChangeCipherSpec < 2 {
1141			hs.writeClientHash(ckx.marshal())
1142		}
1143		c.writeRecord(recordTypeHandshake, ckx.marshal())
1144	}
1145
1146	if hs.serverHello.extensions.extendedMasterSecret && c.vers >= VersionTLS10 {
1147		hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
1148		c.extendedMasterSecret = true
1149	} else {
1150		if c.config.Bugs.RequireExtendedMasterSecret {
1151			return errors.New("tls: extended master secret required but not supported by peer")
1152		}
1153		hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
1154	}
1155
1156	if chainToSend != nil {
1157		certVerify := &certificateVerifyMsg{
1158			hasSignatureAlgorithm: c.vers >= VersionTLS12,
1159		}
1160
1161		// Determine the hash to sign.
1162		privKey := c.config.Certificates[0].PrivateKey
1163
1164		if certVerify.hasSignatureAlgorithm {
1165			certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms)
1166			if err != nil {
1167				c.sendAlert(alertInternalError)
1168				return err
1169			}
1170		}
1171
1172		if c.vers > VersionSSL30 {
1173			certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, hs.finishedHash.buffer)
1174			if err == nil && c.config.Bugs.SendSignatureAlgorithm != 0 {
1175				certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
1176			}
1177		} else {
1178			// SSL 3.0's client certificate construction is
1179			// incompatible with signatureAlgorithm.
1180			rsaKey, ok := privKey.(*rsa.PrivateKey)
1181			if !ok {
1182				err = errors.New("unsupported signature type for client certificate")
1183			} else {
1184				digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret)
1185				if c.config.Bugs.InvalidSignature {
1186					digest[0] ^= 0x80
1187				}
1188				certVerify.signature, err = rsa.SignPKCS1v15(c.config.rand(), rsaKey, crypto.MD5SHA1, digest)
1189			}
1190		}
1191		if err != nil {
1192			c.sendAlert(alertInternalError)
1193			return errors.New("tls: failed to sign handshake with client certificate: " + err.Error())
1194		}
1195
1196		hs.writeClientHash(certVerify.marshal())
1197		c.writeRecord(recordTypeHandshake, certVerify.marshal())
1198	}
1199	// flushHandshake will be called in sendFinished.
1200
1201	hs.finishedHash.discardHandshakeBuffer()
1202
1203	return nil
1204}
1205
1206func (hs *clientHandshakeState) verifyCertificates(certMsg *certificateMsg) error {
1207	c := hs.c
1208
1209	if len(certMsg.certificates) == 0 {
1210		c.sendAlert(alertIllegalParameter)
1211		return errors.New("tls: no certificates sent")
1212	}
1213
1214	certs := make([]*x509.Certificate, len(certMsg.certificates))
1215	for i, certEntry := range certMsg.certificates {
1216		cert, err := x509.ParseCertificate(certEntry.data)
1217		if err != nil {
1218			c.sendAlert(alertBadCertificate)
1219			return errors.New("tls: failed to parse certificate from server: " + err.Error())
1220		}
1221		certs[i] = cert
1222	}
1223
1224	if !c.config.InsecureSkipVerify {
1225		opts := x509.VerifyOptions{
1226			Roots:         c.config.RootCAs,
1227			CurrentTime:   c.config.time(),
1228			DNSName:       c.config.ServerName,
1229			Intermediates: x509.NewCertPool(),
1230		}
1231
1232		for i, cert := range certs {
1233			if i == 0 {
1234				continue
1235			}
1236			opts.Intermediates.AddCert(cert)
1237		}
1238		var err error
1239		c.verifiedChains, err = certs[0].Verify(opts)
1240		if err != nil {
1241			c.sendAlert(alertBadCertificate)
1242			return err
1243		}
1244	}
1245
1246	publicKey := getCertificatePublicKey(certs[0])
1247	switch publicKey.(type) {
1248	case *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey:
1249		break
1250	default:
1251		c.sendAlert(alertUnsupportedCertificate)
1252		return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", publicKey)
1253	}
1254
1255	c.peerCertificates = certs
1256	return nil
1257}
1258
1259func (hs *clientHandshakeState) establishKeys() error {
1260	c := hs.c
1261
1262	clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
1263		keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen(c.vers))
1264	var clientCipher, serverCipher interface{}
1265	var clientHash, serverHash macFunction
1266	if hs.suite.cipher != nil {
1267		clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
1268		clientHash = hs.suite.mac(c.vers, clientMAC)
1269		serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
1270		serverHash = hs.suite.mac(c.vers, serverMAC)
1271	} else {
1272		clientCipher = hs.suite.aead(c.vers, clientKey, clientIV)
1273		serverCipher = hs.suite.aead(c.vers, serverKey, serverIV)
1274	}
1275
1276	c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
1277	c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
1278	return nil
1279}
1280
1281func (hs *clientHandshakeState) processServerExtensions(serverExtensions *serverExtensions) error {
1282	c := hs.c
1283
1284	if c.vers < VersionTLS13 {
1285		if c.config.Bugs.RequireRenegotiationInfo && serverExtensions.secureRenegotiation == nil {
1286			return errors.New("tls: renegotiation extension missing")
1287		}
1288
1289		if len(c.clientVerify) > 0 && !c.noRenegotiationInfo() {
1290			var expectedRenegInfo []byte
1291			expectedRenegInfo = append(expectedRenegInfo, c.clientVerify...)
1292			expectedRenegInfo = append(expectedRenegInfo, c.serverVerify...)
1293			if !bytes.Equal(serverExtensions.secureRenegotiation, expectedRenegInfo) {
1294				c.sendAlert(alertHandshakeFailure)
1295				return fmt.Errorf("tls: renegotiation mismatch")
1296			}
1297		}
1298	} else if serverExtensions.secureRenegotiation != nil {
1299		return errors.New("tls: renegotiation info sent in TLS 1.3")
1300	}
1301
1302	if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
1303		if serverExtensions.customExtension != *expected {
1304			return fmt.Errorf("tls: bad custom extension contents %q", serverExtensions.customExtension)
1305		}
1306	}
1307
1308	clientDidNPN := hs.hello.nextProtoNeg
1309	clientDidALPN := len(hs.hello.alpnProtocols) > 0
1310	serverHasNPN := serverExtensions.nextProtoNeg
1311	serverHasALPN := len(serverExtensions.alpnProtocol) > 0
1312
1313	if !clientDidNPN && serverHasNPN {
1314		c.sendAlert(alertHandshakeFailure)
1315		return errors.New("server advertised unrequested NPN extension")
1316	}
1317
1318	if !clientDidALPN && serverHasALPN {
1319		c.sendAlert(alertHandshakeFailure)
1320		return errors.New("server advertised unrequested ALPN extension")
1321	}
1322
1323	if serverHasNPN && serverHasALPN {
1324		c.sendAlert(alertHandshakeFailure)
1325		return errors.New("server advertised both NPN and ALPN extensions")
1326	}
1327
1328	if serverHasALPN {
1329		c.clientProtocol = serverExtensions.alpnProtocol
1330		c.clientProtocolFallback = false
1331		c.usedALPN = true
1332	}
1333
1334	if serverHasNPN && c.vers >= VersionTLS13 {
1335		c.sendAlert(alertHandshakeFailure)
1336		return errors.New("server advertised NPN over TLS 1.3")
1337	}
1338
1339	if !hs.hello.channelIDSupported && serverExtensions.channelIDRequested {
1340		c.sendAlert(alertHandshakeFailure)
1341		return errors.New("server advertised unrequested Channel ID extension")
1342	}
1343
1344	if serverExtensions.extendedMasterSecret && c.vers >= VersionTLS13 {
1345		return errors.New("tls: server advertised extended master secret over TLS 1.3")
1346	}
1347
1348	if serverExtensions.ticketSupported && c.vers >= VersionTLS13 {
1349		return errors.New("tls: server advertised ticket extension over TLS 1.3")
1350	}
1351
1352	if serverExtensions.ocspStapling && c.vers >= VersionTLS13 {
1353		return errors.New("tls: server advertised OCSP in ServerHello over TLS 1.3")
1354	}
1355
1356	if serverExtensions.ocspStapling && c.config.Bugs.NoOCSPStapling {
1357		return errors.New("tls: server advertised unrequested OCSP extension")
1358	}
1359
1360	if len(serverExtensions.sctList) > 0 && c.vers >= VersionTLS13 {
1361		return errors.New("tls: server advertised SCTs in ServerHello over TLS 1.3")
1362	}
1363
1364	if len(serverExtensions.sctList) > 0 && c.config.Bugs.NoSignedCertificateTimestamps {
1365		return errors.New("tls: server advertised unrequested SCTs")
1366	}
1367
1368	if serverExtensions.srtpProtectionProfile != 0 {
1369		if serverExtensions.srtpMasterKeyIdentifier != "" {
1370			return errors.New("tls: server selected SRTP MKI value")
1371		}
1372
1373		found := false
1374		for _, p := range c.config.SRTPProtectionProfiles {
1375			if p == serverExtensions.srtpProtectionProfile {
1376				found = true
1377				break
1378			}
1379		}
1380		if !found {
1381			return errors.New("tls: server advertised unsupported SRTP profile")
1382		}
1383
1384		c.srtpProtectionProfile = serverExtensions.srtpProtectionProfile
1385	}
1386
1387	if c.vers >= VersionTLS13 && c.didResume {
1388		if c.config.Bugs.ExpectEarlyDataAccepted && !serverExtensions.hasEarlyData {
1389			c.sendAlert(alertHandshakeFailure)
1390			return errors.New("tls: server did not accept early data when expected")
1391		}
1392
1393		if !c.config.Bugs.ExpectEarlyDataAccepted && serverExtensions.hasEarlyData {
1394			c.sendAlert(alertHandshakeFailure)
1395			return errors.New("tls: server accepted early data when not expected")
1396		}
1397	}
1398
1399	return nil
1400}
1401
1402func (hs *clientHandshakeState) serverResumedSession() bool {
1403	// If the server responded with the same sessionId then it means the
1404	// sessionTicket is being used to resume a TLS session.
1405	//
1406	// Note that, if hs.hello.sessionId is a non-nil empty array, this will
1407	// accept an empty session ID from the server as resumption. See
1408	// EmptyTicketSessionID.
1409	return hs.session != nil && hs.hello.sessionId != nil &&
1410		bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
1411}
1412
1413func (hs *clientHandshakeState) processServerHello() (bool, error) {
1414	c := hs.c
1415
1416	if hs.serverResumedSession() {
1417		// For test purposes, assert that the server never accepts the
1418		// resumption offer on renegotiation.
1419		if c.cipherSuite != nil && c.config.Bugs.FailIfResumeOnRenego {
1420			return false, errors.New("tls: server resumed session on renegotiation")
1421		}
1422
1423		if hs.serverHello.extensions.sctList != nil {
1424			return false, errors.New("tls: server sent SCT extension on session resumption")
1425		}
1426
1427		if hs.serverHello.extensions.ocspStapling {
1428			return false, errors.New("tls: server sent OCSP extension on session resumption")
1429		}
1430
1431		// Restore masterSecret and peerCerts from previous state
1432		hs.masterSecret = hs.session.masterSecret
1433		c.peerCertificates = hs.session.serverCertificates
1434		c.extendedMasterSecret = hs.session.extendedMasterSecret
1435		c.sctList = hs.session.sctList
1436		c.ocspResponse = hs.session.ocspResponse
1437		hs.finishedHash.discardHandshakeBuffer()
1438		return true, nil
1439	}
1440
1441	if hs.serverHello.extensions.sctList != nil {
1442		c.sctList = hs.serverHello.extensions.sctList
1443	}
1444
1445	return false, nil
1446}
1447
1448func (hs *clientHandshakeState) readFinished(out []byte) error {
1449	c := hs.c
1450
1451	c.readRecord(recordTypeChangeCipherSpec)
1452	if err := c.in.error(); err != nil {
1453		return err
1454	}
1455
1456	msg, err := c.readHandshake()
1457	if err != nil {
1458		return err
1459	}
1460	serverFinished, ok := msg.(*finishedMsg)
1461	if !ok {
1462		c.sendAlert(alertUnexpectedMessage)
1463		return unexpectedMessageError(serverFinished, msg)
1464	}
1465
1466	if c.config.Bugs.EarlyChangeCipherSpec == 0 {
1467		verify := hs.finishedHash.serverSum(hs.masterSecret)
1468		if len(verify) != len(serverFinished.verifyData) ||
1469			subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
1470			c.sendAlert(alertHandshakeFailure)
1471			return errors.New("tls: server's Finished message was incorrect")
1472		}
1473	}
1474	c.serverVerify = append(c.serverVerify[:0], serverFinished.verifyData...)
1475	copy(out, serverFinished.verifyData)
1476	hs.writeServerHash(serverFinished.marshal())
1477	return nil
1478}
1479
1480func (hs *clientHandshakeState) readSessionTicket() error {
1481	c := hs.c
1482
1483	// Create a session with no server identifier. Either a
1484	// session ID or session ticket will be attached.
1485	session := &ClientSessionState{
1486		vers:               c.vers,
1487		cipherSuite:        hs.suite.id,
1488		masterSecret:       hs.masterSecret,
1489		handshakeHash:      hs.finishedHash.Sum(),
1490		serverCertificates: c.peerCertificates,
1491		sctList:            c.sctList,
1492		ocspResponse:       c.ocspResponse,
1493		ticketExpiration:   c.config.time().Add(time.Duration(7 * 24 * time.Hour)),
1494	}
1495
1496	if !hs.serverHello.extensions.ticketSupported {
1497		if c.config.Bugs.ExpectNewTicket {
1498			return errors.New("tls: expected new ticket")
1499		}
1500		if hs.session == nil && len(hs.serverHello.sessionId) > 0 {
1501			session.sessionId = hs.serverHello.sessionId
1502			hs.session = session
1503		}
1504		return nil
1505	}
1506
1507	if c.vers == VersionSSL30 {
1508		return errors.New("tls: negotiated session tickets in SSL 3.0")
1509	}
1510
1511	msg, err := c.readHandshake()
1512	if err != nil {
1513		return err
1514	}
1515	sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
1516	if !ok {
1517		c.sendAlert(alertUnexpectedMessage)
1518		return unexpectedMessageError(sessionTicketMsg, msg)
1519	}
1520
1521	session.sessionTicket = sessionTicketMsg.ticket
1522	hs.session = session
1523
1524	hs.writeServerHash(sessionTicketMsg.marshal())
1525
1526	return nil
1527}
1528
1529func (hs *clientHandshakeState) sendFinished(out []byte, isResume bool) error {
1530	c := hs.c
1531
1532	var postCCSMsgs [][]byte
1533	seqno := hs.c.sendHandshakeSeq
1534	if hs.serverHello.extensions.nextProtoNeg {
1535		nextProto := new(nextProtoMsg)
1536		proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.extensions.nextProtos)
1537		nextProto.proto = proto
1538		c.clientProtocol = proto
1539		c.clientProtocolFallback = fallback
1540
1541		nextProtoBytes := nextProto.marshal()
1542		hs.writeHash(nextProtoBytes, seqno)
1543		seqno++
1544		postCCSMsgs = append(postCCSMsgs, nextProtoBytes)
1545	}
1546
1547	if hs.serverHello.extensions.channelIDRequested {
1548		var resumeHash []byte
1549		if isResume {
1550			resumeHash = hs.session.handshakeHash
1551		}
1552		channelIDMsgBytes, err := hs.writeChannelIDMessage(hs.finishedHash.hashForChannelID(resumeHash))
1553		if err != nil {
1554			return err
1555		}
1556		hs.writeHash(channelIDMsgBytes, seqno)
1557		seqno++
1558		postCCSMsgs = append(postCCSMsgs, channelIDMsgBytes)
1559	}
1560
1561	finished := new(finishedMsg)
1562	if c.config.Bugs.EarlyChangeCipherSpec == 2 {
1563		finished.verifyData = hs.finishedHash.clientSum(nil)
1564	} else {
1565		finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
1566	}
1567	copy(out, finished.verifyData)
1568	if c.config.Bugs.BadFinished {
1569		finished.verifyData[0]++
1570	}
1571	c.clientVerify = append(c.clientVerify[:0], finished.verifyData...)
1572	hs.finishedBytes = finished.marshal()
1573	hs.writeHash(hs.finishedBytes, seqno)
1574	postCCSMsgs = append(postCCSMsgs, hs.finishedBytes)
1575
1576	if c.config.Bugs.FragmentAcrossChangeCipherSpec {
1577		c.writeRecord(recordTypeHandshake, postCCSMsgs[0][:5])
1578		postCCSMsgs[0] = postCCSMsgs[0][5:]
1579	} else if c.config.Bugs.SendUnencryptedFinished {
1580		c.writeRecord(recordTypeHandshake, postCCSMsgs[0])
1581		postCCSMsgs = postCCSMsgs[1:]
1582	}
1583	c.flushHandshake()
1584
1585	if !c.config.Bugs.SkipChangeCipherSpec &&
1586		c.config.Bugs.EarlyChangeCipherSpec == 0 {
1587		ccs := []byte{1}
1588		if c.config.Bugs.BadChangeCipherSpec != nil {
1589			ccs = c.config.Bugs.BadChangeCipherSpec
1590		}
1591		c.writeRecord(recordTypeChangeCipherSpec, ccs)
1592	}
1593
1594	if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
1595		c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
1596	}
1597	if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
1598		c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
1599		return errors.New("tls: simulating post-CCS alert")
1600	}
1601
1602	if !c.config.Bugs.SkipFinished {
1603		for _, msg := range postCCSMsgs {
1604			c.writeRecord(recordTypeHandshake, msg)
1605		}
1606
1607		if c.config.Bugs.SendExtraFinished {
1608			c.writeRecord(recordTypeHandshake, finished.marshal())
1609		}
1610
1611		c.flushHandshake()
1612	}
1613	return nil
1614}
1615
1616func (hs *clientHandshakeState) writeChannelIDMessage(channelIDHash []byte) ([]byte, error) {
1617	c := hs.c
1618	channelIDMsg := new(channelIDMsg)
1619	if c.config.ChannelID.Curve != elliptic.P256() {
1620		return nil, fmt.Errorf("tls: Channel ID is not on P-256.")
1621	}
1622	r, s, err := ecdsa.Sign(c.config.rand(), c.config.ChannelID, channelIDHash)
1623	if err != nil {
1624		return nil, err
1625	}
1626	channelID := make([]byte, 128)
1627	writeIntPadded(channelID[0:32], c.config.ChannelID.X)
1628	writeIntPadded(channelID[32:64], c.config.ChannelID.Y)
1629	writeIntPadded(channelID[64:96], r)
1630	writeIntPadded(channelID[96:128], s)
1631	if c.config.Bugs.InvalidChannelIDSignature {
1632		channelID[64] ^= 1
1633	}
1634	channelIDMsg.channelID = channelID
1635
1636	c.channelID = &c.config.ChannelID.PublicKey
1637
1638	return channelIDMsg.marshal(), nil
1639}
1640
1641func (hs *clientHandshakeState) writeClientHash(msg []byte) {
1642	// writeClientHash is called before writeRecord.
1643	hs.writeHash(msg, hs.c.sendHandshakeSeq)
1644}
1645
1646func (hs *clientHandshakeState) writeServerHash(msg []byte) {
1647	// writeServerHash is called after readHandshake.
1648	hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
1649}
1650
1651func (hs *clientHandshakeState) writeHash(msg []byte, seqno uint16) {
1652	if hs.c.isDTLS {
1653		// This is somewhat hacky. DTLS hashes a slightly different format.
1654		// First, the TLS header.
1655		hs.finishedHash.Write(msg[:4])
1656		// Then the sequence number and reassembled fragment offset (always 0).
1657		hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1658		// Then the reassembled fragment (always equal to the message length).
1659		hs.finishedHash.Write(msg[1:4])
1660		// And then the message body.
1661		hs.finishedHash.Write(msg[4:])
1662	} else {
1663		hs.finishedHash.Write(msg)
1664	}
1665}
1666
1667// selectClientCertificate selects a certificate for use with the given
1668// certificate, or none if none match. It may return a particular certificate or
1669// nil on success, or an error on internal error.
1670func selectClientCertificate(c *Conn, certReq *certificateRequestMsg) (*Certificate, error) {
1671	// RFC 4346 on the certificateAuthorities field:
1672	// A list of the distinguished names of acceptable certificate
1673	// authorities. These distinguished names may specify a desired
1674	// distinguished name for a root CA or for a subordinate CA; thus, this
1675	// message can be used to describe both known roots and a desired
1676	// authorization space. If the certificate_authorities list is empty
1677	// then the client MAY send any certificate of the appropriate
1678	// ClientCertificateType, unless there is some external arrangement to
1679	// the contrary.
1680
1681	var rsaAvail, ecdsaAvail bool
1682	if !certReq.hasRequestContext {
1683		for _, certType := range certReq.certificateTypes {
1684			switch certType {
1685			case CertTypeRSASign:
1686				rsaAvail = true
1687			case CertTypeECDSASign:
1688				ecdsaAvail = true
1689			}
1690		}
1691	}
1692
1693	// We need to search our list of client certs for one
1694	// where SignatureAlgorithm is RSA and the Issuer is in
1695	// certReq.certificateAuthorities
1696findCert:
1697	for i, chain := range c.config.Certificates {
1698		if !certReq.hasRequestContext && !rsaAvail && !ecdsaAvail {
1699			continue
1700		}
1701
1702		// Ensure the private key supports one of the advertised
1703		// signature algorithms.
1704		if certReq.hasSignatureAlgorithm {
1705			if _, err := selectSignatureAlgorithm(c.vers, chain.PrivateKey, c.config, certReq.signatureAlgorithms); err != nil {
1706				continue
1707			}
1708		}
1709
1710		for j, cert := range chain.Certificate {
1711			x509Cert := chain.Leaf
1712			// parse the certificate if this isn't the leaf
1713			// node, or if chain.Leaf was nil
1714			if j != 0 || x509Cert == nil {
1715				var err error
1716				if x509Cert, err = x509.ParseCertificate(cert); err != nil {
1717					c.sendAlert(alertInternalError)
1718					return nil, errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error())
1719				}
1720			}
1721
1722			if !certReq.hasRequestContext {
1723				switch {
1724				case rsaAvail && x509Cert.PublicKeyAlgorithm == x509.RSA:
1725				case ecdsaAvail && x509Cert.PublicKeyAlgorithm == x509.ECDSA:
1726				case ecdsaAvail && isEd25519Certificate(x509Cert):
1727				default:
1728					continue findCert
1729				}
1730			}
1731
1732			if expected := c.config.Bugs.ExpectCertificateReqNames; expected != nil {
1733				if !eqByteSlices(expected, certReq.certificateAuthorities) {
1734					return nil, fmt.Errorf("tls: CertificateRequest names differed, got %#v but expected %#v", certReq.certificateAuthorities, expected)
1735				}
1736			}
1737
1738			return &chain, nil
1739		}
1740	}
1741
1742	return nil, nil
1743}
1744
1745// clientSessionCacheKey returns a key used to cache sessionTickets that could
1746// be used to resume previously negotiated TLS sessions with a server.
1747func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
1748	if len(config.ServerName) > 0 {
1749		return config.ServerName
1750	}
1751	return serverAddr.String()
1752}
1753
1754// mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
1755// given list of possible protocols and a list of the preference order. The
1756// first list must not be empty. It returns the resulting protocol and flag
1757// indicating if the fallback case was reached.
1758func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
1759	for _, s := range preferenceProtos {
1760		for _, c := range protos {
1761			if s == c {
1762				return s, false
1763			}
1764		}
1765	}
1766
1767	return protos[0], true
1768}
1769
1770// writeIntPadded writes x into b, padded up with leading zeros as
1771// needed.
1772func writeIntPadded(b []byte, x *big.Int) {
1773	for i := range b {
1774		b[i] = 0
1775	}
1776	xb := x.Bytes()
1777	copy(b[len(b)-len(xb):], xb)
1778}
1779
1780func generatePSKBinders(hello *clientHelloMsg, pskCipherSuite *cipherSuite, psk, transcript []byte, config *Config) {
1781	if config.Bugs.SendNoPSKBinder {
1782		return
1783	}
1784
1785	binderLen := pskCipherSuite.hash().Size()
1786	if config.Bugs.SendShortPSKBinder {
1787		binderLen--
1788	}
1789
1790	numBinders := 1
1791	if config.Bugs.SendExtraPSKBinder {
1792		numBinders++
1793	}
1794
1795	// Fill hello.pskBinders with appropriate length arrays of zeros so the
1796	// length prefixes are correct when computing the binder over the truncated
1797	// ClientHello message.
1798	hello.pskBinders = make([][]byte, numBinders)
1799	for i := range hello.pskBinders {
1800		hello.pskBinders[i] = make([]byte, binderLen)
1801	}
1802
1803	helloBytes := hello.marshal()
1804	binderSize := len(hello.pskBinders)*(binderLen+1) + 2
1805	truncatedHello := helloBytes[:len(helloBytes)-binderSize]
1806	binder := computePSKBinder(psk, resumptionPSKBinderLabel, pskCipherSuite, transcript, truncatedHello)
1807	if config.Bugs.SendShortPSKBinder {
1808		binder = binder[:binderLen]
1809	}
1810	if config.Bugs.SendInvalidPSKBinder {
1811		binder[0] ^= 1
1812	}
1813
1814	for i := range hello.pskBinders {
1815		hello.pskBinders[i] = binder
1816	}
1817
1818	hello.raw = nil
1819}
1820