]> Cypherpunks.ru repositories - gostls13.git/blob - src/crypto/tls/handshake_server_tls13.go
6753ad4aee05928ba073ed26c05b18ca10495e9d
[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         "encoding/binary"
14         "errors"
15         "hash"
16         "io"
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         c.isHandshakeComplete.Store(true)
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(roleServer) {
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); !ok {
209                 c.sendAlert(alertInternalError)
210                 return errors.New("tls: CurvePreferences includes unsupported curve")
211         }
212         key, err := generateECDHEKey(c.config.rand(), selectedGroup)
213         if err != nil {
214                 c.sendAlert(alertInternalError)
215                 return err
216         }
217         hs.hello.serverShare = keyShare{group: selectedGroup, data: key.PublicKey().Bytes()}
218         peerKey, err := key.Curve().NewPublicKey(clientKeyShare.data)
219         if err != nil {
220                 c.sendAlert(alertIllegalParameter)
221                 return errors.New("tls: invalid client key share")
222         }
223         hs.sharedKey, err = key.ECDH(peerKey)
224         if err != nil {
225                 c.sendAlert(alertIllegalParameter)
226                 return errors.New("tls: invalid client key share")
227         }
228
229         if c.quic != nil {
230                 if hs.clientHello.quicTransportParameters == nil {
231                         // RFC 9001 Section 8.2.
232                         c.sendAlert(alertMissingExtension)
233                         return errors.New("tls: client did not send a quic_transport_parameters extension")
234                 }
235                 c.quicSetTransportParameters(hs.clientHello.quicTransportParameters)
236         } else {
237                 if hs.clientHello.quicTransportParameters != nil {
238                         c.sendAlert(alertUnsupportedExtension)
239                         return errors.New("tls: client sent an unexpected quic_transport_parameters extension")
240                 }
241         }
242
243         c.serverName = hs.clientHello.serverName
244         return nil
245 }
246
247 func (hs *serverHandshakeStateTLS13) checkForResumption() error {
248         c := hs.c
249
250         if c.config.SessionTicketsDisabled {
251                 return nil
252         }
253
254         modeOK := false
255         for _, mode := range hs.clientHello.pskModes {
256                 if mode == pskModeDHE {
257                         modeOK = true
258                         break
259                 }
260         }
261         if !modeOK {
262                 return nil
263         }
264
265         if len(hs.clientHello.pskIdentities) != len(hs.clientHello.pskBinders) {
266                 c.sendAlert(alertIllegalParameter)
267                 return errors.New("tls: invalid or missing PSK binders")
268         }
269         if len(hs.clientHello.pskIdentities) == 0 {
270                 return nil
271         }
272
273         for i, identity := range hs.clientHello.pskIdentities {
274                 if i >= maxClientPSKIdentities {
275                         break
276                 }
277
278                 plaintext := c.decryptTicket(identity.label)
279                 if plaintext == nil {
280                         continue
281                 }
282                 sessionState, err := ParseSessionState(plaintext)
283                 if err != nil || sessionState.version != VersionTLS13 {
284                         continue
285                 }
286
287                 createdAt := time.Unix(int64(sessionState.createdAt), 0)
288                 if c.config.time().Sub(createdAt) > maxSessionTicketLifetime {
289                         continue
290                 }
291
292                 // We don't check the obfuscated ticket age because it's affected by
293                 // clock skew and it's only a freshness signal useful for shrinking the
294                 // window for replay attacks, which don't affect us as we don't do 0-RTT.
295
296                 pskSuite := cipherSuiteTLS13ByID(sessionState.cipherSuite)
297                 if pskSuite == nil || pskSuite.hash != hs.suite.hash {
298                         continue
299                 }
300
301                 // PSK connections don't re-establish client certificates, but carry
302                 // them over in the session ticket. Ensure the presence of client certs
303                 // in the ticket is consistent with the configured requirements.
304                 sessionHasClientCerts := len(sessionState.peerCertificates) != 0
305                 needClientCerts := requiresClientCert(c.config.ClientAuth)
306                 if needClientCerts && !sessionHasClientCerts {
307                         continue
308                 }
309                 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
310                         continue
311                 }
312
313                 hs.earlySecret = hs.suite.extract(sessionState.secret, nil)
314                 binderKey := hs.suite.deriveSecret(hs.earlySecret, resumptionBinderLabel, nil)
315                 // Clone the transcript in case a HelloRetryRequest was recorded.
316                 transcript := cloneHash(hs.transcript, hs.suite.hash)
317                 if transcript == nil {
318                         c.sendAlert(alertInternalError)
319                         return errors.New("tls: internal error: failed to clone hash")
320                 }
321                 clientHelloBytes, err := hs.clientHello.marshalWithoutBinders()
322                 if err != nil {
323                         c.sendAlert(alertInternalError)
324                         return err
325                 }
326                 transcript.Write(clientHelloBytes)
327                 pskBinder := hs.suite.finishedHash(binderKey, transcript)
328                 if !hmac.Equal(hs.clientHello.pskBinders[i], pskBinder) {
329                         c.sendAlert(alertDecryptError)
330                         return errors.New("tls: invalid PSK binder")
331                 }
332
333                 c.didResume = true
334                 if err := c.processCertsFromClient(sessionState.certificate()); err != nil {
335                         return err
336                 }
337
338                 hs.hello.selectedIdentityPresent = true
339                 hs.hello.selectedIdentity = uint16(i)
340                 hs.usingPSK = true
341                 return nil
342         }
343
344         return nil
345 }
346
347 // cloneHash uses the encoding.BinaryMarshaler and encoding.BinaryUnmarshaler
348 // interfaces implemented by standard library hashes to clone the state of in
349 // to a new instance of h. It returns nil if the operation fails.
350 func cloneHash(in hash.Hash, h crypto.Hash) hash.Hash {
351         // Recreate the interface to avoid importing encoding.
352         type binaryMarshaler interface {
353                 MarshalBinary() (data []byte, err error)
354                 UnmarshalBinary(data []byte) error
355         }
356         marshaler, ok := in.(binaryMarshaler)
357         if !ok {
358                 return nil
359         }
360         state, err := marshaler.MarshalBinary()
361         if err != nil {
362                 return nil
363         }
364         out := h.New()
365         unmarshaler, ok := out.(binaryMarshaler)
366         if !ok {
367                 return nil
368         }
369         if err := unmarshaler.UnmarshalBinary(state); err != nil {
370                 return nil
371         }
372         return out
373 }
374
375 func (hs *serverHandshakeStateTLS13) pickCertificate() error {
376         c := hs.c
377
378         // Only one of PSK and certificates are used at a time.
379         if hs.usingPSK {
380                 return nil
381         }
382
383         // signature_algorithms is required in TLS 1.3. See RFC 8446, Section 4.2.3.
384         if len(hs.clientHello.supportedSignatureAlgorithms) == 0 {
385                 return c.sendAlert(alertMissingExtension)
386         }
387
388         certificate, err := c.config.getCertificate(clientHelloInfo(hs.ctx, c, hs.clientHello))
389         if err != nil {
390                 if err == errNoCertificates {
391                         c.sendAlert(alertUnrecognizedName)
392                 } else {
393                         c.sendAlert(alertInternalError)
394                 }
395                 return err
396         }
397         hs.sigAlg, err = selectSignatureScheme(c.vers, certificate, hs.clientHello.supportedSignatureAlgorithms)
398         if err != nil {
399                 // getCertificate returned a certificate that is unsupported or
400                 // incompatible with the client's signature algorithms.
401                 c.sendAlert(alertHandshakeFailure)
402                 return err
403         }
404         hs.cert = certificate
405
406         return nil
407 }
408
409 // sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility
410 // with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4.
411 func (hs *serverHandshakeStateTLS13) sendDummyChangeCipherSpec() error {
412         if hs.c.quic != nil {
413                 return nil
414         }
415         if hs.sentDummyCCS {
416                 return nil
417         }
418         hs.sentDummyCCS = true
419
420         return hs.c.writeChangeCipherRecord()
421 }
422
423 func (hs *serverHandshakeStateTLS13) doHelloRetryRequest(selectedGroup CurveID) error {
424         c := hs.c
425
426         // The first ClientHello gets double-hashed into the transcript upon a
427         // HelloRetryRequest. See RFC 8446, Section 4.4.1.
428         if err := transcriptMsg(hs.clientHello, hs.transcript); err != nil {
429                 return err
430         }
431         chHash := hs.transcript.Sum(nil)
432         hs.transcript.Reset()
433         hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
434         hs.transcript.Write(chHash)
435
436         helloRetryRequest := &serverHelloMsg{
437                 vers:              hs.hello.vers,
438                 random:            helloRetryRequestRandom,
439                 sessionId:         hs.hello.sessionId,
440                 cipherSuite:       hs.hello.cipherSuite,
441                 compressionMethod: hs.hello.compressionMethod,
442                 supportedVersion:  hs.hello.supportedVersion,
443                 selectedGroup:     selectedGroup,
444         }
445
446         if _, err := hs.c.writeHandshakeRecord(helloRetryRequest, hs.transcript); err != nil {
447                 return err
448         }
449
450         if err := hs.sendDummyChangeCipherSpec(); err != nil {
451                 return err
452         }
453
454         // clientHelloMsg is not included in the transcript.
455         msg, err := c.readHandshake(nil)
456         if err != nil {
457                 return err
458         }
459
460         clientHello, ok := msg.(*clientHelloMsg)
461         if !ok {
462                 c.sendAlert(alertUnexpectedMessage)
463                 return unexpectedMessageError(clientHello, msg)
464         }
465
466         if len(clientHello.keyShares) != 1 || clientHello.keyShares[0].group != selectedGroup {
467                 c.sendAlert(alertIllegalParameter)
468                 return errors.New("tls: client sent invalid key share in second ClientHello")
469         }
470
471         if clientHello.earlyData {
472                 c.sendAlert(alertIllegalParameter)
473                 return errors.New("tls: client indicated early data in second ClientHello")
474         }
475
476         if illegalClientHelloChange(clientHello, hs.clientHello) {
477                 c.sendAlert(alertIllegalParameter)
478                 return errors.New("tls: client illegally modified second ClientHello")
479         }
480
481         hs.clientHello = clientHello
482         return nil
483 }
484
485 // illegalClientHelloChange reports whether the two ClientHello messages are
486 // different, with the exception of the changes allowed before and after a
487 // HelloRetryRequest. See RFC 8446, Section 4.1.2.
488 func illegalClientHelloChange(ch, ch1 *clientHelloMsg) bool {
489         if len(ch.supportedVersions) != len(ch1.supportedVersions) ||
490                 len(ch.cipherSuites) != len(ch1.cipherSuites) ||
491                 len(ch.supportedCurves) != len(ch1.supportedCurves) ||
492                 len(ch.supportedSignatureAlgorithms) != len(ch1.supportedSignatureAlgorithms) ||
493                 len(ch.supportedSignatureAlgorithmsCert) != len(ch1.supportedSignatureAlgorithmsCert) ||
494                 len(ch.alpnProtocols) != len(ch1.alpnProtocols) {
495                 return true
496         }
497         for i := range ch.supportedVersions {
498                 if ch.supportedVersions[i] != ch1.supportedVersions[i] {
499                         return true
500                 }
501         }
502         for i := range ch.cipherSuites {
503                 if ch.cipherSuites[i] != ch1.cipherSuites[i] {
504                         return true
505                 }
506         }
507         for i := range ch.supportedCurves {
508                 if ch.supportedCurves[i] != ch1.supportedCurves[i] {
509                         return true
510                 }
511         }
512         for i := range ch.supportedSignatureAlgorithms {
513                 if ch.supportedSignatureAlgorithms[i] != ch1.supportedSignatureAlgorithms[i] {
514                         return true
515                 }
516         }
517         for i := range ch.supportedSignatureAlgorithmsCert {
518                 if ch.supportedSignatureAlgorithmsCert[i] != ch1.supportedSignatureAlgorithmsCert[i] {
519                         return true
520                 }
521         }
522         for i := range ch.alpnProtocols {
523                 if ch.alpnProtocols[i] != ch1.alpnProtocols[i] {
524                         return true
525                 }
526         }
527         return ch.vers != ch1.vers ||
528                 !bytes.Equal(ch.random, ch1.random) ||
529                 !bytes.Equal(ch.sessionId, ch1.sessionId) ||
530                 !bytes.Equal(ch.compressionMethods, ch1.compressionMethods) ||
531                 ch.serverName != ch1.serverName ||
532                 ch.ocspStapling != ch1.ocspStapling ||
533                 !bytes.Equal(ch.supportedPoints, ch1.supportedPoints) ||
534                 ch.ticketSupported != ch1.ticketSupported ||
535                 !bytes.Equal(ch.sessionTicket, ch1.sessionTicket) ||
536                 ch.secureRenegotiationSupported != ch1.secureRenegotiationSupported ||
537                 !bytes.Equal(ch.secureRenegotiation, ch1.secureRenegotiation) ||
538                 ch.scts != ch1.scts ||
539                 !bytes.Equal(ch.cookie, ch1.cookie) ||
540                 !bytes.Equal(ch.pskModes, ch1.pskModes)
541 }
542
543 func (hs *serverHandshakeStateTLS13) sendServerParameters() error {
544         c := hs.c
545
546         if err := transcriptMsg(hs.clientHello, hs.transcript); err != nil {
547                 return err
548         }
549         if _, err := hs.c.writeHandshakeRecord(hs.hello, hs.transcript); err != nil {
550                 return err
551         }
552
553         if err := hs.sendDummyChangeCipherSpec(); err != nil {
554                 return err
555         }
556
557         earlySecret := hs.earlySecret
558         if earlySecret == nil {
559                 earlySecret = hs.suite.extract(nil, nil)
560         }
561         hs.handshakeSecret = hs.suite.extract(hs.sharedKey,
562                 hs.suite.deriveSecret(earlySecret, "derived", nil))
563
564         clientSecret := hs.suite.deriveSecret(hs.handshakeSecret,
565                 clientHandshakeTrafficLabel, hs.transcript)
566         c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, clientSecret)
567         serverSecret := hs.suite.deriveSecret(hs.handshakeSecret,
568                 serverHandshakeTrafficLabel, hs.transcript)
569         c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, serverSecret)
570
571         if c.quic != nil {
572                 if c.hand.Len() != 0 {
573                         c.sendAlert(alertUnexpectedMessage)
574                 }
575                 c.quicSetWriteSecret(QUICEncryptionLevelHandshake, hs.suite.id, serverSecret)
576                 c.quicSetReadSecret(QUICEncryptionLevelHandshake, hs.suite.id, clientSecret)
577         }
578
579         err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.clientHello.random, clientSecret)
580         if err != nil {
581                 c.sendAlert(alertInternalError)
582                 return err
583         }
584         err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.clientHello.random, serverSecret)
585         if err != nil {
586                 c.sendAlert(alertInternalError)
587                 return err
588         }
589
590         encryptedExtensions := new(encryptedExtensionsMsg)
591
592         selectedProto, err := negotiateALPN(c.config.NextProtos, hs.clientHello.alpnProtocols, c.quic != nil)
593         if err != nil {
594                 c.sendAlert(alertNoApplicationProtocol)
595                 return err
596         }
597         encryptedExtensions.alpnProtocol = selectedProto
598         c.clientProtocol = selectedProto
599
600         if c.quic != nil {
601                 p, err := c.quicGetTransportParameters()
602                 if err != nil {
603                         return err
604                 }
605                 encryptedExtensions.quicTransportParameters = p
606         }
607
608         if _, err := hs.c.writeHandshakeRecord(encryptedExtensions, hs.transcript); err != nil {
609                 return err
610         }
611
612         return nil
613 }
614
615 func (hs *serverHandshakeStateTLS13) requestClientCert() bool {
616         return hs.c.config.ClientAuth >= RequestClientCert && !hs.usingPSK
617 }
618
619 func (hs *serverHandshakeStateTLS13) sendServerCertificate() error {
620         c := hs.c
621
622         // Only one of PSK and certificates are used at a time.
623         if hs.usingPSK {
624                 return nil
625         }
626
627         if hs.requestClientCert() {
628                 // Request a client certificate
629                 certReq := new(certificateRequestMsgTLS13)
630                 certReq.ocspStapling = true
631                 certReq.scts = true
632                 certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms()
633                 if c.config.ClientCAs != nil {
634                         certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
635                 }
636
637                 if _, err := hs.c.writeHandshakeRecord(certReq, hs.transcript); err != nil {
638                         return err
639                 }
640         }
641
642         certMsg := new(certificateMsgTLS13)
643
644         certMsg.certificate = *hs.cert
645         certMsg.scts = hs.clientHello.scts && len(hs.cert.SignedCertificateTimestamps) > 0
646         certMsg.ocspStapling = hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0
647
648         if _, err := hs.c.writeHandshakeRecord(certMsg, hs.transcript); err != nil {
649                 return err
650         }
651
652         certVerifyMsg := new(certificateVerifyMsg)
653         certVerifyMsg.hasSignatureAlgorithm = true
654         certVerifyMsg.signatureAlgorithm = hs.sigAlg
655
656         sigType, sigHash, err := typeAndHashFromSignatureScheme(hs.sigAlg)
657         if err != nil {
658                 return c.sendAlert(alertInternalError)
659         }
660
661         signed := signedMessage(sigHash, serverSignatureContext, hs.transcript)
662         signOpts := crypto.SignerOpts(sigHash)
663         if sigType == signatureRSAPSS {
664                 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
665         }
666         sig, err := hs.cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts)
667         if err != nil {
668                 public := hs.cert.PrivateKey.(crypto.Signer).Public()
669                 if rsaKey, ok := public.(*rsa.PublicKey); ok && sigType == signatureRSAPSS &&
670                         rsaKey.N.BitLen()/8 < sigHash.Size()*2+2 { // key too small for RSA-PSS
671                         c.sendAlert(alertHandshakeFailure)
672                 } else {
673                         c.sendAlert(alertInternalError)
674                 }
675                 return errors.New("tls: failed to sign handshake: " + err.Error())
676         }
677         certVerifyMsg.signature = sig
678
679         if _, err := hs.c.writeHandshakeRecord(certVerifyMsg, hs.transcript); err != nil {
680                 return err
681         }
682
683         return nil
684 }
685
686 func (hs *serverHandshakeStateTLS13) sendServerFinished() error {
687         c := hs.c
688
689         finished := &finishedMsg{
690                 verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
691         }
692
693         if _, err := hs.c.writeHandshakeRecord(finished, hs.transcript); err != nil {
694                 return err
695         }
696
697         // Derive secrets that take context through the server Finished.
698
699         hs.masterSecret = hs.suite.extract(nil,
700                 hs.suite.deriveSecret(hs.handshakeSecret, "derived", nil))
701
702         hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret,
703                 clientApplicationTrafficLabel, hs.transcript)
704         serverSecret := hs.suite.deriveSecret(hs.masterSecret,
705                 serverApplicationTrafficLabel, hs.transcript)
706         c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, serverSecret)
707
708         if c.quic != nil {
709                 if c.hand.Len() != 0 {
710                         // TODO: Handle this in setTrafficSecret?
711                         c.sendAlert(alertUnexpectedMessage)
712                 }
713                 c.quicSetWriteSecret(QUICEncryptionLevelApplication, hs.suite.id, serverSecret)
714         }
715
716         err := c.config.writeKeyLog(keyLogLabelClientTraffic, hs.clientHello.random, hs.trafficSecret)
717         if err != nil {
718                 c.sendAlert(alertInternalError)
719                 return err
720         }
721         err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.clientHello.random, serverSecret)
722         if err != nil {
723                 c.sendAlert(alertInternalError)
724                 return err
725         }
726
727         c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript)
728
729         // If we did not request client certificates, at this point we can
730         // precompute the client finished and roll the transcript forward to send
731         // session tickets in our first flight.
732         if !hs.requestClientCert() {
733                 if err := hs.sendSessionTickets(); err != nil {
734                         return err
735                 }
736         }
737
738         return nil
739 }
740
741 func (hs *serverHandshakeStateTLS13) shouldSendSessionTickets() bool {
742         if hs.c.config.SessionTicketsDisabled {
743                 return false
744         }
745
746         // Don't send tickets the client wouldn't use. See RFC 8446, Section 4.2.9.
747         for _, pskMode := range hs.clientHello.pskModes {
748                 if pskMode == pskModeDHE {
749                         return true
750                 }
751         }
752         return false
753 }
754
755 func (hs *serverHandshakeStateTLS13) sendSessionTickets() error {
756         c := hs.c
757
758         hs.clientFinished = hs.suite.finishedHash(c.in.trafficSecret, hs.transcript)
759         finishedMsg := &finishedMsg{
760                 verifyData: hs.clientFinished,
761         }
762         if err := transcriptMsg(finishedMsg, hs.transcript); err != nil {
763                 return err
764         }
765
766         if !hs.shouldSendSessionTickets() {
767                 return nil
768         }
769
770         resumptionSecret := hs.suite.deriveSecret(hs.masterSecret,
771                 resumptionLabel, hs.transcript)
772         // ticket_nonce, which must be unique per connection, is always left at
773         // zero because we only ever send one ticket per connection.
774         psk := hs.suite.expandLabel(resumptionSecret, "resumption",
775                 nil, hs.suite.hash.Size())
776
777         m := new(newSessionTicketMsgTLS13)
778
779         state, err := c.sessionState()
780         if err != nil {
781                 return err
782         }
783         state.secret = psk
784         stateBytes, err := state.Bytes()
785         if err != nil {
786                 c.sendAlert(alertInternalError)
787                 return err
788         }
789         m.label, err = c.encryptTicket(stateBytes)
790         if err != nil {
791                 return err
792         }
793         m.lifetime = uint32(maxSessionTicketLifetime / time.Second)
794
795         // ticket_age_add is a random 32-bit value. See RFC 8446, section 4.6.1
796         // The value is not stored anywhere; we never need to check the ticket age
797         // because 0-RTT is not supported.
798         ageAdd := make([]byte, 4)
799         _, err = hs.c.config.rand().Read(ageAdd)
800         if err != nil {
801                 return err
802         }
803         m.ageAdd = binary.LittleEndian.Uint32(ageAdd)
804
805         if _, err := c.writeHandshakeRecord(m, nil); err != nil {
806                 return err
807         }
808
809         return nil
810 }
811
812 func (hs *serverHandshakeStateTLS13) readClientCertificate() error {
813         c := hs.c
814
815         if !hs.requestClientCert() {
816                 // Make sure the connection is still being verified whether or not
817                 // the server requested a client certificate.
818                 if c.config.VerifyConnection != nil {
819                         if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
820                                 c.sendAlert(alertBadCertificate)
821                                 return err
822                         }
823                 }
824                 return nil
825         }
826
827         // If we requested a client certificate, then the client must send a
828         // certificate message. If it's empty, no CertificateVerify is sent.
829
830         msg, err := c.readHandshake(hs.transcript)
831         if err != nil {
832                 return err
833         }
834
835         certMsg, ok := msg.(*certificateMsgTLS13)
836         if !ok {
837                 c.sendAlert(alertUnexpectedMessage)
838                 return unexpectedMessageError(certMsg, msg)
839         }
840
841         if err := c.processCertsFromClient(certMsg.certificate); err != nil {
842                 return err
843         }
844
845         if c.config.VerifyConnection != nil {
846                 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
847                         c.sendAlert(alertBadCertificate)
848                         return err
849                 }
850         }
851
852         if len(certMsg.certificate.Certificate) != 0 {
853                 // certificateVerifyMsg is included in the transcript, but not until
854                 // after we verify the handshake signature, since the state before
855                 // this message was sent is used.
856                 msg, err = c.readHandshake(nil)
857                 if err != nil {
858                         return err
859                 }
860
861                 certVerify, ok := msg.(*certificateVerifyMsg)
862                 if !ok {
863                         c.sendAlert(alertUnexpectedMessage)
864                         return unexpectedMessageError(certVerify, msg)
865                 }
866
867                 // See RFC 8446, Section 4.4.3.
868                 if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms()) {
869                         c.sendAlert(alertIllegalParameter)
870                         return errors.New("tls: client certificate used with invalid signature algorithm")
871                 }
872                 sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
873                 if err != nil {
874                         return c.sendAlert(alertInternalError)
875                 }
876                 if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
877                         c.sendAlert(alertIllegalParameter)
878                         return errors.New("tls: client certificate used with invalid signature algorithm")
879                 }
880                 signed := signedMessage(sigHash, clientSignatureContext, hs.transcript)
881                 if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey,
882                         sigHash, signed, certVerify.signature); err != nil {
883                         c.sendAlert(alertDecryptError)
884                         return errors.New("tls: invalid signature by the client certificate: " + err.Error())
885                 }
886
887                 if err := transcriptMsg(certVerify, hs.transcript); err != nil {
888                         return err
889                 }
890         }
891
892         // If we waited until the client certificates to send session tickets, we
893         // are ready to do it now.
894         if err := hs.sendSessionTickets(); err != nil {
895                 return err
896         }
897
898         return nil
899 }
900
901 func (hs *serverHandshakeStateTLS13) readClientFinished() error {
902         c := hs.c
903
904         // finishedMsg is not included in the transcript.
905         msg, err := c.readHandshake(nil)
906         if err != nil {
907                 return err
908         }
909
910         finished, ok := msg.(*finishedMsg)
911         if !ok {
912                 c.sendAlert(alertUnexpectedMessage)
913                 return unexpectedMessageError(finished, msg)
914         }
915
916         if !hmac.Equal(hs.clientFinished, finished.verifyData) {
917                 c.sendAlert(alertDecryptError)
918                 return errors.New("tls: invalid client finished hash")
919         }
920
921         c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, hs.trafficSecret)
922
923         return nil
924 }