Source file
src/crypto/tls/handshake_server.go
1
2
3
4
5 package tls
6
7 import (
8 "context"
9 "crypto"
10 "crypto/ecdsa"
11 "crypto/ed25519"
12 "crypto/rsa"
13 "crypto/subtle"
14 "crypto/x509"
15 "errors"
16 "fmt"
17 "hash"
18 "io"
19 "sync/atomic"
20 "time"
21 )
22
23
24
25 type serverHandshakeState struct {
26 c *Conn
27 ctx context.Context
28 clientHello *clientHelloMsg
29 hello *serverHelloMsg
30 suite *cipherSuite
31 ecdheOk bool
32 ecSignOk bool
33 rsaDecryptOk bool
34 rsaSignOk bool
35 sessionState *sessionState
36 finishedHash finishedHash
37 masterSecret []byte
38 cert *Certificate
39 }
40
41
42 func (c *Conn) serverHandshake(ctx context.Context) error {
43 clientHello, err := c.readClientHello(ctx)
44 if err != nil {
45 return err
46 }
47
48 if c.vers == VersionTLS13 {
49 hs := serverHandshakeStateTLS13{
50 c: c,
51 ctx: ctx,
52 clientHello: clientHello,
53 }
54 return hs.handshake()
55 }
56
57 hs := serverHandshakeState{
58 c: c,
59 ctx: ctx,
60 clientHello: clientHello,
61 }
62 return hs.handshake()
63 }
64
65 func (hs *serverHandshakeState) handshake() error {
66 c := hs.c
67
68 if err := hs.processClientHello(); err != nil {
69 return err
70 }
71
72
73 c.buffering = true
74 if hs.checkForResumption() {
75
76 c.didResume = true
77 if err := hs.doResumeHandshake(); err != nil {
78 return err
79 }
80 if err := hs.establishKeys(); err != nil {
81 return err
82 }
83 if err := hs.sendSessionTicket(); err != nil {
84 return err
85 }
86 if err := hs.sendFinished(c.serverFinished[:]); err != nil {
87 return err
88 }
89 if _, err := c.flush(); err != nil {
90 return err
91 }
92 c.clientFinishedIsFirst = false
93 if err := hs.readFinished(nil); err != nil {
94 return err
95 }
96 } else {
97
98
99 if err := hs.pickCipherSuite(); err != nil {
100 return err
101 }
102 if err := hs.doFullHandshake(); err != nil {
103 return err
104 }
105 if err := hs.establishKeys(); err != nil {
106 return err
107 }
108 if err := hs.readFinished(c.clientFinished[:]); err != nil {
109 return err
110 }
111 c.clientFinishedIsFirst = true
112 c.buffering = true
113 if err := hs.sendSessionTicket(); err != nil {
114 return err
115 }
116 if err := hs.sendFinished(nil); err != nil {
117 return err
118 }
119 if _, err := c.flush(); err != nil {
120 return err
121 }
122 }
123
124 c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random)
125 atomic.StoreUint32(&c.handshakeStatus, 1)
126
127 return nil
128 }
129
130
131 func (c *Conn) readClientHello(ctx context.Context) (*clientHelloMsg, error) {
132 msg, err := c.readHandshake()
133 if err != nil {
134 return nil, err
135 }
136 clientHello, ok := msg.(*clientHelloMsg)
137 if !ok {
138 c.sendAlert(alertUnexpectedMessage)
139 return nil, unexpectedMessageError(clientHello, msg)
140 }
141
142 var configForClient *Config
143 originalConfig := c.config
144 if c.config.GetConfigForClient != nil {
145 chi := clientHelloInfo(ctx, c, clientHello)
146 if configForClient, err = c.config.GetConfigForClient(chi); err != nil {
147 c.sendAlert(alertInternalError)
148 return nil, err
149 } else if configForClient != nil {
150 c.config = configForClient
151 }
152 }
153 c.ticketKeys = originalConfig.ticketKeys(configForClient)
154
155 clientVersions := clientHello.supportedVersions
156 if len(clientHello.supportedVersions) == 0 {
157 clientVersions = supportedVersionsFromMax(clientHello.vers)
158 }
159 c.vers, ok = c.config.mutualVersion(roleServer, clientVersions)
160 if !ok {
161 c.sendAlert(alertProtocolVersion)
162 return nil, fmt.Errorf("tls: client offered only unsupported versions: %x", clientVersions)
163 }
164 c.haveVers = true
165 c.in.version = c.vers
166 c.out.version = c.vers
167
168 return clientHello, nil
169 }
170
171 func (hs *serverHandshakeState) processClientHello() error {
172 c := hs.c
173
174 hs.hello = new(serverHelloMsg)
175 hs.hello.vers = c.vers
176
177 foundCompression := false
178
179 for _, compression := range hs.clientHello.compressionMethods {
180 if compression == compressionNone {
181 foundCompression = true
182 break
183 }
184 }
185
186 if !foundCompression {
187 c.sendAlert(alertHandshakeFailure)
188 return errors.New("tls: client does not support uncompressed connections")
189 }
190
191 hs.hello.random = make([]byte, 32)
192 serverRandom := hs.hello.random
193
194 maxVers := c.config.maxSupportedVersion(roleServer)
195 if maxVers >= VersionTLS12 && c.vers < maxVers || testingOnlyForceDowngradeCanary {
196 if c.vers == VersionTLS12 {
197 copy(serverRandom[24:], downgradeCanaryTLS12)
198 } else {
199 copy(serverRandom[24:], downgradeCanaryTLS11)
200 }
201 serverRandom = serverRandom[:24]
202 }
203 _, err := io.ReadFull(c.config.rand(), serverRandom)
204 if err != nil {
205 c.sendAlert(alertInternalError)
206 return err
207 }
208
209 if len(hs.clientHello.secureRenegotiation) != 0 {
210 c.sendAlert(alertHandshakeFailure)
211 return errors.New("tls: initial handshake had non-empty renegotiation extension")
212 }
213
214 hs.hello.secureRenegotiationSupported = hs.clientHello.secureRenegotiationSupported
215 hs.hello.compressionMethod = compressionNone
216 if len(hs.clientHello.serverName) > 0 {
217 c.serverName = hs.clientHello.serverName
218 }
219
220 selectedProto, err := negotiateALPN(c.config.NextProtos, hs.clientHello.alpnProtocols)
221 if err != nil {
222 c.sendAlert(alertNoApplicationProtocol)
223 return err
224 }
225 hs.hello.alpnProtocol = selectedProto
226 c.clientProtocol = selectedProto
227
228 hs.cert, err = c.config.getCertificate(clientHelloInfo(hs.ctx, c, hs.clientHello))
229 if err != nil {
230 if err == errNoCertificates {
231 c.sendAlert(alertUnrecognizedName)
232 } else {
233 c.sendAlert(alertInternalError)
234 }
235 return err
236 }
237 if hs.clientHello.scts {
238 hs.hello.scts = hs.cert.SignedCertificateTimestamps
239 }
240
241 hs.ecdheOk = supportsECDHE(c.config, hs.clientHello.supportedCurves, hs.clientHello.supportedPoints)
242
243 if hs.ecdheOk {
244
245
246
247
248
249 hs.hello.supportedPoints = []uint8{pointFormatUncompressed}
250 }
251
252 if priv, ok := hs.cert.PrivateKey.(crypto.Signer); ok {
253 switch priv.Public().(type) {
254 case *ecdsa.PublicKey:
255 hs.ecSignOk = true
256 case ed25519.PublicKey:
257 hs.ecSignOk = true
258 case *rsa.PublicKey:
259 hs.rsaSignOk = true
260 default:
261 c.sendAlert(alertInternalError)
262 return fmt.Errorf("tls: unsupported signing key type (%T)", priv.Public())
263 }
264 }
265 if priv, ok := hs.cert.PrivateKey.(crypto.Decrypter); ok {
266 switch priv.Public().(type) {
267 case *rsa.PublicKey:
268 hs.rsaDecryptOk = true
269 default:
270 c.sendAlert(alertInternalError)
271 return fmt.Errorf("tls: unsupported decryption key type (%T)", priv.Public())
272 }
273 }
274
275 return nil
276 }
277
278
279
280
281 func negotiateALPN(serverProtos, clientProtos []string) (string, error) {
282 if len(serverProtos) == 0 || len(clientProtos) == 0 {
283 return "", nil
284 }
285 var http11fallback bool
286 for _, s := range serverProtos {
287 for _, c := range clientProtos {
288 if s == c {
289 return s, nil
290 }
291 if s == "h2" && c == "http/1.1" {
292 http11fallback = true
293 }
294 }
295 }
296
297
298
299
300 if http11fallback {
301 return "", nil
302 }
303 return "", fmt.Errorf("tls: client requested unsupported application protocols (%s)", clientProtos)
304 }
305
306
307
308 func supportsECDHE(c *Config, supportedCurves []CurveID, supportedPoints []uint8) bool {
309 supportsCurve := false
310 for _, curve := range supportedCurves {
311 if c.supportsCurve(curve) {
312 supportsCurve = true
313 break
314 }
315 }
316
317 supportsPointFormat := false
318 for _, pointFormat := range supportedPoints {
319 if pointFormat == pointFormatUncompressed {
320 supportsPointFormat = true
321 break
322 }
323 }
324
325 return supportsCurve && supportsPointFormat
326 }
327
328 func (hs *serverHandshakeState) pickCipherSuite() error {
329 c := hs.c
330
331 preferenceOrder := cipherSuitesPreferenceOrder
332 if !hasAESGCMHardwareSupport || !aesgcmPreferred(hs.clientHello.cipherSuites) {
333 preferenceOrder = cipherSuitesPreferenceOrderNoAES
334 }
335
336 configCipherSuites := c.config.cipherSuites()
337 preferenceList := make([]uint16, 0, len(configCipherSuites))
338 for _, suiteID := range preferenceOrder {
339 for _, id := range configCipherSuites {
340 if id == suiteID {
341 preferenceList = append(preferenceList, id)
342 break
343 }
344 }
345 }
346
347 hs.suite = selectCipherSuite(preferenceList, hs.clientHello.cipherSuites, hs.cipherSuiteOk)
348 if hs.suite == nil {
349 c.sendAlert(alertHandshakeFailure)
350 return errors.New("tls: no cipher suite supported by both client and server")
351 }
352 c.cipherSuite = hs.suite.id
353
354 for _, id := range hs.clientHello.cipherSuites {
355 if id == TLS_FALLBACK_SCSV {
356
357 if hs.clientHello.vers < c.config.maxSupportedVersion(roleServer) {
358 c.sendAlert(alertInappropriateFallback)
359 return errors.New("tls: client using inappropriate protocol fallback")
360 }
361 break
362 }
363 }
364
365 return nil
366 }
367
368 func (hs *serverHandshakeState) cipherSuiteOk(c *cipherSuite) bool {
369 if c.flags&suiteECDHE != 0 {
370 if !hs.ecdheOk {
371 return false
372 }
373 if c.flags&suiteECSign != 0 {
374 if !hs.ecSignOk {
375 return false
376 }
377 } else if !hs.rsaSignOk {
378 return false
379 }
380 } else if !hs.rsaDecryptOk {
381 return false
382 }
383 if hs.c.vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
384 return false
385 }
386 return true
387 }
388
389
390 func (hs *serverHandshakeState) checkForResumption() bool {
391 c := hs.c
392
393 if c.config.SessionTicketsDisabled {
394 return false
395 }
396
397 plaintext, usedOldKey := c.decryptTicket(hs.clientHello.sessionTicket)
398 if plaintext == nil {
399 return false
400 }
401 hs.sessionState = &sessionState{usedOldKey: usedOldKey}
402 ok := hs.sessionState.unmarshal(plaintext)
403 if !ok {
404 return false
405 }
406
407 createdAt := time.Unix(int64(hs.sessionState.createdAt), 0)
408 if c.config.time().Sub(createdAt) > maxSessionTicketLifetime {
409 return false
410 }
411
412
413 if c.vers != hs.sessionState.vers {
414 return false
415 }
416
417 cipherSuiteOk := false
418
419 for _, id := range hs.clientHello.cipherSuites {
420 if id == hs.sessionState.cipherSuite {
421 cipherSuiteOk = true
422 break
423 }
424 }
425 if !cipherSuiteOk {
426 return false
427 }
428
429
430 hs.suite = selectCipherSuite([]uint16{hs.sessionState.cipherSuite},
431 c.config.cipherSuites(), hs.cipherSuiteOk)
432 if hs.suite == nil {
433 return false
434 }
435
436 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
437 needClientCerts := requiresClientCert(c.config.ClientAuth)
438 if needClientCerts && !sessionHasClientCerts {
439 return false
440 }
441 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
442 return false
443 }
444
445 return true
446 }
447
448 func (hs *serverHandshakeState) doResumeHandshake() error {
449 c := hs.c
450
451 hs.hello.cipherSuite = hs.suite.id
452 c.cipherSuite = hs.suite.id
453
454
455 hs.hello.sessionId = hs.clientHello.sessionId
456 hs.hello.ticketSupported = hs.sessionState.usedOldKey
457 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
458 hs.finishedHash.discardHandshakeBuffer()
459 hs.finishedHash.Write(hs.clientHello.marshal())
460 hs.finishedHash.Write(hs.hello.marshal())
461 if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
462 return err
463 }
464
465 if err := c.processCertsFromClient(Certificate{
466 Certificate: hs.sessionState.certificates,
467 }); err != nil {
468 return err
469 }
470
471 if c.config.VerifyConnection != nil {
472 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
473 c.sendAlert(alertBadCertificate)
474 return err
475 }
476 }
477
478 hs.masterSecret = hs.sessionState.masterSecret
479
480 return nil
481 }
482
483 func (hs *serverHandshakeState) doFullHandshake() error {
484 c := hs.c
485
486 if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
487 hs.hello.ocspStapling = true
488 }
489
490 hs.hello.ticketSupported = hs.clientHello.ticketSupported && !c.config.SessionTicketsDisabled
491 hs.hello.cipherSuite = hs.suite.id
492
493 hs.finishedHash = newFinishedHash(hs.c.vers, hs.suite)
494 if c.config.ClientAuth == NoClientCert {
495
496
497 hs.finishedHash.discardHandshakeBuffer()
498 }
499 hs.finishedHash.Write(hs.clientHello.marshal())
500 hs.finishedHash.Write(hs.hello.marshal())
501 if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
502 return err
503 }
504
505 certMsg := new(certificateMsg)
506 certMsg.certificates = hs.cert.Certificate
507 hs.finishedHash.Write(certMsg.marshal())
508 if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
509 return err
510 }
511
512 if hs.hello.ocspStapling {
513 certStatus := new(certificateStatusMsg)
514 certStatus.response = hs.cert.OCSPStaple
515 hs.finishedHash.Write(certStatus.marshal())
516 if _, err := c.writeRecord(recordTypeHandshake, certStatus.marshal()); err != nil {
517 return err
518 }
519 }
520
521 keyAgreement := hs.suite.ka(c.vers)
522 skx, err := keyAgreement.generateServerKeyExchange(c.config, hs.cert, hs.clientHello, hs.hello)
523 if err != nil {
524 c.sendAlert(alertHandshakeFailure)
525 return err
526 }
527 if skx != nil {
528 hs.finishedHash.Write(skx.marshal())
529 if _, err := c.writeRecord(recordTypeHandshake, skx.marshal()); err != nil {
530 return err
531 }
532 }
533
534 var certReq *certificateRequestMsg
535 if c.config.ClientAuth >= RequestClientCert {
536
537 certReq = new(certificateRequestMsg)
538 certReq.certificateTypes = []byte{
539 byte(certTypeRSASign),
540 byte(certTypeECDSASign),
541 }
542 if c.vers >= VersionTLS12 {
543 certReq.hasSignatureAlgorithm = true
544 certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms
545 }
546
547
548
549
550
551
552 if c.config.ClientCAs != nil {
553 certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
554 }
555 hs.finishedHash.Write(certReq.marshal())
556 if _, err := c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil {
557 return err
558 }
559 }
560
561 helloDone := new(serverHelloDoneMsg)
562 hs.finishedHash.Write(helloDone.marshal())
563 if _, err := c.writeRecord(recordTypeHandshake, helloDone.marshal()); err != nil {
564 return err
565 }
566
567 if _, err := c.flush(); err != nil {
568 return err
569 }
570
571 var pub crypto.PublicKey
572
573 msg, err := c.readHandshake()
574 if err != nil {
575 return err
576 }
577
578
579
580 if c.config.ClientAuth >= RequestClientCert {
581 certMsg, ok := msg.(*certificateMsg)
582 if !ok {
583 c.sendAlert(alertUnexpectedMessage)
584 return unexpectedMessageError(certMsg, msg)
585 }
586 hs.finishedHash.Write(certMsg.marshal())
587
588 if err := c.processCertsFromClient(Certificate{
589 Certificate: certMsg.certificates,
590 }); err != nil {
591 return err
592 }
593 if len(certMsg.certificates) != 0 {
594 pub = c.peerCertificates[0].PublicKey
595 }
596
597 msg, err = c.readHandshake()
598 if err != nil {
599 return err
600 }
601 }
602 if c.config.VerifyConnection != nil {
603 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
604 c.sendAlert(alertBadCertificate)
605 return err
606 }
607 }
608
609
610 ckx, ok := msg.(*clientKeyExchangeMsg)
611 if !ok {
612 c.sendAlert(alertUnexpectedMessage)
613 return unexpectedMessageError(ckx, msg)
614 }
615 hs.finishedHash.Write(ckx.marshal())
616
617 preMasterSecret, err := keyAgreement.processClientKeyExchange(c.config, hs.cert, ckx, c.vers)
618 if err != nil {
619 c.sendAlert(alertHandshakeFailure)
620 return err
621 }
622 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
623 if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.clientHello.random, hs.masterSecret); err != nil {
624 c.sendAlert(alertInternalError)
625 return err
626 }
627
628
629
630
631
632
633
634 if len(c.peerCertificates) > 0 {
635 msg, err = c.readHandshake()
636 if err != nil {
637 return err
638 }
639 certVerify, ok := msg.(*certificateVerifyMsg)
640 if !ok {
641 c.sendAlert(alertUnexpectedMessage)
642 return unexpectedMessageError(certVerify, msg)
643 }
644
645 var sigType uint8
646 var sigHash crypto.Hash
647 if c.vers >= VersionTLS12 {
648 if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, certReq.supportedSignatureAlgorithms) {
649 c.sendAlert(alertIllegalParameter)
650 return errors.New("tls: client certificate used with invalid signature algorithm")
651 }
652 sigType, sigHash, err = typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
653 if err != nil {
654 return c.sendAlert(alertInternalError)
655 }
656 } else {
657 sigType, sigHash, err = legacyTypeAndHashFromPublicKey(pub)
658 if err != nil {
659 c.sendAlert(alertIllegalParameter)
660 return err
661 }
662 }
663
664 signed := hs.finishedHash.hashForClientCertificate(sigType, sigHash, hs.masterSecret)
665 if err := verifyHandshakeSignature(sigType, pub, sigHash, signed, certVerify.signature); err != nil {
666 c.sendAlert(alertDecryptError)
667 return errors.New("tls: invalid signature by the client certificate: " + err.Error())
668 }
669
670 hs.finishedHash.Write(certVerify.marshal())
671 }
672
673 hs.finishedHash.discardHandshakeBuffer()
674
675 return nil
676 }
677
678 func (hs *serverHandshakeState) establishKeys() error {
679 c := hs.c
680
681 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
682 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
683
684 var clientCipher, serverCipher any
685 var clientHash, serverHash hash.Hash
686
687 if hs.suite.aead == nil {
688 clientCipher = hs.suite.cipher(clientKey, clientIV, true )
689 clientHash = hs.suite.mac(clientMAC)
690 serverCipher = hs.suite.cipher(serverKey, serverIV, false )
691 serverHash = hs.suite.mac(serverMAC)
692 } else {
693 clientCipher = hs.suite.aead(clientKey, clientIV)
694 serverCipher = hs.suite.aead(serverKey, serverIV)
695 }
696
697 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
698 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
699
700 return nil
701 }
702
703 func (hs *serverHandshakeState) readFinished(out []byte) error {
704 c := hs.c
705
706 if err := c.readChangeCipherSpec(); err != nil {
707 return err
708 }
709
710 msg, err := c.readHandshake()
711 if err != nil {
712 return err
713 }
714 clientFinished, ok := msg.(*finishedMsg)
715 if !ok {
716 c.sendAlert(alertUnexpectedMessage)
717 return unexpectedMessageError(clientFinished, msg)
718 }
719
720 verify := hs.finishedHash.clientSum(hs.masterSecret)
721 if len(verify) != len(clientFinished.verifyData) ||
722 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
723 c.sendAlert(alertHandshakeFailure)
724 return errors.New("tls: client's Finished message is incorrect")
725 }
726
727 hs.finishedHash.Write(clientFinished.marshal())
728 copy(out, verify)
729 return nil
730 }
731
732 func (hs *serverHandshakeState) sendSessionTicket() error {
733
734
735
736 if !hs.hello.ticketSupported {
737 return nil
738 }
739
740 c := hs.c
741 m := new(newSessionTicketMsg)
742
743 createdAt := uint64(c.config.time().Unix())
744 if hs.sessionState != nil {
745
746
747 createdAt = hs.sessionState.createdAt
748 }
749
750 var certsFromClient [][]byte
751 for _, cert := range c.peerCertificates {
752 certsFromClient = append(certsFromClient, cert.Raw)
753 }
754 state := sessionState{
755 vers: c.vers,
756 cipherSuite: hs.suite.id,
757 createdAt: createdAt,
758 masterSecret: hs.masterSecret,
759 certificates: certsFromClient,
760 }
761 var err error
762 m.ticket, err = c.encryptTicket(state.marshal())
763 if err != nil {
764 return err
765 }
766
767 hs.finishedHash.Write(m.marshal())
768 if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
769 return err
770 }
771
772 return nil
773 }
774
775 func (hs *serverHandshakeState) sendFinished(out []byte) error {
776 c := hs.c
777
778 if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
779 return err
780 }
781
782 finished := new(finishedMsg)
783 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
784 hs.finishedHash.Write(finished.marshal())
785 if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
786 return err
787 }
788
789 copy(out, finished.verifyData)
790
791 return nil
792 }
793
794
795
796
797 func (c *Conn) processCertsFromClient(certificate Certificate) error {
798 certificates := certificate.Certificate
799 certs := make([]*x509.Certificate, len(certificates))
800 var err error
801 for i, asn1Data := range certificates {
802 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
803 c.sendAlert(alertBadCertificate)
804 return errors.New("tls: failed to parse client certificate: " + err.Error())
805 }
806 }
807
808 if len(certs) == 0 && requiresClientCert(c.config.ClientAuth) {
809 c.sendAlert(alertBadCertificate)
810 return errors.New("tls: client didn't provide a certificate")
811 }
812
813 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
814 opts := x509.VerifyOptions{
815 Roots: c.config.ClientCAs,
816 CurrentTime: c.config.time(),
817 Intermediates: x509.NewCertPool(),
818 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
819 }
820
821 for _, cert := range certs[1:] {
822 opts.Intermediates.AddCert(cert)
823 }
824
825 chains, err := certs[0].Verify(opts)
826 if err != nil {
827 c.sendAlert(alertBadCertificate)
828 return errors.New("tls: failed to verify client certificate: " + err.Error())
829 }
830
831 c.verifiedChains = chains
832 }
833
834 c.peerCertificates = certs
835 c.ocspResponse = certificate.OCSPStaple
836 c.scts = certificate.SignedCertificateTimestamps
837
838 if len(certs) > 0 {
839 switch certs[0].PublicKey.(type) {
840 case *ecdsa.PublicKey, *rsa.PublicKey, ed25519.PublicKey:
841 default:
842 c.sendAlert(alertUnsupportedCertificate)
843 return fmt.Errorf("tls: client certificate contains an unsupported public key of type %T", certs[0].PublicKey)
844 }
845 }
846
847 if c.config.VerifyPeerCertificate != nil {
848 if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
849 c.sendAlert(alertBadCertificate)
850 return err
851 }
852 }
853
854 return nil
855 }
856
857 func clientHelloInfo(ctx context.Context, c *Conn, clientHello *clientHelloMsg) *ClientHelloInfo {
858 supportedVersions := clientHello.supportedVersions
859 if len(clientHello.supportedVersions) == 0 {
860 supportedVersions = supportedVersionsFromMax(clientHello.vers)
861 }
862
863 return &ClientHelloInfo{
864 CipherSuites: clientHello.cipherSuites,
865 ServerName: clientHello.serverName,
866 SupportedCurves: clientHello.supportedCurves,
867 SupportedPoints: clientHello.supportedPoints,
868 SignatureSchemes: clientHello.supportedSignatureAlgorithms,
869 SupportedProtos: clientHello.alpnProtocols,
870 SupportedVersions: supportedVersions,
871 Conn: c.conn,
872 config: c.config,
873 ctx: ctx,
874 }
875 }
876
View as plain text