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