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/hkdf"
12 "crypto/hmac"
13 "crypto/internal/fips140/mlkem"
14 "crypto/internal/fips140/tls13"
15 "crypto/internal/hpke"
16 "crypto/rsa"
17 "crypto/tls/internal/fips140tls"
18 "errors"
19 "fmt"
20 "hash"
21 "internal/byteorder"
22 "io"
23 "slices"
24 "sort"
25 "time"
26 )
27
28
29
30
31 const maxClientPSKIdentities = 5
32
33 type echServerContext struct {
34 hpkeContext *hpke.Recipient
35 configID uint8
36 ciphersuite echCipher
37 transcript hash.Hash
38
39
40
41
42 inner bool
43 }
44
45 type serverHandshakeStateTLS13 struct {
46 c *Conn
47 ctx context.Context
48 clientHello *clientHelloMsg
49 hello *serverHelloMsg
50 sentDummyCCS bool
51 usingPSK bool
52 earlyData bool
53 suite *cipherSuiteTLS13
54 cert *Certificate
55 sigAlg SignatureScheme
56 earlySecret *tls13.EarlySecret
57 sharedKey []byte
58 handshakeSecret *tls13.HandshakeSecret
59 masterSecret *tls13.MasterSecret
60 trafficSecret []byte
61 transcript hash.Hash
62 clientFinished []byte
63 echContext *echServerContext
64 }
65
66 func (hs *serverHandshakeStateTLS13) handshake() error {
67 c := hs.c
68
69
70 if err := hs.processClientHello(); err != nil {
71 return err
72 }
73 if err := hs.checkForResumption(); err != nil {
74 return err
75 }
76 if err := hs.pickCertificate(); err != nil {
77 return err
78 }
79 c.buffering = true
80 if err := hs.sendServerParameters(); err != nil {
81 return err
82 }
83 if err := hs.sendServerCertificate(); err != nil {
84 return err
85 }
86 if err := hs.sendServerFinished(); err != nil {
87 return err
88 }
89
90
91
92 if _, err := c.flush(); err != nil {
93 return err
94 }
95 if err := hs.readClientCertificate(); err != nil {
96 return err
97 }
98 if err := hs.readClientFinished(); err != nil {
99 return err
100 }
101
102 c.isHandshakeComplete.Store(true)
103
104 return nil
105 }
106
107 func (hs *serverHandshakeStateTLS13) processClientHello() error {
108 c := hs.c
109
110 hs.hello = new(serverHelloMsg)
111
112
113
114 hs.hello.vers = VersionTLS12
115 hs.hello.supportedVersion = c.vers
116
117 if len(hs.clientHello.supportedVersions) == 0 {
118 c.sendAlert(alertIllegalParameter)
119 return errors.New("tls: client used the legacy version field to negotiate TLS 1.3")
120 }
121
122
123
124
125
126
127
128
129
130
131 for _, id := range hs.clientHello.cipherSuites {
132 if id == TLS_FALLBACK_SCSV {
133
134
135 if c.vers < c.config.maxSupportedVersion(roleServer) {
136 c.sendAlert(alertInappropriateFallback)
137 return errors.New("tls: client using inappropriate protocol fallback")
138 }
139 break
140 }
141 }
142
143 if len(hs.clientHello.compressionMethods) != 1 ||
144 hs.clientHello.compressionMethods[0] != compressionNone {
145 c.sendAlert(alertIllegalParameter)
146 return errors.New("tls: TLS 1.3 client supports illegal compression methods")
147 }
148
149 hs.hello.random = make([]byte, 32)
150 if _, err := io.ReadFull(c.config.rand(), hs.hello.random); err != nil {
151 c.sendAlert(alertInternalError)
152 return err
153 }
154
155 if len(hs.clientHello.secureRenegotiation) != 0 {
156 c.sendAlert(alertHandshakeFailure)
157 return errors.New("tls: initial handshake had non-empty renegotiation extension")
158 }
159
160 if hs.clientHello.earlyData && c.quic != nil {
161 if len(hs.clientHello.pskIdentities) == 0 {
162 c.sendAlert(alertIllegalParameter)
163 return errors.New("tls: early_data without pre_shared_key")
164 }
165 } else if hs.clientHello.earlyData {
166
167
168
169
170
171
172 c.sendAlert(alertUnsupportedExtension)
173 return errors.New("tls: client sent unexpected early data")
174 }
175
176 hs.hello.sessionId = hs.clientHello.sessionId
177 hs.hello.compressionMethod = compressionNone
178
179 preferenceList := defaultCipherSuitesTLS13
180 if !hasAESGCMHardwareSupport || !isAESGCMPreferred(hs.clientHello.cipherSuites) {
181 preferenceList = defaultCipherSuitesTLS13NoAES
182 }
183 if fips140tls.Required() {
184 preferenceList = allowedCipherSuitesTLS13FIPS
185 }
186 for _, suiteID := range preferenceList {
187 hs.suite = mutualCipherSuiteTLS13(hs.clientHello.cipherSuites, suiteID)
188 if hs.suite != nil {
189 break
190 }
191 }
192 if hs.suite == nil {
193 c.sendAlert(alertHandshakeFailure)
194 return fmt.Errorf("tls: no cipher suite supported by both client and server; client offered: %x",
195 hs.clientHello.cipherSuites)
196 }
197 c.cipherSuite = hs.suite.id
198 hs.hello.cipherSuite = hs.suite.id
199 hs.transcript = hs.suite.hash.New()
200
201
202
203
204
205
206
207
208
209 preferredGroups := c.config.curvePreferences(c.vers)
210 preferredGroups = slices.DeleteFunc(preferredGroups, func(group CurveID) bool {
211 return !slices.Contains(hs.clientHello.supportedCurves, group)
212 })
213 if len(preferredGroups) == 0 {
214 c.sendAlert(alertHandshakeFailure)
215 return errors.New("tls: no key exchanges supported by both client and server")
216 }
217 hasKeyShare := func(group CurveID) bool {
218 for _, ks := range hs.clientHello.keyShares {
219 if ks.group == group {
220 return true
221 }
222 }
223 return false
224 }
225 sort.SliceStable(preferredGroups, func(i, j int) bool {
226 return hasKeyShare(preferredGroups[i]) && !hasKeyShare(preferredGroups[j])
227 })
228 sort.SliceStable(preferredGroups, func(i, j int) bool {
229 return isPQKeyExchange(preferredGroups[i]) && !isPQKeyExchange(preferredGroups[j])
230 })
231 selectedGroup := preferredGroups[0]
232
233 var clientKeyShare *keyShare
234 for _, ks := range hs.clientHello.keyShares {
235 if ks.group == selectedGroup {
236 clientKeyShare = &ks
237 break
238 }
239 }
240 if clientKeyShare == nil {
241 ks, err := hs.doHelloRetryRequest(selectedGroup)
242 if err != nil {
243 return err
244 }
245 clientKeyShare = ks
246 }
247 c.curveID = selectedGroup
248
249 ecdhGroup := selectedGroup
250 ecdhData := clientKeyShare.data
251 if selectedGroup == X25519MLKEM768 {
252 ecdhGroup = X25519
253 if len(ecdhData) != mlkem.EncapsulationKeySize768+x25519PublicKeySize {
254 c.sendAlert(alertIllegalParameter)
255 return errors.New("tls: invalid X25519MLKEM768 client key share")
256 }
257 ecdhData = ecdhData[mlkem.EncapsulationKeySize768:]
258 }
259 if _, ok := curveForCurveID(ecdhGroup); !ok {
260 c.sendAlert(alertInternalError)
261 return errors.New("tls: CurvePreferences includes unsupported curve")
262 }
263 key, err := generateECDHEKey(c.config.rand(), ecdhGroup)
264 if err != nil {
265 c.sendAlert(alertInternalError)
266 return err
267 }
268 hs.hello.serverShare = keyShare{group: selectedGroup, data: key.PublicKey().Bytes()}
269 peerKey, err := key.Curve().NewPublicKey(ecdhData)
270 if err != nil {
271 c.sendAlert(alertIllegalParameter)
272 return errors.New("tls: invalid client key share")
273 }
274 hs.sharedKey, err = key.ECDH(peerKey)
275 if err != nil {
276 c.sendAlert(alertIllegalParameter)
277 return errors.New("tls: invalid client key share")
278 }
279 if selectedGroup == X25519MLKEM768 {
280 k, err := mlkem.NewEncapsulationKey768(clientKeyShare.data[:mlkem.EncapsulationKeySize768])
281 if err != nil {
282 c.sendAlert(alertIllegalParameter)
283 return errors.New("tls: invalid X25519MLKEM768 client key share")
284 }
285 mlkemSharedSecret, ciphertext := k.Encapsulate()
286
287
288
289
290 hs.sharedKey = append(mlkemSharedSecret, hs.sharedKey...)
291
292
293
294
295
296 hs.hello.serverShare.data = append(ciphertext, hs.hello.serverShare.data...)
297 }
298
299 selectedProto, err := negotiateALPN(c.config.NextProtos, hs.clientHello.alpnProtocols, c.quic != nil)
300 if err != nil {
301 c.sendAlert(alertNoApplicationProtocol)
302 return err
303 }
304 c.clientProtocol = selectedProto
305
306 if c.quic != nil {
307
308 for _, v := range hs.clientHello.supportedVersions {
309 if v < VersionTLS13 {
310 c.sendAlert(alertProtocolVersion)
311 return errors.New("tls: client offered TLS version older than TLS 1.3")
312 }
313 }
314
315 if hs.clientHello.quicTransportParameters == nil {
316 c.sendAlert(alertMissingExtension)
317 return errors.New("tls: client did not send a quic_transport_parameters extension")
318 }
319 c.quicSetTransportParameters(hs.clientHello.quicTransportParameters)
320 } else {
321 if hs.clientHello.quicTransportParameters != nil {
322 c.sendAlert(alertUnsupportedExtension)
323 return errors.New("tls: client sent an unexpected quic_transport_parameters extension")
324 }
325 }
326
327 c.serverName = hs.clientHello.serverName
328 return nil
329 }
330
331 func (hs *serverHandshakeStateTLS13) checkForResumption() error {
332 c := hs.c
333
334 if c.config.SessionTicketsDisabled {
335 return nil
336 }
337
338 modeOK := false
339 for _, mode := range hs.clientHello.pskModes {
340 if mode == pskModeDHE {
341 modeOK = true
342 break
343 }
344 }
345 if !modeOK {
346 return nil
347 }
348
349 if len(hs.clientHello.pskIdentities) != len(hs.clientHello.pskBinders) {
350 c.sendAlert(alertIllegalParameter)
351 return errors.New("tls: invalid or missing PSK binders")
352 }
353 if len(hs.clientHello.pskIdentities) == 0 {
354 return nil
355 }
356
357 for i, identity := range hs.clientHello.pskIdentities {
358 if i >= maxClientPSKIdentities {
359 break
360 }
361
362 var sessionState *SessionState
363 if c.config.UnwrapSession != nil {
364 var err error
365 sessionState, err = c.config.UnwrapSession(identity.label, c.connectionStateLocked())
366 if err != nil {
367 return err
368 }
369 if sessionState == nil {
370 continue
371 }
372 } else {
373 plaintext := c.config.decryptTicket(identity.label, c.ticketKeys)
374 if plaintext == nil {
375 continue
376 }
377 var err error
378 sessionState, err = ParseSessionState(plaintext)
379 if err != nil {
380 continue
381 }
382 }
383
384 if sessionState.version != VersionTLS13 {
385 continue
386 }
387
388 createdAt := time.Unix(int64(sessionState.createdAt), 0)
389 if c.config.time().Sub(createdAt) > maxSessionTicketLifetime {
390 continue
391 }
392
393 pskSuite := cipherSuiteTLS13ByID(sessionState.cipherSuite)
394 if pskSuite == nil || pskSuite.hash != hs.suite.hash {
395 continue
396 }
397
398
399
400
401 sessionHasClientCerts := len(sessionState.peerCertificates) != 0
402 needClientCerts := requiresClientCert(c.config.ClientAuth)
403 if needClientCerts && !sessionHasClientCerts {
404 continue
405 }
406 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
407 continue
408 }
409 if sessionHasClientCerts && c.config.time().After(sessionState.peerCertificates[0].NotAfter) {
410 continue
411 }
412 if sessionHasClientCerts && c.config.ClientAuth >= VerifyClientCertIfGiven &&
413 len(sessionState.verifiedChains) == 0 {
414 continue
415 }
416
417 if c.quic != nil && c.quic.enableSessionEvents {
418 if err := c.quicResumeSession(sessionState); err != nil {
419 return err
420 }
421 }
422
423 hs.earlySecret = tls13.NewEarlySecret(hs.suite.hash.New, sessionState.secret)
424 binderKey := hs.earlySecret.ResumptionBinderKey()
425
426 transcript := cloneHash(hs.transcript, hs.suite.hash)
427 if transcript == nil {
428 c.sendAlert(alertInternalError)
429 return errors.New("tls: internal error: failed to clone hash")
430 }
431 clientHelloBytes, err := hs.clientHello.marshalWithoutBinders()
432 if err != nil {
433 c.sendAlert(alertInternalError)
434 return err
435 }
436 transcript.Write(clientHelloBytes)
437 pskBinder := hs.suite.finishedHash(binderKey, transcript)
438 if !hmac.Equal(hs.clientHello.pskBinders[i], pskBinder) {
439 c.sendAlert(alertDecryptError)
440 return errors.New("tls: invalid PSK binder")
441 }
442
443 if c.quic != nil && hs.clientHello.earlyData && i == 0 &&
444 sessionState.EarlyData && sessionState.cipherSuite == hs.suite.id &&
445 sessionState.alpnProtocol == c.clientProtocol {
446 hs.earlyData = true
447
448 transcript := hs.suite.hash.New()
449 if err := transcriptMsg(hs.clientHello, transcript); err != nil {
450 return err
451 }
452 earlyTrafficSecret := hs.earlySecret.ClientEarlyTrafficSecret(transcript)
453 c.quicSetReadSecret(QUICEncryptionLevelEarly, hs.suite.id, earlyTrafficSecret)
454 }
455
456 c.didResume = true
457 c.peerCertificates = sessionState.peerCertificates
458 c.ocspResponse = sessionState.ocspResponse
459 c.scts = sessionState.scts
460 c.verifiedChains = sessionState.verifiedChains
461
462 hs.hello.selectedIdentityPresent = true
463 hs.hello.selectedIdentity = uint16(i)
464 hs.usingPSK = true
465 return nil
466 }
467
468 return nil
469 }
470
471
472
473
474 func cloneHash(in hash.Hash, h crypto.Hash) hash.Hash {
475
476 type binaryMarshaler interface {
477 MarshalBinary() (data []byte, err error)
478 UnmarshalBinary(data []byte) error
479 }
480 marshaler, ok := in.(binaryMarshaler)
481 if !ok {
482 return nil
483 }
484 state, err := marshaler.MarshalBinary()
485 if err != nil {
486 return nil
487 }
488 out := h.New()
489 unmarshaler, ok := out.(binaryMarshaler)
490 if !ok {
491 return nil
492 }
493 if err := unmarshaler.UnmarshalBinary(state); err != nil {
494 return nil
495 }
496 return out
497 }
498
499 func (hs *serverHandshakeStateTLS13) pickCertificate() error {
500 c := hs.c
501
502
503 if hs.usingPSK {
504 return nil
505 }
506
507
508 if len(hs.clientHello.supportedSignatureAlgorithms) == 0 {
509 return c.sendAlert(alertMissingExtension)
510 }
511
512 certificate, err := c.config.getCertificate(clientHelloInfo(hs.ctx, c, hs.clientHello))
513 if err != nil {
514 if err == errNoCertificates {
515 c.sendAlert(alertUnrecognizedName)
516 } else {
517 c.sendAlert(alertInternalError)
518 }
519 return err
520 }
521 hs.sigAlg, err = selectSignatureScheme(c.vers, certificate, hs.clientHello.supportedSignatureAlgorithms)
522 if err != nil {
523
524
525 c.sendAlert(alertHandshakeFailure)
526 return err
527 }
528 hs.cert = certificate
529
530 return nil
531 }
532
533
534
535 func (hs *serverHandshakeStateTLS13) sendDummyChangeCipherSpec() error {
536 if hs.c.quic != nil {
537 return nil
538 }
539 if hs.sentDummyCCS {
540 return nil
541 }
542 hs.sentDummyCCS = true
543
544 return hs.c.writeChangeCipherRecord()
545 }
546
547 func (hs *serverHandshakeStateTLS13) doHelloRetryRequest(selectedGroup CurveID) (*keyShare, error) {
548 c := hs.c
549
550
551
552 if err := transcriptMsg(hs.clientHello, hs.transcript); err != nil {
553 return nil, err
554 }
555 chHash := hs.transcript.Sum(nil)
556 hs.transcript.Reset()
557 hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
558 hs.transcript.Write(chHash)
559
560 helloRetryRequest := &serverHelloMsg{
561 vers: hs.hello.vers,
562 random: helloRetryRequestRandom,
563 sessionId: hs.hello.sessionId,
564 cipherSuite: hs.hello.cipherSuite,
565 compressionMethod: hs.hello.compressionMethod,
566 supportedVersion: hs.hello.supportedVersion,
567 selectedGroup: selectedGroup,
568 }
569
570 if hs.echContext != nil {
571
572 helloRetryRequest.encryptedClientHello = make([]byte, 8)
573 confTranscript := cloneHash(hs.transcript, hs.suite.hash)
574 if err := transcriptMsg(helloRetryRequest, confTranscript); err != nil {
575 return nil, err
576 }
577 h := hs.suite.hash.New
578 prf, err := hkdf.Extract(h, hs.clientHello.random, nil)
579 if err != nil {
580 c.sendAlert(alertInternalError)
581 return nil, err
582 }
583 acceptConfirmation := tls13.ExpandLabel(h, prf, "hrr ech accept confirmation", confTranscript.Sum(nil), 8)
584 helloRetryRequest.encryptedClientHello = acceptConfirmation
585 }
586
587 if _, err := hs.c.writeHandshakeRecord(helloRetryRequest, hs.transcript); err != nil {
588 return nil, err
589 }
590
591 if err := hs.sendDummyChangeCipherSpec(); err != nil {
592 return nil, err
593 }
594
595
596 msg, err := c.readHandshake(nil)
597 if err != nil {
598 return nil, err
599 }
600
601 clientHello, ok := msg.(*clientHelloMsg)
602 if !ok {
603 c.sendAlert(alertUnexpectedMessage)
604 return nil, unexpectedMessageError(clientHello, msg)
605 }
606
607 if hs.echContext != nil {
608 if len(clientHello.encryptedClientHello) == 0 {
609 c.sendAlert(alertMissingExtension)
610 return nil, errors.New("tls: second client hello missing encrypted client hello extension")
611 }
612
613 echType, echCiphersuite, configID, encap, payload, err := parseECHExt(clientHello.encryptedClientHello)
614 if err != nil {
615 c.sendAlert(alertDecodeError)
616 return nil, errors.New("tls: client sent invalid encrypted client hello extension")
617 }
618
619 if echType == outerECHExt && hs.echContext.inner || echType == innerECHExt && !hs.echContext.inner {
620 c.sendAlert(alertDecodeError)
621 return nil, errors.New("tls: unexpected switch in encrypted client hello extension type")
622 }
623
624 if echType == outerECHExt {
625 if echCiphersuite != hs.echContext.ciphersuite || configID != hs.echContext.configID || len(encap) != 0 {
626 c.sendAlert(alertIllegalParameter)
627 return nil, errors.New("tls: second client hello encrypted client hello extension does not match")
628 }
629
630 encodedInner, err := decryptECHPayload(hs.echContext.hpkeContext, clientHello.original, payload)
631 if err != nil {
632 c.sendAlert(alertDecryptError)
633 return nil, errors.New("tls: failed to decrypt second client hello encrypted client hello extension payload")
634 }
635
636 echInner, err := decodeInnerClientHello(clientHello, encodedInner)
637 if err != nil {
638 c.sendAlert(alertIllegalParameter)
639 return nil, errors.New("tls: client sent invalid encrypted client hello extension")
640 }
641
642 clientHello = echInner
643 }
644 }
645
646 if len(clientHello.keyShares) != 1 {
647 c.sendAlert(alertIllegalParameter)
648 return nil, errors.New("tls: client didn't send one key share in second ClientHello")
649 }
650 ks := &clientHello.keyShares[0]
651
652 if ks.group != selectedGroup {
653 c.sendAlert(alertIllegalParameter)
654 return nil, errors.New("tls: client sent unexpected key share in second ClientHello")
655 }
656
657 if clientHello.earlyData {
658 c.sendAlert(alertIllegalParameter)
659 return nil, errors.New("tls: client indicated early data in second ClientHello")
660 }
661
662 if illegalClientHelloChange(clientHello, hs.clientHello) {
663 c.sendAlert(alertIllegalParameter)
664 return nil, errors.New("tls: client illegally modified second ClientHello")
665 }
666
667 c.didHRR = true
668 hs.clientHello = clientHello
669 return ks, nil
670 }
671
672
673
674
675 func illegalClientHelloChange(ch, ch1 *clientHelloMsg) bool {
676 if len(ch.supportedVersions) != len(ch1.supportedVersions) ||
677 len(ch.cipherSuites) != len(ch1.cipherSuites) ||
678 len(ch.supportedCurves) != len(ch1.supportedCurves) ||
679 len(ch.supportedSignatureAlgorithms) != len(ch1.supportedSignatureAlgorithms) ||
680 len(ch.supportedSignatureAlgorithmsCert) != len(ch1.supportedSignatureAlgorithmsCert) ||
681 len(ch.alpnProtocols) != len(ch1.alpnProtocols) {
682 return true
683 }
684 for i := range ch.supportedVersions {
685 if ch.supportedVersions[i] != ch1.supportedVersions[i] {
686 return true
687 }
688 }
689 for i := range ch.cipherSuites {
690 if ch.cipherSuites[i] != ch1.cipherSuites[i] {
691 return true
692 }
693 }
694 for i := range ch.supportedCurves {
695 if ch.supportedCurves[i] != ch1.supportedCurves[i] {
696 return true
697 }
698 }
699 for i := range ch.supportedSignatureAlgorithms {
700 if ch.supportedSignatureAlgorithms[i] != ch1.supportedSignatureAlgorithms[i] {
701 return true
702 }
703 }
704 for i := range ch.supportedSignatureAlgorithmsCert {
705 if ch.supportedSignatureAlgorithmsCert[i] != ch1.supportedSignatureAlgorithmsCert[i] {
706 return true
707 }
708 }
709 for i := range ch.alpnProtocols {
710 if ch.alpnProtocols[i] != ch1.alpnProtocols[i] {
711 return true
712 }
713 }
714 return ch.vers != ch1.vers ||
715 !bytes.Equal(ch.random, ch1.random) ||
716 !bytes.Equal(ch.sessionId, ch1.sessionId) ||
717 !bytes.Equal(ch.compressionMethods, ch1.compressionMethods) ||
718 ch.serverName != ch1.serverName ||
719 ch.ocspStapling != ch1.ocspStapling ||
720 !bytes.Equal(ch.supportedPoints, ch1.supportedPoints) ||
721 ch.ticketSupported != ch1.ticketSupported ||
722 !bytes.Equal(ch.sessionTicket, ch1.sessionTicket) ||
723 ch.secureRenegotiationSupported != ch1.secureRenegotiationSupported ||
724 !bytes.Equal(ch.secureRenegotiation, ch1.secureRenegotiation) ||
725 ch.scts != ch1.scts ||
726 !bytes.Equal(ch.cookie, ch1.cookie) ||
727 !bytes.Equal(ch.pskModes, ch1.pskModes)
728 }
729
730 func (hs *serverHandshakeStateTLS13) sendServerParameters() error {
731 c := hs.c
732
733 if hs.echContext != nil {
734 copy(hs.hello.random[32-8:], make([]byte, 8))
735 echTranscript := cloneHash(hs.transcript, hs.suite.hash)
736 echTranscript.Write(hs.clientHello.original)
737 if err := transcriptMsg(hs.hello, echTranscript); err != nil {
738 return err
739 }
740
741 h := hs.suite.hash.New
742 prk, err := hkdf.Extract(h, hs.clientHello.random, nil)
743 if err != nil {
744 c.sendAlert(alertInternalError)
745 return err
746 }
747 acceptConfirmation := tls13.ExpandLabel(h, prk, "ech accept confirmation", echTranscript.Sum(nil), 8)
748 copy(hs.hello.random[32-8:], acceptConfirmation)
749 }
750
751 if err := transcriptMsg(hs.clientHello, hs.transcript); err != nil {
752 return err
753 }
754
755 if _, err := hs.c.writeHandshakeRecord(hs.hello, hs.transcript); err != nil {
756 return err
757 }
758
759 if err := hs.sendDummyChangeCipherSpec(); err != nil {
760 return err
761 }
762
763 earlySecret := hs.earlySecret
764 if earlySecret == nil {
765 earlySecret = tls13.NewEarlySecret(hs.suite.hash.New, nil)
766 }
767 hs.handshakeSecret = earlySecret.HandshakeSecret(hs.sharedKey)
768
769 clientSecret := hs.handshakeSecret.ClientHandshakeTrafficSecret(hs.transcript)
770 c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, clientSecret)
771 serverSecret := hs.handshakeSecret.ServerHandshakeTrafficSecret(hs.transcript)
772 c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, serverSecret)
773
774 if c.quic != nil {
775 if c.hand.Len() != 0 {
776 c.sendAlert(alertUnexpectedMessage)
777 }
778 c.quicSetWriteSecret(QUICEncryptionLevelHandshake, hs.suite.id, serverSecret)
779 c.quicSetReadSecret(QUICEncryptionLevelHandshake, hs.suite.id, clientSecret)
780 }
781
782 err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.clientHello.random, clientSecret)
783 if err != nil {
784 c.sendAlert(alertInternalError)
785 return err
786 }
787 err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.clientHello.random, serverSecret)
788 if err != nil {
789 c.sendAlert(alertInternalError)
790 return err
791 }
792
793 encryptedExtensions := new(encryptedExtensionsMsg)
794 encryptedExtensions.alpnProtocol = c.clientProtocol
795
796 if c.quic != nil {
797 p, err := c.quicGetTransportParameters()
798 if err != nil {
799 return err
800 }
801 encryptedExtensions.quicTransportParameters = p
802 encryptedExtensions.earlyData = hs.earlyData
803 }
804
805
806
807 echKeys := hs.c.config.EncryptedClientHelloKeys
808 if hs.c.config.GetEncryptedClientHelloKeys != nil {
809 echKeys, err = hs.c.config.GetEncryptedClientHelloKeys(clientHelloInfo(hs.ctx, c, hs.clientHello))
810 if err != nil {
811 c.sendAlert(alertInternalError)
812 return err
813 }
814 }
815 if len(echKeys) > 0 && len(hs.clientHello.encryptedClientHello) > 0 && hs.echContext == nil {
816 encryptedExtensions.echRetryConfigs, err = buildRetryConfigList(echKeys)
817 if err != nil {
818 c.sendAlert(alertInternalError)
819 return err
820 }
821 }
822
823 if _, err := hs.c.writeHandshakeRecord(encryptedExtensions, hs.transcript); err != nil {
824 return err
825 }
826
827 return nil
828 }
829
830 func (hs *serverHandshakeStateTLS13) requestClientCert() bool {
831 return hs.c.config.ClientAuth >= RequestClientCert && !hs.usingPSK
832 }
833
834 func (hs *serverHandshakeStateTLS13) sendServerCertificate() error {
835 c := hs.c
836
837
838 if hs.usingPSK {
839 return nil
840 }
841
842 if hs.requestClientCert() {
843
844 certReq := new(certificateRequestMsgTLS13)
845 certReq.ocspStapling = true
846 certReq.scts = true
847 certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms(c.vers)
848 certReq.supportedSignatureAlgorithmsCert = supportedSignatureAlgorithmsCert()
849 if c.config.ClientCAs != nil {
850 certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
851 }
852
853 if _, err := hs.c.writeHandshakeRecord(certReq, hs.transcript); err != nil {
854 return err
855 }
856 }
857
858 certMsg := new(certificateMsgTLS13)
859
860 certMsg.certificate = *hs.cert
861 certMsg.scts = hs.clientHello.scts && len(hs.cert.SignedCertificateTimestamps) > 0
862 certMsg.ocspStapling = hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0
863
864 if _, err := hs.c.writeHandshakeRecord(certMsg, hs.transcript); err != nil {
865 return err
866 }
867
868 certVerifyMsg := new(certificateVerifyMsg)
869 certVerifyMsg.hasSignatureAlgorithm = true
870 certVerifyMsg.signatureAlgorithm = hs.sigAlg
871
872 sigType, sigHash, err := typeAndHashFromSignatureScheme(hs.sigAlg)
873 if err != nil {
874 return c.sendAlert(alertInternalError)
875 }
876
877 signed := signedMessage(sigHash, serverSignatureContext, hs.transcript)
878 signOpts := crypto.SignerOpts(sigHash)
879 if sigType == signatureRSAPSS {
880 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
881 }
882 sig, err := hs.cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts)
883 if err != nil {
884 public := hs.cert.PrivateKey.(crypto.Signer).Public()
885 if rsaKey, ok := public.(*rsa.PublicKey); ok && sigType == signatureRSAPSS &&
886 rsaKey.N.BitLen()/8 < sigHash.Size()*2+2 {
887 c.sendAlert(alertHandshakeFailure)
888 } else {
889 c.sendAlert(alertInternalError)
890 }
891 return errors.New("tls: failed to sign handshake: " + err.Error())
892 }
893 certVerifyMsg.signature = sig
894
895 if _, err := hs.c.writeHandshakeRecord(certVerifyMsg, hs.transcript); err != nil {
896 return err
897 }
898
899 return nil
900 }
901
902 func (hs *serverHandshakeStateTLS13) sendServerFinished() error {
903 c := hs.c
904
905 finished := &finishedMsg{
906 verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
907 }
908
909 if _, err := hs.c.writeHandshakeRecord(finished, hs.transcript); err != nil {
910 return err
911 }
912
913
914
915 hs.masterSecret = hs.handshakeSecret.MasterSecret()
916
917 hs.trafficSecret = hs.masterSecret.ClientApplicationTrafficSecret(hs.transcript)
918 serverSecret := hs.masterSecret.ServerApplicationTrafficSecret(hs.transcript)
919 c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, serverSecret)
920
921 if c.quic != nil {
922 if c.hand.Len() != 0 {
923
924 c.sendAlert(alertUnexpectedMessage)
925 }
926 c.quicSetWriteSecret(QUICEncryptionLevelApplication, hs.suite.id, serverSecret)
927 }
928
929 err := c.config.writeKeyLog(keyLogLabelClientTraffic, hs.clientHello.random, hs.trafficSecret)
930 if err != nil {
931 c.sendAlert(alertInternalError)
932 return err
933 }
934 err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.clientHello.random, serverSecret)
935 if err != nil {
936 c.sendAlert(alertInternalError)
937 return err
938 }
939
940 c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript)
941
942
943
944
945 if !hs.requestClientCert() {
946 if err := hs.sendSessionTickets(); err != nil {
947 return err
948 }
949 }
950
951 return nil
952 }
953
954 func (hs *serverHandshakeStateTLS13) shouldSendSessionTickets() bool {
955 if hs.c.config.SessionTicketsDisabled {
956 return false
957 }
958
959
960 if hs.c.quic != nil {
961 return false
962 }
963
964
965 return slices.Contains(hs.clientHello.pskModes, pskModeDHE)
966 }
967
968 func (hs *serverHandshakeStateTLS13) sendSessionTickets() error {
969 c := hs.c
970
971 hs.clientFinished = hs.suite.finishedHash(c.in.trafficSecret, hs.transcript)
972 finishedMsg := &finishedMsg{
973 verifyData: hs.clientFinished,
974 }
975 if err := transcriptMsg(finishedMsg, hs.transcript); err != nil {
976 return err
977 }
978
979 c.resumptionSecret = hs.masterSecret.ResumptionMasterSecret(hs.transcript)
980
981 if !hs.shouldSendSessionTickets() {
982 return nil
983 }
984 return c.sendSessionTicket(false, nil)
985 }
986
987 func (c *Conn) sendSessionTicket(earlyData bool, extra [][]byte) error {
988 suite := cipherSuiteTLS13ByID(c.cipherSuite)
989 if suite == nil {
990 return errors.New("tls: internal error: unknown cipher suite")
991 }
992
993
994 psk := tls13.ExpandLabel(suite.hash.New, c.resumptionSecret, "resumption",
995 nil, suite.hash.Size())
996
997 m := new(newSessionTicketMsgTLS13)
998
999 state := c.sessionState()
1000 state.secret = psk
1001 state.EarlyData = earlyData
1002 state.Extra = extra
1003 if c.config.WrapSession != nil {
1004 var err error
1005 m.label, err = c.config.WrapSession(c.connectionStateLocked(), state)
1006 if err != nil {
1007 return err
1008 }
1009 } else {
1010 stateBytes, err := state.Bytes()
1011 if err != nil {
1012 c.sendAlert(alertInternalError)
1013 return err
1014 }
1015 m.label, err = c.config.encryptTicket(stateBytes, c.ticketKeys)
1016 if err != nil {
1017 return err
1018 }
1019 }
1020 m.lifetime = uint32(maxSessionTicketLifetime / time.Second)
1021
1022
1023
1024
1025 ageAdd := make([]byte, 4)
1026 if _, err := c.config.rand().Read(ageAdd); err != nil {
1027 return err
1028 }
1029 m.ageAdd = byteorder.LEUint32(ageAdd)
1030
1031 if earlyData {
1032
1033 m.maxEarlyData = 0xffffffff
1034 }
1035
1036 if _, err := c.writeHandshakeRecord(m, nil); err != nil {
1037 return err
1038 }
1039
1040 return nil
1041 }
1042
1043 func (hs *serverHandshakeStateTLS13) readClientCertificate() error {
1044 c := hs.c
1045
1046 if !hs.requestClientCert() {
1047
1048
1049 if c.config.VerifyConnection != nil {
1050 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
1051 c.sendAlert(alertBadCertificate)
1052 return err
1053 }
1054 }
1055 return nil
1056 }
1057
1058
1059
1060
1061 msg, err := c.readHandshake(hs.transcript)
1062 if err != nil {
1063 return err
1064 }
1065
1066 certMsg, ok := msg.(*certificateMsgTLS13)
1067 if !ok {
1068 c.sendAlert(alertUnexpectedMessage)
1069 return unexpectedMessageError(certMsg, msg)
1070 }
1071
1072 if err := c.processCertsFromClient(certMsg.certificate); err != nil {
1073 return err
1074 }
1075
1076 if c.config.VerifyConnection != nil {
1077 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
1078 c.sendAlert(alertBadCertificate)
1079 return err
1080 }
1081 }
1082
1083 if len(certMsg.certificate.Certificate) != 0 {
1084
1085
1086
1087 msg, err = c.readHandshake(nil)
1088 if err != nil {
1089 return err
1090 }
1091
1092 certVerify, ok := msg.(*certificateVerifyMsg)
1093 if !ok {
1094 c.sendAlert(alertUnexpectedMessage)
1095 return unexpectedMessageError(certVerify, msg)
1096 }
1097
1098
1099
1100
1101 if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms(c.vers)) {
1102 c.sendAlert(alertIllegalParameter)
1103 return errors.New("tls: client certificate used with invalid signature algorithm")
1104 }
1105 sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
1106 if err != nil {
1107 return c.sendAlert(alertInternalError)
1108 }
1109 if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
1110 return c.sendAlert(alertInternalError)
1111 }
1112 signed := signedMessage(sigHash, clientSignatureContext, hs.transcript)
1113 if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey,
1114 sigHash, signed, certVerify.signature); err != nil {
1115 c.sendAlert(alertDecryptError)
1116 return errors.New("tls: invalid signature by the client certificate: " + err.Error())
1117 }
1118 c.peerSigAlg = certVerify.signatureAlgorithm
1119
1120 if err := transcriptMsg(certVerify, hs.transcript); err != nil {
1121 return err
1122 }
1123 }
1124
1125
1126
1127 if err := hs.sendSessionTickets(); err != nil {
1128 return err
1129 }
1130
1131 return nil
1132 }
1133
1134 func (hs *serverHandshakeStateTLS13) readClientFinished() error {
1135 c := hs.c
1136
1137
1138 msg, err := c.readHandshake(nil)
1139 if err != nil {
1140 return err
1141 }
1142
1143 finished, ok := msg.(*finishedMsg)
1144 if !ok {
1145 c.sendAlert(alertUnexpectedMessage)
1146 return unexpectedMessageError(finished, msg)
1147 }
1148
1149 if !hmac.Equal(hs.clientFinished, finished.verifyData) {
1150 c.sendAlert(alertDecryptError)
1151 return errors.New("tls: invalid client finished hash")
1152 }
1153
1154 c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, hs.trafficSecret)
1155
1156 return nil
1157 }
1158
View as plain text