1// Copyright 2018 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 qtls
6
7import (
8	"bytes"
9	"context"
10	"crypto"
11	"crypto/hmac"
12	"crypto/rsa"
13	"errors"
14	"hash"
15	"io"
16	"sync/atomic"
17	"time"
18)
19
20// maxClientPSKIdentities is the number of client PSK identities the server will
21// attempt to validate. It will ignore the rest not to let cheap ClientHello
22// messages cause too much work in session ticket decryption attempts.
23const maxClientPSKIdentities = 5
24
25type serverHandshakeStateTLS13 struct {
26	c                   *Conn
27	ctx                 context.Context
28	clientHello         *clientHelloMsg
29	hello               *serverHelloMsg
30	alpnNegotiationErr  error
31	encryptedExtensions *encryptedExtensionsMsg
32	sentDummyCCS        bool
33	usingPSK            bool
34	suite               *cipherSuiteTLS13
35	cert                *Certificate
36	sigAlg              SignatureScheme
37	earlySecret         []byte
38	sharedKey           []byte
39	handshakeSecret     []byte
40	masterSecret        []byte
41	trafficSecret       []byte // client_application_traffic_secret_0
42	transcript          hash.Hash
43	clientFinished      []byte
44}
45
46func (hs *serverHandshakeStateTLS13) handshake() error {
47	c := hs.c
48
49	// For an overview of the TLS 1.3 handshake, see RFC 8446, Section 2.
50	if err := hs.processClientHello(); err != nil {
51		return err
52	}
53	if err := hs.checkForResumption(); err != nil {
54		return err
55	}
56	if err := hs.pickCertificate(); err != nil {
57		return err
58	}
59	c.buffering = true
60	if err := hs.sendServerParameters(); err != nil {
61		return err
62	}
63	if err := hs.sendServerCertificate(); err != nil {
64		return err
65	}
66	if err := hs.sendServerFinished(); err != nil {
67		return err
68	}
69	// Note that at this point we could start sending application data without
70	// waiting for the client's second flight, but the application might not
71	// expect the lack of replay protection of the ClientHello parameters.
72	if _, err := c.flush(); err != nil {
73		return err
74	}
75	if err := hs.readClientCertificate(); err != nil {
76		return err
77	}
78	if err := hs.readClientFinished(); err != nil {
79		return err
80	}
81
82	atomic.StoreUint32(&c.handshakeStatus, 1)
83
84	return nil
85}
86
87func (hs *serverHandshakeStateTLS13) processClientHello() error {
88	c := hs.c
89
90	hs.hello = new(serverHelloMsg)
91	hs.encryptedExtensions = new(encryptedExtensionsMsg)
92
93	// TLS 1.3 froze the ServerHello.legacy_version field, and uses
94	// supported_versions instead. See RFC 8446, sections 4.1.3 and 4.2.1.
95	hs.hello.vers = VersionTLS12
96	hs.hello.supportedVersion = c.vers
97
98	if len(hs.clientHello.supportedVersions) == 0 {
99		c.sendAlert(alertIllegalParameter)
100		return errors.New("tls: client used the legacy version field to negotiate TLS 1.3")
101	}
102
103	// Abort if the client is doing a fallback and landing lower than what we
104	// support. See RFC 7507, which however does not specify the interaction
105	// with supported_versions. The only difference is that with
106	// supported_versions a client has a chance to attempt a [TLS 1.2, TLS 1.4]
107	// handshake in case TLS 1.3 is broken but 1.2 is not. Alas, in that case,
108	// it will have to drop the TLS_FALLBACK_SCSV protection if it falls back to
109	// TLS 1.2, because a TLS 1.3 server would abort here. The situation before
110	// supported_versions was not better because there was just no way to do a
111	// TLS 1.4 handshake without risking the server selecting TLS 1.3.
112	for _, id := range hs.clientHello.cipherSuites {
113		if id == TLS_FALLBACK_SCSV {
114			// Use c.vers instead of max(supported_versions) because an attacker
115			// could defeat this by adding an arbitrary high version otherwise.
116			if c.vers < c.config.maxSupportedVersion() {
117				c.sendAlert(alertInappropriateFallback)
118				return errors.New("tls: client using inappropriate protocol fallback")
119			}
120			break
121		}
122	}
123
124	if len(hs.clientHello.compressionMethods) != 1 ||
125		hs.clientHello.compressionMethods[0] != compressionNone {
126		c.sendAlert(alertIllegalParameter)
127		return errors.New("tls: TLS 1.3 client supports illegal compression methods")
128	}
129
130	hs.hello.random = make([]byte, 32)
131	if _, err := io.ReadFull(c.config.rand(), hs.hello.random); err != nil {
132		c.sendAlert(alertInternalError)
133		return err
134	}
135
136	if len(hs.clientHello.secureRenegotiation) != 0 {
137		c.sendAlert(alertHandshakeFailure)
138		return errors.New("tls: initial handshake had non-empty renegotiation extension")
139	}
140
141	hs.hello.sessionId = hs.clientHello.sessionId
142	hs.hello.compressionMethod = compressionNone
143
144	if hs.suite == nil {
145		var preferenceList []uint16
146		for _, suiteID := range c.config.CipherSuites {
147			for _, suite := range cipherSuitesTLS13 {
148				if suite.id == suiteID {
149					preferenceList = append(preferenceList, suiteID)
150					break
151				}
152			}
153		}
154		if len(preferenceList) == 0 {
155			preferenceList = defaultCipherSuitesTLS13
156			if !hasAESGCMHardwareSupport || !aesgcmPreferred(hs.clientHello.cipherSuites) {
157				preferenceList = defaultCipherSuitesTLS13NoAES
158			}
159		}
160		for _, suiteID := range preferenceList {
161			hs.suite = mutualCipherSuiteTLS13(hs.clientHello.cipherSuites, suiteID)
162			if hs.suite != nil {
163				break
164			}
165		}
166	}
167	if hs.suite == nil {
168		c.sendAlert(alertHandshakeFailure)
169		return errors.New("tls: no cipher suite supported by both client and server")
170	}
171	c.cipherSuite = hs.suite.id
172	hs.hello.cipherSuite = hs.suite.id
173	hs.transcript = hs.suite.hash.New()
174
175	// Pick the ECDHE group in server preference order, but give priority to
176	// groups with a key share, to avoid a HelloRetryRequest round-trip.
177	var selectedGroup CurveID
178	var clientKeyShare *keyShare
179GroupSelection:
180	for _, preferredGroup := range c.config.curvePreferences() {
181		for _, ks := range hs.clientHello.keyShares {
182			if ks.group == preferredGroup {
183				selectedGroup = ks.group
184				clientKeyShare = &ks
185				break GroupSelection
186			}
187		}
188		if selectedGroup != 0 {
189			continue
190		}
191		for _, group := range hs.clientHello.supportedCurves {
192			if group == preferredGroup {
193				selectedGroup = group
194				break
195			}
196		}
197	}
198	if selectedGroup == 0 {
199		c.sendAlert(alertHandshakeFailure)
200		return errors.New("tls: no ECDHE curve supported by both client and server")
201	}
202	if clientKeyShare == nil {
203		if err := hs.doHelloRetryRequest(selectedGroup); err != nil {
204			return err
205		}
206		clientKeyShare = &hs.clientHello.keyShares[0]
207	}
208
209	if _, ok := curveForCurveID(selectedGroup); selectedGroup != X25519 && !ok {
210		c.sendAlert(alertInternalError)
211		return errors.New("tls: CurvePreferences includes unsupported curve")
212	}
213	params, err := generateECDHEParameters(c.config.rand(), selectedGroup)
214	if err != nil {
215		c.sendAlert(alertInternalError)
216		return err
217	}
218	hs.hello.serverShare = keyShare{group: selectedGroup, data: params.PublicKey()}
219	hs.sharedKey = params.SharedKey(clientKeyShare.data)
220	if hs.sharedKey == nil {
221		c.sendAlert(alertIllegalParameter)
222		return errors.New("tls: invalid client key share")
223	}
224
225	c.serverName = hs.clientHello.serverName
226
227	if c.extraConfig != nil && c.extraConfig.ReceivedExtensions != nil {
228		c.extraConfig.ReceivedExtensions(typeClientHello, hs.clientHello.additionalExtensions)
229	}
230
231	selectedProto, err := negotiateALPN(c.config.NextProtos, hs.clientHello.alpnProtocols)
232	if err != nil {
233		hs.alpnNegotiationErr = err
234	}
235	hs.encryptedExtensions.alpnProtocol = selectedProto
236	c.clientProtocol = selectedProto
237
238	return nil
239}
240
241func (hs *serverHandshakeStateTLS13) checkForResumption() error {
242	c := hs.c
243
244	if c.config.SessionTicketsDisabled {
245		return nil
246	}
247
248	modeOK := false
249	for _, mode := range hs.clientHello.pskModes {
250		if mode == pskModeDHE {
251			modeOK = true
252			break
253		}
254	}
255	if !modeOK {
256		return nil
257	}
258
259	if len(hs.clientHello.pskIdentities) != len(hs.clientHello.pskBinders) {
260		c.sendAlert(alertIllegalParameter)
261		return errors.New("tls: invalid or missing PSK binders")
262	}
263	if len(hs.clientHello.pskIdentities) == 0 {
264		return nil
265	}
266
267	for i, identity := range hs.clientHello.pskIdentities {
268		if i >= maxClientPSKIdentities {
269			break
270		}
271
272		plaintext, _ := c.decryptTicket(identity.label)
273		if plaintext == nil {
274			continue
275		}
276		sessionState := new(sessionStateTLS13)
277		if ok := sessionState.unmarshal(plaintext); !ok {
278			continue
279		}
280
281		if hs.clientHello.earlyData {
282			if sessionState.maxEarlyData == 0 {
283				c.sendAlert(alertUnsupportedExtension)
284				return errors.New("tls: client sent unexpected early data")
285			}
286
287			if hs.alpnNegotiationErr == nil && sessionState.alpn == c.clientProtocol &&
288				c.extraConfig != nil && c.extraConfig.MaxEarlyData > 0 &&
289				c.extraConfig.Accept0RTT != nil && c.extraConfig.Accept0RTT(sessionState.appData) {
290				hs.encryptedExtensions.earlyData = true
291				c.used0RTT = true
292			}
293		}
294
295		createdAt := time.Unix(int64(sessionState.createdAt), 0)
296		if c.config.time().Sub(createdAt) > maxSessionTicketLifetime {
297			continue
298		}
299
300		// We don't check the obfuscated ticket age because it's affected by
301		// clock skew and it's only a freshness signal useful for shrinking the
302		// window for replay attacks, which don't affect us as we don't do 0-RTT.
303
304		pskSuite := cipherSuiteTLS13ByID(sessionState.cipherSuite)
305		if pskSuite == nil || pskSuite.hash != hs.suite.hash {
306			continue
307		}
308
309		// PSK connections don't re-establish client certificates, but carry
310		// them over in the session ticket. Ensure the presence of client certs
311		// in the ticket is consistent with the configured requirements.
312		sessionHasClientCerts := len(sessionState.certificate.Certificate) != 0
313		needClientCerts := requiresClientCert(c.config.ClientAuth)
314		if needClientCerts && !sessionHasClientCerts {
315			continue
316		}
317		if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
318			continue
319		}
320
321		psk := hs.suite.expandLabel(sessionState.resumptionSecret, "resumption",
322			nil, hs.suite.hash.Size())
323		hs.earlySecret = hs.suite.extract(psk, nil)
324		binderKey := hs.suite.deriveSecret(hs.earlySecret, resumptionBinderLabel, nil)
325		// Clone the transcript in case a HelloRetryRequest was recorded.
326		transcript := cloneHash(hs.transcript, hs.suite.hash)
327		if transcript == nil {
328			c.sendAlert(alertInternalError)
329			return errors.New("tls: internal error: failed to clone hash")
330		}
331		transcript.Write(hs.clientHello.marshalWithoutBinders())
332		pskBinder := hs.suite.finishedHash(binderKey, transcript)
333		if !hmac.Equal(hs.clientHello.pskBinders[i], pskBinder) {
334			c.sendAlert(alertDecryptError)
335			return errors.New("tls: invalid PSK binder")
336		}
337
338		c.didResume = true
339		if err := c.processCertsFromClient(sessionState.certificate); err != nil {
340			return err
341		}
342
343		h := cloneHash(hs.transcript, hs.suite.hash)
344		h.Write(hs.clientHello.marshal())
345		if hs.encryptedExtensions.earlyData {
346			clientEarlySecret := hs.suite.deriveSecret(hs.earlySecret, "c e traffic", h)
347			c.in.exportKey(Encryption0RTT, hs.suite, clientEarlySecret)
348			if err := c.config.writeKeyLog(keyLogLabelEarlyTraffic, hs.clientHello.random, clientEarlySecret); err != nil {
349				c.sendAlert(alertInternalError)
350				return err
351			}
352		}
353
354		hs.hello.selectedIdentityPresent = true
355		hs.hello.selectedIdentity = uint16(i)
356		hs.usingPSK = true
357		return nil
358	}
359
360	return nil
361}
362
363// cloneHash uses the encoding.BinaryMarshaler and encoding.BinaryUnmarshaler
364// interfaces implemented by standard library hashes to clone the state of in
365// to a new instance of h. It returns nil if the operation fails.
366func cloneHash(in hash.Hash, h crypto.Hash) hash.Hash {
367	// Recreate the interface to avoid importing encoding.
368	type binaryMarshaler interface {
369		MarshalBinary() (data []byte, err error)
370		UnmarshalBinary(data []byte) error
371	}
372	marshaler, ok := in.(binaryMarshaler)
373	if !ok {
374		return nil
375	}
376	state, err := marshaler.MarshalBinary()
377	if err != nil {
378		return nil
379	}
380	out := h.New()
381	unmarshaler, ok := out.(binaryMarshaler)
382	if !ok {
383		return nil
384	}
385	if err := unmarshaler.UnmarshalBinary(state); err != nil {
386		return nil
387	}
388	return out
389}
390
391func (hs *serverHandshakeStateTLS13) pickCertificate() error {
392	c := hs.c
393
394	// Only one of PSK and certificates are used at a time.
395	if hs.usingPSK {
396		return nil
397	}
398
399	// signature_algorithms is required in TLS 1.3. See RFC 8446, Section 4.2.3.
400	if len(hs.clientHello.supportedSignatureAlgorithms) == 0 {
401		return c.sendAlert(alertMissingExtension)
402	}
403
404	certificate, err := c.config.getCertificate(newClientHelloInfo(hs.ctx, c, hs.clientHello))
405	if err != nil {
406		if err == errNoCertificates {
407			c.sendAlert(alertUnrecognizedName)
408		} else {
409			c.sendAlert(alertInternalError)
410		}
411		return err
412	}
413	hs.sigAlg, err = selectSignatureScheme(c.vers, certificate, hs.clientHello.supportedSignatureAlgorithms)
414	if err != nil {
415		// getCertificate returned a certificate that is unsupported or
416		// incompatible with the client's signature algorithms.
417		c.sendAlert(alertHandshakeFailure)
418		return err
419	}
420	hs.cert = certificate
421
422	return nil
423}
424
425// sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility
426// with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4.
427func (hs *serverHandshakeStateTLS13) sendDummyChangeCipherSpec() error {
428	if hs.sentDummyCCS {
429		return nil
430	}
431	hs.sentDummyCCS = true
432
433	_, err := hs.c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
434	return err
435}
436
437func (hs *serverHandshakeStateTLS13) doHelloRetryRequest(selectedGroup CurveID) error {
438	c := hs.c
439
440	// The first ClientHello gets double-hashed into the transcript upon a
441	// HelloRetryRequest. See RFC 8446, Section 4.4.1.
442	hs.transcript.Write(hs.clientHello.marshal())
443	chHash := hs.transcript.Sum(nil)
444	hs.transcript.Reset()
445	hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
446	hs.transcript.Write(chHash)
447
448	helloRetryRequest := &serverHelloMsg{
449		vers:              hs.hello.vers,
450		random:            helloRetryRequestRandom,
451		sessionId:         hs.hello.sessionId,
452		cipherSuite:       hs.hello.cipherSuite,
453		compressionMethod: hs.hello.compressionMethod,
454		supportedVersion:  hs.hello.supportedVersion,
455		selectedGroup:     selectedGroup,
456	}
457
458	hs.transcript.Write(helloRetryRequest.marshal())
459	if _, err := c.writeRecord(recordTypeHandshake, helloRetryRequest.marshal()); err != nil {
460		return err
461	}
462
463	if err := hs.sendDummyChangeCipherSpec(); err != nil {
464		return err
465	}
466
467	msg, err := c.readHandshake()
468	if err != nil {
469		return err
470	}
471
472	clientHello, ok := msg.(*clientHelloMsg)
473	if !ok {
474		c.sendAlert(alertUnexpectedMessage)
475		return unexpectedMessageError(clientHello, msg)
476	}
477
478	if len(clientHello.keyShares) != 1 || clientHello.keyShares[0].group != selectedGroup {
479		c.sendAlert(alertIllegalParameter)
480		return errors.New("tls: client sent invalid key share in second ClientHello")
481	}
482
483	if clientHello.earlyData {
484		c.sendAlert(alertIllegalParameter)
485		return errors.New("tls: client indicated early data in second ClientHello")
486	}
487
488	if illegalClientHelloChange(clientHello, hs.clientHello) {
489		c.sendAlert(alertIllegalParameter)
490		return errors.New("tls: client illegally modified second ClientHello")
491	}
492
493	if clientHello.earlyData {
494		c.sendAlert(alertIllegalParameter)
495		return errors.New("tls: client offered 0-RTT data in second ClientHello")
496	}
497
498	hs.clientHello = clientHello
499	return nil
500}
501
502// illegalClientHelloChange reports whether the two ClientHello messages are
503// different, with the exception of the changes allowed before and after a
504// HelloRetryRequest. See RFC 8446, Section 4.1.2.
505func illegalClientHelloChange(ch, ch1 *clientHelloMsg) bool {
506	if len(ch.supportedVersions) != len(ch1.supportedVersions) ||
507		len(ch.cipherSuites) != len(ch1.cipherSuites) ||
508		len(ch.supportedCurves) != len(ch1.supportedCurves) ||
509		len(ch.supportedSignatureAlgorithms) != len(ch1.supportedSignatureAlgorithms) ||
510		len(ch.supportedSignatureAlgorithmsCert) != len(ch1.supportedSignatureAlgorithmsCert) ||
511		len(ch.alpnProtocols) != len(ch1.alpnProtocols) {
512		return true
513	}
514	for i := range ch.supportedVersions {
515		if ch.supportedVersions[i] != ch1.supportedVersions[i] {
516			return true
517		}
518	}
519	for i := range ch.cipherSuites {
520		if ch.cipherSuites[i] != ch1.cipherSuites[i] {
521			return true
522		}
523	}
524	for i := range ch.supportedCurves {
525		if ch.supportedCurves[i] != ch1.supportedCurves[i] {
526			return true
527		}
528	}
529	for i := range ch.supportedSignatureAlgorithms {
530		if ch.supportedSignatureAlgorithms[i] != ch1.supportedSignatureAlgorithms[i] {
531			return true
532		}
533	}
534	for i := range ch.supportedSignatureAlgorithmsCert {
535		if ch.supportedSignatureAlgorithmsCert[i] != ch1.supportedSignatureAlgorithmsCert[i] {
536			return true
537		}
538	}
539	for i := range ch.alpnProtocols {
540		if ch.alpnProtocols[i] != ch1.alpnProtocols[i] {
541			return true
542		}
543	}
544	return ch.vers != ch1.vers ||
545		!bytes.Equal(ch.random, ch1.random) ||
546		!bytes.Equal(ch.sessionId, ch1.sessionId) ||
547		!bytes.Equal(ch.compressionMethods, ch1.compressionMethods) ||
548		ch.serverName != ch1.serverName ||
549		ch.ocspStapling != ch1.ocspStapling ||
550		!bytes.Equal(ch.supportedPoints, ch1.supportedPoints) ||
551		ch.ticketSupported != ch1.ticketSupported ||
552		!bytes.Equal(ch.sessionTicket, ch1.sessionTicket) ||
553		ch.secureRenegotiationSupported != ch1.secureRenegotiationSupported ||
554		!bytes.Equal(ch.secureRenegotiation, ch1.secureRenegotiation) ||
555		ch.scts != ch1.scts ||
556		!bytes.Equal(ch.cookie, ch1.cookie) ||
557		!bytes.Equal(ch.pskModes, ch1.pskModes)
558}
559
560func (hs *serverHandshakeStateTLS13) sendServerParameters() error {
561	c := hs.c
562
563	hs.transcript.Write(hs.clientHello.marshal())
564	hs.transcript.Write(hs.hello.marshal())
565	if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
566		return err
567	}
568
569	if err := hs.sendDummyChangeCipherSpec(); err != nil {
570		return err
571	}
572
573	earlySecret := hs.earlySecret
574	if earlySecret == nil {
575		earlySecret = hs.suite.extract(nil, nil)
576	}
577	hs.handshakeSecret = hs.suite.extract(hs.sharedKey,
578		hs.suite.deriveSecret(earlySecret, "derived", nil))
579
580	clientSecret := hs.suite.deriveSecret(hs.handshakeSecret,
581		clientHandshakeTrafficLabel, hs.transcript)
582	c.in.exportKey(EncryptionHandshake, hs.suite, clientSecret)
583	c.in.setTrafficSecret(hs.suite, clientSecret)
584	serverSecret := hs.suite.deriveSecret(hs.handshakeSecret,
585		serverHandshakeTrafficLabel, hs.transcript)
586	c.out.exportKey(EncryptionHandshake, hs.suite, serverSecret)
587	c.out.setTrafficSecret(hs.suite, serverSecret)
588
589	err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.clientHello.random, clientSecret)
590	if err != nil {
591		c.sendAlert(alertInternalError)
592		return err
593	}
594	err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.clientHello.random, serverSecret)
595	if err != nil {
596		c.sendAlert(alertInternalError)
597		return err
598	}
599
600	if hs.alpnNegotiationErr != nil {
601		c.sendAlert(alertNoApplicationProtocol)
602		return hs.alpnNegotiationErr
603	}
604	if hs.c.extraConfig != nil && hs.c.extraConfig.GetExtensions != nil {
605		hs.encryptedExtensions.additionalExtensions = hs.c.extraConfig.GetExtensions(typeEncryptedExtensions)
606	}
607
608	hs.transcript.Write(hs.encryptedExtensions.marshal())
609	if _, err := c.writeRecord(recordTypeHandshake, hs.encryptedExtensions.marshal()); err != nil {
610		return err
611	}
612
613	return nil
614}
615
616func (hs *serverHandshakeStateTLS13) requestClientCert() bool {
617	return hs.c.config.ClientAuth >= RequestClientCert && !hs.usingPSK
618}
619
620func (hs *serverHandshakeStateTLS13) sendServerCertificate() error {
621	c := hs.c
622
623	// Only one of PSK and certificates are used at a time.
624	if hs.usingPSK {
625		return nil
626	}
627
628	if hs.requestClientCert() {
629		// Request a client certificate
630		certReq := new(certificateRequestMsgTLS13)
631		certReq.ocspStapling = true
632		certReq.scts = true
633		certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms
634		if c.config.ClientCAs != nil {
635			certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
636		}
637
638		hs.transcript.Write(certReq.marshal())
639		if _, err := c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil {
640			return err
641		}
642	}
643
644	certMsg := new(certificateMsgTLS13)
645
646	certMsg.certificate = *hs.cert
647	certMsg.scts = hs.clientHello.scts && len(hs.cert.SignedCertificateTimestamps) > 0
648	certMsg.ocspStapling = hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0
649
650	hs.transcript.Write(certMsg.marshal())
651	if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
652		return err
653	}
654
655	certVerifyMsg := new(certificateVerifyMsg)
656	certVerifyMsg.hasSignatureAlgorithm = true
657	certVerifyMsg.signatureAlgorithm = hs.sigAlg
658
659	sigType, sigHash, err := typeAndHashFromSignatureScheme(hs.sigAlg)
660	if err != nil {
661		return c.sendAlert(alertInternalError)
662	}
663
664	signed := signedMessage(sigHash, serverSignatureContext, hs.transcript)
665	signOpts := crypto.SignerOpts(sigHash)
666	if sigType == signatureRSAPSS {
667		signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
668	}
669	sig, err := hs.cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts)
670	if err != nil {
671		public := hs.cert.PrivateKey.(crypto.Signer).Public()
672		if rsaKey, ok := public.(*rsa.PublicKey); ok && sigType == signatureRSAPSS &&
673			rsaKey.N.BitLen()/8 < sigHash.Size()*2+2 { // key too small for RSA-PSS
674			c.sendAlert(alertHandshakeFailure)
675		} else {
676			c.sendAlert(alertInternalError)
677		}
678		return errors.New("tls: failed to sign handshake: " + err.Error())
679	}
680	certVerifyMsg.signature = sig
681
682	hs.transcript.Write(certVerifyMsg.marshal())
683	if _, err := c.writeRecord(recordTypeHandshake, certVerifyMsg.marshal()); err != nil {
684		return err
685	}
686
687	return nil
688}
689
690func (hs *serverHandshakeStateTLS13) sendServerFinished() error {
691	c := hs.c
692
693	finished := &finishedMsg{
694		verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
695	}
696
697	hs.transcript.Write(finished.marshal())
698	if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
699		return err
700	}
701
702	// Derive secrets that take context through the server Finished.
703
704	hs.masterSecret = hs.suite.extract(nil,
705		hs.suite.deriveSecret(hs.handshakeSecret, "derived", nil))
706
707	hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret,
708		clientApplicationTrafficLabel, hs.transcript)
709	serverSecret := hs.suite.deriveSecret(hs.masterSecret,
710		serverApplicationTrafficLabel, hs.transcript)
711	c.out.exportKey(EncryptionApplication, hs.suite, serverSecret)
712	c.out.setTrafficSecret(hs.suite, serverSecret)
713
714	err := c.config.writeKeyLog(keyLogLabelClientTraffic, hs.clientHello.random, hs.trafficSecret)
715	if err != nil {
716		c.sendAlert(alertInternalError)
717		return err
718	}
719	err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.clientHello.random, serverSecret)
720	if err != nil {
721		c.sendAlert(alertInternalError)
722		return err
723	}
724
725	c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript)
726
727	// If we did not request client certificates, at this point we can
728	// precompute the client finished and roll the transcript forward to send
729	// session tickets in our first flight.
730	if !hs.requestClientCert() {
731		if err := hs.sendSessionTickets(); err != nil {
732			return err
733		}
734	}
735
736	return nil
737}
738
739func (hs *serverHandshakeStateTLS13) shouldSendSessionTickets() bool {
740	if hs.c.config.SessionTicketsDisabled {
741		return false
742	}
743
744	// Don't send tickets the client wouldn't use. See RFC 8446, Section 4.2.9.
745	for _, pskMode := range hs.clientHello.pskModes {
746		if pskMode == pskModeDHE {
747			return true
748		}
749	}
750	return false
751}
752
753func (hs *serverHandshakeStateTLS13) sendSessionTickets() error {
754	c := hs.c
755
756	hs.clientFinished = hs.suite.finishedHash(c.in.trafficSecret, hs.transcript)
757	finishedMsg := &finishedMsg{
758		verifyData: hs.clientFinished,
759	}
760	hs.transcript.Write(finishedMsg.marshal())
761
762	if !hs.shouldSendSessionTickets() {
763		return nil
764	}
765
766	c.resumptionSecret = hs.suite.deriveSecret(hs.masterSecret,
767		resumptionLabel, hs.transcript)
768
769	// Don't send session tickets when the alternative record layer is set.
770	// Instead, save the resumption secret on the Conn.
771	// Session tickets can then be generated by calling Conn.GetSessionTicket().
772	if hs.c.extraConfig != nil && hs.c.extraConfig.AlternativeRecordLayer != nil {
773		return nil
774	}
775
776	m, err := hs.c.getSessionTicketMsg(nil)
777	if err != nil {
778		return err
779	}
780	if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
781		return err
782	}
783
784	return nil
785}
786
787func (hs *serverHandshakeStateTLS13) readClientCertificate() error {
788	c := hs.c
789
790	if !hs.requestClientCert() {
791		// Make sure the connection is still being verified whether or not
792		// the server requested a client certificate.
793		if c.config.VerifyConnection != nil {
794			if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
795				c.sendAlert(alertBadCertificate)
796				return err
797			}
798		}
799		return nil
800	}
801
802	// If we requested a client certificate, then the client must send a
803	// certificate message. If it's empty, no CertificateVerify is sent.
804
805	msg, err := c.readHandshake()
806	if err != nil {
807		return err
808	}
809
810	certMsg, ok := msg.(*certificateMsgTLS13)
811	if !ok {
812		c.sendAlert(alertUnexpectedMessage)
813		return unexpectedMessageError(certMsg, msg)
814	}
815	hs.transcript.Write(certMsg.marshal())
816
817	if err := c.processCertsFromClient(certMsg.certificate); err != nil {
818		return err
819	}
820
821	if c.config.VerifyConnection != nil {
822		if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
823			c.sendAlert(alertBadCertificate)
824			return err
825		}
826	}
827
828	if len(certMsg.certificate.Certificate) != 0 {
829		msg, err = c.readHandshake()
830		if err != nil {
831			return err
832		}
833
834		certVerify, ok := msg.(*certificateVerifyMsg)
835		if !ok {
836			c.sendAlert(alertUnexpectedMessage)
837			return unexpectedMessageError(certVerify, msg)
838		}
839
840		// See RFC 8446, Section 4.4.3.
841		if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms) {
842			c.sendAlert(alertIllegalParameter)
843			return errors.New("tls: client certificate used with invalid signature algorithm")
844		}
845		sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
846		if err != nil {
847			return c.sendAlert(alertInternalError)
848		}
849		if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
850			c.sendAlert(alertIllegalParameter)
851			return errors.New("tls: client certificate used with invalid signature algorithm")
852		}
853		signed := signedMessage(sigHash, clientSignatureContext, hs.transcript)
854		if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey,
855			sigHash, signed, certVerify.signature); err != nil {
856			c.sendAlert(alertDecryptError)
857			return errors.New("tls: invalid signature by the client certificate: " + err.Error())
858		}
859
860		hs.transcript.Write(certVerify.marshal())
861	}
862
863	// If we waited until the client certificates to send session tickets, we
864	// are ready to do it now.
865	if err := hs.sendSessionTickets(); err != nil {
866		return err
867	}
868
869	return nil
870}
871
872func (hs *serverHandshakeStateTLS13) readClientFinished() error {
873	c := hs.c
874
875	msg, err := c.readHandshake()
876	if err != nil {
877		return err
878	}
879
880	finished, ok := msg.(*finishedMsg)
881	if !ok {
882		c.sendAlert(alertUnexpectedMessage)
883		return unexpectedMessageError(finished, msg)
884	}
885
886	if !hmac.Equal(hs.clientFinished, finished.verifyData) {
887		c.sendAlert(alertDecryptError)
888		return errors.New("tls: invalid client finished hash")
889	}
890
891	c.in.exportKey(EncryptionApplication, hs.suite, hs.trafficSecret)
892	c.in.setTrafficSecret(hs.suite, hs.trafficSecret)
893
894	return nil
895}
896