Source file
src/crypto/tls/handshake_client.go
1
2
3
4
5 package tls
6
7 import (
8 "bytes"
9 "context"
10 "crypto"
11 "crypto/ecdsa"
12 "crypto/ed25519"
13 "crypto/internal/hpke"
14 "crypto/internal/mlkem768"
15 "crypto/rsa"
16 "crypto/subtle"
17 "crypto/x509"
18 "errors"
19 "fmt"
20 "hash"
21 "internal/byteorder"
22 "internal/godebug"
23 "io"
24 "net"
25 "strconv"
26 "strings"
27 "time"
28 )
29
30 type clientHandshakeState struct {
31 c *Conn
32 ctx context.Context
33 serverHello *serverHelloMsg
34 hello *clientHelloMsg
35 suite *cipherSuite
36 finishedHash finishedHash
37 masterSecret []byte
38 session *SessionState
39 ticket []byte
40 }
41
42 var testingOnlyForceClientHelloSignatureAlgorithms []SignatureScheme
43
44 func (c *Conn) makeClientHello() (*clientHelloMsg, *keySharePrivateKeys, *echContext, error) {
45 config := c.config
46 if len(config.ServerName) == 0 && !config.InsecureSkipVerify {
47 return nil, nil, nil, errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
48 }
49
50 nextProtosLength := 0
51 for _, proto := range config.NextProtos {
52 if l := len(proto); l == 0 || l > 255 {
53 return nil, nil, nil, errors.New("tls: invalid NextProtos value")
54 } else {
55 nextProtosLength += 1 + l
56 }
57 }
58 if nextProtosLength > 0xffff {
59 return nil, nil, nil, errors.New("tls: NextProtos values too large")
60 }
61
62 supportedVersions := config.supportedVersions(roleClient)
63 if len(supportedVersions) == 0 {
64 return nil, nil, nil, errors.New("tls: no supported versions satisfy MinVersion and MaxVersion")
65 }
66 maxVersion := config.maxSupportedVersion(roleClient)
67
68 hello := &clientHelloMsg{
69 vers: maxVersion,
70 compressionMethods: []uint8{compressionNone},
71 random: make([]byte, 32),
72 extendedMasterSecret: true,
73 ocspStapling: true,
74 scts: true,
75 serverName: hostnameInSNI(config.ServerName),
76 supportedCurves: config.curvePreferences(maxVersion),
77 supportedPoints: []uint8{pointFormatUncompressed},
78 secureRenegotiationSupported: true,
79 alpnProtocols: config.NextProtos,
80 supportedVersions: supportedVersions,
81 }
82
83
84
85
86 if hello.vers > VersionTLS12 {
87 hello.vers = VersionTLS12
88 }
89
90 if c.handshakes > 0 {
91 hello.secureRenegotiation = c.clientFinished[:]
92 }
93
94 preferenceOrder := cipherSuitesPreferenceOrder
95 if !hasAESGCMHardwareSupport {
96 preferenceOrder = cipherSuitesPreferenceOrderNoAES
97 }
98 configCipherSuites := config.cipherSuites()
99 hello.cipherSuites = make([]uint16, 0, len(configCipherSuites))
100
101 for _, suiteId := range preferenceOrder {
102 suite := mutualCipherSuite(configCipherSuites, suiteId)
103 if suite == nil {
104 continue
105 }
106
107
108 if maxVersion < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
109 continue
110 }
111 hello.cipherSuites = append(hello.cipherSuites, suiteId)
112 }
113
114 _, err := io.ReadFull(config.rand(), hello.random)
115 if err != nil {
116 return nil, nil, nil, errors.New("tls: short read from Rand: " + err.Error())
117 }
118
119
120
121
122
123
124 if c.quic == nil {
125 hello.sessionId = make([]byte, 32)
126 if _, err := io.ReadFull(config.rand(), hello.sessionId); err != nil {
127 return nil, nil, nil, errors.New("tls: short read from Rand: " + err.Error())
128 }
129 }
130
131 if maxVersion >= VersionTLS12 {
132 hello.supportedSignatureAlgorithms = supportedSignatureAlgorithms()
133 }
134 if testingOnlyForceClientHelloSignatureAlgorithms != nil {
135 hello.supportedSignatureAlgorithms = testingOnlyForceClientHelloSignatureAlgorithms
136 }
137
138 var keyShareKeys *keySharePrivateKeys
139 if hello.supportedVersions[0] == VersionTLS13 {
140
141 if len(hello.supportedVersions) == 1 {
142 hello.cipherSuites = nil
143 }
144 if hasAESGCMHardwareSupport {
145 hello.cipherSuites = append(hello.cipherSuites, defaultCipherSuitesTLS13...)
146 } else {
147 hello.cipherSuites = append(hello.cipherSuites, defaultCipherSuitesTLS13NoAES...)
148 }
149
150 curveID := config.curvePreferences(maxVersion)[0]
151 keyShareKeys = &keySharePrivateKeys{curveID: curveID}
152 if curveID == x25519Kyber768Draft00 {
153 keyShareKeys.ecdhe, err = generateECDHEKey(config.rand(), X25519)
154 if err != nil {
155 return nil, nil, nil, err
156 }
157 seed := make([]byte, mlkem768.SeedSize)
158 if _, err := io.ReadFull(config.rand(), seed); err != nil {
159 return nil, nil, nil, err
160 }
161 keyShareKeys.kyber, err = mlkem768.NewKeyFromSeed(seed)
162 if err != nil {
163 return nil, nil, nil, err
164 }
165
166
167
168
169 hello.keyShares = []keyShare{
170 {group: x25519Kyber768Draft00, data: append(keyShareKeys.ecdhe.PublicKey().Bytes(),
171 keyShareKeys.kyber.EncapsulationKey()...)},
172 {group: X25519, data: keyShareKeys.ecdhe.PublicKey().Bytes()},
173 }
174 } else {
175 if _, ok := curveForCurveID(curveID); !ok {
176 return nil, nil, nil, errors.New("tls: CurvePreferences includes unsupported curve")
177 }
178 keyShareKeys.ecdhe, err = generateECDHEKey(config.rand(), curveID)
179 if err != nil {
180 return nil, nil, nil, err
181 }
182 hello.keyShares = []keyShare{{group: curveID, data: keyShareKeys.ecdhe.PublicKey().Bytes()}}
183 }
184 }
185
186 if c.quic != nil {
187 p, err := c.quicGetTransportParameters()
188 if err != nil {
189 return nil, nil, nil, err
190 }
191 if p == nil {
192 p = []byte{}
193 }
194 hello.quicTransportParameters = p
195 }
196
197 var ech *echContext
198 if c.config.EncryptedClientHelloConfigList != nil {
199 if c.config.MinVersion != 0 && c.config.MinVersion < VersionTLS13 {
200 return nil, nil, nil, errors.New("tls: MinVersion must be >= VersionTLS13 if EncryptedClientHelloConfigList is populated")
201 }
202 if c.config.MaxVersion != 0 && c.config.MaxVersion <= VersionTLS12 {
203 return nil, nil, nil, errors.New("tls: MaxVersion must be >= VersionTLS13 if EncryptedClientHelloConfigList is populated")
204 }
205 echConfigs, err := parseECHConfigList(c.config.EncryptedClientHelloConfigList)
206 if err != nil {
207 return nil, nil, nil, err
208 }
209 echConfig := pickECHConfig(echConfigs)
210 if echConfig == nil {
211 return nil, nil, nil, errors.New("tls: EncryptedClientHelloConfigList contains no valid configs")
212 }
213 ech = &echContext{config: echConfig}
214 hello.encryptedClientHello = []byte{1}
215
216
217
218 hello.supportedPoints = nil
219 hello.ticketSupported = false
220 hello.secureRenegotiationSupported = false
221 hello.extendedMasterSecret = false
222
223 echPK, err := hpke.ParseHPKEPublicKey(ech.config.KemID, ech.config.PublicKey)
224 if err != nil {
225 return nil, nil, nil, err
226 }
227 suite, err := pickECHCipherSuite(ech.config.SymmetricCipherSuite)
228 if err != nil {
229 return nil, nil, nil, err
230 }
231 ech.kdfID, ech.aeadID = suite.KDFID, suite.AEADID
232 info := append([]byte("tls ech\x00"), ech.config.raw...)
233 ech.encapsulatedKey, ech.hpkeContext, err = hpke.SetupSender(ech.config.KemID, suite.KDFID, suite.AEADID, echPK, info)
234 if err != nil {
235 return nil, nil, nil, err
236 }
237 }
238
239 return hello, keyShareKeys, ech, nil
240 }
241
242 type echContext struct {
243 config *echConfig
244 hpkeContext *hpke.Sender
245 encapsulatedKey []byte
246 innerHello *clientHelloMsg
247 innerTranscript hash.Hash
248 kdfID uint16
249 aeadID uint16
250 echRejected bool
251 }
252
253 func (c *Conn) clientHandshake(ctx context.Context) (err error) {
254 if c.config == nil {
255 c.config = defaultConfig()
256 }
257
258
259
260 c.didResume = false
261
262 hello, keyShareKeys, ech, err := c.makeClientHello()
263 if err != nil {
264 return err
265 }
266
267 session, earlySecret, binderKey, err := c.loadSession(hello)
268 if err != nil {
269 return err
270 }
271 if session != nil {
272 defer func() {
273
274
275
276
277
278
279 if err != nil {
280 if cacheKey := c.clientSessionCacheKey(); cacheKey != "" {
281 c.config.ClientSessionCache.Put(cacheKey, nil)
282 }
283 }
284 }()
285 }
286
287 if ech != nil {
288
289 ech.innerHello = hello.clone()
290
291
292
293 hello.serverName = string(ech.config.PublicName)
294
295 hello.random = make([]byte, 32)
296 _, err = io.ReadFull(c.config.rand(), hello.random)
297 if err != nil {
298 return errors.New("tls: short read from Rand: " + err.Error())
299 }
300
301
302
303
304
305 if err := computeAndUpdateOuterECHExtension(hello, ech.innerHello, ech, true); err != nil {
306 return err
307 }
308 }
309
310 c.serverName = hello.serverName
311
312 if _, err := c.writeHandshakeRecord(hello, nil); err != nil {
313 return err
314 }
315
316 if hello.earlyData {
317 suite := cipherSuiteTLS13ByID(session.cipherSuite)
318 transcript := suite.hash.New()
319 if err := transcriptMsg(hello, transcript); err != nil {
320 return err
321 }
322 earlyTrafficSecret := suite.deriveSecret(earlySecret, clientEarlyTrafficLabel, transcript)
323 c.quicSetWriteSecret(QUICEncryptionLevelEarly, suite.id, earlyTrafficSecret)
324 }
325
326
327 msg, err := c.readHandshake(nil)
328 if err != nil {
329 return err
330 }
331
332 serverHello, ok := msg.(*serverHelloMsg)
333 if !ok {
334 c.sendAlert(alertUnexpectedMessage)
335 return unexpectedMessageError(serverHello, msg)
336 }
337
338 if err := c.pickTLSVersion(serverHello); err != nil {
339 return err
340 }
341
342
343
344
345 maxVers := c.config.maxSupportedVersion(roleClient)
346 tls12Downgrade := string(serverHello.random[24:]) == downgradeCanaryTLS12
347 tls11Downgrade := string(serverHello.random[24:]) == downgradeCanaryTLS11
348 if maxVers == VersionTLS13 && c.vers <= VersionTLS12 && (tls12Downgrade || tls11Downgrade) ||
349 maxVers == VersionTLS12 && c.vers <= VersionTLS11 && tls11Downgrade {
350 c.sendAlert(alertIllegalParameter)
351 return errors.New("tls: downgrade attempt detected, possibly due to a MitM attack or a broken middlebox")
352 }
353
354 if c.vers == VersionTLS13 {
355 hs := &clientHandshakeStateTLS13{
356 c: c,
357 ctx: ctx,
358 serverHello: serverHello,
359 hello: hello,
360 keyShareKeys: keyShareKeys,
361 session: session,
362 earlySecret: earlySecret,
363 binderKey: binderKey,
364 echContext: ech,
365 }
366 return hs.handshake()
367 }
368
369 hs := &clientHandshakeState{
370 c: c,
371 ctx: ctx,
372 serverHello: serverHello,
373 hello: hello,
374 session: session,
375 }
376 return hs.handshake()
377 }
378
379 func (c *Conn) loadSession(hello *clientHelloMsg) (
380 session *SessionState, earlySecret, binderKey []byte, err error) {
381 if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil {
382 return nil, nil, nil, nil
383 }
384
385 echInner := bytes.Equal(hello.encryptedClientHello, []byte{1})
386
387
388
389 hello.ticketSupported = true && !echInner
390
391 if hello.supportedVersions[0] == VersionTLS13 {
392
393
394 hello.pskModes = []uint8{pskModeDHE}
395 }
396
397
398
399
400 if c.handshakes != 0 {
401 return nil, nil, nil, nil
402 }
403
404
405 cacheKey := c.clientSessionCacheKey()
406 if cacheKey == "" {
407 return nil, nil, nil, nil
408 }
409 cs, ok := c.config.ClientSessionCache.Get(cacheKey)
410 if !ok || cs == nil {
411 return nil, nil, nil, nil
412 }
413 session = cs.session
414
415
416 versOk := false
417 for _, v := range hello.supportedVersions {
418 if v == session.version {
419 versOk = true
420 break
421 }
422 }
423 if !versOk {
424 return nil, nil, nil, nil
425 }
426
427
428
429
430 if c.config.time().After(session.peerCertificates[0].NotAfter) {
431
432 c.config.ClientSessionCache.Put(cacheKey, nil)
433 return nil, nil, nil, nil
434 }
435 if !c.config.InsecureSkipVerify {
436 if len(session.verifiedChains) == 0 {
437
438 return nil, nil, nil, nil
439 }
440 if err := session.peerCertificates[0].VerifyHostname(c.config.ServerName); err != nil {
441 return nil, nil, nil, nil
442 }
443 }
444
445 if session.version != VersionTLS13 {
446
447
448 if mutualCipherSuite(hello.cipherSuites, session.cipherSuite) == nil {
449 return nil, nil, nil, nil
450 }
451
452 hello.sessionTicket = session.ticket
453 return
454 }
455
456
457 if c.config.time().After(time.Unix(int64(session.useBy), 0)) {
458 c.config.ClientSessionCache.Put(cacheKey, nil)
459 return nil, nil, nil, nil
460 }
461
462
463
464 cipherSuite := cipherSuiteTLS13ByID(session.cipherSuite)
465 if cipherSuite == nil {
466 return nil, nil, nil, nil
467 }
468 cipherSuiteOk := false
469 for _, offeredID := range hello.cipherSuites {
470 offeredSuite := cipherSuiteTLS13ByID(offeredID)
471 if offeredSuite != nil && offeredSuite.hash == cipherSuite.hash {
472 cipherSuiteOk = true
473 break
474 }
475 }
476 if !cipherSuiteOk {
477 return nil, nil, nil, nil
478 }
479
480 if c.quic != nil {
481 if c.quic.enableSessionEvents {
482 c.quicResumeSession(session)
483 }
484
485
486
487 if session.EarlyData && mutualCipherSuiteTLS13(hello.cipherSuites, session.cipherSuite) != nil {
488 for _, alpn := range hello.alpnProtocols {
489 if alpn == session.alpnProtocol {
490 hello.earlyData = true
491 break
492 }
493 }
494 }
495 }
496
497
498 ticketAge := c.config.time().Sub(time.Unix(int64(session.createdAt), 0))
499 identity := pskIdentity{
500 label: session.ticket,
501 obfuscatedTicketAge: uint32(ticketAge/time.Millisecond) + session.ageAdd,
502 }
503 hello.pskIdentities = []pskIdentity{identity}
504 hello.pskBinders = [][]byte{make([]byte, cipherSuite.hash.Size())}
505
506
507 earlySecret = cipherSuite.extract(session.secret, nil)
508 binderKey = cipherSuite.deriveSecret(earlySecret, resumptionBinderLabel, nil)
509 transcript := cipherSuite.hash.New()
510 if err := computeAndUpdatePSK(hello, binderKey, transcript, cipherSuite.finishedHash); err != nil {
511 return nil, nil, nil, err
512 }
513
514 return
515 }
516
517 func (c *Conn) pickTLSVersion(serverHello *serverHelloMsg) error {
518 peerVersion := serverHello.vers
519 if serverHello.supportedVersion != 0 {
520 peerVersion = serverHello.supportedVersion
521 }
522
523 vers, ok := c.config.mutualVersion(roleClient, []uint16{peerVersion})
524 if !ok {
525 c.sendAlert(alertProtocolVersion)
526 return fmt.Errorf("tls: server selected unsupported protocol version %x", peerVersion)
527 }
528
529 c.vers = vers
530 c.haveVers = true
531 c.in.version = vers
532 c.out.version = vers
533
534 return nil
535 }
536
537
538
539 func (hs *clientHandshakeState) handshake() error {
540 c := hs.c
541
542 isResume, err := hs.processServerHello()
543 if err != nil {
544 return err
545 }
546
547 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
548
549
550
551
552
553 if isResume || (len(c.config.Certificates) == 0 && c.config.GetClientCertificate == nil) {
554 hs.finishedHash.discardHandshakeBuffer()
555 }
556
557 if err := transcriptMsg(hs.hello, &hs.finishedHash); err != nil {
558 return err
559 }
560 if err := transcriptMsg(hs.serverHello, &hs.finishedHash); err != nil {
561 return err
562 }
563
564 c.buffering = true
565 c.didResume = isResume
566 if isResume {
567 if err := hs.establishKeys(); err != nil {
568 return err
569 }
570 if err := hs.readSessionTicket(); err != nil {
571 return err
572 }
573 if err := hs.readFinished(c.serverFinished[:]); err != nil {
574 return err
575 }
576 c.clientFinishedIsFirst = false
577
578
579
580 if c.config.VerifyConnection != nil {
581 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
582 c.sendAlert(alertBadCertificate)
583 return err
584 }
585 }
586 if err := hs.sendFinished(c.clientFinished[:]); err != nil {
587 return err
588 }
589 if _, err := c.flush(); err != nil {
590 return err
591 }
592 } else {
593 if err := hs.doFullHandshake(); err != nil {
594 return err
595 }
596 if err := hs.establishKeys(); err != nil {
597 return err
598 }
599 if err := hs.sendFinished(c.clientFinished[:]); err != nil {
600 return err
601 }
602 if _, err := c.flush(); err != nil {
603 return err
604 }
605 c.clientFinishedIsFirst = true
606 if err := hs.readSessionTicket(); err != nil {
607 return err
608 }
609 if err := hs.readFinished(c.serverFinished[:]); err != nil {
610 return err
611 }
612 }
613 if err := hs.saveSessionTicket(); err != nil {
614 return err
615 }
616
617 c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random)
618 c.isHandshakeComplete.Store(true)
619
620 return nil
621 }
622
623 func (hs *clientHandshakeState) pickCipherSuite() error {
624 if hs.suite = mutualCipherSuite(hs.hello.cipherSuites, hs.serverHello.cipherSuite); hs.suite == nil {
625 hs.c.sendAlert(alertHandshakeFailure)
626 return errors.New("tls: server chose an unconfigured cipher suite")
627 }
628
629 if hs.c.config.CipherSuites == nil && !needFIPS() && rsaKexCiphers[hs.suite.id] {
630 tlsrsakex.Value()
631 tlsrsakex.IncNonDefault()
632 }
633 if hs.c.config.CipherSuites == nil && !needFIPS() && tdesCiphers[hs.suite.id] {
634 tls3des.Value()
635 tls3des.IncNonDefault()
636 }
637
638 hs.c.cipherSuite = hs.suite.id
639 return nil
640 }
641
642 func (hs *clientHandshakeState) doFullHandshake() error {
643 c := hs.c
644
645 msg, err := c.readHandshake(&hs.finishedHash)
646 if err != nil {
647 return err
648 }
649 certMsg, ok := msg.(*certificateMsg)
650 if !ok || len(certMsg.certificates) == 0 {
651 c.sendAlert(alertUnexpectedMessage)
652 return unexpectedMessageError(certMsg, msg)
653 }
654
655 msg, err = c.readHandshake(&hs.finishedHash)
656 if err != nil {
657 return err
658 }
659
660 cs, ok := msg.(*certificateStatusMsg)
661 if ok {
662
663
664
665 if !hs.serverHello.ocspStapling {
666
667
668
669
670 c.sendAlert(alertUnexpectedMessage)
671 return errors.New("tls: received unexpected CertificateStatus message")
672 }
673
674 c.ocspResponse = cs.response
675
676 msg, err = c.readHandshake(&hs.finishedHash)
677 if err != nil {
678 return err
679 }
680 }
681
682 if c.handshakes == 0 {
683
684
685 if err := c.verifyServerCertificate(certMsg.certificates); err != nil {
686 return err
687 }
688 } else {
689
690
691
692
693
694
695 if !bytes.Equal(c.peerCertificates[0].Raw, certMsg.certificates[0]) {
696 c.sendAlert(alertBadCertificate)
697 return errors.New("tls: server's identity changed during renegotiation")
698 }
699 }
700
701 keyAgreement := hs.suite.ka(c.vers)
702
703 skx, ok := msg.(*serverKeyExchangeMsg)
704 if ok {
705 err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, c.peerCertificates[0], skx)
706 if err != nil {
707 c.sendAlert(alertUnexpectedMessage)
708 return err
709 }
710 if len(skx.key) >= 3 && skx.key[0] == 3 {
711 c.curveID = CurveID(byteorder.BeUint16(skx.key[1:]))
712 }
713
714 msg, err = c.readHandshake(&hs.finishedHash)
715 if err != nil {
716 return err
717 }
718 }
719
720 var chainToSend *Certificate
721 var certRequested bool
722 certReq, ok := msg.(*certificateRequestMsg)
723 if ok {
724 certRequested = true
725
726 cri := certificateRequestInfoFromMsg(hs.ctx, c.vers, certReq)
727 if chainToSend, err = c.getClientCertificate(cri); err != nil {
728 c.sendAlert(alertInternalError)
729 return err
730 }
731
732 msg, err = c.readHandshake(&hs.finishedHash)
733 if err != nil {
734 return err
735 }
736 }
737
738 shd, ok := msg.(*serverHelloDoneMsg)
739 if !ok {
740 c.sendAlert(alertUnexpectedMessage)
741 return unexpectedMessageError(shd, msg)
742 }
743
744
745
746
747 if certRequested {
748 certMsg = new(certificateMsg)
749 certMsg.certificates = chainToSend.Certificate
750 if _, err := hs.c.writeHandshakeRecord(certMsg, &hs.finishedHash); err != nil {
751 return err
752 }
753 }
754
755 preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, c.peerCertificates[0])
756 if err != nil {
757 c.sendAlert(alertInternalError)
758 return err
759 }
760 if ckx != nil {
761 if _, err := hs.c.writeHandshakeRecord(ckx, &hs.finishedHash); err != nil {
762 return err
763 }
764 }
765
766 if hs.serverHello.extendedMasterSecret {
767 c.extMasterSecret = true
768 hs.masterSecret = extMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret,
769 hs.finishedHash.Sum())
770 } else {
771 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret,
772 hs.hello.random, hs.serverHello.random)
773 }
774 if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.hello.random, hs.masterSecret); err != nil {
775 c.sendAlert(alertInternalError)
776 return errors.New("tls: failed to write to key log: " + err.Error())
777 }
778
779 if chainToSend != nil && len(chainToSend.Certificate) > 0 {
780 certVerify := &certificateVerifyMsg{}
781
782 key, ok := chainToSend.PrivateKey.(crypto.Signer)
783 if !ok {
784 c.sendAlert(alertInternalError)
785 return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey)
786 }
787
788 var sigType uint8
789 var sigHash crypto.Hash
790 if c.vers >= VersionTLS12 {
791 signatureAlgorithm, err := selectSignatureScheme(c.vers, chainToSend, certReq.supportedSignatureAlgorithms)
792 if err != nil {
793 c.sendAlert(alertIllegalParameter)
794 return err
795 }
796 sigType, sigHash, err = typeAndHashFromSignatureScheme(signatureAlgorithm)
797 if err != nil {
798 return c.sendAlert(alertInternalError)
799 }
800 certVerify.hasSignatureAlgorithm = true
801 certVerify.signatureAlgorithm = signatureAlgorithm
802 } else {
803 sigType, sigHash, err = legacyTypeAndHashFromPublicKey(key.Public())
804 if err != nil {
805 c.sendAlert(alertIllegalParameter)
806 return err
807 }
808 }
809
810 signed := hs.finishedHash.hashForClientCertificate(sigType, sigHash)
811 signOpts := crypto.SignerOpts(sigHash)
812 if sigType == signatureRSAPSS {
813 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
814 }
815 certVerify.signature, err = key.Sign(c.config.rand(), signed, signOpts)
816 if err != nil {
817 c.sendAlert(alertInternalError)
818 return err
819 }
820
821 if _, err := hs.c.writeHandshakeRecord(certVerify, &hs.finishedHash); err != nil {
822 return err
823 }
824 }
825
826 hs.finishedHash.discardHandshakeBuffer()
827
828 return nil
829 }
830
831 func (hs *clientHandshakeState) establishKeys() error {
832 c := hs.c
833
834 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
835 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
836 var clientCipher, serverCipher any
837 var clientHash, serverHash hash.Hash
838 if hs.suite.cipher != nil {
839 clientCipher = hs.suite.cipher(clientKey, clientIV, false )
840 clientHash = hs.suite.mac(clientMAC)
841 serverCipher = hs.suite.cipher(serverKey, serverIV, true )
842 serverHash = hs.suite.mac(serverMAC)
843 } else {
844 clientCipher = hs.suite.aead(clientKey, clientIV)
845 serverCipher = hs.suite.aead(serverKey, serverIV)
846 }
847
848 c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
849 c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
850 return nil
851 }
852
853 func (hs *clientHandshakeState) serverResumedSession() bool {
854
855
856 return hs.session != nil && hs.hello.sessionId != nil &&
857 bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
858 }
859
860 func (hs *clientHandshakeState) processServerHello() (bool, error) {
861 c := hs.c
862
863 if err := hs.pickCipherSuite(); err != nil {
864 return false, err
865 }
866
867 if hs.serverHello.compressionMethod != compressionNone {
868 c.sendAlert(alertUnexpectedMessage)
869 return false, errors.New("tls: server selected unsupported compression format")
870 }
871
872 if c.handshakes == 0 && hs.serverHello.secureRenegotiationSupported {
873 c.secureRenegotiation = true
874 if len(hs.serverHello.secureRenegotiation) != 0 {
875 c.sendAlert(alertHandshakeFailure)
876 return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
877 }
878 }
879
880 if c.handshakes > 0 && c.secureRenegotiation {
881 var expectedSecureRenegotiation [24]byte
882 copy(expectedSecureRenegotiation[:], c.clientFinished[:])
883 copy(expectedSecureRenegotiation[12:], c.serverFinished[:])
884 if !bytes.Equal(hs.serverHello.secureRenegotiation, expectedSecureRenegotiation[:]) {
885 c.sendAlert(alertHandshakeFailure)
886 return false, errors.New("tls: incorrect renegotiation extension contents")
887 }
888 }
889
890 if err := checkALPN(hs.hello.alpnProtocols, hs.serverHello.alpnProtocol, false); err != nil {
891 c.sendAlert(alertUnsupportedExtension)
892 return false, err
893 }
894 c.clientProtocol = hs.serverHello.alpnProtocol
895
896 c.scts = hs.serverHello.scts
897
898 if !hs.serverResumedSession() {
899 return false, nil
900 }
901
902 if hs.session.version != c.vers {
903 c.sendAlert(alertHandshakeFailure)
904 return false, errors.New("tls: server resumed a session with a different version")
905 }
906
907 if hs.session.cipherSuite != hs.suite.id {
908 c.sendAlert(alertHandshakeFailure)
909 return false, errors.New("tls: server resumed a session with a different cipher suite")
910 }
911
912
913 if hs.session.extMasterSecret != hs.serverHello.extendedMasterSecret {
914 c.sendAlert(alertHandshakeFailure)
915 return false, errors.New("tls: server resumed a session with a different EMS extension")
916 }
917
918
919 hs.masterSecret = hs.session.secret
920 c.extMasterSecret = hs.session.extMasterSecret
921 c.peerCertificates = hs.session.peerCertificates
922 c.activeCertHandles = hs.c.activeCertHandles
923 c.verifiedChains = hs.session.verifiedChains
924 c.ocspResponse = hs.session.ocspResponse
925
926
927 if len(c.scts) == 0 && len(hs.session.scts) != 0 {
928 c.scts = hs.session.scts
929 }
930
931 return true, nil
932 }
933
934
935
936 func checkALPN(clientProtos []string, serverProto string, quic bool) error {
937 if serverProto == "" {
938 if quic && len(clientProtos) > 0 {
939
940 return errors.New("tls: server did not select an ALPN protocol")
941 }
942 return nil
943 }
944 if len(clientProtos) == 0 {
945 return errors.New("tls: server advertised unrequested ALPN extension")
946 }
947 for _, proto := range clientProtos {
948 if proto == serverProto {
949 return nil
950 }
951 }
952 return errors.New("tls: server selected unadvertised ALPN protocol")
953 }
954
955 func (hs *clientHandshakeState) readFinished(out []byte) error {
956 c := hs.c
957
958 if err := c.readChangeCipherSpec(); err != nil {
959 return err
960 }
961
962
963
964
965 msg, err := c.readHandshake(nil)
966 if err != nil {
967 return err
968 }
969 serverFinished, ok := msg.(*finishedMsg)
970 if !ok {
971 c.sendAlert(alertUnexpectedMessage)
972 return unexpectedMessageError(serverFinished, msg)
973 }
974
975 verify := hs.finishedHash.serverSum(hs.masterSecret)
976 if len(verify) != len(serverFinished.verifyData) ||
977 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
978 c.sendAlert(alertHandshakeFailure)
979 return errors.New("tls: server's Finished message was incorrect")
980 }
981
982 if err := transcriptMsg(serverFinished, &hs.finishedHash); err != nil {
983 return err
984 }
985
986 copy(out, verify)
987 return nil
988 }
989
990 func (hs *clientHandshakeState) readSessionTicket() error {
991 if !hs.serverHello.ticketSupported {
992 return nil
993 }
994 c := hs.c
995
996 if !hs.hello.ticketSupported {
997 c.sendAlert(alertIllegalParameter)
998 return errors.New("tls: server sent unrequested session ticket")
999 }
1000
1001 msg, err := c.readHandshake(&hs.finishedHash)
1002 if err != nil {
1003 return err
1004 }
1005 sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
1006 if !ok {
1007 c.sendAlert(alertUnexpectedMessage)
1008 return unexpectedMessageError(sessionTicketMsg, msg)
1009 }
1010
1011 hs.ticket = sessionTicketMsg.ticket
1012 return nil
1013 }
1014
1015 func (hs *clientHandshakeState) saveSessionTicket() error {
1016 if hs.ticket == nil {
1017 return nil
1018 }
1019 c := hs.c
1020
1021 cacheKey := c.clientSessionCacheKey()
1022 if cacheKey == "" {
1023 return nil
1024 }
1025
1026 session := c.sessionState()
1027 session.secret = hs.masterSecret
1028 session.ticket = hs.ticket
1029
1030 cs := &ClientSessionState{session: session}
1031 c.config.ClientSessionCache.Put(cacheKey, cs)
1032 return nil
1033 }
1034
1035 func (hs *clientHandshakeState) sendFinished(out []byte) error {
1036 c := hs.c
1037
1038 if err := c.writeChangeCipherRecord(); err != nil {
1039 return err
1040 }
1041
1042 finished := new(finishedMsg)
1043 finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
1044 if _, err := hs.c.writeHandshakeRecord(finished, &hs.finishedHash); err != nil {
1045 return err
1046 }
1047 copy(out, finished.verifyData)
1048 return nil
1049 }
1050
1051
1052
1053 const defaultMaxRSAKeySize = 8192
1054
1055 var tlsmaxrsasize = godebug.New("tlsmaxrsasize")
1056
1057 func checkKeySize(n int) (max int, ok bool) {
1058 if v := tlsmaxrsasize.Value(); v != "" {
1059 if max, err := strconv.Atoi(v); err == nil {
1060 if (n <= max) != (n <= defaultMaxRSAKeySize) {
1061 tlsmaxrsasize.IncNonDefault()
1062 }
1063 return max, n <= max
1064 }
1065 }
1066 return defaultMaxRSAKeySize, n <= defaultMaxRSAKeySize
1067 }
1068
1069
1070
1071 func (c *Conn) verifyServerCertificate(certificates [][]byte) error {
1072 activeHandles := make([]*activeCert, len(certificates))
1073 certs := make([]*x509.Certificate, len(certificates))
1074 for i, asn1Data := range certificates {
1075 cert, err := globalCertCache.newCert(asn1Data)
1076 if err != nil {
1077 c.sendAlert(alertBadCertificate)
1078 return errors.New("tls: failed to parse certificate from server: " + err.Error())
1079 }
1080 if cert.cert.PublicKeyAlgorithm == x509.RSA {
1081 n := cert.cert.PublicKey.(*rsa.PublicKey).N.BitLen()
1082 if max, ok := checkKeySize(n); !ok {
1083 c.sendAlert(alertBadCertificate)
1084 return fmt.Errorf("tls: server sent certificate containing RSA key larger than %d bits", max)
1085 }
1086 }
1087 activeHandles[i] = cert
1088 certs[i] = cert.cert
1089 }
1090
1091 echRejected := c.config.EncryptedClientHelloConfigList != nil && !c.echAccepted
1092 if echRejected {
1093 if c.config.EncryptedClientHelloRejectionVerify != nil {
1094 if err := c.config.EncryptedClientHelloRejectionVerify(c.connectionStateLocked()); err != nil {
1095 c.sendAlert(alertBadCertificate)
1096 return err
1097 }
1098 } else {
1099 opts := x509.VerifyOptions{
1100 Roots: c.config.RootCAs,
1101 CurrentTime: c.config.time(),
1102 DNSName: c.serverName,
1103 Intermediates: x509.NewCertPool(),
1104 }
1105
1106 for _, cert := range certs[1:] {
1107 opts.Intermediates.AddCert(cert)
1108 }
1109 var err error
1110 c.verifiedChains, err = certs[0].Verify(opts)
1111 if err != nil {
1112 c.sendAlert(alertBadCertificate)
1113 return &CertificateVerificationError{UnverifiedCertificates: certs, Err: err}
1114 }
1115 }
1116 } else if !c.config.InsecureSkipVerify {
1117 opts := x509.VerifyOptions{
1118 Roots: c.config.RootCAs,
1119 CurrentTime: c.config.time(),
1120 DNSName: c.config.ServerName,
1121 Intermediates: x509.NewCertPool(),
1122 }
1123
1124 for _, cert := range certs[1:] {
1125 opts.Intermediates.AddCert(cert)
1126 }
1127 var err error
1128 c.verifiedChains, err = certs[0].Verify(opts)
1129 if err != nil {
1130 c.sendAlert(alertBadCertificate)
1131 return &CertificateVerificationError{UnverifiedCertificates: certs, Err: err}
1132 }
1133 }
1134
1135 switch certs[0].PublicKey.(type) {
1136 case *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey:
1137 break
1138 default:
1139 c.sendAlert(alertUnsupportedCertificate)
1140 return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
1141 }
1142
1143 c.activeCertHandles = activeHandles
1144 c.peerCertificates = certs
1145
1146 if c.config.VerifyPeerCertificate != nil && !echRejected {
1147 if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
1148 c.sendAlert(alertBadCertificate)
1149 return err
1150 }
1151 }
1152
1153 if c.config.VerifyConnection != nil && !echRejected {
1154 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
1155 c.sendAlert(alertBadCertificate)
1156 return err
1157 }
1158 }
1159
1160 return nil
1161 }
1162
1163
1164
1165 func certificateRequestInfoFromMsg(ctx context.Context, vers uint16, certReq *certificateRequestMsg) *CertificateRequestInfo {
1166 cri := &CertificateRequestInfo{
1167 AcceptableCAs: certReq.certificateAuthorities,
1168 Version: vers,
1169 ctx: ctx,
1170 }
1171
1172 var rsaAvail, ecAvail bool
1173 for _, certType := range certReq.certificateTypes {
1174 switch certType {
1175 case certTypeRSASign:
1176 rsaAvail = true
1177 case certTypeECDSASign:
1178 ecAvail = true
1179 }
1180 }
1181
1182 if !certReq.hasSignatureAlgorithm {
1183
1184
1185
1186
1187
1188 switch {
1189 case rsaAvail && ecAvail:
1190 cri.SignatureSchemes = []SignatureScheme{
1191 ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512,
1192 PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1,
1193 }
1194 case rsaAvail:
1195 cri.SignatureSchemes = []SignatureScheme{
1196 PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1,
1197 }
1198 case ecAvail:
1199 cri.SignatureSchemes = []SignatureScheme{
1200 ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512,
1201 }
1202 }
1203 return cri
1204 }
1205
1206
1207
1208 cri.SignatureSchemes = make([]SignatureScheme, 0, len(certReq.supportedSignatureAlgorithms))
1209 for _, sigScheme := range certReq.supportedSignatureAlgorithms {
1210 sigType, _, err := typeAndHashFromSignatureScheme(sigScheme)
1211 if err != nil {
1212 continue
1213 }
1214 switch sigType {
1215 case signatureECDSA, signatureEd25519:
1216 if ecAvail {
1217 cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme)
1218 }
1219 case signatureRSAPSS, signaturePKCS1v15:
1220 if rsaAvail {
1221 cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme)
1222 }
1223 }
1224 }
1225
1226 return cri
1227 }
1228
1229 func (c *Conn) getClientCertificate(cri *CertificateRequestInfo) (*Certificate, error) {
1230 if c.config.GetClientCertificate != nil {
1231 return c.config.GetClientCertificate(cri)
1232 }
1233
1234 for _, chain := range c.config.Certificates {
1235 if err := cri.SupportsCertificate(&chain); err != nil {
1236 continue
1237 }
1238 return &chain, nil
1239 }
1240
1241
1242 return new(Certificate), nil
1243 }
1244
1245
1246
1247 func (c *Conn) clientSessionCacheKey() string {
1248 if len(c.config.ServerName) > 0 {
1249 return c.config.ServerName
1250 }
1251 if c.conn != nil {
1252 return c.conn.RemoteAddr().String()
1253 }
1254 return ""
1255 }
1256
1257
1258
1259
1260 func hostnameInSNI(name string) string {
1261 host := name
1262 if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' {
1263 host = host[1 : len(host)-1]
1264 }
1265 if i := strings.LastIndex(host, "%"); i > 0 {
1266 host = host[:i]
1267 }
1268 if net.ParseIP(host) != nil {
1269 return ""
1270 }
1271 for len(name) > 0 && name[len(name)-1] == '.' {
1272 name = name[:len(name)-1]
1273 }
1274 return name
1275 }
1276
1277 func computeAndUpdatePSK(m *clientHelloMsg, binderKey []byte, transcript hash.Hash, finishedHash func([]byte, hash.Hash) []byte) error {
1278 helloBytes, err := m.marshalWithoutBinders()
1279 if err != nil {
1280 return err
1281 }
1282 transcript.Write(helloBytes)
1283 pskBinders := [][]byte{finishedHash(binderKey, transcript)}
1284 return m.updateBinders(pskBinders)
1285 }
1286
View as plain text