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