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