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