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