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