Source file
src/crypto/tls/handshake_server_tls13.go
1
2
3
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
21
22
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
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
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
73
74
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
96
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
106
107
108
109
110
111
112
113
114 for _, id := range hs.clientHello.cipherSuites {
115 if id == TLS_FALLBACK_SCSV {
116
117
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
150
151
152
153
154
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
181
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
244 for _, v := range hs.clientHello.supportedVersions {
245 if v < VersionTLS13 {
246 c.sendAlert(alertProtocolVersion)
247 return errors.New("tls: client offered TLS version older than TLS 1.3")
248 }
249 }
250
251 if hs.clientHello.quicTransportParameters == nil {
252 c.sendAlert(alertMissingExtension)
253 return errors.New("tls: client did not send a quic_transport_parameters extension")
254 }
255 c.quicSetTransportParameters(hs.clientHello.quicTransportParameters)
256 } else {
257 if hs.clientHello.quicTransportParameters != nil {
258 c.sendAlert(alertUnsupportedExtension)
259 return errors.New("tls: client sent an unexpected quic_transport_parameters extension")
260 }
261 }
262
263 c.serverName = hs.clientHello.serverName
264 return nil
265 }
266
267 func (hs *serverHandshakeStateTLS13) checkForResumption() error {
268 c := hs.c
269
270 if c.config.SessionTicketsDisabled {
271 return nil
272 }
273
274 modeOK := false
275 for _, mode := range hs.clientHello.pskModes {
276 if mode == pskModeDHE {
277 modeOK = true
278 break
279 }
280 }
281 if !modeOK {
282 return nil
283 }
284
285 if len(hs.clientHello.pskIdentities) != len(hs.clientHello.pskBinders) {
286 c.sendAlert(alertIllegalParameter)
287 return errors.New("tls: invalid or missing PSK binders")
288 }
289 if len(hs.clientHello.pskIdentities) == 0 {
290 return nil
291 }
292
293 for i, identity := range hs.clientHello.pskIdentities {
294 if i >= maxClientPSKIdentities {
295 break
296 }
297
298 var sessionState *SessionState
299 if c.config.UnwrapSession != nil {
300 var err error
301 sessionState, err = c.config.UnwrapSession(identity.label, c.connectionStateLocked())
302 if err != nil {
303 return err
304 }
305 if sessionState == nil {
306 continue
307 }
308 } else {
309 plaintext := c.config.decryptTicket(identity.label, c.ticketKeys)
310 if plaintext == nil {
311 continue
312 }
313 var err error
314 sessionState, err = ParseSessionState(plaintext)
315 if err != nil {
316 continue
317 }
318 }
319
320 if sessionState.version != VersionTLS13 {
321 continue
322 }
323
324 createdAt := time.Unix(int64(sessionState.createdAt), 0)
325 if c.config.time().Sub(createdAt) > maxSessionTicketLifetime {
326 continue
327 }
328
329 pskSuite := cipherSuiteTLS13ByID(sessionState.cipherSuite)
330 if pskSuite == nil || pskSuite.hash != hs.suite.hash {
331 continue
332 }
333
334
335
336
337 sessionHasClientCerts := len(sessionState.peerCertificates) != 0
338 needClientCerts := requiresClientCert(c.config.ClientAuth)
339 if needClientCerts && !sessionHasClientCerts {
340 continue
341 }
342 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
343 continue
344 }
345 if sessionHasClientCerts && c.config.time().After(sessionState.peerCertificates[0].NotAfter) {
346 continue
347 }
348 if sessionHasClientCerts && c.config.ClientAuth >= VerifyClientCertIfGiven &&
349 len(sessionState.verifiedChains) == 0 {
350 continue
351 }
352
353 hs.earlySecret = hs.suite.extract(sessionState.secret, nil)
354 binderKey := hs.suite.deriveSecret(hs.earlySecret, resumptionBinderLabel, nil)
355
356 transcript := cloneHash(hs.transcript, hs.suite.hash)
357 if transcript == nil {
358 c.sendAlert(alertInternalError)
359 return errors.New("tls: internal error: failed to clone hash")
360 }
361 clientHelloBytes, err := hs.clientHello.marshalWithoutBinders()
362 if err != nil {
363 c.sendAlert(alertInternalError)
364 return err
365 }
366 transcript.Write(clientHelloBytes)
367 pskBinder := hs.suite.finishedHash(binderKey, transcript)
368 if !hmac.Equal(hs.clientHello.pskBinders[i], pskBinder) {
369 c.sendAlert(alertDecryptError)
370 return errors.New("tls: invalid PSK binder")
371 }
372
373 if c.quic != nil && hs.clientHello.earlyData && i == 0 &&
374 sessionState.EarlyData && sessionState.cipherSuite == hs.suite.id &&
375 sessionState.alpnProtocol == c.clientProtocol {
376 hs.earlyData = true
377
378 transcript := hs.suite.hash.New()
379 if err := transcriptMsg(hs.clientHello, transcript); err != nil {
380 return err
381 }
382 earlyTrafficSecret := hs.suite.deriveSecret(hs.earlySecret, clientEarlyTrafficLabel, transcript)
383 c.quicSetReadSecret(QUICEncryptionLevelEarly, hs.suite.id, earlyTrafficSecret)
384 }
385
386 c.didResume = true
387 c.peerCertificates = sessionState.peerCertificates
388 c.ocspResponse = sessionState.ocspResponse
389 c.scts = sessionState.scts
390 c.verifiedChains = sessionState.verifiedChains
391
392 hs.hello.selectedIdentityPresent = true
393 hs.hello.selectedIdentity = uint16(i)
394 hs.usingPSK = true
395 return nil
396 }
397
398 return nil
399 }
400
401
402
403
404 func cloneHash(in hash.Hash, h crypto.Hash) hash.Hash {
405
406 type binaryMarshaler interface {
407 MarshalBinary() (data []byte, err error)
408 UnmarshalBinary(data []byte) error
409 }
410 marshaler, ok := in.(binaryMarshaler)
411 if !ok {
412 return nil
413 }
414 state, err := marshaler.MarshalBinary()
415 if err != nil {
416 return nil
417 }
418 out := h.New()
419 unmarshaler, ok := out.(binaryMarshaler)
420 if !ok {
421 return nil
422 }
423 if err := unmarshaler.UnmarshalBinary(state); err != nil {
424 return nil
425 }
426 return out
427 }
428
429 func (hs *serverHandshakeStateTLS13) pickCertificate() error {
430 c := hs.c
431
432
433 if hs.usingPSK {
434 return nil
435 }
436
437
438 if len(hs.clientHello.supportedSignatureAlgorithms) == 0 {
439 return c.sendAlert(alertMissingExtension)
440 }
441
442 certificate, err := c.config.getCertificate(clientHelloInfo(hs.ctx, c, hs.clientHello))
443 if err != nil {
444 if err == errNoCertificates {
445 c.sendAlert(alertUnrecognizedName)
446 } else {
447 c.sendAlert(alertInternalError)
448 }
449 return err
450 }
451 hs.sigAlg, err = selectSignatureScheme(c.vers, certificate, hs.clientHello.supportedSignatureAlgorithms)
452 if err != nil {
453
454
455 c.sendAlert(alertHandshakeFailure)
456 return err
457 }
458 hs.cert = certificate
459
460 return nil
461 }
462
463
464
465 func (hs *serverHandshakeStateTLS13) sendDummyChangeCipherSpec() error {
466 if hs.c.quic != nil {
467 return nil
468 }
469 if hs.sentDummyCCS {
470 return nil
471 }
472 hs.sentDummyCCS = true
473
474 return hs.c.writeChangeCipherRecord()
475 }
476
477 func (hs *serverHandshakeStateTLS13) doHelloRetryRequest(selectedGroup CurveID) error {
478 c := hs.c
479
480
481
482 if err := transcriptMsg(hs.clientHello, hs.transcript); err != nil {
483 return err
484 }
485 chHash := hs.transcript.Sum(nil)
486 hs.transcript.Reset()
487 hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
488 hs.transcript.Write(chHash)
489
490 helloRetryRequest := &serverHelloMsg{
491 vers: hs.hello.vers,
492 random: helloRetryRequestRandom,
493 sessionId: hs.hello.sessionId,
494 cipherSuite: hs.hello.cipherSuite,
495 compressionMethod: hs.hello.compressionMethod,
496 supportedVersion: hs.hello.supportedVersion,
497 selectedGroup: selectedGroup,
498 }
499
500 if _, err := hs.c.writeHandshakeRecord(helloRetryRequest, hs.transcript); err != nil {
501 return err
502 }
503
504 if err := hs.sendDummyChangeCipherSpec(); err != nil {
505 return err
506 }
507
508
509 msg, err := c.readHandshake(nil)
510 if err != nil {
511 return err
512 }
513
514 clientHello, ok := msg.(*clientHelloMsg)
515 if !ok {
516 c.sendAlert(alertUnexpectedMessage)
517 return unexpectedMessageError(clientHello, msg)
518 }
519
520 if len(clientHello.keyShares) != 1 || clientHello.keyShares[0].group != selectedGroup {
521 c.sendAlert(alertIllegalParameter)
522 return errors.New("tls: client sent invalid key share in second ClientHello")
523 }
524
525 if clientHello.earlyData {
526 c.sendAlert(alertIllegalParameter)
527 return errors.New("tls: client indicated early data in second ClientHello")
528 }
529
530 if illegalClientHelloChange(clientHello, hs.clientHello) {
531 c.sendAlert(alertIllegalParameter)
532 return errors.New("tls: client illegally modified second ClientHello")
533 }
534
535 hs.clientHello = clientHello
536 return nil
537 }
538
539
540
541
542 func illegalClientHelloChange(ch, ch1 *clientHelloMsg) bool {
543 if len(ch.supportedVersions) != len(ch1.supportedVersions) ||
544 len(ch.cipherSuites) != len(ch1.cipherSuites) ||
545 len(ch.supportedCurves) != len(ch1.supportedCurves) ||
546 len(ch.supportedSignatureAlgorithms) != len(ch1.supportedSignatureAlgorithms) ||
547 len(ch.supportedSignatureAlgorithmsCert) != len(ch1.supportedSignatureAlgorithmsCert) ||
548 len(ch.alpnProtocols) != len(ch1.alpnProtocols) {
549 return true
550 }
551 for i := range ch.supportedVersions {
552 if ch.supportedVersions[i] != ch1.supportedVersions[i] {
553 return true
554 }
555 }
556 for i := range ch.cipherSuites {
557 if ch.cipherSuites[i] != ch1.cipherSuites[i] {
558 return true
559 }
560 }
561 for i := range ch.supportedCurves {
562 if ch.supportedCurves[i] != ch1.supportedCurves[i] {
563 return true
564 }
565 }
566 for i := range ch.supportedSignatureAlgorithms {
567 if ch.supportedSignatureAlgorithms[i] != ch1.supportedSignatureAlgorithms[i] {
568 return true
569 }
570 }
571 for i := range ch.supportedSignatureAlgorithmsCert {
572 if ch.supportedSignatureAlgorithmsCert[i] != ch1.supportedSignatureAlgorithmsCert[i] {
573 return true
574 }
575 }
576 for i := range ch.alpnProtocols {
577 if ch.alpnProtocols[i] != ch1.alpnProtocols[i] {
578 return true
579 }
580 }
581 return ch.vers != ch1.vers ||
582 !bytes.Equal(ch.random, ch1.random) ||
583 !bytes.Equal(ch.sessionId, ch1.sessionId) ||
584 !bytes.Equal(ch.compressionMethods, ch1.compressionMethods) ||
585 ch.serverName != ch1.serverName ||
586 ch.ocspStapling != ch1.ocspStapling ||
587 !bytes.Equal(ch.supportedPoints, ch1.supportedPoints) ||
588 ch.ticketSupported != ch1.ticketSupported ||
589 !bytes.Equal(ch.sessionTicket, ch1.sessionTicket) ||
590 ch.secureRenegotiationSupported != ch1.secureRenegotiationSupported ||
591 !bytes.Equal(ch.secureRenegotiation, ch1.secureRenegotiation) ||
592 ch.scts != ch1.scts ||
593 !bytes.Equal(ch.cookie, ch1.cookie) ||
594 !bytes.Equal(ch.pskModes, ch1.pskModes)
595 }
596
597 func (hs *serverHandshakeStateTLS13) sendServerParameters() error {
598 c := hs.c
599
600 if err := transcriptMsg(hs.clientHello, hs.transcript); err != nil {
601 return err
602 }
603 if _, err := hs.c.writeHandshakeRecord(hs.hello, hs.transcript); err != nil {
604 return err
605 }
606
607 if err := hs.sendDummyChangeCipherSpec(); err != nil {
608 return err
609 }
610
611 earlySecret := hs.earlySecret
612 if earlySecret == nil {
613 earlySecret = hs.suite.extract(nil, nil)
614 }
615 hs.handshakeSecret = hs.suite.extract(hs.sharedKey,
616 hs.suite.deriveSecret(earlySecret, "derived", nil))
617
618 clientSecret := hs.suite.deriveSecret(hs.handshakeSecret,
619 clientHandshakeTrafficLabel, hs.transcript)
620 c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, clientSecret)
621 serverSecret := hs.suite.deriveSecret(hs.handshakeSecret,
622 serverHandshakeTrafficLabel, hs.transcript)
623 c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, serverSecret)
624
625 if c.quic != nil {
626 if c.hand.Len() != 0 {
627 c.sendAlert(alertUnexpectedMessage)
628 }
629 c.quicSetWriteSecret(QUICEncryptionLevelHandshake, hs.suite.id, serverSecret)
630 c.quicSetReadSecret(QUICEncryptionLevelHandshake, hs.suite.id, clientSecret)
631 }
632
633 err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.clientHello.random, clientSecret)
634 if err != nil {
635 c.sendAlert(alertInternalError)
636 return err
637 }
638 err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.clientHello.random, serverSecret)
639 if err != nil {
640 c.sendAlert(alertInternalError)
641 return err
642 }
643
644 encryptedExtensions := new(encryptedExtensionsMsg)
645 encryptedExtensions.alpnProtocol = c.clientProtocol
646
647 if c.quic != nil {
648 p, err := c.quicGetTransportParameters()
649 if err != nil {
650 return err
651 }
652 encryptedExtensions.quicTransportParameters = p
653 encryptedExtensions.earlyData = hs.earlyData
654 }
655
656 if _, err := hs.c.writeHandshakeRecord(encryptedExtensions, hs.transcript); err != nil {
657 return err
658 }
659
660 return nil
661 }
662
663 func (hs *serverHandshakeStateTLS13) requestClientCert() bool {
664 return hs.c.config.ClientAuth >= RequestClientCert && !hs.usingPSK
665 }
666
667 func (hs *serverHandshakeStateTLS13) sendServerCertificate() error {
668 c := hs.c
669
670
671 if hs.usingPSK {
672 return nil
673 }
674
675 if hs.requestClientCert() {
676
677 certReq := new(certificateRequestMsgTLS13)
678 certReq.ocspStapling = true
679 certReq.scts = true
680 certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms()
681 if c.config.ClientCAs != nil {
682 certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
683 }
684
685 if _, err := hs.c.writeHandshakeRecord(certReq, hs.transcript); err != nil {
686 return err
687 }
688 }
689
690 certMsg := new(certificateMsgTLS13)
691
692 certMsg.certificate = *hs.cert
693 certMsg.scts = hs.clientHello.scts && len(hs.cert.SignedCertificateTimestamps) > 0
694 certMsg.ocspStapling = hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0
695
696 if _, err := hs.c.writeHandshakeRecord(certMsg, hs.transcript); err != nil {
697 return err
698 }
699
700 certVerifyMsg := new(certificateVerifyMsg)
701 certVerifyMsg.hasSignatureAlgorithm = true
702 certVerifyMsg.signatureAlgorithm = hs.sigAlg
703
704 sigType, sigHash, err := typeAndHashFromSignatureScheme(hs.sigAlg)
705 if err != nil {
706 return c.sendAlert(alertInternalError)
707 }
708
709 signed := signedMessage(sigHash, serverSignatureContext, hs.transcript)
710 signOpts := crypto.SignerOpts(sigHash)
711 if sigType == signatureRSAPSS {
712 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
713 }
714 sig, err := hs.cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts)
715 if err != nil {
716 public := hs.cert.PrivateKey.(crypto.Signer).Public()
717 if rsaKey, ok := public.(*rsa.PublicKey); ok && sigType == signatureRSAPSS &&
718 rsaKey.N.BitLen()/8 < sigHash.Size()*2+2 {
719 c.sendAlert(alertHandshakeFailure)
720 } else {
721 c.sendAlert(alertInternalError)
722 }
723 return errors.New("tls: failed to sign handshake: " + err.Error())
724 }
725 certVerifyMsg.signature = sig
726
727 if _, err := hs.c.writeHandshakeRecord(certVerifyMsg, hs.transcript); err != nil {
728 return err
729 }
730
731 return nil
732 }
733
734 func (hs *serverHandshakeStateTLS13) sendServerFinished() error {
735 c := hs.c
736
737 finished := &finishedMsg{
738 verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
739 }
740
741 if _, err := hs.c.writeHandshakeRecord(finished, hs.transcript); err != nil {
742 return err
743 }
744
745
746
747 hs.masterSecret = hs.suite.extract(nil,
748 hs.suite.deriveSecret(hs.handshakeSecret, "derived", nil))
749
750 hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret,
751 clientApplicationTrafficLabel, hs.transcript)
752 serverSecret := hs.suite.deriveSecret(hs.masterSecret,
753 serverApplicationTrafficLabel, hs.transcript)
754 c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, serverSecret)
755
756 if c.quic != nil {
757 if c.hand.Len() != 0 {
758
759 c.sendAlert(alertUnexpectedMessage)
760 }
761 c.quicSetWriteSecret(QUICEncryptionLevelApplication, hs.suite.id, serverSecret)
762 }
763
764 err := c.config.writeKeyLog(keyLogLabelClientTraffic, hs.clientHello.random, hs.trafficSecret)
765 if err != nil {
766 c.sendAlert(alertInternalError)
767 return err
768 }
769 err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.clientHello.random, serverSecret)
770 if err != nil {
771 c.sendAlert(alertInternalError)
772 return err
773 }
774
775 c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript)
776
777
778
779
780 if !hs.requestClientCert() {
781 if err := hs.sendSessionTickets(); err != nil {
782 return err
783 }
784 }
785
786 return nil
787 }
788
789 func (hs *serverHandshakeStateTLS13) shouldSendSessionTickets() bool {
790 if hs.c.config.SessionTicketsDisabled {
791 return false
792 }
793
794
795 if hs.c.quic != nil {
796 return false
797 }
798
799
800 for _, pskMode := range hs.clientHello.pskModes {
801 if pskMode == pskModeDHE {
802 return true
803 }
804 }
805 return false
806 }
807
808 func (hs *serverHandshakeStateTLS13) sendSessionTickets() error {
809 c := hs.c
810
811 hs.clientFinished = hs.suite.finishedHash(c.in.trafficSecret, hs.transcript)
812 finishedMsg := &finishedMsg{
813 verifyData: hs.clientFinished,
814 }
815 if err := transcriptMsg(finishedMsg, hs.transcript); err != nil {
816 return err
817 }
818
819 c.resumptionSecret = hs.suite.deriveSecret(hs.masterSecret,
820 resumptionLabel, hs.transcript)
821
822 if !hs.shouldSendSessionTickets() {
823 return nil
824 }
825 return c.sendSessionTicket(false)
826 }
827
828 func (c *Conn) sendSessionTicket(earlyData bool) error {
829 suite := cipherSuiteTLS13ByID(c.cipherSuite)
830 if suite == nil {
831 return errors.New("tls: internal error: unknown cipher suite")
832 }
833
834
835 psk := suite.expandLabel(c.resumptionSecret, "resumption",
836 nil, suite.hash.Size())
837
838 m := new(newSessionTicketMsgTLS13)
839
840 state, err := c.sessionState()
841 if err != nil {
842 return err
843 }
844 state.secret = psk
845 state.EarlyData = earlyData
846 if c.config.WrapSession != nil {
847 m.label, err = c.config.WrapSession(c.connectionStateLocked(), state)
848 if err != nil {
849 return err
850 }
851 } else {
852 stateBytes, err := state.Bytes()
853 if err != nil {
854 c.sendAlert(alertInternalError)
855 return err
856 }
857 m.label, err = c.config.encryptTicket(stateBytes, c.ticketKeys)
858 if err != nil {
859 return err
860 }
861 }
862 m.lifetime = uint32(maxSessionTicketLifetime / time.Second)
863
864
865
866
867 ageAdd := make([]byte, 4)
868 _, err = c.config.rand().Read(ageAdd)
869 if err != nil {
870 return err
871 }
872 m.ageAdd = binary.LittleEndian.Uint32(ageAdd)
873
874 if earlyData {
875
876 m.maxEarlyData = 0xffffffff
877 }
878
879 if _, err := c.writeHandshakeRecord(m, nil); err != nil {
880 return err
881 }
882
883 return nil
884 }
885
886 func (hs *serverHandshakeStateTLS13) readClientCertificate() error {
887 c := hs.c
888
889 if !hs.requestClientCert() {
890
891
892 if c.config.VerifyConnection != nil {
893 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
894 c.sendAlert(alertBadCertificate)
895 return err
896 }
897 }
898 return nil
899 }
900
901
902
903
904 msg, err := c.readHandshake(hs.transcript)
905 if err != nil {
906 return err
907 }
908
909 certMsg, ok := msg.(*certificateMsgTLS13)
910 if !ok {
911 c.sendAlert(alertUnexpectedMessage)
912 return unexpectedMessageError(certMsg, msg)
913 }
914
915 if err := c.processCertsFromClient(certMsg.certificate); err != nil {
916 return err
917 }
918
919 if c.config.VerifyConnection != nil {
920 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
921 c.sendAlert(alertBadCertificate)
922 return err
923 }
924 }
925
926 if len(certMsg.certificate.Certificate) != 0 {
927
928
929
930 msg, err = c.readHandshake(nil)
931 if err != nil {
932 return err
933 }
934
935 certVerify, ok := msg.(*certificateVerifyMsg)
936 if !ok {
937 c.sendAlert(alertUnexpectedMessage)
938 return unexpectedMessageError(certVerify, msg)
939 }
940
941
942 if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms()) {
943 c.sendAlert(alertIllegalParameter)
944 return errors.New("tls: client certificate used with invalid signature algorithm")
945 }
946 sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
947 if err != nil {
948 return c.sendAlert(alertInternalError)
949 }
950 if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
951 c.sendAlert(alertIllegalParameter)
952 return errors.New("tls: client certificate used with invalid signature algorithm")
953 }
954 signed := signedMessage(sigHash, clientSignatureContext, hs.transcript)
955 if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey,
956 sigHash, signed, certVerify.signature); err != nil {
957 c.sendAlert(alertDecryptError)
958 return errors.New("tls: invalid signature by the client certificate: " + err.Error())
959 }
960
961 if err := transcriptMsg(certVerify, hs.transcript); err != nil {
962 return err
963 }
964 }
965
966
967
968 if err := hs.sendSessionTickets(); err != nil {
969 return err
970 }
971
972 return nil
973 }
974
975 func (hs *serverHandshakeStateTLS13) readClientFinished() error {
976 c := hs.c
977
978
979 msg, err := c.readHandshake(nil)
980 if err != nil {
981 return err
982 }
983
984 finished, ok := msg.(*finishedMsg)
985 if !ok {
986 c.sendAlert(alertUnexpectedMessage)
987 return unexpectedMessageError(finished, msg)
988 }
989
990 if !hmac.Equal(hs.clientFinished, finished.verifyData) {
991 c.sendAlert(alertDecryptError)
992 return errors.New("tls: invalid client finished hash")
993 }
994
995 c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, hs.trafficSecret)
996
997 return nil
998 }
999
View as plain text