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