]> Cypherpunks.ru repositories - gostls13.git/blob - src/crypto/tls/handshake_client.go
[dev.boringcrypto] all: merge master 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/rsa"
12         "crypto/subtle"
13         "crypto/x509"
14         "errors"
15         "fmt"
16         "io"
17         "net"
18         "strconv"
19         "strings"
20 )
21
22 type clientHandshakeState struct {
23         c            *Conn
24         serverHello  *serverHelloMsg
25         hello        *clientHelloMsg
26         suite        *cipherSuite
27         finishedHash finishedHash
28         masterSecret []byte
29         session      *ClientSessionState
30 }
31
32 func makeClientHello(config *Config) (*clientHelloMsg, error) {
33         if len(config.ServerName) == 0 && !config.InsecureSkipVerify {
34                 return nil, errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
35         }
36
37         nextProtosLength := 0
38         for _, proto := range config.NextProtos {
39                 if l := len(proto); l == 0 || l > 255 {
40                         return nil, errors.New("tls: invalid NextProtos value")
41                 } else {
42                         nextProtosLength += 1 + l
43                 }
44         }
45
46         if nextProtosLength > 0xffff {
47                 return nil, errors.New("tls: NextProtos values too large")
48         }
49
50         hello := &clientHelloMsg{
51                 vers:                         config.maxVersion(),
52                 compressionMethods:           []uint8{compressionNone},
53                 random:                       make([]byte, 32),
54                 ocspStapling:                 true,
55                 scts:                         true,
56                 serverName:                   hostnameInSNI(config.ServerName),
57                 supportedCurves:              config.curvePreferences(),
58                 supportedPoints:              []uint8{pointFormatUncompressed},
59                 nextProtoNeg:                 len(config.NextProtos) > 0,
60                 secureRenegotiationSupported: true,
61                 alpnProtocols:                config.NextProtos,
62         }
63         possibleCipherSuites := config.cipherSuites()
64         hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites))
65
66 NextCipherSuite:
67         for _, suiteId := range possibleCipherSuites {
68                 for _, suite := range cipherSuites {
69                         if suite.id != suiteId {
70                                 continue
71                         }
72                         // Don't advertise TLS 1.2-only cipher suites unless
73                         // we're attempting TLS 1.2.
74                         if hello.vers < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
75                                 continue
76                         }
77                         hello.cipherSuites = append(hello.cipherSuites, suiteId)
78                         continue NextCipherSuite
79                 }
80         }
81
82         _, err := io.ReadFull(config.rand(), hello.random)
83         if err != nil {
84                 return nil, errors.New("tls: short read from Rand: " + err.Error())
85         }
86
87         if hello.vers >= VersionTLS12 {
88                 hello.supportedSignatureAlgorithms = supportedSignatureAlgorithms()
89         }
90         if testingOnlyForceClientHelloSignatureAlgorithms != nil {
91                 hello.supportedSignatureAlgorithms = testingOnlyForceClientHelloSignatureAlgorithms
92         }
93
94         return hello, nil
95 }
96
97 func (c *Conn) clientHandshake() error {
98         if c.config == nil {
99                 c.config = defaultConfig()
100         }
101
102         // This may be a renegotiation handshake, in which case some fields
103         // need to be reset.
104         c.didResume = false
105
106         hello, err := makeClientHello(c.config)
107         if err != nil {
108                 return err
109         }
110
111         if c.handshakes > 0 {
112                 hello.secureRenegotiation = c.clientFinished[:]
113         }
114
115         var session *ClientSessionState
116         var cacheKey string
117         sessionCache := c.config.ClientSessionCache
118         if c.config.SessionTicketsDisabled {
119                 sessionCache = nil
120         }
121
122         if sessionCache != nil {
123                 hello.ticketSupported = true
124         }
125
126         // Session resumption is not allowed if renegotiating because
127         // renegotiation is primarily used to allow a client to send a client
128         // certificate, which would be skipped if session resumption occurred.
129         if sessionCache != nil && c.handshakes == 0 {
130                 // Try to resume a previously negotiated TLS session, if
131                 // available.
132                 cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
133                 candidateSession, ok := sessionCache.Get(cacheKey)
134                 if ok {
135                         // Check that the ciphersuite/version used for the
136                         // previous session are still valid.
137                         cipherSuiteOk := false
138                         for _, id := range hello.cipherSuites {
139                                 if id == candidateSession.cipherSuite {
140                                         cipherSuiteOk = true
141                                         break
142                                 }
143                         }
144
145                         versOk := candidateSession.vers >= c.config.minVersion() &&
146                                 candidateSession.vers <= c.config.maxVersion()
147                         if versOk && cipherSuiteOk {
148                                 session = candidateSession
149                         }
150                 }
151         }
152
153         if session != nil {
154                 hello.sessionTicket = session.sessionTicket
155                 // A random session ID is used to detect when the
156                 // server accepted the ticket and is resuming a session
157                 // (see RFC 5077).
158                 hello.sessionId = make([]byte, 16)
159                 if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil {
160                         return errors.New("tls: short read from Rand: " + err.Error())
161                 }
162         }
163
164         hs := &clientHandshakeState{
165                 c:       c,
166                 hello:   hello,
167                 session: session,
168         }
169
170         if err = hs.handshake(); err != nil {
171                 return err
172         }
173
174         // If we had a successful handshake and hs.session is different from
175         // the one already cached - cache a new one
176         if sessionCache != nil && hs.session != nil && session != hs.session {
177                 sessionCache.Put(cacheKey, hs.session)
178         }
179
180         return nil
181 }
182
183 // Does the handshake, either a full one or resumes old session.
184 // Requires hs.c, hs.hello, and, optionally, hs.session to be set.
185 func (hs *clientHandshakeState) handshake() error {
186         c := hs.c
187
188         // send ClientHello
189         if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
190                 return err
191         }
192
193         msg, err := c.readHandshake()
194         if err != nil {
195                 return err
196         }
197
198         var ok bool
199         if hs.serverHello, ok = msg.(*serverHelloMsg); !ok {
200                 c.sendAlert(alertUnexpectedMessage)
201                 return unexpectedMessageError(hs.serverHello, msg)
202         }
203
204         if err = hs.pickTLSVersion(); err != nil {
205                 return err
206         }
207
208         if err = hs.pickCipherSuite(); err != nil {
209                 return err
210         }
211
212         isResume, err := hs.processServerHello()
213         if err != nil {
214                 return err
215         }
216
217         hs.finishedHash = newFinishedHash(c.vers, hs.suite)
218
219         // No signatures of the handshake are needed in a resumption.
220         // Otherwise, in a full handshake, if we don't have any certificates
221         // configured then we will never send a CertificateVerify message and
222         // thus no signatures are needed in that case either.
223         if isResume || (len(c.config.Certificates) == 0 && c.config.GetClientCertificate == nil) {
224                 hs.finishedHash.discardHandshakeBuffer()
225         }
226
227         hs.finishedHash.Write(hs.hello.marshal())
228         hs.finishedHash.Write(hs.serverHello.marshal())
229
230         c.buffering = true
231         if isResume {
232                 if err := hs.establishKeys(); err != nil {
233                         return err
234                 }
235                 if err := hs.readSessionTicket(); err != nil {
236                         return err
237                 }
238                 if err := hs.readFinished(c.serverFinished[:]); err != nil {
239                         return err
240                 }
241                 c.clientFinishedIsFirst = false
242                 if err := hs.sendFinished(c.clientFinished[:]); err != nil {
243                         return err
244                 }
245                 if _, err := c.flush(); err != nil {
246                         return err
247                 }
248         } else {
249                 if err := hs.doFullHandshake(); err != nil {
250                         return err
251                 }
252                 if err := hs.establishKeys(); err != nil {
253                         return err
254                 }
255                 if err := hs.sendFinished(c.clientFinished[:]); err != nil {
256                         return err
257                 }
258                 if _, err := c.flush(); err != nil {
259                         return err
260                 }
261                 c.clientFinishedIsFirst = true
262                 if err := hs.readSessionTicket(); err != nil {
263                         return err
264                 }
265                 if err := hs.readFinished(c.serverFinished[:]); err != nil {
266                         return err
267                 }
268         }
269
270         c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random)
271         c.didResume = isResume
272         c.handshakeComplete = true
273
274         return nil
275 }
276
277 func (hs *clientHandshakeState) pickTLSVersion() error {
278         vers, ok := hs.c.config.mutualVersion(hs.serverHello.vers)
279         if !ok || vers < VersionTLS10 {
280                 // TLS 1.0 is the minimum version supported as a client.
281                 hs.c.sendAlert(alertProtocolVersion)
282                 return fmt.Errorf("tls: server selected unsupported protocol version %x", hs.serverHello.vers)
283         }
284
285         hs.c.vers = vers
286         hs.c.haveVers = true
287
288         return nil
289 }
290
291 func (hs *clientHandshakeState) pickCipherSuite() error {
292         if hs.suite = mutualCipherSuite(hs.hello.cipherSuites, hs.serverHello.cipherSuite); hs.suite == nil {
293                 hs.c.sendAlert(alertHandshakeFailure)
294                 return errors.New("tls: server chose an unconfigured cipher suite")
295         }
296
297         hs.c.cipherSuite = hs.suite.id
298         return nil
299 }
300
301 func (hs *clientHandshakeState) doFullHandshake() error {
302         c := hs.c
303
304         msg, err := c.readHandshake()
305         if err != nil {
306                 return err
307         }
308         certMsg, ok := msg.(*certificateMsg)
309         if !ok || len(certMsg.certificates) == 0 {
310                 c.sendAlert(alertUnexpectedMessage)
311                 return unexpectedMessageError(certMsg, msg)
312         }
313         hs.finishedHash.Write(certMsg.marshal())
314
315         if c.handshakes == 0 {
316                 // If this is the first handshake on a connection, process and
317                 // (optionally) verify the server's certificates.
318                 certs := make([]*x509.Certificate, len(certMsg.certificates))
319                 for i, asn1Data := range certMsg.certificates {
320                         cert, err := x509.ParseCertificate(asn1Data)
321                         if err != nil {
322                                 c.sendAlert(alertBadCertificate)
323                                 return errors.New("tls: failed to parse certificate from server: " + err.Error())
324                         }
325                         certs[i] = cert
326                 }
327
328                 if !c.config.InsecureSkipVerify {
329                         opts := x509.VerifyOptions{
330                                 IsBoring: isBoringCertificate,
331
332                                 Roots:         c.config.RootCAs,
333                                 CurrentTime:   c.config.time(),
334                                 DNSName:       c.config.ServerName,
335                                 Intermediates: x509.NewCertPool(),
336                         }
337
338                         for i, cert := range certs {
339                                 if i == 0 {
340                                         continue
341                                 }
342                                 opts.Intermediates.AddCert(cert)
343                         }
344                         c.verifiedChains, err = certs[0].Verify(opts)
345                         if err != nil {
346                                 c.sendAlert(alertBadCertificate)
347                                 return err
348                         }
349                 }
350
351                 if c.config.VerifyPeerCertificate != nil {
352                         if err := c.config.VerifyPeerCertificate(certMsg.certificates, c.verifiedChains); err != nil {
353                                 c.sendAlert(alertBadCertificate)
354                                 return err
355                         }
356                 }
357
358                 switch certs[0].PublicKey.(type) {
359                 case *rsa.PublicKey, *ecdsa.PublicKey:
360                         break
361                 default:
362                         c.sendAlert(alertUnsupportedCertificate)
363                         return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
364                 }
365
366                 c.peerCertificates = certs
367         } else {
368                 // This is a renegotiation handshake. We require that the
369                 // server's identity (i.e. leaf certificate) is unchanged and
370                 // thus any previous trust decision is still valid.
371                 //
372                 // See https://mitls.org/pages/attacks/3SHAKE for the
373                 // motivation behind this requirement.
374                 if !bytes.Equal(c.peerCertificates[0].Raw, certMsg.certificates[0]) {
375                         c.sendAlert(alertBadCertificate)
376                         return errors.New("tls: server's identity changed during renegotiation")
377                 }
378         }
379
380         msg, err = c.readHandshake()
381         if err != nil {
382                 return err
383         }
384
385         cs, ok := msg.(*certificateStatusMsg)
386         if ok {
387                 // RFC4366 on Certificate Status Request:
388                 // The server MAY return a "certificate_status" message.
389
390                 if !hs.serverHello.ocspStapling {
391                         // If a server returns a "CertificateStatus" message, then the
392                         // server MUST have included an extension of type "status_request"
393                         // with empty "extension_data" in the extended server hello.
394
395                         c.sendAlert(alertUnexpectedMessage)
396                         return errors.New("tls: received unexpected CertificateStatus message")
397                 }
398                 hs.finishedHash.Write(cs.marshal())
399
400                 if cs.statusType == statusTypeOCSP {
401                         c.ocspResponse = cs.response
402                 }
403
404                 msg, err = c.readHandshake()
405                 if err != nil {
406                         return err
407                 }
408         }
409
410         keyAgreement := hs.suite.ka(c.vers)
411
412         skx, ok := msg.(*serverKeyExchangeMsg)
413         if ok {
414                 hs.finishedHash.Write(skx.marshal())
415                 err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, c.peerCertificates[0], skx)
416                 if err != nil {
417                         c.sendAlert(alertUnexpectedMessage)
418                         return err
419                 }
420
421                 msg, err = c.readHandshake()
422                 if err != nil {
423                         return err
424                 }
425         }
426
427         var chainToSend *Certificate
428         var certRequested bool
429         certReq, ok := msg.(*certificateRequestMsg)
430         if ok {
431                 certRequested = true
432                 hs.finishedHash.Write(certReq.marshal())
433
434                 if chainToSend, err = hs.getCertificate(certReq); err != nil {
435                         c.sendAlert(alertInternalError)
436                         return err
437                 }
438
439                 msg, err = c.readHandshake()
440                 if err != nil {
441                         return err
442                 }
443         }
444
445         shd, ok := msg.(*serverHelloDoneMsg)
446         if !ok {
447                 c.sendAlert(alertUnexpectedMessage)
448                 return unexpectedMessageError(shd, msg)
449         }
450         hs.finishedHash.Write(shd.marshal())
451
452         // If the server requested a certificate then we have to send a
453         // Certificate message, even if it's empty because we don't have a
454         // certificate to send.
455         if certRequested {
456                 certMsg = new(certificateMsg)
457                 certMsg.certificates = chainToSend.Certificate
458                 hs.finishedHash.Write(certMsg.marshal())
459                 if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
460                         return err
461                 }
462         }
463
464         preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, c.peerCertificates[0])
465         if err != nil {
466                 c.sendAlert(alertInternalError)
467                 return err
468         }
469         if ckx != nil {
470                 hs.finishedHash.Write(ckx.marshal())
471                 if _, err := c.writeRecord(recordTypeHandshake, ckx.marshal()); err != nil {
472                         return err
473                 }
474         }
475
476         if chainToSend != nil && len(chainToSend.Certificate) > 0 {
477                 certVerify := &certificateVerifyMsg{
478                         hasSignatureAndHash: c.vers >= VersionTLS12,
479                 }
480
481                 key, ok := chainToSend.PrivateKey.(crypto.Signer)
482                 if !ok {
483                         c.sendAlert(alertInternalError)
484                         return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey)
485                 }
486
487                 signatureAlgorithm, sigType, hashFunc, err := pickSignatureAlgorithm(key.Public(), certReq.supportedSignatureAlgorithms, hs.hello.supportedSignatureAlgorithms, c.vers)
488                 if err != nil {
489                         c.sendAlert(alertInternalError)
490                         return err
491                 }
492                 // SignatureAndHashAlgorithm was introduced in TLS 1.2.
493                 if certVerify.hasSignatureAndHash {
494                         certVerify.signatureAlgorithm = signatureAlgorithm
495                 }
496                 digest, err := hs.finishedHash.hashForClientCertificate(sigType, hashFunc, hs.masterSecret)
497                 if err != nil {
498                         c.sendAlert(alertInternalError)
499                         return err
500                 }
501                 signOpts := crypto.SignerOpts(hashFunc)
502                 if sigType == signatureRSAPSS {
503                         signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: hashFunc}
504                 }
505                 certVerify.signature, err = key.Sign(c.config.rand(), digest, signOpts)
506                 if err != nil {
507                         c.sendAlert(alertInternalError)
508                         return err
509                 }
510
511                 hs.finishedHash.Write(certVerify.marshal())
512                 if _, err := c.writeRecord(recordTypeHandshake, certVerify.marshal()); err != nil {
513                         return err
514                 }
515         }
516
517         hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
518         if err := c.config.writeKeyLog(hs.hello.random, hs.masterSecret); err != nil {
519                 c.sendAlert(alertInternalError)
520                 return errors.New("tls: failed to write to key log: " + err.Error())
521         }
522
523         hs.finishedHash.discardHandshakeBuffer()
524
525         return nil
526 }
527
528 func (hs *clientHandshakeState) establishKeys() error {
529         c := hs.c
530
531         clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
532                 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
533         var clientCipher, serverCipher interface{}
534         var clientHash, serverHash macFunction
535         if hs.suite.cipher != nil {
536                 clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
537                 clientHash = hs.suite.mac(c.vers, clientMAC)
538                 serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
539                 serverHash = hs.suite.mac(c.vers, serverMAC)
540         } else {
541                 clientCipher = hs.suite.aead(clientKey, clientIV)
542                 serverCipher = hs.suite.aead(serverKey, serverIV)
543         }
544
545         c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
546         c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
547         return nil
548 }
549
550 func (hs *clientHandshakeState) serverResumedSession() bool {
551         // If the server responded with the same sessionId then it means the
552         // sessionTicket is being used to resume a TLS session.
553         return hs.session != nil && hs.hello.sessionId != nil &&
554                 bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
555 }
556
557 func (hs *clientHandshakeState) processServerHello() (bool, error) {
558         c := hs.c
559
560         if hs.serverHello.compressionMethod != compressionNone {
561                 c.sendAlert(alertUnexpectedMessage)
562                 return false, errors.New("tls: server selected unsupported compression format")
563         }
564
565         if c.handshakes == 0 && hs.serverHello.secureRenegotiationSupported {
566                 c.secureRenegotiation = true
567                 if len(hs.serverHello.secureRenegotiation) != 0 {
568                         c.sendAlert(alertHandshakeFailure)
569                         return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
570                 }
571         }
572
573         if c.handshakes > 0 && c.secureRenegotiation {
574                 var expectedSecureRenegotiation [24]byte
575                 copy(expectedSecureRenegotiation[:], c.clientFinished[:])
576                 copy(expectedSecureRenegotiation[12:], c.serverFinished[:])
577                 if !bytes.Equal(hs.serverHello.secureRenegotiation, expectedSecureRenegotiation[:]) {
578                         c.sendAlert(alertHandshakeFailure)
579                         return false, errors.New("tls: incorrect renegotiation extension contents")
580                 }
581         }
582
583         clientDidNPN := hs.hello.nextProtoNeg
584         clientDidALPN := len(hs.hello.alpnProtocols) > 0
585         serverHasNPN := hs.serverHello.nextProtoNeg
586         serverHasALPN := len(hs.serverHello.alpnProtocol) > 0
587
588         if !clientDidNPN && serverHasNPN {
589                 c.sendAlert(alertHandshakeFailure)
590                 return false, errors.New("tls: server advertised unrequested NPN extension")
591         }
592
593         if !clientDidALPN && serverHasALPN {
594                 c.sendAlert(alertHandshakeFailure)
595                 return false, errors.New("tls: server advertised unrequested ALPN extension")
596         }
597
598         if serverHasNPN && serverHasALPN {
599                 c.sendAlert(alertHandshakeFailure)
600                 return false, errors.New("tls: server advertised both NPN and ALPN extensions")
601         }
602
603         if serverHasALPN {
604                 c.clientProtocol = hs.serverHello.alpnProtocol
605                 c.clientProtocolFallback = false
606         }
607         c.scts = hs.serverHello.scts
608
609         if !hs.serverResumedSession() {
610                 return false, nil
611         }
612
613         if hs.session.vers != c.vers {
614                 c.sendAlert(alertHandshakeFailure)
615                 return false, errors.New("tls: server resumed a session with a different version")
616         }
617
618         if hs.session.cipherSuite != hs.suite.id {
619                 c.sendAlert(alertHandshakeFailure)
620                 return false, errors.New("tls: server resumed a session with a different cipher suite")
621         }
622
623         // Restore masterSecret and peerCerts from previous state
624         hs.masterSecret = hs.session.masterSecret
625         c.peerCertificates = hs.session.serverCertificates
626         c.verifiedChains = hs.session.verifiedChains
627         return true, nil
628 }
629
630 func (hs *clientHandshakeState) readFinished(out []byte) error {
631         c := hs.c
632
633         c.readRecord(recordTypeChangeCipherSpec)
634         if c.in.err != nil {
635                 return c.in.err
636         }
637
638         msg, err := c.readHandshake()
639         if err != nil {
640                 return err
641         }
642         serverFinished, ok := msg.(*finishedMsg)
643         if !ok {
644                 c.sendAlert(alertUnexpectedMessage)
645                 return unexpectedMessageError(serverFinished, msg)
646         }
647
648         verify := hs.finishedHash.serverSum(hs.masterSecret)
649         if len(verify) != len(serverFinished.verifyData) ||
650                 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
651                 c.sendAlert(alertHandshakeFailure)
652                 return errors.New("tls: server's Finished message was incorrect")
653         }
654         hs.finishedHash.Write(serverFinished.marshal())
655         copy(out, verify)
656         return nil
657 }
658
659 func (hs *clientHandshakeState) readSessionTicket() error {
660         if !hs.serverHello.ticketSupported {
661                 return nil
662         }
663
664         c := hs.c
665         msg, err := c.readHandshake()
666         if err != nil {
667                 return err
668         }
669         sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
670         if !ok {
671                 c.sendAlert(alertUnexpectedMessage)
672                 return unexpectedMessageError(sessionTicketMsg, msg)
673         }
674         hs.finishedHash.Write(sessionTicketMsg.marshal())
675
676         hs.session = &ClientSessionState{
677                 sessionTicket:      sessionTicketMsg.ticket,
678                 vers:               c.vers,
679                 cipherSuite:        hs.suite.id,
680                 masterSecret:       hs.masterSecret,
681                 serverCertificates: c.peerCertificates,
682                 verifiedChains:     c.verifiedChains,
683         }
684
685         return nil
686 }
687
688 func (hs *clientHandshakeState) sendFinished(out []byte) error {
689         c := hs.c
690
691         if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
692                 return err
693         }
694         if hs.serverHello.nextProtoNeg {
695                 nextProto := new(nextProtoMsg)
696                 proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.nextProtos)
697                 nextProto.proto = proto
698                 c.clientProtocol = proto
699                 c.clientProtocolFallback = fallback
700
701                 hs.finishedHash.Write(nextProto.marshal())
702                 if _, err := c.writeRecord(recordTypeHandshake, nextProto.marshal()); err != nil {
703                         return err
704                 }
705         }
706
707         finished := new(finishedMsg)
708         finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
709         hs.finishedHash.Write(finished.marshal())
710         if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
711                 return err
712         }
713         copy(out, finished.verifyData)
714         return nil
715 }
716
717 // tls11SignatureSchemes contains the signature schemes that we synthesise for
718 // a TLS <= 1.1 connection, based on the supported certificate types.
719 var tls11SignatureSchemes = []SignatureScheme{ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1}
720
721 const (
722         // tls11SignatureSchemesNumECDSA is the number of initial elements of
723         // tls11SignatureSchemes that use ECDSA.
724         tls11SignatureSchemesNumECDSA = 3
725         // tls11SignatureSchemesNumRSA is the number of trailing elements of
726         // tls11SignatureSchemes that use RSA.
727         tls11SignatureSchemesNumRSA = 4
728 )
729
730 func (hs *clientHandshakeState) getCertificate(certReq *certificateRequestMsg) (*Certificate, error) {
731         c := hs.c
732
733         var rsaAvail, ecdsaAvail bool
734         for _, certType := range certReq.certificateTypes {
735                 switch certType {
736                 case certTypeRSASign:
737                         rsaAvail = true
738                 case certTypeECDSASign:
739                         ecdsaAvail = true
740                 }
741         }
742
743         if c.config.GetClientCertificate != nil {
744                 var signatureSchemes []SignatureScheme
745
746                 if !certReq.hasSignatureAndHash {
747                         // Prior to TLS 1.2, the signature schemes were not
748                         // included in the certificate request message. In this
749                         // case we use a plausible list based on the acceptable
750                         // certificate types.
751                         signatureSchemes = tls11SignatureSchemes
752                         if !ecdsaAvail {
753                                 signatureSchemes = signatureSchemes[tls11SignatureSchemesNumECDSA:]
754                         }
755                         if !rsaAvail {
756                                 signatureSchemes = signatureSchemes[:len(signatureSchemes)-tls11SignatureSchemesNumRSA]
757                         }
758                 } else {
759                         signatureSchemes = certReq.supportedSignatureAlgorithms
760                 }
761
762                 return c.config.GetClientCertificate(&CertificateRequestInfo{
763                         AcceptableCAs:    certReq.certificateAuthorities,
764                         SignatureSchemes: signatureSchemes,
765                 })
766         }
767
768         // RFC 4346 on the certificateAuthorities field: A list of the
769         // distinguished names of acceptable certificate authorities.
770         // These distinguished names may specify a desired
771         // distinguished name for a root CA or for a subordinate CA;
772         // thus, this message can be used to describe both known roots
773         // and a desired authorization space. If the
774         // certificate_authorities list is empty then the client MAY
775         // send any certificate of the appropriate
776         // ClientCertificateType, unless there is some external
777         // arrangement to the contrary.
778
779         // We need to search our list of client certs for one
780         // where SignatureAlgorithm is acceptable to the server and the
781         // Issuer is in certReq.certificateAuthorities
782 findCert:
783         for i, chain := range c.config.Certificates {
784                 if !rsaAvail && !ecdsaAvail {
785                         continue
786                 }
787
788                 for j, cert := range chain.Certificate {
789                         x509Cert := chain.Leaf
790                         // parse the certificate if this isn't the leaf
791                         // node, or if chain.Leaf was nil
792                         if j != 0 || x509Cert == nil {
793                                 var err error
794                                 if x509Cert, err = x509.ParseCertificate(cert); err != nil {
795                                         c.sendAlert(alertInternalError)
796                                         return nil, errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error())
797                                 }
798                         }
799
800                         switch {
801                         case rsaAvail && x509Cert.PublicKeyAlgorithm == x509.RSA:
802                         case ecdsaAvail && x509Cert.PublicKeyAlgorithm == x509.ECDSA:
803                         default:
804                                 continue findCert
805                         }
806
807                         if len(certReq.certificateAuthorities) == 0 {
808                                 // they gave us an empty list, so just take the
809                                 // first cert from c.config.Certificates
810                                 return &chain, nil
811                         }
812
813                         for _, ca := range certReq.certificateAuthorities {
814                                 if bytes.Equal(x509Cert.RawIssuer, ca) {
815                                         return &chain, nil
816                                 }
817                         }
818                 }
819         }
820
821         // No acceptable certificate found. Don't send a certificate.
822         return new(Certificate), nil
823 }
824
825 // clientSessionCacheKey returns a key used to cache sessionTickets that could
826 // be used to resume previously negotiated TLS sessions with a server.
827 func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
828         if len(config.ServerName) > 0 {
829                 return config.ServerName
830         }
831         return serverAddr.String()
832 }
833
834 // mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
835 // given list of possible protocols and a list of the preference order. The
836 // first list must not be empty. It returns the resulting protocol and flag
837 // indicating if the fallback case was reached.
838 func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
839         for _, s := range preferenceProtos {
840                 for _, c := range protos {
841                         if s == c {
842                                 return s, false
843                         }
844                 }
845         }
846
847         return protos[0], true
848 }
849
850 // hostnameInSNI converts name into an approriate hostname for SNI.
851 // Literal IP addresses and absolute FQDNs are not permitted as SNI values.
852 // See https://tools.ietf.org/html/rfc6066#section-3.
853 func hostnameInSNI(name string) string {
854         host := name
855         if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' {
856                 host = host[1 : len(host)-1]
857         }
858         if i := strings.LastIndex(host, "%"); i > 0 {
859                 host = host[:i]
860         }
861         if net.ParseIP(host) != nil {
862                 return ""
863         }
864         for len(name) > 0 && name[len(name)-1] == '.' {
865                 name = name[:len(name)-1]
866         }
867         return name
868 }