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/rsa"
14 "crypto/subtle"
15 "crypto/x509"
16 "errors"
17 "fmt"
18 "hash"
19 "io"
20 "net"
21 "strings"
22 "sync/atomic"
23 "time"
24 )
25
26 type clientHandshakeState struct {
27 c *Conn
28 ctx context.Context
29 serverHello *serverHelloMsg
30 hello *clientHelloMsg
31 suite *cipherSuite
32 finishedHash finishedHash
33 masterSecret []byte
34 session *ClientSessionState
35 }
36
37 func (c *Conn) makeClientHello() (*clientHelloMsg, ecdheParameters, error) {
38 config := c.config
39 if len(config.ServerName) == 0 && !config.InsecureSkipVerify {
40 return nil, nil, errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
41 }
42
43 nextProtosLength := 0
44 for _, proto := range config.NextProtos {
45 if l := len(proto); l == 0 || l > 255 {
46 return nil, nil, errors.New("tls: invalid NextProtos value")
47 } else {
48 nextProtosLength += 1 + l
49 }
50 }
51 if nextProtosLength > 0xffff {
52 return nil, nil, errors.New("tls: NextProtos values too large")
53 }
54
55 supportedVersions := config.supportedVersions()
56 if len(supportedVersions) == 0 {
57 return nil, nil, errors.New("tls: no supported versions satisfy MinVersion and MaxVersion")
58 }
59
60 clientHelloVersion := config.maxSupportedVersion()
61
62
63
64 if clientHelloVersion > VersionTLS12 {
65 clientHelloVersion = VersionTLS12
66 }
67
68 hello := &clientHelloMsg{
69 vers: clientHelloVersion,
70 compressionMethods: []uint8{compressionNone},
71 random: make([]byte, 32),
72 sessionId: make([]byte, 32),
73 ocspStapling: true,
74 scts: true,
75 serverName: hostnameInSNI(config.ServerName),
76 supportedCurves: config.curvePreferences(),
77 supportedPoints: []uint8{pointFormatUncompressed},
78 secureRenegotiationSupported: true,
79 alpnProtocols: config.NextProtos,
80 supportedVersions: supportedVersions,
81 }
82
83 if c.handshakes > 0 {
84 hello.secureRenegotiation = c.clientFinished[:]
85 }
86
87 preferenceOrder := cipherSuitesPreferenceOrder
88 if !hasAESGCMHardwareSupport {
89 preferenceOrder = cipherSuitesPreferenceOrderNoAES
90 }
91 configCipherSuites := config.cipherSuites()
92 hello.cipherSuites = make([]uint16, 0, len(configCipherSuites))
93
94 for _, suiteId := range preferenceOrder {
95 suite := mutualCipherSuite(configCipherSuites, suiteId)
96 if suite == nil {
97 continue
98 }
99
100
101 if hello.vers < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
102 continue
103 }
104 hello.cipherSuites = append(hello.cipherSuites, suiteId)
105 }
106
107 _, err := io.ReadFull(config.rand(), hello.random)
108 if err != nil {
109 return nil, nil, errors.New("tls: short read from Rand: " + err.Error())
110 }
111
112
113
114
115 if _, err := io.ReadFull(config.rand(), hello.sessionId); err != nil {
116 return nil, nil, errors.New("tls: short read from Rand: " + err.Error())
117 }
118
119 if hello.vers >= VersionTLS12 {
120 hello.supportedSignatureAlgorithms = supportedSignatureAlgorithms
121 }
122
123 var params ecdheParameters
124 if hello.supportedVersions[0] == VersionTLS13 {
125 if hasAESGCMHardwareSupport {
126 hello.cipherSuites = append(hello.cipherSuites, defaultCipherSuitesTLS13...)
127 } else {
128 hello.cipherSuites = append(hello.cipherSuites, defaultCipherSuitesTLS13NoAES...)
129 }
130
131 curveID := config.curvePreferences()[0]
132 if _, ok := curveForCurveID(curveID); curveID != X25519 && !ok {
133 return nil, nil, errors.New("tls: CurvePreferences includes unsupported curve")
134 }
135 params, err = generateECDHEParameters(config.rand(), curveID)
136 if err != nil {
137 return nil, nil, err
138 }
139 hello.keyShares = []keyShare{{group: curveID, data: params.PublicKey()}}
140 }
141
142 return hello, params, nil
143 }
144
145 func (c *Conn) clientHandshake(ctx context.Context) (err error) {
146 if c.config == nil {
147 c.config = defaultConfig()
148 }
149
150
151
152 c.didResume = false
153
154 hello, ecdheParams, err := c.makeClientHello()
155 if err != nil {
156 return err
157 }
158 c.serverName = hello.serverName
159
160 cacheKey, session, earlySecret, binderKey := c.loadSession(hello)
161 if cacheKey != "" && session != nil {
162 defer func() {
163
164
165
166
167
168
169 if err != nil {
170 c.config.ClientSessionCache.Put(cacheKey, nil)
171 }
172 }()
173 }
174
175 if _, err := c.writeRecord(recordTypeHandshake, hello.marshal()); err != nil {
176 return err
177 }
178
179 msg, err := c.readHandshake()
180 if err != nil {
181 return err
182 }
183
184 serverHello, ok := msg.(*serverHelloMsg)
185 if !ok {
186 c.sendAlert(alertUnexpectedMessage)
187 return unexpectedMessageError(serverHello, msg)
188 }
189
190 if err := c.pickTLSVersion(serverHello); err != nil {
191 return err
192 }
193
194
195
196
197 maxVers := c.config.maxSupportedVersion()
198 tls12Downgrade := string(serverHello.random[24:]) == downgradeCanaryTLS12
199 tls11Downgrade := string(serverHello.random[24:]) == downgradeCanaryTLS11
200 if maxVers == VersionTLS13 && c.vers <= VersionTLS12 && (tls12Downgrade || tls11Downgrade) ||
201 maxVers == VersionTLS12 && c.vers <= VersionTLS11 && tls11Downgrade {
202 c.sendAlert(alertIllegalParameter)
203 return errors.New("tls: downgrade attempt detected, possibly due to a MitM attack or a broken middlebox")
204 }
205
206 if c.vers == VersionTLS13 {
207 hs := &clientHandshakeStateTLS13{
208 c: c,
209 ctx: ctx,
210 serverHello: serverHello,
211 hello: hello,
212 ecdheParams: ecdheParams,
213 session: session,
214 earlySecret: earlySecret,
215 binderKey: binderKey,
216 }
217
218
219 return hs.handshake()
220 }
221
222 hs := &clientHandshakeState{
223 c: c,
224 ctx: ctx,
225 serverHello: serverHello,
226 hello: hello,
227 session: session,
228 }
229
230 if err := hs.handshake(); err != nil {
231 return err
232 }
233
234
235
236 if cacheKey != "" && hs.session != nil && session != hs.session {
237 c.config.ClientSessionCache.Put(cacheKey, hs.session)
238 }
239
240 return nil
241 }
242
243 func (c *Conn) loadSession(hello *clientHelloMsg) (cacheKey string,
244 session *ClientSessionState, earlySecret, binderKey []byte) {
245 if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil {
246 return "", nil, nil, nil
247 }
248
249 hello.ticketSupported = true
250
251 if hello.supportedVersions[0] == VersionTLS13 {
252
253
254 hello.pskModes = []uint8{pskModeDHE}
255 }
256
257
258
259
260 if c.handshakes != 0 {
261 return "", nil, nil, nil
262 }
263
264
265 cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
266 session, ok := c.config.ClientSessionCache.Get(cacheKey)
267 if !ok || session == nil {
268 return cacheKey, nil, nil, nil
269 }
270
271
272 versOk := false
273 for _, v := range hello.supportedVersions {
274 if v == session.vers {
275 versOk = true
276 break
277 }
278 }
279 if !versOk {
280 return cacheKey, nil, nil, nil
281 }
282
283
284
285
286 if !c.config.InsecureSkipVerify {
287 if len(session.verifiedChains) == 0 {
288
289 return cacheKey, nil, nil, nil
290 }
291 serverCert := session.serverCertificates[0]
292 if c.config.time().After(serverCert.NotAfter) {
293
294 c.config.ClientSessionCache.Put(cacheKey, nil)
295 return cacheKey, nil, nil, nil
296 }
297 if err := serverCert.VerifyHostname(c.config.ServerName); err != nil {
298 return cacheKey, nil, nil, nil
299 }
300 }
301
302 if session.vers != VersionTLS13 {
303
304
305 if mutualCipherSuite(hello.cipherSuites, session.cipherSuite) == nil {
306 return cacheKey, nil, nil, nil
307 }
308
309 hello.sessionTicket = session.sessionTicket
310 return
311 }
312
313
314 if c.config.time().After(session.useBy) {
315 c.config.ClientSessionCache.Put(cacheKey, nil)
316 return cacheKey, nil, nil, nil
317 }
318
319
320
321 cipherSuite := cipherSuiteTLS13ByID(session.cipherSuite)
322 if cipherSuite == nil {
323 return cacheKey, nil, nil, nil
324 }
325 cipherSuiteOk := false
326 for _, offeredID := range hello.cipherSuites {
327 offeredSuite := cipherSuiteTLS13ByID(offeredID)
328 if offeredSuite != nil && offeredSuite.hash == cipherSuite.hash {
329 cipherSuiteOk = true
330 break
331 }
332 }
333 if !cipherSuiteOk {
334 return cacheKey, nil, nil, nil
335 }
336
337
338 ticketAge := uint32(c.config.time().Sub(session.receivedAt) / time.Millisecond)
339 identity := pskIdentity{
340 label: session.sessionTicket,
341 obfuscatedTicketAge: ticketAge + session.ageAdd,
342 }
343 hello.pskIdentities = []pskIdentity{identity}
344 hello.pskBinders = [][]byte{make([]byte, cipherSuite.hash.Size())}
345
346
347 psk := cipherSuite.expandLabel(session.masterSecret, "resumption",
348 session.nonce, cipherSuite.hash.Size())
349 earlySecret = cipherSuite.extract(psk, nil)
350 binderKey = cipherSuite.deriveSecret(earlySecret, resumptionBinderLabel, nil)
351 transcript := cipherSuite.hash.New()
352 transcript.Write(hello.marshalWithoutBinders())
353 pskBinders := [][]byte{cipherSuite.finishedHash(binderKey, transcript)}
354 hello.updateBinders(pskBinders)
355
356 return
357 }
358
359 func (c *Conn) pickTLSVersion(serverHello *serverHelloMsg) error {
360 peerVersion := serverHello.vers
361 if serverHello.supportedVersion != 0 {
362 peerVersion = serverHello.supportedVersion
363 }
364
365 vers, ok := c.config.mutualVersion([]uint16{peerVersion})
366 if !ok {
367 c.sendAlert(alertProtocolVersion)
368 return fmt.Errorf("tls: server selected unsupported protocol version %x", peerVersion)
369 }
370
371 c.vers = vers
372 c.haveVers = true
373 c.in.version = vers
374 c.out.version = vers
375
376 return nil
377 }
378
379
380
381 func (hs *clientHandshakeState) handshake() error {
382 c := hs.c
383
384 isResume, err := hs.processServerHello()
385 if err != nil {
386 return err
387 }
388
389 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
390
391
392
393
394
395 if isResume || (len(c.config.Certificates) == 0 && c.config.GetClientCertificate == nil) {
396 hs.finishedHash.discardHandshakeBuffer()
397 }
398
399 hs.finishedHash.Write(hs.hello.marshal())
400 hs.finishedHash.Write(hs.serverHello.marshal())
401
402 c.buffering = true
403 c.didResume = isResume
404 if isResume {
405 if err := hs.establishKeys(); err != nil {
406 return err
407 }
408 if err := hs.readSessionTicket(); err != nil {
409 return err
410 }
411 if err := hs.readFinished(c.serverFinished[:]); err != nil {
412 return err
413 }
414 c.clientFinishedIsFirst = false
415
416
417
418 if c.config.VerifyConnection != nil {
419 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
420 c.sendAlert(alertBadCertificate)
421 return err
422 }
423 }
424 if err := hs.sendFinished(c.clientFinished[:]); err != nil {
425 return err
426 }
427 if _, err := c.flush(); err != nil {
428 return err
429 }
430 } else {
431 if err := hs.doFullHandshake(); err != nil {
432 return err
433 }
434 if err := hs.establishKeys(); err != nil {
435 return err
436 }
437 if err := hs.sendFinished(c.clientFinished[:]); err != nil {
438 return err
439 }
440 if _, err := c.flush(); err != nil {
441 return err
442 }
443 c.clientFinishedIsFirst = true
444 if err := hs.readSessionTicket(); err != nil {
445 return err
446 }
447 if err := hs.readFinished(c.serverFinished[:]); err != nil {
448 return err
449 }
450 }
451
452 c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random)
453 atomic.StoreUint32(&c.handshakeStatus, 1)
454
455 return nil
456 }
457
458 func (hs *clientHandshakeState) pickCipherSuite() error {
459 if hs.suite = mutualCipherSuite(hs.hello.cipherSuites, hs.serverHello.cipherSuite); hs.suite == nil {
460 hs.c.sendAlert(alertHandshakeFailure)
461 return errors.New("tls: server chose an unconfigured cipher suite")
462 }
463
464 hs.c.cipherSuite = hs.suite.id
465 return nil
466 }
467
468 func (hs *clientHandshakeState) doFullHandshake() error {
469 c := hs.c
470
471 msg, err := c.readHandshake()
472 if err != nil {
473 return err
474 }
475 certMsg, ok := msg.(*certificateMsg)
476 if !ok || len(certMsg.certificates) == 0 {
477 c.sendAlert(alertUnexpectedMessage)
478 return unexpectedMessageError(certMsg, msg)
479 }
480 hs.finishedHash.Write(certMsg.marshal())
481
482 msg, err = c.readHandshake()
483 if err != nil {
484 return err
485 }
486
487 cs, ok := msg.(*certificateStatusMsg)
488 if ok {
489
490
491
492 if !hs.serverHello.ocspStapling {
493
494
495
496
497 c.sendAlert(alertUnexpectedMessage)
498 return errors.New("tls: received unexpected CertificateStatus message")
499 }
500 hs.finishedHash.Write(cs.marshal())
501
502 c.ocspResponse = cs.response
503
504 msg, err = c.readHandshake()
505 if err != nil {
506 return err
507 }
508 }
509
510 if c.handshakes == 0 {
511
512
513 if err := c.verifyServerCertificate(certMsg.certificates); err != nil {
514 return err
515 }
516 } else {
517
518
519
520
521
522
523 if !bytes.Equal(c.peerCertificates[0].Raw, certMsg.certificates[0]) {
524 c.sendAlert(alertBadCertificate)
525 return errors.New("tls: server's identity changed during renegotiation")
526 }
527 }
528
529 keyAgreement := hs.suite.ka(c.vers)
530
531 skx, ok := msg.(*serverKeyExchangeMsg)
532 if ok {
533 hs.finishedHash.Write(skx.marshal())
534 err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, c.peerCertificates[0], skx)
535 if err != nil {
536 c.sendAlert(alertUnexpectedMessage)
537 return err
538 }
539
540 msg, err = c.readHandshake()
541 if err != nil {
542 return err
543 }
544 }
545
546 var chainToSend *Certificate
547 var certRequested bool
548 certReq, ok := msg.(*certificateRequestMsg)
549 if ok {
550 certRequested = true
551 hs.finishedHash.Write(certReq.marshal())
552
553 cri := certificateRequestInfoFromMsg(hs.ctx, c.vers, certReq)
554 if chainToSend, err = c.getClientCertificate(cri); err != nil {
555 c.sendAlert(alertInternalError)
556 return err
557 }
558
559 msg, err = c.readHandshake()
560 if err != nil {
561 return err
562 }
563 }
564
565 shd, ok := msg.(*serverHelloDoneMsg)
566 if !ok {
567 c.sendAlert(alertUnexpectedMessage)
568 return unexpectedMessageError(shd, msg)
569 }
570 hs.finishedHash.Write(shd.marshal())
571
572
573
574
575 if certRequested {
576 certMsg = new(certificateMsg)
577 certMsg.certificates = chainToSend.Certificate
578 hs.finishedHash.Write(certMsg.marshal())
579 if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
580 return err
581 }
582 }
583
584 preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, c.peerCertificates[0])
585 if err != nil {
586 c.sendAlert(alertInternalError)
587 return err
588 }
589 if ckx != nil {
590 hs.finishedHash.Write(ckx.marshal())
591 if _, err := c.writeRecord(recordTypeHandshake, ckx.marshal()); err != nil {
592 return err
593 }
594 }
595
596 if chainToSend != nil && len(chainToSend.Certificate) > 0 {
597 certVerify := &certificateVerifyMsg{}
598
599 key, ok := chainToSend.PrivateKey.(crypto.Signer)
600 if !ok {
601 c.sendAlert(alertInternalError)
602 return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey)
603 }
604
605 var sigType uint8
606 var sigHash crypto.Hash
607 if c.vers >= VersionTLS12 {
608 signatureAlgorithm, err := selectSignatureScheme(c.vers, chainToSend, certReq.supportedSignatureAlgorithms)
609 if err != nil {
610 c.sendAlert(alertIllegalParameter)
611 return err
612 }
613 sigType, sigHash, err = typeAndHashFromSignatureScheme(signatureAlgorithm)
614 if err != nil {
615 return c.sendAlert(alertInternalError)
616 }
617 certVerify.hasSignatureAlgorithm = true
618 certVerify.signatureAlgorithm = signatureAlgorithm
619 } else {
620 sigType, sigHash, err = legacyTypeAndHashFromPublicKey(key.Public())
621 if err != nil {
622 c.sendAlert(alertIllegalParameter)
623 return err
624 }
625 }
626
627 signed := hs.finishedHash.hashForClientCertificate(sigType, sigHash, hs.masterSecret)
628 signOpts := crypto.SignerOpts(sigHash)
629 if sigType == signatureRSAPSS {
630 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
631 }
632 certVerify.signature, err = key.Sign(c.config.rand(), signed, signOpts)
633 if err != nil {
634 c.sendAlert(alertInternalError)
635 return err
636 }
637
638 hs.finishedHash.Write(certVerify.marshal())
639 if _, err := c.writeRecord(recordTypeHandshake, certVerify.marshal()); err != nil {
640 return err
641 }
642 }
643
644 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
645 if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.hello.random, hs.masterSecret); err != nil {
646 c.sendAlert(alertInternalError)
647 return errors.New("tls: failed to write to key log: " + err.Error())
648 }
649
650 hs.finishedHash.discardHandshakeBuffer()
651
652 return nil
653 }
654
655 func (hs *clientHandshakeState) establishKeys() error {
656 c := hs.c
657
658 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
659 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
660 var clientCipher, serverCipher interface{}
661 var clientHash, serverHash hash.Hash
662 if hs.suite.cipher != nil {
663 clientCipher = hs.suite.cipher(clientKey, clientIV, false )
664 clientHash = hs.suite.mac(clientMAC)
665 serverCipher = hs.suite.cipher(serverKey, serverIV, true )
666 serverHash = hs.suite.mac(serverMAC)
667 } else {
668 clientCipher = hs.suite.aead(clientKey, clientIV)
669 serverCipher = hs.suite.aead(serverKey, serverIV)
670 }
671
672 c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
673 c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
674 return nil
675 }
676
677 func (hs *clientHandshakeState) serverResumedSession() bool {
678
679
680 return hs.session != nil && hs.hello.sessionId != nil &&
681 bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
682 }
683
684 func (hs *clientHandshakeState) processServerHello() (bool, error) {
685 c := hs.c
686
687 if err := hs.pickCipherSuite(); err != nil {
688 return false, err
689 }
690
691 if hs.serverHello.compressionMethod != compressionNone {
692 c.sendAlert(alertUnexpectedMessage)
693 return false, errors.New("tls: server selected unsupported compression format")
694 }
695
696 if c.handshakes == 0 && hs.serverHello.secureRenegotiationSupported {
697 c.secureRenegotiation = true
698 if len(hs.serverHello.secureRenegotiation) != 0 {
699 c.sendAlert(alertHandshakeFailure)
700 return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
701 }
702 }
703
704 if c.handshakes > 0 && c.secureRenegotiation {
705 var expectedSecureRenegotiation [24]byte
706 copy(expectedSecureRenegotiation[:], c.clientFinished[:])
707 copy(expectedSecureRenegotiation[12:], c.serverFinished[:])
708 if !bytes.Equal(hs.serverHello.secureRenegotiation, expectedSecureRenegotiation[:]) {
709 c.sendAlert(alertHandshakeFailure)
710 return false, errors.New("tls: incorrect renegotiation extension contents")
711 }
712 }
713
714 if err := checkALPN(hs.hello.alpnProtocols, hs.serverHello.alpnProtocol); err != nil {
715 c.sendAlert(alertUnsupportedExtension)
716 return false, err
717 }
718 c.clientProtocol = hs.serverHello.alpnProtocol
719
720 c.scts = hs.serverHello.scts
721
722 if !hs.serverResumedSession() {
723 return false, nil
724 }
725
726 if hs.session.vers != c.vers {
727 c.sendAlert(alertHandshakeFailure)
728 return false, errors.New("tls: server resumed a session with a different version")
729 }
730
731 if hs.session.cipherSuite != hs.suite.id {
732 c.sendAlert(alertHandshakeFailure)
733 return false, errors.New("tls: server resumed a session with a different cipher suite")
734 }
735
736
737 hs.masterSecret = hs.session.masterSecret
738 c.peerCertificates = hs.session.serverCertificates
739 c.verifiedChains = hs.session.verifiedChains
740 c.ocspResponse = hs.session.ocspResponse
741
742
743 if len(c.scts) == 0 && len(hs.session.scts) != 0 {
744 c.scts = hs.session.scts
745 }
746
747 return true, nil
748 }
749
750
751
752 func checkALPN(clientProtos []string, serverProto string) error {
753 if serverProto == "" {
754 return nil
755 }
756 if len(clientProtos) == 0 {
757 return errors.New("tls: server advertised unrequested ALPN extension")
758 }
759 for _, proto := range clientProtos {
760 if proto == serverProto {
761 return nil
762 }
763 }
764 return errors.New("tls: server selected unadvertised ALPN protocol")
765 }
766
767 func (hs *clientHandshakeState) readFinished(out []byte) error {
768 c := hs.c
769
770 if err := c.readChangeCipherSpec(); err != nil {
771 return err
772 }
773
774 msg, err := c.readHandshake()
775 if err != nil {
776 return err
777 }
778 serverFinished, ok := msg.(*finishedMsg)
779 if !ok {
780 c.sendAlert(alertUnexpectedMessage)
781 return unexpectedMessageError(serverFinished, msg)
782 }
783
784 verify := hs.finishedHash.serverSum(hs.masterSecret)
785 if len(verify) != len(serverFinished.verifyData) ||
786 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
787 c.sendAlert(alertHandshakeFailure)
788 return errors.New("tls: server's Finished message was incorrect")
789 }
790 hs.finishedHash.Write(serverFinished.marshal())
791 copy(out, verify)
792 return nil
793 }
794
795 func (hs *clientHandshakeState) readSessionTicket() error {
796 if !hs.serverHello.ticketSupported {
797 return nil
798 }
799
800 c := hs.c
801 msg, err := c.readHandshake()
802 if err != nil {
803 return err
804 }
805 sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
806 if !ok {
807 c.sendAlert(alertUnexpectedMessage)
808 return unexpectedMessageError(sessionTicketMsg, msg)
809 }
810 hs.finishedHash.Write(sessionTicketMsg.marshal())
811
812 hs.session = &ClientSessionState{
813 sessionTicket: sessionTicketMsg.ticket,
814 vers: c.vers,
815 cipherSuite: hs.suite.id,
816 masterSecret: hs.masterSecret,
817 serverCertificates: c.peerCertificates,
818 verifiedChains: c.verifiedChains,
819 receivedAt: c.config.time(),
820 ocspResponse: c.ocspResponse,
821 scts: c.scts,
822 }
823
824 return nil
825 }
826
827 func (hs *clientHandshakeState) sendFinished(out []byte) error {
828 c := hs.c
829
830 if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
831 return err
832 }
833
834 finished := new(finishedMsg)
835 finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
836 hs.finishedHash.Write(finished.marshal())
837 if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
838 return err
839 }
840 copy(out, finished.verifyData)
841 return nil
842 }
843
844
845
846 func (c *Conn) verifyServerCertificate(certificates [][]byte) error {
847 certs := make([]*x509.Certificate, len(certificates))
848 for i, asn1Data := range certificates {
849 cert, err := x509.ParseCertificate(asn1Data)
850 if err != nil {
851 c.sendAlert(alertBadCertificate)
852 return errors.New("tls: failed to parse certificate from server: " + err.Error())
853 }
854 certs[i] = cert
855 }
856
857 if !c.config.InsecureSkipVerify {
858 opts := x509.VerifyOptions{
859 Roots: c.config.RootCAs,
860 CurrentTime: c.config.time(),
861 DNSName: c.config.ServerName,
862 Intermediates: x509.NewCertPool(),
863 }
864 for _, cert := range certs[1:] {
865 opts.Intermediates.AddCert(cert)
866 }
867 var err error
868 c.verifiedChains, err = certs[0].Verify(opts)
869 if err != nil {
870 c.sendAlert(alertBadCertificate)
871 return err
872 }
873 }
874
875 switch certs[0].PublicKey.(type) {
876 case *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey:
877 break
878 default:
879 c.sendAlert(alertUnsupportedCertificate)
880 return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
881 }
882
883 c.peerCertificates = certs
884
885 if c.config.VerifyPeerCertificate != nil {
886 if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
887 c.sendAlert(alertBadCertificate)
888 return err
889 }
890 }
891
892 if c.config.VerifyConnection != nil {
893 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
894 c.sendAlert(alertBadCertificate)
895 return err
896 }
897 }
898
899 return nil
900 }
901
902
903
904 func certificateRequestInfoFromMsg(ctx context.Context, vers uint16, certReq *certificateRequestMsg) *CertificateRequestInfo {
905 cri := &CertificateRequestInfo{
906 AcceptableCAs: certReq.certificateAuthorities,
907 Version: vers,
908 ctx: ctx,
909 }
910
911 var rsaAvail, ecAvail bool
912 for _, certType := range certReq.certificateTypes {
913 switch certType {
914 case certTypeRSASign:
915 rsaAvail = true
916 case certTypeECDSASign:
917 ecAvail = true
918 }
919 }
920
921 if !certReq.hasSignatureAlgorithm {
922
923
924
925
926
927 switch {
928 case rsaAvail && ecAvail:
929 cri.SignatureSchemes = []SignatureScheme{
930 ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512,
931 PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1,
932 }
933 case rsaAvail:
934 cri.SignatureSchemes = []SignatureScheme{
935 PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1,
936 }
937 case ecAvail:
938 cri.SignatureSchemes = []SignatureScheme{
939 ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512,
940 }
941 }
942 return cri
943 }
944
945
946
947 cri.SignatureSchemes = make([]SignatureScheme, 0, len(certReq.supportedSignatureAlgorithms))
948 for _, sigScheme := range certReq.supportedSignatureAlgorithms {
949 sigType, _, err := typeAndHashFromSignatureScheme(sigScheme)
950 if err != nil {
951 continue
952 }
953 switch sigType {
954 case signatureECDSA, signatureEd25519:
955 if ecAvail {
956 cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme)
957 }
958 case signatureRSAPSS, signaturePKCS1v15:
959 if rsaAvail {
960 cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme)
961 }
962 }
963 }
964
965 return cri
966 }
967
968 func (c *Conn) getClientCertificate(cri *CertificateRequestInfo) (*Certificate, error) {
969 if c.config.GetClientCertificate != nil {
970 return c.config.GetClientCertificate(cri)
971 }
972
973 for _, chain := range c.config.Certificates {
974 if err := cri.SupportsCertificate(&chain); err != nil {
975 continue
976 }
977 return &chain, nil
978 }
979
980
981 return new(Certificate), nil
982 }
983
984
985
986 func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
987 if len(config.ServerName) > 0 {
988 return config.ServerName
989 }
990 return serverAddr.String()
991 }
992
993
994
995
996 func hostnameInSNI(name string) string {
997 host := name
998 if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' {
999 host = host[1 : len(host)-1]
1000 }
1001 if i := strings.LastIndex(host, "%"); i > 0 {
1002 host = host[:i]
1003 }
1004 if net.ParseIP(host) != nil {
1005 return ""
1006 }
1007 for len(name) > 0 && name[len(name)-1] == '.' {
1008 name = name[:len(name)-1]
1009 }
1010 return name
1011 }
1012
View as plain text