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
5package main
6
7import (
8	"bytes"
9	"crypto/ecdsa"
10	"crypto/elliptic"
11	"crypto/rsa"
12	"crypto/subtle"
13	"crypto/x509"
14	"encoding/asn1"
15	"errors"
16	"fmt"
17	"io"
18	"math/big"
19	"net"
20	"strconv"
21)
22
23type clientHandshakeState struct {
24	c             *Conn
25	serverHello   *serverHelloMsg
26	hello         *clientHelloMsg
27	suite         *cipherSuite
28	finishedHash  finishedHash
29	masterSecret  []byte
30	session       *ClientSessionState
31	finishedBytes []byte
32}
33
34func (c *Conn) clientHandshake() error {
35	if c.config == nil {
36		c.config = defaultConfig()
37	}
38
39	if len(c.config.ServerName) == 0 && !c.config.InsecureSkipVerify {
40		return errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
41	}
42
43	c.sendHandshakeSeq = 0
44	c.recvHandshakeSeq = 0
45
46	nextProtosLength := 0
47	for _, proto := range c.config.NextProtos {
48		if l := len(proto); l == 0 || l > 255 {
49			return errors.New("tls: invalid NextProtos value")
50		} else {
51			nextProtosLength += 1 + l
52		}
53	}
54	if nextProtosLength > 0xffff {
55		return errors.New("tls: NextProtos values too large")
56	}
57
58	hello := &clientHelloMsg{
59		isDTLS:                  c.isDTLS,
60		vers:                    c.config.maxVersion(),
61		compressionMethods:      []uint8{compressionNone},
62		random:                  make([]byte, 32),
63		ocspStapling:            true,
64		serverName:              c.config.ServerName,
65		supportedCurves:         c.config.curvePreferences(),
66		supportedPoints:         []uint8{pointFormatUncompressed},
67		nextProtoNeg:            len(c.config.NextProtos) > 0,
68		secureRenegotiation:     []byte{},
69		alpnProtocols:           c.config.NextProtos,
70		duplicateExtension:      c.config.Bugs.DuplicateExtension,
71		channelIDSupported:      c.config.ChannelID != nil,
72		npnLast:                 c.config.Bugs.SwapNPNAndALPN,
73		extendedMasterSecret:    c.config.maxVersion() >= VersionTLS10,
74		srtpProtectionProfiles:  c.config.SRTPProtectionProfiles,
75		srtpMasterKeyIdentifier: c.config.Bugs.SRTPMasterKeyIdentifer,
76	}
77
78	if c.config.Bugs.SendClientVersion != 0 {
79		hello.vers = c.config.Bugs.SendClientVersion
80	}
81
82	if c.config.Bugs.NoExtendedMasterSecret {
83		hello.extendedMasterSecret = false
84	}
85
86	if c.config.Bugs.NoSupportedCurves {
87		hello.supportedCurves = nil
88	}
89
90	if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
91		if c.config.Bugs.BadRenegotiationInfo {
92			hello.secureRenegotiation = append(hello.secureRenegotiation, c.clientVerify...)
93			hello.secureRenegotiation[0] ^= 0x80
94		} else {
95			hello.secureRenegotiation = c.clientVerify
96		}
97	}
98
99	if c.config.Bugs.NoRenegotiationInfo {
100		hello.secureRenegotiation = nil
101	}
102
103	possibleCipherSuites := c.config.cipherSuites()
104	hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites))
105
106NextCipherSuite:
107	for _, suiteId := range possibleCipherSuites {
108		for _, suite := range cipherSuites {
109			if suite.id != suiteId {
110				continue
111			}
112			// Don't advertise TLS 1.2-only cipher suites unless
113			// we're attempting TLS 1.2.
114			if hello.vers < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
115				continue
116			}
117			// Don't advertise non-DTLS cipher suites on DTLS.
118			if c.isDTLS && suite.flags&suiteNoDTLS != 0 && !c.config.Bugs.EnableAllCiphersInDTLS {
119				continue
120			}
121			hello.cipherSuites = append(hello.cipherSuites, suiteId)
122			continue NextCipherSuite
123		}
124	}
125
126	if c.config.Bugs.SendFallbackSCSV {
127		hello.cipherSuites = append(hello.cipherSuites, fallbackSCSV)
128	}
129
130	_, err := io.ReadFull(c.config.rand(), hello.random)
131	if err != nil {
132		c.sendAlert(alertInternalError)
133		return errors.New("tls: short read from Rand: " + err.Error())
134	}
135
136	if hello.vers >= VersionTLS12 && !c.config.Bugs.NoSignatureAndHashes {
137		hello.signatureAndHashes = c.config.signatureAndHashesForClient()
138	}
139
140	var session *ClientSessionState
141	var cacheKey string
142	sessionCache := c.config.ClientSessionCache
143
144	if sessionCache != nil {
145		hello.ticketSupported = !c.config.SessionTicketsDisabled
146
147		// Try to resume a previously negotiated TLS session, if
148		// available.
149		cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
150		candidateSession, ok := sessionCache.Get(cacheKey)
151		if ok {
152			ticketOk := !c.config.SessionTicketsDisabled || candidateSession.sessionTicket == nil
153
154			// Check that the ciphersuite/version used for the
155			// previous session are still valid.
156			cipherSuiteOk := false
157			for _, id := range hello.cipherSuites {
158				if id == candidateSession.cipherSuite {
159					cipherSuiteOk = true
160					break
161				}
162			}
163
164			versOk := candidateSession.vers >= c.config.minVersion() &&
165				candidateSession.vers <= c.config.maxVersion()
166			if ticketOk && versOk && cipherSuiteOk {
167				session = candidateSession
168			}
169		}
170	}
171
172	if session != nil {
173		if session.sessionTicket != nil {
174			hello.sessionTicket = session.sessionTicket
175			if c.config.Bugs.CorruptTicket {
176				hello.sessionTicket = make([]byte, len(session.sessionTicket))
177				copy(hello.sessionTicket, session.sessionTicket)
178				if len(hello.sessionTicket) > 0 {
179					offset := 40
180					if offset > len(hello.sessionTicket) {
181						offset = len(hello.sessionTicket) - 1
182					}
183					hello.sessionTicket[offset] ^= 0x40
184				}
185			}
186			// A random session ID is used to detect when the
187			// server accepted the ticket and is resuming a session
188			// (see RFC 5077).
189			sessionIdLen := 16
190			if c.config.Bugs.OversizedSessionId {
191				sessionIdLen = 33
192			}
193			hello.sessionId = make([]byte, sessionIdLen)
194			if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil {
195				c.sendAlert(alertInternalError)
196				return errors.New("tls: short read from Rand: " + err.Error())
197			}
198		} else {
199			hello.sessionId = session.sessionId
200		}
201	}
202
203	var helloBytes []byte
204	if c.config.Bugs.SendV2ClientHello {
205		// Test that the peer left-pads random.
206		hello.random[0] = 0
207		v2Hello := &v2ClientHelloMsg{
208			vers:         hello.vers,
209			cipherSuites: hello.cipherSuites,
210			// No session resumption for V2ClientHello.
211			sessionId: nil,
212			challenge: hello.random[1:],
213		}
214		helloBytes = v2Hello.marshal()
215		c.writeV2Record(helloBytes)
216	} else {
217		helloBytes = hello.marshal()
218		c.writeRecord(recordTypeHandshake, helloBytes)
219	}
220	c.dtlsFlushHandshake()
221
222	if err := c.simulatePacketLoss(nil); err != nil {
223		return err
224	}
225	msg, err := c.readHandshake()
226	if err != nil {
227		return err
228	}
229
230	if c.isDTLS {
231		helloVerifyRequest, ok := msg.(*helloVerifyRequestMsg)
232		if ok {
233			if helloVerifyRequest.vers != VersionTLS10 {
234				// Per RFC 6347, the version field in
235				// HelloVerifyRequest SHOULD be always DTLS
236				// 1.0. Enforce this for testing purposes.
237				return errors.New("dtls: bad HelloVerifyRequest version")
238			}
239
240			hello.raw = nil
241			hello.cookie = helloVerifyRequest.cookie
242			helloBytes = hello.marshal()
243			c.writeRecord(recordTypeHandshake, helloBytes)
244			c.dtlsFlushHandshake()
245
246			if err := c.simulatePacketLoss(nil); err != nil {
247				return err
248			}
249			msg, err = c.readHandshake()
250			if err != nil {
251				return err
252			}
253		}
254	}
255
256	serverHello, ok := msg.(*serverHelloMsg)
257	if !ok {
258		c.sendAlert(alertUnexpectedMessage)
259		return unexpectedMessageError(serverHello, msg)
260	}
261
262	c.vers, ok = c.config.mutualVersion(serverHello.vers)
263	if !ok {
264		c.sendAlert(alertProtocolVersion)
265		return fmt.Errorf("tls: server selected unsupported protocol version %x", serverHello.vers)
266	}
267	c.haveVers = true
268
269	suite := mutualCipherSuite(c.config.cipherSuites(), serverHello.cipherSuite)
270	if suite == nil {
271		c.sendAlert(alertHandshakeFailure)
272		return fmt.Errorf("tls: server selected an unsupported cipher suite")
273	}
274
275	if len(c.clientVerify) > 0 && !c.config.Bugs.NoRenegotiationInfo {
276		var expectedRenegInfo []byte
277		expectedRenegInfo = append(expectedRenegInfo, c.clientVerify...)
278		expectedRenegInfo = append(expectedRenegInfo, c.serverVerify...)
279		if !bytes.Equal(serverHello.secureRenegotiation, expectedRenegInfo) {
280			c.sendAlert(alertHandshakeFailure)
281			return fmt.Errorf("tls: renegotiation mismatch")
282		}
283	}
284
285	hs := &clientHandshakeState{
286		c:            c,
287		serverHello:  serverHello,
288		hello:        hello,
289		suite:        suite,
290		finishedHash: newFinishedHash(c.vers, suite),
291		session:      session,
292	}
293
294	hs.writeHash(helloBytes, hs.c.sendHandshakeSeq-1)
295	hs.writeServerHash(hs.serverHello.marshal())
296
297	if c.config.Bugs.EarlyChangeCipherSpec > 0 {
298		hs.establishKeys()
299		c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
300	}
301
302	isResume, err := hs.processServerHello()
303	if err != nil {
304		return err
305	}
306
307	if isResume {
308		if c.config.Bugs.EarlyChangeCipherSpec == 0 {
309			if err := hs.establishKeys(); err != nil {
310				return err
311			}
312		}
313		if err := hs.readSessionTicket(); err != nil {
314			return err
315		}
316		if err := hs.readFinished(c.firstFinished[:]); err != nil {
317			return err
318		}
319		if err := hs.sendFinished(nil, isResume); err != nil {
320			return err
321		}
322	} else {
323		if err := hs.doFullHandshake(); err != nil {
324			return err
325		}
326		if err := hs.establishKeys(); err != nil {
327			return err
328		}
329		if err := hs.sendFinished(c.firstFinished[:], isResume); err != nil {
330			return err
331		}
332		// Most retransmits are triggered by a timeout, but the final
333		// leg of the handshake is retransmited upon re-receiving a
334		// Finished.
335		if err := c.simulatePacketLoss(func() {
336			c.writeRecord(recordTypeHandshake, hs.finishedBytes)
337			c.dtlsFlushHandshake()
338		}); err != nil {
339			return err
340		}
341		if err := hs.readSessionTicket(); err != nil {
342			return err
343		}
344		if err := hs.readFinished(nil); err != nil {
345			return err
346		}
347	}
348
349	if sessionCache != nil && hs.session != nil && session != hs.session {
350		sessionCache.Put(cacheKey, hs.session)
351	}
352
353	c.didResume = isResume
354	c.handshakeComplete = true
355	c.cipherSuite = suite
356	copy(c.clientRandom[:], hs.hello.random)
357	copy(c.serverRandom[:], hs.serverHello.random)
358	copy(c.masterSecret[:], hs.masterSecret)
359	return nil
360}
361
362func (hs *clientHandshakeState) doFullHandshake() error {
363	c := hs.c
364
365	var leaf *x509.Certificate
366	if hs.suite.flags&suitePSK == 0 {
367		msg, err := c.readHandshake()
368		if err != nil {
369			return err
370		}
371
372		certMsg, ok := msg.(*certificateMsg)
373		if !ok || len(certMsg.certificates) == 0 {
374			c.sendAlert(alertUnexpectedMessage)
375			return unexpectedMessageError(certMsg, msg)
376		}
377		hs.writeServerHash(certMsg.marshal())
378
379		certs := make([]*x509.Certificate, len(certMsg.certificates))
380		for i, asn1Data := range certMsg.certificates {
381			cert, err := x509.ParseCertificate(asn1Data)
382			if err != nil {
383				c.sendAlert(alertBadCertificate)
384				return errors.New("tls: failed to parse certificate from server: " + err.Error())
385			}
386			certs[i] = cert
387		}
388		leaf = certs[0]
389
390		if !c.config.InsecureSkipVerify {
391			opts := x509.VerifyOptions{
392				Roots:         c.config.RootCAs,
393				CurrentTime:   c.config.time(),
394				DNSName:       c.config.ServerName,
395				Intermediates: x509.NewCertPool(),
396			}
397
398			for i, cert := range certs {
399				if i == 0 {
400					continue
401				}
402				opts.Intermediates.AddCert(cert)
403			}
404			c.verifiedChains, err = leaf.Verify(opts)
405			if err != nil {
406				c.sendAlert(alertBadCertificate)
407				return err
408			}
409		}
410
411		switch leaf.PublicKey.(type) {
412		case *rsa.PublicKey, *ecdsa.PublicKey:
413			break
414		default:
415			c.sendAlert(alertUnsupportedCertificate)
416			return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", leaf.PublicKey)
417		}
418
419		c.peerCertificates = certs
420	}
421
422	if hs.serverHello.ocspStapling {
423		msg, err := c.readHandshake()
424		if err != nil {
425			return err
426		}
427		cs, ok := msg.(*certificateStatusMsg)
428		if !ok {
429			c.sendAlert(alertUnexpectedMessage)
430			return unexpectedMessageError(cs, msg)
431		}
432		hs.writeServerHash(cs.marshal())
433
434		if cs.statusType == statusTypeOCSP {
435			c.ocspResponse = cs.response
436		}
437	}
438
439	msg, err := c.readHandshake()
440	if err != nil {
441		return err
442	}
443
444	keyAgreement := hs.suite.ka(c.vers)
445
446	skx, ok := msg.(*serverKeyExchangeMsg)
447	if ok {
448		hs.writeServerHash(skx.marshal())
449		err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, leaf, skx)
450		if err != nil {
451			c.sendAlert(alertUnexpectedMessage)
452			return err
453		}
454
455		msg, err = c.readHandshake()
456		if err != nil {
457			return err
458		}
459	}
460
461	var chainToSend *Certificate
462	var certRequested bool
463	certReq, ok := msg.(*certificateRequestMsg)
464	if ok {
465		certRequested = true
466
467		// RFC 4346 on the certificateAuthorities field:
468		// A list of the distinguished names of acceptable certificate
469		// authorities. These distinguished names may specify a desired
470		// distinguished name for a root CA or for a subordinate CA;
471		// thus, this message can be used to describe both known roots
472		// and a desired authorization space. If the
473		// certificate_authorities list is empty then the client MAY
474		// send any certificate of the appropriate
475		// ClientCertificateType, unless there is some external
476		// arrangement to the contrary.
477
478		hs.writeServerHash(certReq.marshal())
479
480		var rsaAvail, ecdsaAvail bool
481		for _, certType := range certReq.certificateTypes {
482			switch certType {
483			case CertTypeRSASign:
484				rsaAvail = true
485			case CertTypeECDSASign:
486				ecdsaAvail = true
487			}
488		}
489
490		// We need to search our list of client certs for one
491		// where SignatureAlgorithm is RSA and the Issuer is in
492		// certReq.certificateAuthorities
493	findCert:
494		for i, chain := range c.config.Certificates {
495			if !rsaAvail && !ecdsaAvail {
496				continue
497			}
498
499			for j, cert := range chain.Certificate {
500				x509Cert := chain.Leaf
501				// parse the certificate if this isn't the leaf
502				// node, or if chain.Leaf was nil
503				if j != 0 || x509Cert == nil {
504					if x509Cert, err = x509.ParseCertificate(cert); err != nil {
505						c.sendAlert(alertInternalError)
506						return errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error())
507					}
508				}
509
510				switch {
511				case rsaAvail && x509Cert.PublicKeyAlgorithm == x509.RSA:
512				case ecdsaAvail && x509Cert.PublicKeyAlgorithm == x509.ECDSA:
513				default:
514					continue findCert
515				}
516
517				if len(certReq.certificateAuthorities) == 0 {
518					// they gave us an empty list, so just take the
519					// first RSA cert from c.config.Certificates
520					chainToSend = &chain
521					break findCert
522				}
523
524				for _, ca := range certReq.certificateAuthorities {
525					if bytes.Equal(x509Cert.RawIssuer, ca) {
526						chainToSend = &chain
527						break findCert
528					}
529				}
530			}
531		}
532
533		msg, err = c.readHandshake()
534		if err != nil {
535			return err
536		}
537	}
538
539	shd, ok := msg.(*serverHelloDoneMsg)
540	if !ok {
541		c.sendAlert(alertUnexpectedMessage)
542		return unexpectedMessageError(shd, msg)
543	}
544	hs.writeServerHash(shd.marshal())
545
546	// If the server requested a certificate then we have to send a
547	// Certificate message, even if it's empty because we don't have a
548	// certificate to send.
549	if certRequested {
550		certMsg := new(certificateMsg)
551		if chainToSend != nil {
552			certMsg.certificates = chainToSend.Certificate
553		}
554		hs.writeClientHash(certMsg.marshal())
555		c.writeRecord(recordTypeHandshake, certMsg.marshal())
556	}
557
558	preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, leaf)
559	if err != nil {
560		c.sendAlert(alertInternalError)
561		return err
562	}
563	if ckx != nil {
564		if c.config.Bugs.EarlyChangeCipherSpec < 2 {
565			hs.writeClientHash(ckx.marshal())
566		}
567		c.writeRecord(recordTypeHandshake, ckx.marshal())
568	}
569
570	if hs.serverHello.extendedMasterSecret && c.vers >= VersionTLS10 {
571		hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
572		c.extendedMasterSecret = true
573	} else {
574		if c.config.Bugs.RequireExtendedMasterSecret {
575			return errors.New("tls: extended master secret required but not supported by peer")
576		}
577		hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
578	}
579
580	if chainToSend != nil {
581		var signed []byte
582		certVerify := &certificateVerifyMsg{
583			hasSignatureAndHash: c.vers >= VersionTLS12,
584		}
585
586		// Determine the hash to sign.
587		var signatureType uint8
588		switch c.config.Certificates[0].PrivateKey.(type) {
589		case *ecdsa.PrivateKey:
590			signatureType = signatureECDSA
591		case *rsa.PrivateKey:
592			signatureType = signatureRSA
593		default:
594			c.sendAlert(alertInternalError)
595			return errors.New("unknown private key type")
596		}
597		if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
598			certReq.signatureAndHashes = c.config.signatureAndHashesForClient()
599		}
600		certVerify.signatureAndHash, err = hs.finishedHash.selectClientCertSignatureAlgorithm(certReq.signatureAndHashes, c.config.signatureAndHashesForClient(), signatureType)
601		if err != nil {
602			c.sendAlert(alertInternalError)
603			return err
604		}
605		digest, hashFunc, err := hs.finishedHash.hashForClientCertificate(certVerify.signatureAndHash, hs.masterSecret)
606		if err != nil {
607			c.sendAlert(alertInternalError)
608			return err
609		}
610
611		switch key := c.config.Certificates[0].PrivateKey.(type) {
612		case *ecdsa.PrivateKey:
613			var r, s *big.Int
614			r, s, err = ecdsa.Sign(c.config.rand(), key, digest)
615			if err == nil {
616				signed, err = asn1.Marshal(ecdsaSignature{r, s})
617			}
618		case *rsa.PrivateKey:
619			signed, err = rsa.SignPKCS1v15(c.config.rand(), key, hashFunc, digest)
620		default:
621			err = errors.New("unknown private key type")
622		}
623		if err != nil {
624			c.sendAlert(alertInternalError)
625			return errors.New("tls: failed to sign handshake with client certificate: " + err.Error())
626		}
627		certVerify.signature = signed
628
629		hs.writeClientHash(certVerify.marshal())
630		c.writeRecord(recordTypeHandshake, certVerify.marshal())
631	}
632	c.dtlsFlushHandshake()
633
634	hs.finishedHash.discardHandshakeBuffer()
635
636	return nil
637}
638
639func (hs *clientHandshakeState) establishKeys() error {
640	c := hs.c
641
642	clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
643		keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
644	var clientCipher, serverCipher interface{}
645	var clientHash, serverHash macFunction
646	if hs.suite.cipher != nil {
647		clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
648		clientHash = hs.suite.mac(c.vers, clientMAC)
649		serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
650		serverHash = hs.suite.mac(c.vers, serverMAC)
651	} else {
652		clientCipher = hs.suite.aead(clientKey, clientIV)
653		serverCipher = hs.suite.aead(serverKey, serverIV)
654	}
655
656	c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
657	c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
658	return nil
659}
660
661func (hs *clientHandshakeState) serverResumedSession() bool {
662	// If the server responded with the same sessionId then it means the
663	// sessionTicket is being used to resume a TLS session.
664	return hs.session != nil && hs.hello.sessionId != nil &&
665		bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
666}
667
668func (hs *clientHandshakeState) processServerHello() (bool, error) {
669	c := hs.c
670
671	if hs.serverHello.compressionMethod != compressionNone {
672		c.sendAlert(alertUnexpectedMessage)
673		return false, errors.New("tls: server selected unsupported compression format")
674	}
675
676	clientDidNPN := hs.hello.nextProtoNeg
677	clientDidALPN := len(hs.hello.alpnProtocols) > 0
678	serverHasNPN := hs.serverHello.nextProtoNeg
679	serverHasALPN := len(hs.serverHello.alpnProtocol) > 0
680
681	if !clientDidNPN && serverHasNPN {
682		c.sendAlert(alertHandshakeFailure)
683		return false, errors.New("server advertised unrequested NPN extension")
684	}
685
686	if !clientDidALPN && serverHasALPN {
687		c.sendAlert(alertHandshakeFailure)
688		return false, errors.New("server advertised unrequested ALPN extension")
689	}
690
691	if serverHasNPN && serverHasALPN {
692		c.sendAlert(alertHandshakeFailure)
693		return false, errors.New("server advertised both NPN and ALPN extensions")
694	}
695
696	if serverHasALPN {
697		c.clientProtocol = hs.serverHello.alpnProtocol
698		c.clientProtocolFallback = false
699		c.usedALPN = true
700	}
701
702	if !hs.hello.channelIDSupported && hs.serverHello.channelIDRequested {
703		c.sendAlert(alertHandshakeFailure)
704		return false, errors.New("server advertised unrequested Channel ID extension")
705	}
706
707	if hs.serverHello.srtpProtectionProfile != 0 {
708		if hs.serverHello.srtpMasterKeyIdentifier != "" {
709			return false, errors.New("tls: server selected SRTP MKI value")
710		}
711
712		found := false
713		for _, p := range c.config.SRTPProtectionProfiles {
714			if p == hs.serverHello.srtpProtectionProfile {
715				found = true
716				break
717			}
718		}
719		if !found {
720			return false, errors.New("tls: server advertised unsupported SRTP profile")
721		}
722
723		c.srtpProtectionProfile = hs.serverHello.srtpProtectionProfile
724	}
725
726	if hs.serverResumedSession() {
727		// For test purposes, assert that the server never accepts the
728		// resumption offer on renegotiation.
729		if c.cipherSuite != nil && c.config.Bugs.FailIfResumeOnRenego {
730			return false, errors.New("tls: server resumed session on renegotiation")
731		}
732
733		// Restore masterSecret and peerCerts from previous state
734		hs.masterSecret = hs.session.masterSecret
735		c.peerCertificates = hs.session.serverCertificates
736		c.extendedMasterSecret = hs.session.extendedMasterSecret
737		hs.finishedHash.discardHandshakeBuffer()
738		return true, nil
739	}
740	return false, nil
741}
742
743func (hs *clientHandshakeState) readFinished(out []byte) error {
744	c := hs.c
745
746	c.readRecord(recordTypeChangeCipherSpec)
747	if err := c.in.error(); err != nil {
748		return err
749	}
750
751	msg, err := c.readHandshake()
752	if err != nil {
753		return err
754	}
755	serverFinished, ok := msg.(*finishedMsg)
756	if !ok {
757		c.sendAlert(alertUnexpectedMessage)
758		return unexpectedMessageError(serverFinished, msg)
759	}
760
761	if c.config.Bugs.EarlyChangeCipherSpec == 0 {
762		verify := hs.finishedHash.serverSum(hs.masterSecret)
763		if len(verify) != len(serverFinished.verifyData) ||
764			subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
765			c.sendAlert(alertHandshakeFailure)
766			return errors.New("tls: server's Finished message was incorrect")
767		}
768	}
769	c.serverVerify = append(c.serverVerify[:0], serverFinished.verifyData...)
770	copy(out, serverFinished.verifyData)
771	hs.writeServerHash(serverFinished.marshal())
772	return nil
773}
774
775func (hs *clientHandshakeState) readSessionTicket() error {
776	c := hs.c
777
778	// Create a session with no server identifier. Either a
779	// session ID or session ticket will be attached.
780	session := &ClientSessionState{
781		vers:               c.vers,
782		cipherSuite:        hs.suite.id,
783		masterSecret:       hs.masterSecret,
784		handshakeHash:      hs.finishedHash.server.Sum(nil),
785		serverCertificates: c.peerCertificates,
786	}
787
788	if !hs.serverHello.ticketSupported {
789		if hs.session == nil && len(hs.serverHello.sessionId) > 0 {
790			session.sessionId = hs.serverHello.sessionId
791			hs.session = session
792		}
793		return nil
794	}
795
796	msg, err := c.readHandshake()
797	if err != nil {
798		return err
799	}
800	sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
801	if !ok {
802		c.sendAlert(alertUnexpectedMessage)
803		return unexpectedMessageError(sessionTicketMsg, msg)
804	}
805
806	session.sessionTicket = sessionTicketMsg.ticket
807	hs.session = session
808
809	hs.writeServerHash(sessionTicketMsg.marshal())
810
811	return nil
812}
813
814func (hs *clientHandshakeState) sendFinished(out []byte, isResume bool) error {
815	c := hs.c
816
817	var postCCSBytes []byte
818	seqno := hs.c.sendHandshakeSeq
819	if hs.serverHello.nextProtoNeg {
820		nextProto := new(nextProtoMsg)
821		proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.nextProtos)
822		nextProto.proto = proto
823		c.clientProtocol = proto
824		c.clientProtocolFallback = fallback
825
826		nextProtoBytes := nextProto.marshal()
827		hs.writeHash(nextProtoBytes, seqno)
828		seqno++
829		postCCSBytes = append(postCCSBytes, nextProtoBytes...)
830	}
831
832	if hs.serverHello.channelIDRequested {
833		encryptedExtensions := new(encryptedExtensionsMsg)
834		if c.config.ChannelID.Curve != elliptic.P256() {
835			return fmt.Errorf("tls: Channel ID is not on P-256.")
836		}
837		var resumeHash []byte
838		if isResume {
839			resumeHash = hs.session.handshakeHash
840		}
841		r, s, err := ecdsa.Sign(c.config.rand(), c.config.ChannelID, hs.finishedHash.hashForChannelID(resumeHash))
842		if err != nil {
843			return err
844		}
845		channelID := make([]byte, 128)
846		writeIntPadded(channelID[0:32], c.config.ChannelID.X)
847		writeIntPadded(channelID[32:64], c.config.ChannelID.Y)
848		writeIntPadded(channelID[64:96], r)
849		writeIntPadded(channelID[96:128], s)
850		encryptedExtensions.channelID = channelID
851
852		c.channelID = &c.config.ChannelID.PublicKey
853
854		encryptedExtensionsBytes := encryptedExtensions.marshal()
855		hs.writeHash(encryptedExtensionsBytes, seqno)
856		seqno++
857		postCCSBytes = append(postCCSBytes, encryptedExtensionsBytes...)
858	}
859
860	finished := new(finishedMsg)
861	if c.config.Bugs.EarlyChangeCipherSpec == 2 {
862		finished.verifyData = hs.finishedHash.clientSum(nil)
863	} else {
864		finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
865	}
866	copy(out, finished.verifyData)
867	if c.config.Bugs.BadFinished {
868		finished.verifyData[0]++
869	}
870	c.clientVerify = append(c.clientVerify[:0], finished.verifyData...)
871	hs.finishedBytes = finished.marshal()
872	hs.writeHash(hs.finishedBytes, seqno)
873	postCCSBytes = append(postCCSBytes, hs.finishedBytes...)
874
875	if c.config.Bugs.FragmentAcrossChangeCipherSpec {
876		c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
877		postCCSBytes = postCCSBytes[5:]
878	}
879	c.dtlsFlushHandshake()
880
881	if !c.config.Bugs.SkipChangeCipherSpec &&
882		c.config.Bugs.EarlyChangeCipherSpec == 0 {
883		c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
884	}
885
886	if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
887		c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
888	}
889	if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
890		c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
891		return errors.New("tls: simulating post-CCS alert")
892	}
893
894	if !c.config.Bugs.SkipFinished {
895		c.writeRecord(recordTypeHandshake, postCCSBytes)
896		c.dtlsFlushHandshake()
897	}
898	return nil
899}
900
901func (hs *clientHandshakeState) writeClientHash(msg []byte) {
902	// writeClientHash is called before writeRecord.
903	hs.writeHash(msg, hs.c.sendHandshakeSeq)
904}
905
906func (hs *clientHandshakeState) writeServerHash(msg []byte) {
907	// writeServerHash is called after readHandshake.
908	hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
909}
910
911func (hs *clientHandshakeState) writeHash(msg []byte, seqno uint16) {
912	if hs.c.isDTLS {
913		// This is somewhat hacky. DTLS hashes a slightly different format.
914		// First, the TLS header.
915		hs.finishedHash.Write(msg[:4])
916		// Then the sequence number and reassembled fragment offset (always 0).
917		hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
918		// Then the reassembled fragment (always equal to the message length).
919		hs.finishedHash.Write(msg[1:4])
920		// And then the message body.
921		hs.finishedHash.Write(msg[4:])
922	} else {
923		hs.finishedHash.Write(msg)
924	}
925}
926
927// clientSessionCacheKey returns a key used to cache sessionTickets that could
928// be used to resume previously negotiated TLS sessions with a server.
929func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
930	if len(config.ServerName) > 0 {
931		return config.ServerName
932	}
933	return serverAddr.String()
934}
935
936// mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
937// given list of possible protocols and a list of the preference order. The
938// first list must not be empty. It returns the resulting protocol and flag
939// indicating if the fallback case was reached.
940func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
941	for _, s := range preferenceProtos {
942		for _, c := range protos {
943			if s == c {
944				return s, false
945			}
946		}
947	}
948
949	return protos[0], true
950}
951
952// writeIntPadded writes x into b, padded up with leading zeros as
953// needed.
954func writeIntPadded(b []byte, x *big.Int) {
955	for i := range b {
956		b[i] = 0
957	}
958	xb := x.Bytes()
959	copy(b[len(b)-len(xb):], xb)
960}
961