]> Cypherpunks.ru repositories - gostls13.git/blob - src/crypto/tls/handshake_client.go
crypto/tls: support QUIC as a transport
[gostls13.git] / src / crypto / tls / handshake_client.go
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package tls
6
7 import (
8         "bytes"
9         "context"
10         "crypto"
11         "crypto/ecdh"
12         "crypto/ecdsa"
13         "crypto/ed25519"
14         "crypto/rsa"
15         "crypto/subtle"
16         "crypto/x509"
17         "errors"
18         "fmt"
19         "hash"
20         "io"
21         "net"
22         "strings"
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 var testingOnlyForceClientHelloSignatureAlgorithms []SignatureScheme
38
39 func (c *Conn) makeClientHello() (*clientHelloMsg, *ecdh.PrivateKey, error) {
40         config := c.config
41         if len(config.ServerName) == 0 && !config.InsecureSkipVerify {
42                 return nil, nil, errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
43         }
44
45         nextProtosLength := 0
46         for _, proto := range config.NextProtos {
47                 if l := len(proto); l == 0 || l > 255 {
48                         return nil, nil, errors.New("tls: invalid NextProtos value")
49                 } else {
50                         nextProtosLength += 1 + l
51                 }
52         }
53         if nextProtosLength > 0xffff {
54                 return nil, nil, errors.New("tls: NextProtos values too large")
55         }
56
57         supportedVersions := config.supportedVersions(roleClient)
58         if len(supportedVersions) == 0 {
59                 return nil, nil, errors.New("tls: no supported versions satisfy MinVersion and MaxVersion")
60         }
61
62         clientHelloVersion := config.maxSupportedVersion(roleClient)
63         // The version at the beginning of the ClientHello was capped at TLS 1.2
64         // for compatibility reasons. The supported_versions extension is used
65         // to negotiate versions now. See RFC 8446, Section 4.2.1.
66         if clientHelloVersion > VersionTLS12 {
67                 clientHelloVersion = VersionTLS12
68         }
69
70         hello := &clientHelloMsg{
71                 vers:                         clientHelloVersion,
72                 compressionMethods:           []uint8{compressionNone},
73                 random:                       make([]byte, 32),
74                 ocspStapling:                 true,
75                 scts:                         true,
76                 serverName:                   hostnameInSNI(config.ServerName),
77                 supportedCurves:              config.curvePreferences(),
78                 supportedPoints:              []uint8{pointFormatUncompressed},
79                 secureRenegotiationSupported: true,
80                 alpnProtocols:                config.NextProtos,
81                 supportedVersions:            supportedVersions,
82         }
83
84         if c.handshakes > 0 {
85                 hello.secureRenegotiation = c.clientFinished[:]
86         }
87
88         preferenceOrder := cipherSuitesPreferenceOrder
89         if !hasAESGCMHardwareSupport {
90                 preferenceOrder = cipherSuitesPreferenceOrderNoAES
91         }
92         configCipherSuites := config.cipherSuites()
93         hello.cipherSuites = make([]uint16, 0, len(configCipherSuites))
94
95         for _, suiteId := range preferenceOrder {
96                 suite := mutualCipherSuite(configCipherSuites, suiteId)
97                 if suite == nil {
98                         continue
99                 }
100                 // Don't advertise TLS 1.2-only cipher suites unless
101                 // we're attempting TLS 1.2.
102                 if hello.vers < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
103                         continue
104                 }
105                 hello.cipherSuites = append(hello.cipherSuites, suiteId)
106         }
107
108         _, err := io.ReadFull(config.rand(), hello.random)
109         if err != nil {
110                 return nil, nil, errors.New("tls: short read from Rand: " + err.Error())
111         }
112
113         // A random session ID is used to detect when the server accepted a ticket
114         // and is resuming a session (see RFC 5077). In TLS 1.3, it's always set as
115         // a compatibility measure (see RFC 8446, Section 4.1.2).
116         //
117         // The session ID is not set for QUIC connections (see RFC 9001, Section 8.4).
118         if c.quic == nil {
119                 hello.sessionId = make([]byte, 32)
120                 if _, err := io.ReadFull(config.rand(), hello.sessionId); err != nil {
121                         return nil, nil, errors.New("tls: short read from Rand: " + err.Error())
122                 }
123         }
124
125         if hello.vers >= VersionTLS12 {
126                 hello.supportedSignatureAlgorithms = supportedSignatureAlgorithms()
127         }
128         if testingOnlyForceClientHelloSignatureAlgorithms != nil {
129                 hello.supportedSignatureAlgorithms = testingOnlyForceClientHelloSignatureAlgorithms
130         }
131
132         var key *ecdh.PrivateKey
133         if hello.supportedVersions[0] == VersionTLS13 {
134                 if hasAESGCMHardwareSupport {
135                         hello.cipherSuites = append(hello.cipherSuites, defaultCipherSuitesTLS13...)
136                 } else {
137                         hello.cipherSuites = append(hello.cipherSuites, defaultCipherSuitesTLS13NoAES...)
138                 }
139
140                 curveID := config.curvePreferences()[0]
141                 if _, ok := curveForCurveID(curveID); !ok {
142                         return nil, nil, errors.New("tls: CurvePreferences includes unsupported curve")
143                 }
144                 key, err = generateECDHEKey(config.rand(), curveID)
145                 if err != nil {
146                         return nil, nil, err
147                 }
148                 hello.keyShares = []keyShare{{group: curveID, data: key.PublicKey().Bytes()}}
149         }
150
151         if c.quic != nil {
152                 p, err := c.quicGetTransportParameters()
153                 if err != nil {
154                         return nil, nil, err
155                 }
156                 if p == nil {
157                         p = []byte{}
158                 }
159                 hello.quicTransportParameters = p
160         }
161
162         return hello, key, nil
163 }
164
165 func (c *Conn) clientHandshake(ctx context.Context) (err error) {
166         if c.config == nil {
167                 c.config = defaultConfig()
168         }
169
170         // This may be a renegotiation handshake, in which case some fields
171         // need to be reset.
172         c.didResume = false
173
174         hello, ecdheKey, err := c.makeClientHello()
175         if err != nil {
176                 return err
177         }
178         c.serverName = hello.serverName
179
180         cacheKey, session, earlySecret, binderKey, err := c.loadSession(hello)
181         if err != nil {
182                 return err
183         }
184         if cacheKey != "" && session != nil {
185                 defer func() {
186                         // If we got a handshake failure when resuming a session, throw away
187                         // the session ticket. See RFC 5077, Section 3.2.
188                         //
189                         // RFC 8446 makes no mention of dropping tickets on failure, but it
190                         // does require servers to abort on invalid binders, so we need to
191                         // delete tickets to recover from a corrupted PSK.
192                         if err != nil {
193                                 c.config.ClientSessionCache.Put(cacheKey, nil)
194                         }
195                 }()
196         }
197
198         if _, err := c.writeHandshakeRecord(hello, nil); err != nil {
199                 return err
200         }
201
202         // serverHelloMsg is not included in the transcript
203         msg, err := c.readHandshake(nil)
204         if err != nil {
205                 return err
206         }
207
208         serverHello, ok := msg.(*serverHelloMsg)
209         if !ok {
210                 c.sendAlert(alertUnexpectedMessage)
211                 return unexpectedMessageError(serverHello, msg)
212         }
213
214         if err := c.pickTLSVersion(serverHello); err != nil {
215                 return err
216         }
217
218         // If we are negotiating a protocol version that's lower than what we
219         // support, check for the server downgrade canaries.
220         // See RFC 8446, Section 4.1.3.
221         maxVers := c.config.maxSupportedVersion(roleClient)
222         tls12Downgrade := string(serverHello.random[24:]) == downgradeCanaryTLS12
223         tls11Downgrade := string(serverHello.random[24:]) == downgradeCanaryTLS11
224         if maxVers == VersionTLS13 && c.vers <= VersionTLS12 && (tls12Downgrade || tls11Downgrade) ||
225                 maxVers == VersionTLS12 && c.vers <= VersionTLS11 && tls11Downgrade {
226                 c.sendAlert(alertIllegalParameter)
227                 return errors.New("tls: downgrade attempt detected, possibly due to a MitM attack or a broken middlebox")
228         }
229
230         if c.vers == VersionTLS13 {
231                 hs := &clientHandshakeStateTLS13{
232                         c:           c,
233                         ctx:         ctx,
234                         serverHello: serverHello,
235                         hello:       hello,
236                         ecdheKey:    ecdheKey,
237                         session:     session,
238                         earlySecret: earlySecret,
239                         binderKey:   binderKey,
240                 }
241
242                 // In TLS 1.3, session tickets are delivered after the handshake.
243                 return hs.handshake()
244         }
245
246         hs := &clientHandshakeState{
247                 c:           c,
248                 ctx:         ctx,
249                 serverHello: serverHello,
250                 hello:       hello,
251                 session:     session,
252         }
253
254         if err := hs.handshake(); err != nil {
255                 return err
256         }
257
258         // If we had a successful handshake and hs.session is different from
259         // the one already cached - cache a new one.
260         if cacheKey != "" && hs.session != nil && session != hs.session {
261                 c.config.ClientSessionCache.Put(cacheKey, hs.session)
262         }
263
264         return nil
265 }
266
267 func (c *Conn) loadSession(hello *clientHelloMsg) (cacheKey string,
268         session *ClientSessionState, earlySecret, binderKey []byte, err error) {
269         if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil {
270                 return "", nil, nil, nil, nil
271         }
272
273         hello.ticketSupported = true
274
275         if hello.supportedVersions[0] == VersionTLS13 {
276                 // Require DHE on resumption as it guarantees forward secrecy against
277                 // compromise of the session ticket key. See RFC 8446, Section 4.2.9.
278                 hello.pskModes = []uint8{pskModeDHE}
279         }
280
281         // Session resumption is not allowed if renegotiating because
282         // renegotiation is primarily used to allow a client to send a client
283         // certificate, which would be skipped if session resumption occurred.
284         if c.handshakes != 0 {
285                 return "", nil, nil, nil, nil
286         }
287
288         // Try to resume a previously negotiated TLS session, if available.
289         cacheKey = c.clientSessionCacheKey()
290         if cacheKey == "" {
291                 return "", nil, nil, nil, nil
292         }
293         session, ok := c.config.ClientSessionCache.Get(cacheKey)
294         if !ok || session == nil {
295                 return cacheKey, nil, nil, nil, nil
296         }
297
298         // Check that version used for the previous session is still valid.
299         versOk := false
300         for _, v := range hello.supportedVersions {
301                 if v == session.vers {
302                         versOk = true
303                         break
304                 }
305         }
306         if !versOk {
307                 return cacheKey, nil, nil, nil, nil
308         }
309
310         // Check that the cached server certificate is not expired, and that it's
311         // valid for the ServerName. This should be ensured by the cache key, but
312         // protect the application from a faulty ClientSessionCache implementation.
313         if !c.config.InsecureSkipVerify {
314                 if len(session.verifiedChains) == 0 {
315                         // The original connection had InsecureSkipVerify, while this doesn't.
316                         return cacheKey, nil, nil, nil, nil
317                 }
318                 serverCert := session.serverCertificates[0]
319                 if c.config.time().After(serverCert.NotAfter) {
320                         // Expired certificate, delete the entry.
321                         c.config.ClientSessionCache.Put(cacheKey, nil)
322                         return cacheKey, nil, nil, nil, nil
323                 }
324                 if err := serverCert.VerifyHostname(c.config.ServerName); err != nil {
325                         return cacheKey, nil, nil, nil, nil
326                 }
327         }
328
329         if session.vers != VersionTLS13 {
330                 // In TLS 1.2 the cipher suite must match the resumed session. Ensure we
331                 // are still offering it.
332                 if mutualCipherSuite(hello.cipherSuites, session.cipherSuite) == nil {
333                         return cacheKey, nil, nil, nil, nil
334                 }
335
336                 hello.sessionTicket = session.sessionTicket
337                 return
338         }
339
340         // Check that the session ticket is not expired.
341         if c.config.time().After(session.useBy) {
342                 c.config.ClientSessionCache.Put(cacheKey, nil)
343                 return cacheKey, nil, nil, nil, nil
344         }
345
346         // In TLS 1.3 the KDF hash must match the resumed session. Ensure we
347         // offer at least one cipher suite with that hash.
348         cipherSuite := cipherSuiteTLS13ByID(session.cipherSuite)
349         if cipherSuite == nil {
350                 return cacheKey, nil, nil, nil, nil
351         }
352         cipherSuiteOk := false
353         for _, offeredID := range hello.cipherSuites {
354                 offeredSuite := cipherSuiteTLS13ByID(offeredID)
355                 if offeredSuite != nil && offeredSuite.hash == cipherSuite.hash {
356                         cipherSuiteOk = true
357                         break
358                 }
359         }
360         if !cipherSuiteOk {
361                 return cacheKey, nil, nil, nil, nil
362         }
363
364         // Set the pre_shared_key extension. See RFC 8446, Section 4.2.11.1.
365         ticketAge := uint32(c.config.time().Sub(session.receivedAt) / time.Millisecond)
366         identity := pskIdentity{
367                 label:               session.sessionTicket,
368                 obfuscatedTicketAge: ticketAge + session.ageAdd,
369         }
370         hello.pskIdentities = []pskIdentity{identity}
371         hello.pskBinders = [][]byte{make([]byte, cipherSuite.hash.Size())}
372
373         // Compute the PSK binders. See RFC 8446, Section 4.2.11.2.
374         psk := cipherSuite.expandLabel(session.masterSecret, "resumption",
375                 session.nonce, cipherSuite.hash.Size())
376         earlySecret = cipherSuite.extract(psk, nil)
377         binderKey = cipherSuite.deriveSecret(earlySecret, resumptionBinderLabel, nil)
378         transcript := cipherSuite.hash.New()
379         helloBytes, err := hello.marshalWithoutBinders()
380         if err != nil {
381                 return "", nil, nil, nil, err
382         }
383         transcript.Write(helloBytes)
384         pskBinders := [][]byte{cipherSuite.finishedHash(binderKey, transcript)}
385         if err := hello.updateBinders(pskBinders); err != nil {
386                 return "", nil, nil, nil, err
387         }
388
389         return
390 }
391
392 func (c *Conn) pickTLSVersion(serverHello *serverHelloMsg) error {
393         peerVersion := serverHello.vers
394         if serverHello.supportedVersion != 0 {
395                 peerVersion = serverHello.supportedVersion
396         }
397
398         vers, ok := c.config.mutualVersion(roleClient, []uint16{peerVersion})
399         if !ok {
400                 c.sendAlert(alertProtocolVersion)
401                 return fmt.Errorf("tls: server selected unsupported protocol version %x", peerVersion)
402         }
403
404         c.vers = vers
405         c.haveVers = true
406         c.in.version = vers
407         c.out.version = vers
408
409         return nil
410 }
411
412 // Does the handshake, either a full one or resumes old session. Requires hs.c,
413 // hs.hello, hs.serverHello, and, optionally, hs.session to be set.
414 func (hs *clientHandshakeState) handshake() error {
415         c := hs.c
416
417         isResume, err := hs.processServerHello()
418         if err != nil {
419                 return err
420         }
421
422         hs.finishedHash = newFinishedHash(c.vers, hs.suite)
423
424         // No signatures of the handshake are needed in a resumption.
425         // Otherwise, in a full handshake, if we don't have any certificates
426         // configured then we will never send a CertificateVerify message and
427         // thus no signatures are needed in that case either.
428         if isResume || (len(c.config.Certificates) == 0 && c.config.GetClientCertificate == nil) {
429                 hs.finishedHash.discardHandshakeBuffer()
430         }
431
432         if err := transcriptMsg(hs.hello, &hs.finishedHash); err != nil {
433                 return err
434         }
435         if err := transcriptMsg(hs.serverHello, &hs.finishedHash); err != nil {
436                 return err
437         }
438
439         c.buffering = true
440         c.didResume = isResume
441         if isResume {
442                 if err := hs.establishKeys(); err != nil {
443                         return err
444                 }
445                 if err := hs.readSessionTicket(); err != nil {
446                         return err
447                 }
448                 if err := hs.readFinished(c.serverFinished[:]); err != nil {
449                         return err
450                 }
451                 c.clientFinishedIsFirst = false
452                 // Make sure the connection is still being verified whether or not this
453                 // is a resumption. Resumptions currently don't reverify certificates so
454                 // they don't call verifyServerCertificate. See Issue 31641.
455                 if c.config.VerifyConnection != nil {
456                         if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
457                                 c.sendAlert(alertBadCertificate)
458                                 return err
459                         }
460                 }
461                 if err := hs.sendFinished(c.clientFinished[:]); err != nil {
462                         return err
463                 }
464                 if _, err := c.flush(); err != nil {
465                         return err
466                 }
467         } else {
468                 if err := hs.doFullHandshake(); err != nil {
469                         return err
470                 }
471                 if err := hs.establishKeys(); err != nil {
472                         return err
473                 }
474                 if err := hs.sendFinished(c.clientFinished[:]); err != nil {
475                         return err
476                 }
477                 if _, err := c.flush(); err != nil {
478                         return err
479                 }
480                 c.clientFinishedIsFirst = true
481                 if err := hs.readSessionTicket(); err != nil {
482                         return err
483                 }
484                 if err := hs.readFinished(c.serverFinished[:]); err != nil {
485                         return err
486                 }
487         }
488
489         c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random)
490         c.isHandshakeComplete.Store(true)
491
492         return nil
493 }
494
495 func (hs *clientHandshakeState) pickCipherSuite() error {
496         if hs.suite = mutualCipherSuite(hs.hello.cipherSuites, hs.serverHello.cipherSuite); hs.suite == nil {
497                 hs.c.sendAlert(alertHandshakeFailure)
498                 return errors.New("tls: server chose an unconfigured cipher suite")
499         }
500
501         hs.c.cipherSuite = hs.suite.id
502         return nil
503 }
504
505 func (hs *clientHandshakeState) doFullHandshake() error {
506         c := hs.c
507
508         msg, err := c.readHandshake(&hs.finishedHash)
509         if err != nil {
510                 return err
511         }
512         certMsg, ok := msg.(*certificateMsg)
513         if !ok || len(certMsg.certificates) == 0 {
514                 c.sendAlert(alertUnexpectedMessage)
515                 return unexpectedMessageError(certMsg, msg)
516         }
517
518         msg, err = c.readHandshake(&hs.finishedHash)
519         if err != nil {
520                 return err
521         }
522
523         cs, ok := msg.(*certificateStatusMsg)
524         if ok {
525                 // RFC4366 on Certificate Status Request:
526                 // The server MAY return a "certificate_status" message.
527
528                 if !hs.serverHello.ocspStapling {
529                         // If a server returns a "CertificateStatus" message, then the
530                         // server MUST have included an extension of type "status_request"
531                         // with empty "extension_data" in the extended server hello.
532
533                         c.sendAlert(alertUnexpectedMessage)
534                         return errors.New("tls: received unexpected CertificateStatus message")
535                 }
536
537                 c.ocspResponse = cs.response
538
539                 msg, err = c.readHandshake(&hs.finishedHash)
540                 if err != nil {
541                         return err
542                 }
543         }
544
545         if c.handshakes == 0 {
546                 // If this is the first handshake on a connection, process and
547                 // (optionally) verify the server's certificates.
548                 if err := c.verifyServerCertificate(certMsg.certificates); err != nil {
549                         return err
550                 }
551         } else {
552                 // This is a renegotiation handshake. We require that the
553                 // server's identity (i.e. leaf certificate) is unchanged and
554                 // thus any previous trust decision is still valid.
555                 //
556                 // See https://mitls.org/pages/attacks/3SHAKE for the
557                 // motivation behind this requirement.
558                 if !bytes.Equal(c.peerCertificates[0].Raw, certMsg.certificates[0]) {
559                         c.sendAlert(alertBadCertificate)
560                         return errors.New("tls: server's identity changed during renegotiation")
561                 }
562         }
563
564         keyAgreement := hs.suite.ka(c.vers)
565
566         skx, ok := msg.(*serverKeyExchangeMsg)
567         if ok {
568                 err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, c.peerCertificates[0], skx)
569                 if err != nil {
570                         c.sendAlert(alertUnexpectedMessage)
571                         return err
572                 }
573
574                 msg, err = c.readHandshake(&hs.finishedHash)
575                 if err != nil {
576                         return err
577                 }
578         }
579
580         var chainToSend *Certificate
581         var certRequested bool
582         certReq, ok := msg.(*certificateRequestMsg)
583         if ok {
584                 certRequested = true
585
586                 cri := certificateRequestInfoFromMsg(hs.ctx, c.vers, certReq)
587                 if chainToSend, err = c.getClientCertificate(cri); err != nil {
588                         c.sendAlert(alertInternalError)
589                         return err
590                 }
591
592                 msg, err = c.readHandshake(&hs.finishedHash)
593                 if err != nil {
594                         return err
595                 }
596         }
597
598         shd, ok := msg.(*serverHelloDoneMsg)
599         if !ok {
600                 c.sendAlert(alertUnexpectedMessage)
601                 return unexpectedMessageError(shd, msg)
602         }
603
604         // If the server requested a certificate then we have to send a
605         // Certificate message, even if it's empty because we don't have a
606         // certificate to send.
607         if certRequested {
608                 certMsg = new(certificateMsg)
609                 certMsg.certificates = chainToSend.Certificate
610                 if _, err := hs.c.writeHandshakeRecord(certMsg, &hs.finishedHash); err != nil {
611                         return err
612                 }
613         }
614
615         preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, c.peerCertificates[0])
616         if err != nil {
617                 c.sendAlert(alertInternalError)
618                 return err
619         }
620         if ckx != nil {
621                 if _, err := hs.c.writeHandshakeRecord(ckx, &hs.finishedHash); err != nil {
622                         return err
623                 }
624         }
625
626         if chainToSend != nil && len(chainToSend.Certificate) > 0 {
627                 certVerify := &certificateVerifyMsg{}
628
629                 key, ok := chainToSend.PrivateKey.(crypto.Signer)
630                 if !ok {
631                         c.sendAlert(alertInternalError)
632                         return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey)
633                 }
634
635                 var sigType uint8
636                 var sigHash crypto.Hash
637                 if c.vers >= VersionTLS12 {
638                         signatureAlgorithm, err := selectSignatureScheme(c.vers, chainToSend, certReq.supportedSignatureAlgorithms)
639                         if err != nil {
640                                 c.sendAlert(alertIllegalParameter)
641                                 return err
642                         }
643                         sigType, sigHash, err = typeAndHashFromSignatureScheme(signatureAlgorithm)
644                         if err != nil {
645                                 return c.sendAlert(alertInternalError)
646                         }
647                         certVerify.hasSignatureAlgorithm = true
648                         certVerify.signatureAlgorithm = signatureAlgorithm
649                 } else {
650                         sigType, sigHash, err = legacyTypeAndHashFromPublicKey(key.Public())
651                         if err != nil {
652                                 c.sendAlert(alertIllegalParameter)
653                                 return err
654                         }
655                 }
656
657                 signed := hs.finishedHash.hashForClientCertificate(sigType, sigHash)
658                 signOpts := crypto.SignerOpts(sigHash)
659                 if sigType == signatureRSAPSS {
660                         signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
661                 }
662                 certVerify.signature, err = key.Sign(c.config.rand(), signed, signOpts)
663                 if err != nil {
664                         c.sendAlert(alertInternalError)
665                         return err
666                 }
667
668                 if _, err := hs.c.writeHandshakeRecord(certVerify, &hs.finishedHash); err != nil {
669                         return err
670                 }
671         }
672
673         hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
674         if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.hello.random, hs.masterSecret); err != nil {
675                 c.sendAlert(alertInternalError)
676                 return errors.New("tls: failed to write to key log: " + err.Error())
677         }
678
679         hs.finishedHash.discardHandshakeBuffer()
680
681         return nil
682 }
683
684 func (hs *clientHandshakeState) establishKeys() error {
685         c := hs.c
686
687         clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
688                 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
689         var clientCipher, serverCipher any
690         var clientHash, serverHash hash.Hash
691         if hs.suite.cipher != nil {
692                 clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
693                 clientHash = hs.suite.mac(clientMAC)
694                 serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
695                 serverHash = hs.suite.mac(serverMAC)
696         } else {
697                 clientCipher = hs.suite.aead(clientKey, clientIV)
698                 serverCipher = hs.suite.aead(serverKey, serverIV)
699         }
700
701         c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
702         c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
703         return nil
704 }
705
706 func (hs *clientHandshakeState) serverResumedSession() bool {
707         // If the server responded with the same sessionId then it means the
708         // sessionTicket is being used to resume a TLS session.
709         return hs.session != nil && hs.hello.sessionId != nil &&
710                 bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
711 }
712
713 func (hs *clientHandshakeState) processServerHello() (bool, error) {
714         c := hs.c
715
716         if err := hs.pickCipherSuite(); err != nil {
717                 return false, err
718         }
719
720         if hs.serverHello.compressionMethod != compressionNone {
721                 c.sendAlert(alertUnexpectedMessage)
722                 return false, errors.New("tls: server selected unsupported compression format")
723         }
724
725         if c.handshakes == 0 && hs.serverHello.secureRenegotiationSupported {
726                 c.secureRenegotiation = true
727                 if len(hs.serverHello.secureRenegotiation) != 0 {
728                         c.sendAlert(alertHandshakeFailure)
729                         return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
730                 }
731         }
732
733         if c.handshakes > 0 && c.secureRenegotiation {
734                 var expectedSecureRenegotiation [24]byte
735                 copy(expectedSecureRenegotiation[:], c.clientFinished[:])
736                 copy(expectedSecureRenegotiation[12:], c.serverFinished[:])
737                 if !bytes.Equal(hs.serverHello.secureRenegotiation, expectedSecureRenegotiation[:]) {
738                         c.sendAlert(alertHandshakeFailure)
739                         return false, errors.New("tls: incorrect renegotiation extension contents")
740                 }
741         }
742
743         if err := checkALPN(hs.hello.alpnProtocols, hs.serverHello.alpnProtocol, false); err != nil {
744                 c.sendAlert(alertUnsupportedExtension)
745                 return false, err
746         }
747         c.clientProtocol = hs.serverHello.alpnProtocol
748
749         c.scts = hs.serverHello.scts
750
751         if !hs.serverResumedSession() {
752                 return false, nil
753         }
754
755         if hs.session.vers != c.vers {
756                 c.sendAlert(alertHandshakeFailure)
757                 return false, errors.New("tls: server resumed a session with a different version")
758         }
759
760         if hs.session.cipherSuite != hs.suite.id {
761                 c.sendAlert(alertHandshakeFailure)
762                 return false, errors.New("tls: server resumed a session with a different cipher suite")
763         }
764
765         // Restore masterSecret, peerCerts, and ocspResponse from previous state
766         hs.masterSecret = hs.session.masterSecret
767         c.peerCertificates = hs.session.serverCertificates
768         c.verifiedChains = hs.session.verifiedChains
769         c.ocspResponse = hs.session.ocspResponse
770         // Let the ServerHello SCTs override the session SCTs from the original
771         // connection, if any are provided
772         if len(c.scts) == 0 && len(hs.session.scts) != 0 {
773                 c.scts = hs.session.scts
774         }
775
776         return true, nil
777 }
778
779 // checkALPN ensure that the server's choice of ALPN protocol is compatible with
780 // the protocols that we advertised in the Client Hello.
781 func checkALPN(clientProtos []string, serverProto string, quic bool) error {
782         if serverProto == "" {
783                 if quic && len(clientProtos) > 0 {
784                         // RFC 9001, Section 8.1
785                         return errors.New("tls: server did not select an ALPN protocol")
786                 }
787                 return nil
788         }
789         if len(clientProtos) == 0 {
790                 return errors.New("tls: server advertised unrequested ALPN extension")
791         }
792         for _, proto := range clientProtos {
793                 if proto == serverProto {
794                         return nil
795                 }
796         }
797         return errors.New("tls: server selected unadvertised ALPN protocol")
798 }
799
800 func (hs *clientHandshakeState) readFinished(out []byte) error {
801         c := hs.c
802
803         if err := c.readChangeCipherSpec(); err != nil {
804                 return err
805         }
806
807         // finishedMsg is included in the transcript, but not until after we
808         // check the client version, since the state before this message was
809         // sent is used during verification.
810         msg, err := c.readHandshake(nil)
811         if err != nil {
812                 return err
813         }
814         serverFinished, ok := msg.(*finishedMsg)
815         if !ok {
816                 c.sendAlert(alertUnexpectedMessage)
817                 return unexpectedMessageError(serverFinished, msg)
818         }
819
820         verify := hs.finishedHash.serverSum(hs.masterSecret)
821         if len(verify) != len(serverFinished.verifyData) ||
822                 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
823                 c.sendAlert(alertHandshakeFailure)
824                 return errors.New("tls: server's Finished message was incorrect")
825         }
826
827         if err := transcriptMsg(serverFinished, &hs.finishedHash); err != nil {
828                 return err
829         }
830
831         copy(out, verify)
832         return nil
833 }
834
835 func (hs *clientHandshakeState) readSessionTicket() error {
836         if !hs.serverHello.ticketSupported {
837                 return nil
838         }
839
840         c := hs.c
841         msg, err := c.readHandshake(&hs.finishedHash)
842         if err != nil {
843                 return err
844         }
845         sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
846         if !ok {
847                 c.sendAlert(alertUnexpectedMessage)
848                 return unexpectedMessageError(sessionTicketMsg, msg)
849         }
850
851         hs.session = &ClientSessionState{
852                 sessionTicket:      sessionTicketMsg.ticket,
853                 vers:               c.vers,
854                 cipherSuite:        hs.suite.id,
855                 masterSecret:       hs.masterSecret,
856                 serverCertificates: c.peerCertificates,
857                 verifiedChains:     c.verifiedChains,
858                 receivedAt:         c.config.time(),
859                 ocspResponse:       c.ocspResponse,
860                 scts:               c.scts,
861         }
862
863         return nil
864 }
865
866 func (hs *clientHandshakeState) sendFinished(out []byte) error {
867         c := hs.c
868
869         if err := c.writeChangeCipherRecord(); err != nil {
870                 return err
871         }
872
873         finished := new(finishedMsg)
874         finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
875         if _, err := hs.c.writeHandshakeRecord(finished, &hs.finishedHash); err != nil {
876                 return err
877         }
878         copy(out, finished.verifyData)
879         return nil
880 }
881
882 // verifyServerCertificate parses and verifies the provided chain, setting
883 // c.verifiedChains and c.peerCertificates or sending the appropriate alert.
884 func (c *Conn) verifyServerCertificate(certificates [][]byte) error {
885         activeHandles := make([]*activeCert, len(certificates))
886         certs := make([]*x509.Certificate, len(certificates))
887         for i, asn1Data := range certificates {
888                 cert, err := clientCertCache.newCert(asn1Data)
889                 if err != nil {
890                         c.sendAlert(alertBadCertificate)
891                         return errors.New("tls: failed to parse certificate from server: " + err.Error())
892                 }
893                 activeHandles[i] = cert
894                 certs[i] = cert.cert
895         }
896
897         if !c.config.InsecureSkipVerify {
898                 opts := x509.VerifyOptions{
899                         Roots:         c.config.RootCAs,
900                         CurrentTime:   c.config.time(),
901                         DNSName:       c.config.ServerName,
902                         Intermediates: x509.NewCertPool(),
903                 }
904
905                 for _, cert := range certs[1:] {
906                         opts.Intermediates.AddCert(cert)
907                 }
908                 var err error
909                 c.verifiedChains, err = certs[0].Verify(opts)
910                 if err != nil {
911                         c.sendAlert(alertBadCertificate)
912                         return &CertificateVerificationError{UnverifiedCertificates: certs, Err: err}
913                 }
914         }
915
916         switch certs[0].PublicKey.(type) {
917         case *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey:
918                 break
919         default:
920                 c.sendAlert(alertUnsupportedCertificate)
921                 return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
922         }
923
924         c.activeCertHandles = activeHandles
925         c.peerCertificates = certs
926
927         if c.config.VerifyPeerCertificate != nil {
928                 if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
929                         c.sendAlert(alertBadCertificate)
930                         return err
931                 }
932         }
933
934         if c.config.VerifyConnection != nil {
935                 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
936                         c.sendAlert(alertBadCertificate)
937                         return err
938                 }
939         }
940
941         return nil
942 }
943
944 // certificateRequestInfoFromMsg generates a CertificateRequestInfo from a TLS
945 // <= 1.2 CertificateRequest, making an effort to fill in missing information.
946 func certificateRequestInfoFromMsg(ctx context.Context, vers uint16, certReq *certificateRequestMsg) *CertificateRequestInfo {
947         cri := &CertificateRequestInfo{
948                 AcceptableCAs: certReq.certificateAuthorities,
949                 Version:       vers,
950                 ctx:           ctx,
951         }
952
953         var rsaAvail, ecAvail bool
954         for _, certType := range certReq.certificateTypes {
955                 switch certType {
956                 case certTypeRSASign:
957                         rsaAvail = true
958                 case certTypeECDSASign:
959                         ecAvail = true
960                 }
961         }
962
963         if !certReq.hasSignatureAlgorithm {
964                 // Prior to TLS 1.2, signature schemes did not exist. In this case we
965                 // make up a list based on the acceptable certificate types, to help
966                 // GetClientCertificate and SupportsCertificate select the right certificate.
967                 // The hash part of the SignatureScheme is a lie here, because
968                 // TLS 1.0 and 1.1 always use MD5+SHA1 for RSA and SHA1 for ECDSA.
969                 switch {
970                 case rsaAvail && ecAvail:
971                         cri.SignatureSchemes = []SignatureScheme{
972                                 ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512,
973                                 PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1,
974                         }
975                 case rsaAvail:
976                         cri.SignatureSchemes = []SignatureScheme{
977                                 PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1,
978                         }
979                 case ecAvail:
980                         cri.SignatureSchemes = []SignatureScheme{
981                                 ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512,
982                         }
983                 }
984                 return cri
985         }
986
987         // Filter the signature schemes based on the certificate types.
988         // See RFC 5246, Section 7.4.4 (where it calls this "somewhat complicated").
989         cri.SignatureSchemes = make([]SignatureScheme, 0, len(certReq.supportedSignatureAlgorithms))
990         for _, sigScheme := range certReq.supportedSignatureAlgorithms {
991                 sigType, _, err := typeAndHashFromSignatureScheme(sigScheme)
992                 if err != nil {
993                         continue
994                 }
995                 switch sigType {
996                 case signatureECDSA, signatureEd25519:
997                         if ecAvail {
998                                 cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme)
999                         }
1000                 case signatureRSAPSS, signaturePKCS1v15:
1001                         if rsaAvail {
1002                                 cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme)
1003                         }
1004                 }
1005         }
1006
1007         return cri
1008 }
1009
1010 func (c *Conn) getClientCertificate(cri *CertificateRequestInfo) (*Certificate, error) {
1011         if c.config.GetClientCertificate != nil {
1012                 return c.config.GetClientCertificate(cri)
1013         }
1014
1015         for _, chain := range c.config.Certificates {
1016                 if err := cri.SupportsCertificate(&chain); err != nil {
1017                         continue
1018                 }
1019                 return &chain, nil
1020         }
1021
1022         // No acceptable certificate found. Don't send a certificate.
1023         return new(Certificate), nil
1024 }
1025
1026 // clientSessionCacheKey returns a key used to cache sessionTickets that could
1027 // be used to resume previously negotiated TLS sessions with a server.
1028 func (c *Conn) clientSessionCacheKey() string {
1029         if len(c.config.ServerName) > 0 {
1030                 return c.config.ServerName
1031         }
1032         if c.conn != nil {
1033                 return c.conn.RemoteAddr().String()
1034         }
1035         return ""
1036 }
1037
1038 // hostnameInSNI converts name into an appropriate hostname for SNI.
1039 // Literal IP addresses and absolute FQDNs are not permitted as SNI values.
1040 // See RFC 6066, Section 3.
1041 func hostnameInSNI(name string) string {
1042         host := name
1043         if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' {
1044                 host = host[1 : len(host)-1]
1045         }
1046         if i := strings.LastIndex(host, "%"); i > 0 {
1047                 host = host[:i]
1048         }
1049         if net.ParseIP(host) != nil {
1050                 return ""
1051         }
1052         for len(name) > 0 && name[len(name)-1] == '.' {
1053                 name = name[:len(name)-1]
1054         }
1055         return name
1056 }