• 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 main
6
7import (
8	"bytes"
9	"crypto"
10	"crypto/ecdsa"
11	"crypto/elliptic"
12	"crypto/rsa"
13	"crypto/subtle"
14	"crypto/x509"
15	"encoding/asn1"
16	"errors"
17	"fmt"
18	"io"
19	"math/big"
20)
21
22// serverHandshakeState contains details of a server handshake in progress.
23// It's discarded once the handshake has completed.
24type serverHandshakeState struct {
25	c               *Conn
26	clientHello     *clientHelloMsg
27	hello           *serverHelloMsg
28	suite           *cipherSuite
29	ellipticOk      bool
30	ecdsaOk         bool
31	sessionState    *sessionState
32	finishedHash    finishedHash
33	masterSecret    []byte
34	certsFromClient [][]byte
35	cert            *Certificate
36	finishedBytes   []byte
37}
38
39// serverHandshake performs a TLS handshake as a server.
40func (c *Conn) serverHandshake() error {
41	config := c.config
42
43	// If this is the first server handshake, we generate a random key to
44	// encrypt the tickets with.
45	config.serverInitOnce.Do(config.serverInit)
46
47	c.sendHandshakeSeq = 0
48	c.recvHandshakeSeq = 0
49
50	hs := serverHandshakeState{
51		c: c,
52	}
53	isResume, err := hs.readClientHello()
54	if err != nil {
55		return err
56	}
57
58	// For an overview of TLS handshaking, see https://tools.ietf.org/html/rfc5246#section-7.3
59	if isResume {
60		// The client has included a session ticket and so we do an abbreviated handshake.
61		if err := hs.doResumeHandshake(); err != nil {
62			return err
63		}
64		if err := hs.establishKeys(); err != nil {
65			return err
66		}
67		if c.config.Bugs.RenewTicketOnResume {
68			if err := hs.sendSessionTicket(); err != nil {
69				return err
70			}
71		}
72		if err := hs.sendFinished(c.firstFinished[:]); err != nil {
73			return err
74		}
75		// Most retransmits are triggered by a timeout, but the final
76		// leg of the handshake is retransmited upon re-receiving a
77		// Finished.
78		if err := c.simulatePacketLoss(func() {
79			c.writeRecord(recordTypeHandshake, hs.finishedBytes)
80			c.dtlsFlushHandshake()
81		}); err != nil {
82			return err
83		}
84		if err := hs.readFinished(nil, isResume); err != nil {
85			return err
86		}
87		c.didResume = true
88	} else {
89		// The client didn't include a session ticket, or it wasn't
90		// valid so we do a full handshake.
91		if err := hs.doFullHandshake(); err != nil {
92			return err
93		}
94		if err := hs.establishKeys(); err != nil {
95			return err
96		}
97		if err := hs.readFinished(c.firstFinished[:], isResume); err != nil {
98			return err
99		}
100		if c.config.Bugs.AlertBeforeFalseStartTest != 0 {
101			c.sendAlert(c.config.Bugs.AlertBeforeFalseStartTest)
102		}
103		if c.config.Bugs.ExpectFalseStart {
104			if err := c.readRecord(recordTypeApplicationData); err != nil {
105				return fmt.Errorf("tls: peer did not false start: %s", err)
106			}
107		}
108		if err := hs.sendSessionTicket(); err != nil {
109			return err
110		}
111		if err := hs.sendFinished(nil); err != nil {
112			return err
113		}
114	}
115	c.handshakeComplete = true
116	copy(c.clientRandom[:], hs.clientHello.random)
117	copy(c.serverRandom[:], hs.hello.random)
118	copy(c.masterSecret[:], hs.masterSecret)
119
120	return nil
121}
122
123// readClientHello reads a ClientHello message from the client and decides
124// whether we will perform session resumption.
125func (hs *serverHandshakeState) readClientHello() (isResume bool, err error) {
126	config := hs.c.config
127	c := hs.c
128
129	if err := c.simulatePacketLoss(nil); err != nil {
130		return false, err
131	}
132	msg, err := c.readHandshake()
133	if err != nil {
134		return false, err
135	}
136	var ok bool
137	hs.clientHello, ok = msg.(*clientHelloMsg)
138	if !ok {
139		c.sendAlert(alertUnexpectedMessage)
140		return false, unexpectedMessageError(hs.clientHello, msg)
141	}
142	if config.Bugs.RequireFastradioPadding && len(hs.clientHello.raw) < 1000 {
143		return false, errors.New("tls: ClientHello record size should be larger than 1000 bytes when padding enabled.")
144	}
145
146	if c.isDTLS && !config.Bugs.SkipHelloVerifyRequest {
147		// Per RFC 6347, the version field in HelloVerifyRequest SHOULD
148		// be always DTLS 1.0
149		helloVerifyRequest := &helloVerifyRequestMsg{
150			vers:   VersionTLS10,
151			cookie: make([]byte, 32),
152		}
153		if _, err := io.ReadFull(c.config.rand(), helloVerifyRequest.cookie); err != nil {
154			c.sendAlert(alertInternalError)
155			return false, errors.New("dtls: short read from Rand: " + err.Error())
156		}
157		c.writeRecord(recordTypeHandshake, helloVerifyRequest.marshal())
158		c.dtlsFlushHandshake()
159
160		if err := c.simulatePacketLoss(nil); err != nil {
161			return false, err
162		}
163		msg, err := c.readHandshake()
164		if err != nil {
165			return false, err
166		}
167		newClientHello, ok := msg.(*clientHelloMsg)
168		if !ok {
169			c.sendAlert(alertUnexpectedMessage)
170			return false, unexpectedMessageError(hs.clientHello, msg)
171		}
172		if !bytes.Equal(newClientHello.cookie, helloVerifyRequest.cookie) {
173			return false, errors.New("dtls: invalid cookie")
174		}
175
176		// Apart from the cookie, the two ClientHellos must
177		// match. Note that clientHello.equal compares the
178		// serialization, so we make a copy.
179		oldClientHelloCopy := *hs.clientHello
180		oldClientHelloCopy.raw = nil
181		oldClientHelloCopy.cookie = nil
182		newClientHelloCopy := *newClientHello
183		newClientHelloCopy.raw = nil
184		newClientHelloCopy.cookie = nil
185		if !oldClientHelloCopy.equal(&newClientHelloCopy) {
186			return false, errors.New("dtls: retransmitted ClientHello does not match")
187		}
188		hs.clientHello = newClientHello
189	}
190
191	if config.Bugs.RequireSameRenegoClientVersion && c.clientVersion != 0 {
192		if c.clientVersion != hs.clientHello.vers {
193			return false, fmt.Errorf("tls: client offered different version on renego")
194		}
195	}
196	c.clientVersion = hs.clientHello.vers
197
198	// Reject < 1.2 ClientHellos with signature_algorithms.
199	if c.clientVersion < VersionTLS12 && len(hs.clientHello.signatureAndHashes) > 0 {
200		return false, fmt.Errorf("tls: client included signature_algorithms before TLS 1.2")
201	}
202	if config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
203		hs.clientHello.signatureAndHashes = config.signatureAndHashesForServer()
204	}
205
206	c.vers, ok = config.mutualVersion(hs.clientHello.vers)
207	if !ok {
208		c.sendAlert(alertProtocolVersion)
209		return false, fmt.Errorf("tls: client offered an unsupported, maximum protocol version of %x", hs.clientHello.vers)
210	}
211	c.haveVers = true
212
213	hs.hello = new(serverHelloMsg)
214	hs.hello.isDTLS = c.isDTLS
215
216	supportedCurve := false
217	preferredCurves := config.curvePreferences()
218	if config.Bugs.IgnorePeerCurvePreferences {
219		hs.clientHello.supportedCurves = preferredCurves
220	}
221Curves:
222	for _, curve := range hs.clientHello.supportedCurves {
223		for _, supported := range preferredCurves {
224			if supported == curve {
225				supportedCurve = true
226				break Curves
227			}
228		}
229	}
230
231	supportedPointFormat := false
232	for _, pointFormat := range hs.clientHello.supportedPoints {
233		if pointFormat == pointFormatUncompressed {
234			supportedPointFormat = true
235			break
236		}
237	}
238	hs.ellipticOk = supportedCurve && supportedPointFormat
239
240	foundCompression := false
241	// We only support null compression, so check that the client offered it.
242	for _, compression := range hs.clientHello.compressionMethods {
243		if compression == compressionNone {
244			foundCompression = true
245			break
246		}
247	}
248
249	if !foundCompression {
250		c.sendAlert(alertHandshakeFailure)
251		return false, errors.New("tls: client does not support uncompressed connections")
252	}
253
254	hs.hello.vers = c.vers
255	hs.hello.random = make([]byte, 32)
256	_, err = io.ReadFull(config.rand(), hs.hello.random)
257	if err != nil {
258		c.sendAlert(alertInternalError)
259		return false, err
260	}
261
262	if !bytes.Equal(c.clientVerify, hs.clientHello.secureRenegotiation) {
263		c.sendAlert(alertHandshakeFailure)
264		return false, errors.New("tls: renegotiation mismatch")
265	}
266
267	if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
268		hs.hello.secureRenegotiation = append(hs.hello.secureRenegotiation, c.clientVerify...)
269		hs.hello.secureRenegotiation = append(hs.hello.secureRenegotiation, c.serverVerify...)
270		if c.config.Bugs.BadRenegotiationInfo {
271			hs.hello.secureRenegotiation[0] ^= 0x80
272		}
273	} else {
274		hs.hello.secureRenegotiation = hs.clientHello.secureRenegotiation
275	}
276
277	if c.config.Bugs.NoRenegotiationInfo {
278		hs.hello.secureRenegotiation = nil
279	}
280
281	hs.hello.compressionMethod = compressionNone
282	hs.hello.duplicateExtension = c.config.Bugs.DuplicateExtension
283	if len(hs.clientHello.serverName) > 0 {
284		c.serverName = hs.clientHello.serverName
285	}
286
287	if len(hs.clientHello.alpnProtocols) > 0 {
288		if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
289			hs.hello.alpnProtocol = selectedProto
290			c.clientProtocol = selectedProto
291			c.usedALPN = true
292		}
293	} else {
294		// Although sending an empty NPN extension is reasonable, Firefox has
295		// had a bug around this. Best to send nothing at all if
296		// config.NextProtos is empty. See
297		// https://code.google.com/p/go/issues/detail?id=5445.
298		if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 {
299			hs.hello.nextProtoNeg = true
300			hs.hello.nextProtos = config.NextProtos
301		}
302	}
303	hs.hello.extendedMasterSecret = c.vers >= VersionTLS10 && hs.clientHello.extendedMasterSecret && !c.config.Bugs.NoExtendedMasterSecret
304
305	if len(config.Certificates) == 0 {
306		c.sendAlert(alertInternalError)
307		return false, errors.New("tls: no certificates configured")
308	}
309	hs.cert = &config.Certificates[0]
310	if len(hs.clientHello.serverName) > 0 {
311		hs.cert = config.getCertificateForName(hs.clientHello.serverName)
312	}
313	if expected := c.config.Bugs.ExpectServerName; expected != "" && expected != hs.clientHello.serverName {
314		return false, errors.New("tls: unexpected server name")
315	}
316
317	if hs.clientHello.channelIDSupported && config.RequestChannelID {
318		hs.hello.channelIDRequested = true
319	}
320
321	if hs.clientHello.srtpProtectionProfiles != nil {
322	SRTPLoop:
323		for _, p1 := range c.config.SRTPProtectionProfiles {
324			for _, p2 := range hs.clientHello.srtpProtectionProfiles {
325				if p1 == p2 {
326					hs.hello.srtpProtectionProfile = p1
327					c.srtpProtectionProfile = p1
328					break SRTPLoop
329				}
330			}
331		}
332	}
333
334	if c.config.Bugs.SendSRTPProtectionProfile != 0 {
335		hs.hello.srtpProtectionProfile = c.config.Bugs.SendSRTPProtectionProfile
336	}
337
338	_, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
339
340	// For test purposes, check that the peer never offers a session when
341	// renegotiating.
342	if c.cipherSuite != nil && len(hs.clientHello.sessionId) > 0 && c.config.Bugs.FailIfResumeOnRenego {
343		return false, errors.New("tls: offered resumption on renegotiation")
344	}
345
346	if hs.checkForResumption() {
347		return true, nil
348	}
349
350	var scsvFound bool
351
352	for _, cipherSuite := range hs.clientHello.cipherSuites {
353		if cipherSuite == fallbackSCSV {
354			scsvFound = true
355			break
356		}
357	}
358
359	if !scsvFound && config.Bugs.FailIfNotFallbackSCSV {
360		return false, errors.New("tls: no fallback SCSV found when expected")
361	} else if scsvFound && !config.Bugs.FailIfNotFallbackSCSV {
362		return false, errors.New("tls: fallback SCSV found when not expected")
363	}
364
365	if config.Bugs.IgnorePeerCipherPreferences {
366		hs.clientHello.cipherSuites = c.config.cipherSuites()
367	}
368	var preferenceList, supportedList []uint16
369	if c.config.PreferServerCipherSuites {
370		preferenceList = c.config.cipherSuites()
371		supportedList = hs.clientHello.cipherSuites
372	} else {
373		preferenceList = hs.clientHello.cipherSuites
374		supportedList = c.config.cipherSuites()
375	}
376
377	for _, id := range preferenceList {
378		if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk); hs.suite != nil {
379			break
380		}
381	}
382
383	if hs.suite == nil {
384		c.sendAlert(alertHandshakeFailure)
385		return false, errors.New("tls: no cipher suite supported by both client and server")
386	}
387
388	return false, nil
389}
390
391// checkForResumption returns true if we should perform resumption on this connection.
392func (hs *serverHandshakeState) checkForResumption() bool {
393	c := hs.c
394
395	if len(hs.clientHello.sessionTicket) > 0 {
396		if c.config.SessionTicketsDisabled {
397			return false
398		}
399
400		var ok bool
401		if hs.sessionState, ok = c.decryptTicket(hs.clientHello.sessionTicket); !ok {
402			return false
403		}
404	} else {
405		if c.config.ServerSessionCache == nil {
406			return false
407		}
408
409		var ok bool
410		sessionId := string(hs.clientHello.sessionId)
411		if hs.sessionState, ok = c.config.ServerSessionCache.Get(sessionId); !ok {
412			return false
413		}
414	}
415
416	// Never resume a session for a different SSL version.
417	if !c.config.Bugs.AllowSessionVersionMismatch && c.vers != hs.sessionState.vers {
418		return false
419	}
420
421	cipherSuiteOk := false
422	// Check that the client is still offering the ciphersuite in the session.
423	for _, id := range hs.clientHello.cipherSuites {
424		if id == hs.sessionState.cipherSuite {
425			cipherSuiteOk = true
426			break
427		}
428	}
429	if !cipherSuiteOk {
430		return false
431	}
432
433	// Check that we also support the ciphersuite from the session.
434	hs.suite = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers, hs.ellipticOk, hs.ecdsaOk)
435	if hs.suite == nil {
436		return false
437	}
438
439	sessionHasClientCerts := len(hs.sessionState.certificates) != 0
440	needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
441	if needClientCerts && !sessionHasClientCerts {
442		return false
443	}
444	if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
445		return false
446	}
447
448	return true
449}
450
451func (hs *serverHandshakeState) doResumeHandshake() error {
452	c := hs.c
453
454	hs.hello.cipherSuite = hs.suite.id
455	if c.config.Bugs.SendCipherSuite != 0 {
456		hs.hello.cipherSuite = c.config.Bugs.SendCipherSuite
457	}
458	// We echo the client's session ID in the ServerHello to let it know
459	// that we're doing a resumption.
460	hs.hello.sessionId = hs.clientHello.sessionId
461	hs.hello.ticketSupported = c.config.Bugs.RenewTicketOnResume
462
463	hs.finishedHash = newFinishedHash(c.vers, hs.suite)
464	hs.finishedHash.discardHandshakeBuffer()
465	hs.writeClientHash(hs.clientHello.marshal())
466	hs.writeServerHash(hs.hello.marshal())
467
468	c.writeRecord(recordTypeHandshake, hs.hello.marshal())
469
470	if len(hs.sessionState.certificates) > 0 {
471		if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
472			return err
473		}
474	}
475
476	hs.masterSecret = hs.sessionState.masterSecret
477	c.extendedMasterSecret = hs.sessionState.extendedMasterSecret
478
479	return nil
480}
481
482func (hs *serverHandshakeState) doFullHandshake() error {
483	config := hs.c.config
484	c := hs.c
485
486	isPSK := hs.suite.flags&suitePSK != 0
487	if !isPSK && hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
488		hs.hello.ocspStapling = true
489	}
490
491	if hs.clientHello.sctListSupported && len(hs.cert.SignedCertificateTimestampList) > 0 {
492		hs.hello.sctList = hs.cert.SignedCertificateTimestampList
493	}
494
495	hs.hello.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled && c.vers > VersionSSL30
496	hs.hello.cipherSuite = hs.suite.id
497	if config.Bugs.SendCipherSuite != 0 {
498		hs.hello.cipherSuite = config.Bugs.SendCipherSuite
499	}
500	c.extendedMasterSecret = hs.hello.extendedMasterSecret
501
502	// Generate a session ID if we're to save the session.
503	if !hs.hello.ticketSupported && config.ServerSessionCache != nil {
504		hs.hello.sessionId = make([]byte, 32)
505		if _, err := io.ReadFull(config.rand(), hs.hello.sessionId); err != nil {
506			c.sendAlert(alertInternalError)
507			return errors.New("tls: short read from Rand: " + err.Error())
508		}
509	}
510
511	hs.finishedHash = newFinishedHash(c.vers, hs.suite)
512	hs.writeClientHash(hs.clientHello.marshal())
513	hs.writeServerHash(hs.hello.marshal())
514
515	c.writeRecord(recordTypeHandshake, hs.hello.marshal())
516
517	if !isPSK {
518		certMsg := new(certificateMsg)
519		certMsg.certificates = hs.cert.Certificate
520		if !config.Bugs.UnauthenticatedECDH {
521			certMsgBytes := certMsg.marshal()
522			if config.Bugs.WrongCertificateMessageType {
523				certMsgBytes[0] += 42
524			}
525			hs.writeServerHash(certMsgBytes)
526			c.writeRecord(recordTypeHandshake, certMsgBytes)
527		}
528	}
529
530	if hs.hello.ocspStapling && !c.config.Bugs.SkipCertificateStatus {
531		certStatus := new(certificateStatusMsg)
532		certStatus.statusType = statusTypeOCSP
533		certStatus.response = hs.cert.OCSPStaple
534		hs.writeServerHash(certStatus.marshal())
535		c.writeRecord(recordTypeHandshake, certStatus.marshal())
536	}
537
538	keyAgreement := hs.suite.ka(c.vers)
539	skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
540	if err != nil {
541		c.sendAlert(alertHandshakeFailure)
542		return err
543	}
544	if skx != nil && !config.Bugs.SkipServerKeyExchange {
545		hs.writeServerHash(skx.marshal())
546		c.writeRecord(recordTypeHandshake, skx.marshal())
547	}
548
549	if config.ClientAuth >= RequestClientCert {
550		// Request a client certificate
551		certReq := &certificateRequestMsg{
552			certificateTypes: config.ClientCertificateTypes,
553		}
554		if certReq.certificateTypes == nil {
555			certReq.certificateTypes = []byte{
556				byte(CertTypeRSASign),
557				byte(CertTypeECDSASign),
558			}
559		}
560		if c.vers >= VersionTLS12 {
561			certReq.hasSignatureAndHash = true
562			if !config.Bugs.NoSignatureAndHashes {
563				certReq.signatureAndHashes = config.signatureAndHashesForServer()
564			}
565		}
566
567		// An empty list of certificateAuthorities signals to
568		// the client that it may send any certificate in response
569		// to our request. When we know the CAs we trust, then
570		// we can send them down, so that the client can choose
571		// an appropriate certificate to give to us.
572		if config.ClientCAs != nil {
573			certReq.certificateAuthorities = config.ClientCAs.Subjects()
574		}
575		hs.writeServerHash(certReq.marshal())
576		c.writeRecord(recordTypeHandshake, certReq.marshal())
577	}
578
579	helloDone := new(serverHelloDoneMsg)
580	hs.writeServerHash(helloDone.marshal())
581	c.writeRecord(recordTypeHandshake, helloDone.marshal())
582	c.dtlsFlushHandshake()
583
584	var pub crypto.PublicKey // public key for client auth, if any
585
586	if err := c.simulatePacketLoss(nil); err != nil {
587		return err
588	}
589	msg, err := c.readHandshake()
590	if err != nil {
591		return err
592	}
593
594	var ok bool
595	// If we requested a client certificate, then the client must send a
596	// certificate message, even if it's empty.
597	if config.ClientAuth >= RequestClientCert {
598		var certMsg *certificateMsg
599		if certMsg, ok = msg.(*certificateMsg); !ok {
600			c.sendAlert(alertUnexpectedMessage)
601			return unexpectedMessageError(certMsg, msg)
602		}
603		hs.writeClientHash(certMsg.marshal())
604
605		if len(certMsg.certificates) == 0 {
606			// The client didn't actually send a certificate
607			switch config.ClientAuth {
608			case RequireAnyClientCert, RequireAndVerifyClientCert:
609				c.sendAlert(alertBadCertificate)
610				return errors.New("tls: client didn't provide a certificate")
611			}
612		}
613
614		pub, err = hs.processCertsFromClient(certMsg.certificates)
615		if err != nil {
616			return err
617		}
618
619		msg, err = c.readHandshake()
620		if err != nil {
621			return err
622		}
623	}
624
625	// Get client key exchange
626	ckx, ok := msg.(*clientKeyExchangeMsg)
627	if !ok {
628		c.sendAlert(alertUnexpectedMessage)
629		return unexpectedMessageError(ckx, msg)
630	}
631	hs.writeClientHash(ckx.marshal())
632
633	preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
634	if err != nil {
635		c.sendAlert(alertHandshakeFailure)
636		return err
637	}
638	if c.extendedMasterSecret {
639		hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
640	} else {
641		if c.config.Bugs.RequireExtendedMasterSecret {
642			return errors.New("tls: extended master secret required but not supported by peer")
643		}
644		hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
645	}
646
647	// If we received a client cert in response to our certificate request message,
648	// the client will send us a certificateVerifyMsg immediately after the
649	// clientKeyExchangeMsg.  This message is a digest of all preceding
650	// handshake-layer messages that is signed using the private key corresponding
651	// to the client's certificate. This allows us to verify that the client is in
652	// possession of the private key of the certificate.
653	if len(c.peerCertificates) > 0 {
654		msg, err = c.readHandshake()
655		if err != nil {
656			return err
657		}
658		certVerify, ok := msg.(*certificateVerifyMsg)
659		if !ok {
660			c.sendAlert(alertUnexpectedMessage)
661			return unexpectedMessageError(certVerify, msg)
662		}
663
664		// Determine the signature type.
665		var signatureAndHash signatureAndHash
666		if certVerify.hasSignatureAndHash {
667			signatureAndHash = certVerify.signatureAndHash
668			if !isSupportedSignatureAndHash(signatureAndHash, config.signatureAndHashesForServer()) {
669				return errors.New("tls: unsupported hash function for client certificate")
670			}
671		} else {
672			// Before TLS 1.2 the signature algorithm was implicit
673			// from the key type, and only one hash per signature
674			// algorithm was possible. Leave the hash as zero.
675			switch pub.(type) {
676			case *ecdsa.PublicKey:
677				signatureAndHash.signature = signatureECDSA
678			case *rsa.PublicKey:
679				signatureAndHash.signature = signatureRSA
680			}
681		}
682
683		switch key := pub.(type) {
684		case *ecdsa.PublicKey:
685			if signatureAndHash.signature != signatureECDSA {
686				err = errors.New("tls: bad signature type for client's ECDSA certificate")
687				break
688			}
689			ecdsaSig := new(ecdsaSignature)
690			if _, err = asn1.Unmarshal(certVerify.signature, ecdsaSig); err != nil {
691				break
692			}
693			if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
694				err = errors.New("ECDSA signature contained zero or negative values")
695				break
696			}
697			var digest []byte
698			digest, _, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
699			if err != nil {
700				break
701			}
702			if !ecdsa.Verify(key, digest, ecdsaSig.R, ecdsaSig.S) {
703				err = errors.New("ECDSA verification failure")
704				break
705			}
706		case *rsa.PublicKey:
707			if signatureAndHash.signature != signatureRSA {
708				err = errors.New("tls: bad signature type for client's RSA certificate")
709				break
710			}
711			var digest []byte
712			var hashFunc crypto.Hash
713			digest, hashFunc, err = hs.finishedHash.hashForClientCertificate(signatureAndHash, hs.masterSecret)
714			if err != nil {
715				break
716			}
717			err = rsa.VerifyPKCS1v15(key, hashFunc, digest, certVerify.signature)
718		}
719		if err != nil {
720			c.sendAlert(alertBadCertificate)
721			return errors.New("could not validate signature of connection nonces: " + err.Error())
722		}
723
724		hs.writeClientHash(certVerify.marshal())
725	}
726
727	hs.finishedHash.discardHandshakeBuffer()
728
729	return nil
730}
731
732func (hs *serverHandshakeState) establishKeys() error {
733	c := hs.c
734
735	clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
736		keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
737
738	var clientCipher, serverCipher interface{}
739	var clientHash, serverHash macFunction
740
741	if hs.suite.aead == nil {
742		clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
743		clientHash = hs.suite.mac(c.vers, clientMAC)
744		serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
745		serverHash = hs.suite.mac(c.vers, serverMAC)
746	} else {
747		clientCipher = hs.suite.aead(clientKey, clientIV)
748		serverCipher = hs.suite.aead(serverKey, serverIV)
749	}
750
751	c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
752	c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
753
754	return nil
755}
756
757func (hs *serverHandshakeState) readFinished(out []byte, isResume bool) error {
758	c := hs.c
759
760	c.readRecord(recordTypeChangeCipherSpec)
761	if err := c.in.error(); err != nil {
762		return err
763	}
764
765	if hs.hello.nextProtoNeg {
766		msg, err := c.readHandshake()
767		if err != nil {
768			return err
769		}
770		nextProto, ok := msg.(*nextProtoMsg)
771		if !ok {
772			c.sendAlert(alertUnexpectedMessage)
773			return unexpectedMessageError(nextProto, msg)
774		}
775		hs.writeClientHash(nextProto.marshal())
776		c.clientProtocol = nextProto.proto
777	}
778
779	if hs.hello.channelIDRequested {
780		msg, err := c.readHandshake()
781		if err != nil {
782			return err
783		}
784		encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
785		if !ok {
786			c.sendAlert(alertUnexpectedMessage)
787			return unexpectedMessageError(encryptedExtensions, msg)
788		}
789		x := new(big.Int).SetBytes(encryptedExtensions.channelID[0:32])
790		y := new(big.Int).SetBytes(encryptedExtensions.channelID[32:64])
791		r := new(big.Int).SetBytes(encryptedExtensions.channelID[64:96])
792		s := new(big.Int).SetBytes(encryptedExtensions.channelID[96:128])
793		if !elliptic.P256().IsOnCurve(x, y) {
794			return errors.New("tls: invalid channel ID public key")
795		}
796		channelID := &ecdsa.PublicKey{elliptic.P256(), x, y}
797		var resumeHash []byte
798		if isResume {
799			resumeHash = hs.sessionState.handshakeHash
800		}
801		if !ecdsa.Verify(channelID, hs.finishedHash.hashForChannelID(resumeHash), r, s) {
802			return errors.New("tls: invalid channel ID signature")
803		}
804		c.channelID = channelID
805
806		hs.writeClientHash(encryptedExtensions.marshal())
807	}
808
809	msg, err := c.readHandshake()
810	if err != nil {
811		return err
812	}
813	clientFinished, ok := msg.(*finishedMsg)
814	if !ok {
815		c.sendAlert(alertUnexpectedMessage)
816		return unexpectedMessageError(clientFinished, msg)
817	}
818
819	verify := hs.finishedHash.clientSum(hs.masterSecret)
820	if len(verify) != len(clientFinished.verifyData) ||
821		subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
822		c.sendAlert(alertHandshakeFailure)
823		return errors.New("tls: client's Finished message is incorrect")
824	}
825	c.clientVerify = append(c.clientVerify[:0], clientFinished.verifyData...)
826	copy(out, clientFinished.verifyData)
827
828	hs.writeClientHash(clientFinished.marshal())
829	return nil
830}
831
832func (hs *serverHandshakeState) sendSessionTicket() error {
833	c := hs.c
834	state := sessionState{
835		vers:          c.vers,
836		cipherSuite:   hs.suite.id,
837		masterSecret:  hs.masterSecret,
838		certificates:  hs.certsFromClient,
839		handshakeHash: hs.finishedHash.server.Sum(nil),
840	}
841
842	if !hs.hello.ticketSupported || hs.c.config.Bugs.SkipNewSessionTicket {
843		if c.config.ServerSessionCache != nil && len(hs.hello.sessionId) != 0 {
844			c.config.ServerSessionCache.Put(string(hs.hello.sessionId), &state)
845		}
846		return nil
847	}
848
849	m := new(newSessionTicketMsg)
850
851	var err error
852	m.ticket, err = c.encryptTicket(&state)
853	if err != nil {
854		return err
855	}
856
857	hs.writeServerHash(m.marshal())
858	c.writeRecord(recordTypeHandshake, m.marshal())
859
860	return nil
861}
862
863func (hs *serverHandshakeState) sendFinished(out []byte) error {
864	c := hs.c
865
866	finished := new(finishedMsg)
867	finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
868	copy(out, finished.verifyData)
869	if c.config.Bugs.BadFinished {
870		finished.verifyData[0]++
871	}
872	c.serverVerify = append(c.serverVerify[:0], finished.verifyData...)
873	hs.finishedBytes = finished.marshal()
874	hs.writeServerHash(hs.finishedBytes)
875	postCCSBytes := hs.finishedBytes
876
877	if c.config.Bugs.FragmentAcrossChangeCipherSpec {
878		c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
879		postCCSBytes = postCCSBytes[5:]
880	}
881	c.dtlsFlushHandshake()
882
883	if !c.config.Bugs.SkipChangeCipherSpec {
884		c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
885	}
886
887	if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
888		c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
889	}
890	if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
891		c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
892		return errors.New("tls: simulating post-CCS alert")
893	}
894
895	if !c.config.Bugs.SkipFinished {
896		c.writeRecord(recordTypeHandshake, postCCSBytes)
897		c.dtlsFlushHandshake()
898	}
899
900	c.cipherSuite = hs.suite
901
902	return nil
903}
904
905// processCertsFromClient takes a chain of client certificates either from a
906// Certificates message or from a sessionState and verifies them. It returns
907// the public key of the leaf certificate.
908func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
909	c := hs.c
910
911	hs.certsFromClient = certificates
912	certs := make([]*x509.Certificate, len(certificates))
913	var err error
914	for i, asn1Data := range certificates {
915		if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
916			c.sendAlert(alertBadCertificate)
917			return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
918		}
919	}
920
921	if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
922		opts := x509.VerifyOptions{
923			Roots:         c.config.ClientCAs,
924			CurrentTime:   c.config.time(),
925			Intermediates: x509.NewCertPool(),
926			KeyUsages:     []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
927		}
928
929		for _, cert := range certs[1:] {
930			opts.Intermediates.AddCert(cert)
931		}
932
933		chains, err := certs[0].Verify(opts)
934		if err != nil {
935			c.sendAlert(alertBadCertificate)
936			return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
937		}
938
939		ok := false
940		for _, ku := range certs[0].ExtKeyUsage {
941			if ku == x509.ExtKeyUsageClientAuth {
942				ok = true
943				break
944			}
945		}
946		if !ok {
947			c.sendAlert(alertHandshakeFailure)
948			return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
949		}
950
951		c.verifiedChains = chains
952	}
953
954	if len(certs) > 0 {
955		var pub crypto.PublicKey
956		switch key := certs[0].PublicKey.(type) {
957		case *ecdsa.PublicKey, *rsa.PublicKey:
958			pub = key
959		default:
960			c.sendAlert(alertUnsupportedCertificate)
961			return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
962		}
963		c.peerCertificates = certs
964		return pub, nil
965	}
966
967	return nil, nil
968}
969
970func (hs *serverHandshakeState) writeServerHash(msg []byte) {
971	// writeServerHash is called before writeRecord.
972	hs.writeHash(msg, hs.c.sendHandshakeSeq)
973}
974
975func (hs *serverHandshakeState) writeClientHash(msg []byte) {
976	// writeClientHash is called after readHandshake.
977	hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
978}
979
980func (hs *serverHandshakeState) writeHash(msg []byte, seqno uint16) {
981	if hs.c.isDTLS {
982		// This is somewhat hacky. DTLS hashes a slightly different format.
983		// First, the TLS header.
984		hs.finishedHash.Write(msg[:4])
985		// Then the sequence number and reassembled fragment offset (always 0).
986		hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
987		// Then the reassembled fragment (always equal to the message length).
988		hs.finishedHash.Write(msg[1:4])
989		// And then the message body.
990		hs.finishedHash.Write(msg[4:])
991	} else {
992		hs.finishedHash.Write(msg)
993	}
994}
995
996// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
997// is acceptable to use.
998func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk bool) *cipherSuite {
999	for _, supported := range supportedCipherSuites {
1000		if id == supported {
1001			var candidate *cipherSuite
1002
1003			for _, s := range cipherSuites {
1004				if s.id == id {
1005					candidate = s
1006					break
1007				}
1008			}
1009			if candidate == nil {
1010				continue
1011			}
1012			// Don't select a ciphersuite which we can't
1013			// support for this client.
1014			if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
1015				continue
1016			}
1017			if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
1018				continue
1019			}
1020			if !c.config.Bugs.SkipCipherVersionCheck && version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
1021				continue
1022			}
1023			if c.isDTLS && candidate.flags&suiteNoDTLS != 0 {
1024				continue
1025			}
1026			return candidate
1027		}
1028	}
1029
1030	return nil
1031}
1032