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