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	"crypto"
9	"crypto/ecdsa"
10	"crypto/rsa"
11	"crypto/subtle"
12	"crypto/x509"
13	"errors"
14	"fmt"
15	"io"
16	"sync/atomic"
17)
18
19// serverHandshakeState contains details of a server handshake in progress.
20// It's discarded once the handshake has completed.
21type serverHandshakeState struct {
22	c            *Conn
23	clientHello  *clientHelloMsg
24	hello        *serverHelloMsg
25	suite        *cipherSuite
26	ellipticOk   bool
27	ecdsaOk      bool
28	rsaDecryptOk bool
29	rsaSignOk    bool
30	sessionState *sessionState
31	finishedHash finishedHash
32	masterSecret []byte
33	cert         *Certificate
34}
35
36// serverHandshake performs a TLS handshake as a server.
37func (c *Conn) serverHandshake() error {
38	// If this is the first server handshake, we generate a random key to
39	// encrypt the tickets with.
40	c.config.serverInitOnce.Do(func() { c.config.serverInit(nil) })
41
42	clientHello, err := c.readClientHello()
43	if err != nil {
44		return err
45	}
46
47	if c.vers == VersionTLS13 {
48		hs := serverHandshakeStateTLS13{
49			c:           c,
50			clientHello: clientHello,
51		}
52		return hs.handshake()
53	}
54
55	hs := serverHandshakeState{
56		c:           c,
57		clientHello: clientHello,
58	}
59	return hs.handshake()
60}
61
62func (hs *serverHandshakeState) handshake() error {
63	c := hs.c
64
65	if err := hs.processClientHello(); err != nil {
66		return err
67	}
68
69	// For an overview of TLS handshaking, see RFC 5246, Section 7.3.
70	c.buffering = true
71	if hs.checkForResumption() {
72		// The client has included a session ticket and so we do an abbreviated handshake.
73		if err := hs.doResumeHandshake(); err != nil {
74			return err
75		}
76		if err := hs.establishKeys(); err != nil {
77			return err
78		}
79		// ticketSupported is set in a resumption handshake if the
80		// ticket from the client was encrypted with an old session
81		// ticket key and thus a refreshed ticket should be sent.
82		if hs.hello.ticketSupported {
83			if err := hs.sendSessionTicket(); err != nil {
84				return err
85			}
86		}
87		if err := hs.sendFinished(c.serverFinished[:]); err != nil {
88			return err
89		}
90		if _, err := c.flush(); err != nil {
91			return err
92		}
93		c.clientFinishedIsFirst = false
94		if err := hs.readFinished(nil); err != nil {
95			return err
96		}
97		c.didResume = true
98	} else {
99		// The client didn't include a session ticket, or it wasn't
100		// valid so we do a full handshake.
101		if err := hs.pickCipherSuite(); err != nil {
102			return err
103		}
104		if err := hs.doFullHandshake(); err != nil {
105			return err
106		}
107		if err := hs.establishKeys(); err != nil {
108			return err
109		}
110		if err := hs.readFinished(c.clientFinished[:]); err != nil {
111			return err
112		}
113		c.clientFinishedIsFirst = true
114		c.buffering = true
115		if err := hs.sendSessionTicket(); err != nil {
116			return err
117		}
118		if err := hs.sendFinished(nil); err != nil {
119			return err
120		}
121		if _, err := c.flush(); err != nil {
122			return err
123		}
124	}
125
126	c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random)
127	atomic.StoreUint32(&c.handshakeStatus, 1)
128
129	return nil
130}
131
132// readClientHello reads a ClientHello message and selects the protocol version.
133func (c *Conn) readClientHello() (*clientHelloMsg, error) {
134	msg, err := c.readHandshake()
135	if err != nil {
136		return nil, err
137	}
138	clientHello, ok := msg.(*clientHelloMsg)
139	if !ok {
140		c.sendAlert(alertUnexpectedMessage)
141		return nil, unexpectedMessageError(clientHello, msg)
142	}
143
144	if c.config.GetConfigForClient != nil {
145		chi := clientHelloInfo(c, clientHello)
146		if newConfig, err := c.config.GetConfigForClient(chi); err != nil {
147			c.sendAlert(alertInternalError)
148			return nil, err
149		} else if newConfig != nil {
150			newConfig.serverInitOnce.Do(func() { newConfig.serverInit(c.config) })
151			c.config = newConfig
152		}
153	}
154
155	clientVersions := clientHello.supportedVersions
156	if len(clientHello.supportedVersions) == 0 {
157		clientVersions = supportedVersionsFromMax(clientHello.vers)
158	}
159	c.vers, ok = c.config.mutualVersion(false, clientVersions)
160	if !ok {
161		c.sendAlert(alertProtocolVersion)
162		return nil, fmt.Errorf("tls: client offered only unsupported versions: %x", clientVersions)
163	}
164	c.haveVers = true
165	c.in.version = c.vers
166	c.out.version = c.vers
167
168	return clientHello, nil
169}
170
171func (hs *serverHandshakeState) processClientHello() error {
172	c := hs.c
173
174	hs.hello = new(serverHelloMsg)
175	hs.hello.vers = c.vers
176
177	supportedCurve := false
178	preferredCurves := c.config.curvePreferences()
179Curves:
180	for _, curve := range hs.clientHello.supportedCurves {
181		for _, supported := range preferredCurves {
182			if supported == curve {
183				supportedCurve = true
184				break Curves
185			}
186		}
187	}
188
189	supportedPointFormat := false
190	for _, pointFormat := range hs.clientHello.supportedPoints {
191		if pointFormat == pointFormatUncompressed {
192			supportedPointFormat = true
193			break
194		}
195	}
196	hs.ellipticOk = supportedCurve && supportedPointFormat
197
198	foundCompression := false
199	// We only support null compression, so check that the client offered it.
200	for _, compression := range hs.clientHello.compressionMethods {
201		if compression == compressionNone {
202			foundCompression = true
203			break
204		}
205	}
206
207	if !foundCompression {
208		c.sendAlert(alertHandshakeFailure)
209		return errors.New("tls: client does not support uncompressed connections")
210	}
211
212	hs.hello.random = make([]byte, 32)
213	serverRandom := hs.hello.random
214	// Downgrade protection canaries. See RFC 8446, Section 4.1.3.
215	maxVers := c.config.maxSupportedVersion(false)
216	if maxVers >= VersionTLS12 && c.vers < maxVers {
217		if c.vers == VersionTLS12 {
218			copy(serverRandom[24:], downgradeCanaryTLS12)
219		} else {
220			copy(serverRandom[24:], downgradeCanaryTLS11)
221		}
222		serverRandom = serverRandom[:24]
223	}
224	_, err := io.ReadFull(c.config.rand(), serverRandom)
225	if err != nil {
226		c.sendAlert(alertInternalError)
227		return err
228	}
229
230	if len(hs.clientHello.secureRenegotiation) != 0 {
231		c.sendAlert(alertHandshakeFailure)
232		return errors.New("tls: initial handshake had non-empty renegotiation extension")
233	}
234
235	hs.hello.secureRenegotiationSupported = hs.clientHello.secureRenegotiationSupported
236	hs.hello.compressionMethod = compressionNone
237	if len(hs.clientHello.serverName) > 0 {
238		c.serverName = hs.clientHello.serverName
239	}
240
241	if len(hs.clientHello.alpnProtocols) > 0 {
242		if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
243			hs.hello.alpnProtocol = selectedProto
244			c.clientProtocol = selectedProto
245		}
246	} else {
247		// Although sending an empty NPN extension is reasonable, Firefox has
248		// had a bug around this. Best to send nothing at all if
249		// c.config.NextProtos is empty. See
250		// https://golang.org/issue/5445.
251		if hs.clientHello.nextProtoNeg && len(c.config.NextProtos) > 0 {
252			hs.hello.nextProtoNeg = true
253			hs.hello.nextProtos = c.config.NextProtos
254		}
255	}
256
257	hs.cert, err = c.config.getCertificate(clientHelloInfo(c, hs.clientHello))
258	if err != nil {
259		c.sendAlert(alertInternalError)
260		return err
261	}
262	if hs.clientHello.scts {
263		hs.hello.scts = hs.cert.SignedCertificateTimestamps
264	}
265
266	if priv, ok := hs.cert.PrivateKey.(crypto.Signer); ok {
267		switch priv.Public().(type) {
268		case *ecdsa.PublicKey:
269			hs.ecdsaOk = true
270		case *rsa.PublicKey:
271			hs.rsaSignOk = true
272		default:
273			c.sendAlert(alertInternalError)
274			return fmt.Errorf("tls: unsupported signing key type (%T)", priv.Public())
275		}
276	}
277	if priv, ok := hs.cert.PrivateKey.(crypto.Decrypter); ok {
278		switch priv.Public().(type) {
279		case *rsa.PublicKey:
280			hs.rsaDecryptOk = true
281		default:
282			c.sendAlert(alertInternalError)
283			return fmt.Errorf("tls: unsupported decryption key type (%T)", priv.Public())
284		}
285	}
286
287	return nil
288}
289
290func (hs *serverHandshakeState) pickCipherSuite() error {
291	c := hs.c
292
293	var preferenceList, supportedList []uint16
294	if c.config.PreferServerCipherSuites {
295		preferenceList = c.config.cipherSuites()
296		supportedList = hs.clientHello.cipherSuites
297	} else {
298		preferenceList = hs.clientHello.cipherSuites
299		supportedList = c.config.cipherSuites()
300	}
301
302	for _, id := range preferenceList {
303		if hs.setCipherSuite(id, supportedList, c.vers) {
304			break
305		}
306	}
307
308	if hs.suite == nil {
309		c.sendAlert(alertHandshakeFailure)
310		return errors.New("tls: no cipher suite supported by both client and server")
311	}
312
313	for _, id := range hs.clientHello.cipherSuites {
314		if id == TLS_FALLBACK_SCSV {
315			// The client is doing a fallback connection. See RFC 7507.
316			if hs.clientHello.vers < c.config.maxSupportedVersion(false) {
317				c.sendAlert(alertInappropriateFallback)
318				return errors.New("tls: client using inappropriate protocol fallback")
319			}
320			break
321		}
322	}
323
324	return nil
325}
326
327// checkForResumption reports whether we should perform resumption on this connection.
328func (hs *serverHandshakeState) checkForResumption() bool {
329	c := hs.c
330
331	if c.config.SessionTicketsDisabled {
332		return false
333	}
334
335	plaintext, usedOldKey := c.decryptTicket(hs.clientHello.sessionTicket)
336	if plaintext == nil {
337		return false
338	}
339	hs.sessionState = &sessionState{usedOldKey: usedOldKey}
340	ok := hs.sessionState.unmarshal(plaintext)
341	if !ok {
342		return false
343	}
344
345	// Never resume a session for a different TLS version.
346	if c.vers != hs.sessionState.vers {
347		return false
348	}
349
350	cipherSuiteOk := false
351	// Check that the client is still offering the ciphersuite in the session.
352	for _, id := range hs.clientHello.cipherSuites {
353		if id == hs.sessionState.cipherSuite {
354			cipherSuiteOk = true
355			break
356		}
357	}
358	if !cipherSuiteOk {
359		return false
360	}
361
362	// Check that we also support the ciphersuite from the session.
363	if !hs.setCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers) {
364		return false
365	}
366
367	sessionHasClientCerts := len(hs.sessionState.certificates) != 0
368	needClientCerts := requiresClientCert(c.config.ClientAuth)
369	if needClientCerts && !sessionHasClientCerts {
370		return false
371	}
372	if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
373		return false
374	}
375
376	return true
377}
378
379func (hs *serverHandshakeState) doResumeHandshake() error {
380	c := hs.c
381
382	hs.hello.cipherSuite = hs.suite.id
383	// We echo the client's session ID in the ServerHello to let it know
384	// that we're doing a resumption.
385	hs.hello.sessionId = hs.clientHello.sessionId
386	hs.hello.ticketSupported = hs.sessionState.usedOldKey
387	hs.finishedHash = newFinishedHash(c.vers, hs.suite)
388	hs.finishedHash.discardHandshakeBuffer()
389	hs.finishedHash.Write(hs.clientHello.marshal())
390	hs.finishedHash.Write(hs.hello.marshal())
391	if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
392		return err
393	}
394
395	if err := c.processCertsFromClient(Certificate{
396		Certificate: hs.sessionState.certificates,
397	}); err != nil {
398		return err
399	}
400
401	hs.masterSecret = hs.sessionState.masterSecret
402
403	return nil
404}
405
406func (hs *serverHandshakeState) doFullHandshake() error {
407	c := hs.c
408
409	if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
410		hs.hello.ocspStapling = true
411	}
412
413	hs.hello.ticketSupported = hs.clientHello.ticketSupported && !c.config.SessionTicketsDisabled
414	hs.hello.cipherSuite = hs.suite.id
415
416	hs.finishedHash = newFinishedHash(hs.c.vers, hs.suite)
417	if c.config.ClientAuth == NoClientCert {
418		// No need to keep a full record of the handshake if client
419		// certificates won't be used.
420		hs.finishedHash.discardHandshakeBuffer()
421	}
422	hs.finishedHash.Write(hs.clientHello.marshal())
423	hs.finishedHash.Write(hs.hello.marshal())
424	if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
425		return err
426	}
427
428	certMsg := new(certificateMsg)
429	certMsg.certificates = hs.cert.Certificate
430	hs.finishedHash.Write(certMsg.marshal())
431	if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
432		return err
433	}
434
435	if hs.hello.ocspStapling {
436		certStatus := new(certificateStatusMsg)
437		certStatus.response = hs.cert.OCSPStaple
438		hs.finishedHash.Write(certStatus.marshal())
439		if _, err := c.writeRecord(recordTypeHandshake, certStatus.marshal()); err != nil {
440			return err
441		}
442	}
443
444	keyAgreement := hs.suite.ka(c.vers)
445	skx, err := keyAgreement.generateServerKeyExchange(c.config, hs.cert, hs.clientHello, hs.hello)
446	if err != nil {
447		c.sendAlert(alertHandshakeFailure)
448		return err
449	}
450	if skx != nil {
451		hs.finishedHash.Write(skx.marshal())
452		if _, err := c.writeRecord(recordTypeHandshake, skx.marshal()); err != nil {
453			return err
454		}
455	}
456
457	if c.config.ClientAuth >= RequestClientCert {
458		// Request a client certificate
459		certReq := new(certificateRequestMsg)
460		certReq.certificateTypes = []byte{
461			byte(certTypeRSASign),
462			byte(certTypeECDSASign),
463		}
464		if c.vers >= VersionTLS12 {
465			certReq.hasSignatureAlgorithm = true
466			certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms
467		}
468
469		// An empty list of certificateAuthorities signals to
470		// the client that it may send any certificate in response
471		// to our request. When we know the CAs we trust, then
472		// we can send them down, so that the client can choose
473		// an appropriate certificate to give to us.
474		if c.config.ClientCAs != nil {
475			certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
476		}
477		hs.finishedHash.Write(certReq.marshal())
478		if _, err := c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil {
479			return err
480		}
481	}
482
483	helloDone := new(serverHelloDoneMsg)
484	hs.finishedHash.Write(helloDone.marshal())
485	if _, err := c.writeRecord(recordTypeHandshake, helloDone.marshal()); err != nil {
486		return err
487	}
488
489	if _, err := c.flush(); err != nil {
490		return err
491	}
492
493	var pub crypto.PublicKey // public key for client auth, if any
494
495	msg, err := c.readHandshake()
496	if err != nil {
497		return err
498	}
499
500	// If we requested a client certificate, then the client must send a
501	// certificate message, even if it's empty.
502	if c.config.ClientAuth >= RequestClientCert {
503		certMsg, ok := msg.(*certificateMsg)
504		if !ok {
505			c.sendAlert(alertUnexpectedMessage)
506			return unexpectedMessageError(certMsg, msg)
507		}
508		hs.finishedHash.Write(certMsg.marshal())
509
510		if err := c.processCertsFromClient(Certificate{
511			Certificate: certMsg.certificates,
512		}); err != nil {
513			return err
514		}
515		if len(certMsg.certificates) != 0 {
516			pub = c.peerCertificates[0].PublicKey
517		}
518
519		msg, err = c.readHandshake()
520		if err != nil {
521			return err
522		}
523	}
524
525	// Get client key exchange
526	ckx, ok := msg.(*clientKeyExchangeMsg)
527	if !ok {
528		c.sendAlert(alertUnexpectedMessage)
529		return unexpectedMessageError(ckx, msg)
530	}
531	hs.finishedHash.Write(ckx.marshal())
532
533	preMasterSecret, err := keyAgreement.processClientKeyExchange(c.config, hs.cert, ckx, c.vers)
534	if err != nil {
535		c.sendAlert(alertHandshakeFailure)
536		return err
537	}
538	hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
539	if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.clientHello.random, hs.masterSecret); err != nil {
540		c.sendAlert(alertInternalError)
541		return err
542	}
543
544	// If we received a client cert in response to our certificate request message,
545	// the client will send us a certificateVerifyMsg immediately after the
546	// clientKeyExchangeMsg. This message is a digest of all preceding
547	// handshake-layer messages that is signed using the private key corresponding
548	// to the client's certificate. This allows us to verify that the client is in
549	// possession of the private key of the certificate.
550	if len(c.peerCertificates) > 0 {
551		msg, err = c.readHandshake()
552		if err != nil {
553			return err
554		}
555		certVerify, ok := msg.(*certificateVerifyMsg)
556		if !ok {
557			c.sendAlert(alertUnexpectedMessage)
558			return unexpectedMessageError(certVerify, msg)
559		}
560
561		// Determine the signature type.
562		_, sigType, hashFunc, err := pickSignatureAlgorithm(pub, []SignatureScheme{certVerify.signatureAlgorithm}, supportedSignatureAlgorithms, c.vers)
563		if err != nil {
564			c.sendAlert(alertIllegalParameter)
565			return err
566		}
567
568		var digest []byte
569		if digest, err = hs.finishedHash.hashForClientCertificate(sigType, hashFunc, hs.masterSecret); err == nil {
570			err = verifyHandshakeSignature(sigType, pub, hashFunc, digest, certVerify.signature)
571		}
572		if err != nil {
573			c.sendAlert(alertBadCertificate)
574			return errors.New("tls: could not validate signature of connection nonces: " + err.Error())
575		}
576
577		hs.finishedHash.Write(certVerify.marshal())
578	}
579
580	hs.finishedHash.discardHandshakeBuffer()
581
582	return nil
583}
584
585func (hs *serverHandshakeState) establishKeys() error {
586	c := hs.c
587
588	clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
589		keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
590
591	var clientCipher, serverCipher interface{}
592	var clientHash, serverHash macFunction
593
594	if hs.suite.aead == nil {
595		clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
596		clientHash = hs.suite.mac(c.vers, clientMAC)
597		serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
598		serverHash = hs.suite.mac(c.vers, serverMAC)
599	} else {
600		clientCipher = hs.suite.aead(clientKey, clientIV)
601		serverCipher = hs.suite.aead(serverKey, serverIV)
602	}
603
604	c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
605	c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
606
607	return nil
608}
609
610func (hs *serverHandshakeState) readFinished(out []byte) error {
611	c := hs.c
612
613	if err := c.readChangeCipherSpec(); err != nil {
614		return err
615	}
616
617	if hs.hello.nextProtoNeg {
618		msg, err := c.readHandshake()
619		if err != nil {
620			return err
621		}
622		nextProto, ok := msg.(*nextProtoMsg)
623		if !ok {
624			c.sendAlert(alertUnexpectedMessage)
625			return unexpectedMessageError(nextProto, msg)
626		}
627		hs.finishedHash.Write(nextProto.marshal())
628		c.clientProtocol = nextProto.proto
629	}
630
631	msg, err := c.readHandshake()
632	if err != nil {
633		return err
634	}
635	clientFinished, ok := msg.(*finishedMsg)
636	if !ok {
637		c.sendAlert(alertUnexpectedMessage)
638		return unexpectedMessageError(clientFinished, msg)
639	}
640
641	verify := hs.finishedHash.clientSum(hs.masterSecret)
642	if len(verify) != len(clientFinished.verifyData) ||
643		subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
644		c.sendAlert(alertHandshakeFailure)
645		return errors.New("tls: client's Finished message is incorrect")
646	}
647
648	hs.finishedHash.Write(clientFinished.marshal())
649	copy(out, verify)
650	return nil
651}
652
653func (hs *serverHandshakeState) sendSessionTicket() error {
654	if !hs.hello.ticketSupported {
655		return nil
656	}
657
658	c := hs.c
659	m := new(newSessionTicketMsg)
660
661	var certsFromClient [][]byte
662	for _, cert := range c.peerCertificates {
663		certsFromClient = append(certsFromClient, cert.Raw)
664	}
665	state := sessionState{
666		vers:         c.vers,
667		cipherSuite:  hs.suite.id,
668		masterSecret: hs.masterSecret,
669		certificates: certsFromClient,
670	}
671	var err error
672	m.ticket, err = c.encryptTicket(state.marshal())
673	if err != nil {
674		return err
675	}
676
677	hs.finishedHash.Write(m.marshal())
678	if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
679		return err
680	}
681
682	return nil
683}
684
685func (hs *serverHandshakeState) sendFinished(out []byte) error {
686	c := hs.c
687
688	if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
689		return err
690	}
691
692	finished := new(finishedMsg)
693	finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
694	hs.finishedHash.Write(finished.marshal())
695	if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
696		return err
697	}
698
699	c.cipherSuite = hs.suite.id
700	copy(out, finished.verifyData)
701
702	return nil
703}
704
705// processCertsFromClient takes a chain of client certificates either from a
706// Certificates message or from a sessionState and verifies them. It returns
707// the public key of the leaf certificate.
708func (c *Conn) processCertsFromClient(certificate Certificate) error {
709	certificates := certificate.Certificate
710	certs := make([]*x509.Certificate, len(certificates))
711	var err error
712	for i, asn1Data := range certificates {
713		if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
714			c.sendAlert(alertBadCertificate)
715			return errors.New("tls: failed to parse client certificate: " + err.Error())
716		}
717	}
718
719	if len(certs) == 0 && requiresClientCert(c.config.ClientAuth) {
720		c.sendAlert(alertBadCertificate)
721		return errors.New("tls: client didn't provide a certificate")
722	}
723
724	if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
725		opts := x509.VerifyOptions{
726			Roots:         c.config.ClientCAs,
727			CurrentTime:   c.config.time(),
728			Intermediates: x509.NewCertPool(),
729			KeyUsages:     []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
730		}
731
732		for _, cert := range certs[1:] {
733			opts.Intermediates.AddCert(cert)
734		}
735
736		chains, err := certs[0].Verify(opts)
737		if err != nil {
738			c.sendAlert(alertBadCertificate)
739			return errors.New("tls: failed to verify client's certificate: " + err.Error())
740		}
741
742		c.verifiedChains = chains
743	}
744
745	if c.config.VerifyPeerCertificate != nil {
746		if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
747			c.sendAlert(alertBadCertificate)
748			return err
749		}
750	}
751
752	if len(certs) == 0 {
753		return nil
754	}
755
756	switch certs[0].PublicKey.(type) {
757	case *ecdsa.PublicKey, *rsa.PublicKey:
758	default:
759		c.sendAlert(alertUnsupportedCertificate)
760		return fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
761	}
762
763	c.peerCertificates = certs
764	c.ocspResponse = certificate.OCSPStaple
765	c.scts = certificate.SignedCertificateTimestamps
766	return nil
767}
768
769// setCipherSuite sets a cipherSuite with the given id as the serverHandshakeState
770// suite if that cipher suite is acceptable to use.
771// It returns a bool indicating if the suite was set.
772func (hs *serverHandshakeState) setCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16) bool {
773	for _, supported := range supportedCipherSuites {
774		if id == supported {
775			candidate := cipherSuiteByID(id)
776			if candidate == nil {
777				continue
778			}
779			// Don't select a ciphersuite which we can't
780			// support for this client.
781			if candidate.flags&suiteECDHE != 0 {
782				if !hs.ellipticOk {
783					continue
784				}
785				if candidate.flags&suiteECDSA != 0 {
786					if !hs.ecdsaOk {
787						continue
788					}
789				} else if !hs.rsaSignOk {
790					continue
791				}
792			} else if !hs.rsaDecryptOk {
793				continue
794			}
795			if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
796				continue
797			}
798			hs.suite = candidate
799			return true
800		}
801	}
802	return false
803}
804
805func clientHelloInfo(c *Conn, clientHello *clientHelloMsg) *ClientHelloInfo {
806	supportedVersions := clientHello.supportedVersions
807	if len(clientHello.supportedVersions) == 0 {
808		supportedVersions = supportedVersionsFromMax(clientHello.vers)
809	}
810
811	return &ClientHelloInfo{
812		CipherSuites:      clientHello.cipherSuites,
813		ServerName:        clientHello.serverName,
814		SupportedCurves:   clientHello.supportedCurves,
815		SupportedPoints:   clientHello.supportedPoints,
816		SignatureSchemes:  clientHello.supportedSignatureAlgorithms,
817		SupportedProtos:   clientHello.alpnProtocols,
818		SupportedVersions: supportedVersions,
819		Conn:              c.conn,
820	}
821}
822