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