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