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