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 tls
6
7import (
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	"sync/atomic"
19	"time"
20
21	"github.com/ooni/psiphon/oopsi/github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/obfuscator"
22)
23
24// serverHandshakeState contains details of a server handshake in progress.
25// It's discarded once the handshake has completed.
26type serverHandshakeState struct {
27	c                     *Conn
28	suite                 *cipherSuite
29	masterSecret          []byte
30	cachedClientHelloInfo *ClientHelloInfo
31	clientHello           *clientHelloMsg
32	hello                 *serverHelloMsg
33	cert                  *Certificate
34	privateKey            crypto.PrivateKey
35
36	// A marshalled DelegatedCredential to be sent to the client in the
37	// handshake.
38	delegatedCredential []byte
39
40	// TLS 1.0-1.2 fields
41	ellipticOk      bool
42	ecdsaOk         bool
43	rsaDecryptOk    bool
44	rsaSignOk       bool
45	sessionState    *sessionState
46	finishedHash    finishedHash
47	certsFromClient [][]byte
48
49	// TLS 1.3 fields
50	hello13Enc        *encryptedExtensionsMsg
51	keySchedule       *keySchedule13
52	clientFinishedKey []byte
53	hsClientCipher    interface{}
54	appClientCipher   interface{}
55}
56
57// serverHandshake performs a TLS handshake as a server.
58// c.out.Mutex <= L; c.handshakeMutex <= L.
59func (c *Conn) serverHandshake() error {
60	// If this is the first server handshake, we generate a random key to
61	// encrypt the tickets with.
62	c.config.serverInitOnce.Do(func() { c.config.serverInit(nil) })
63
64	hs := serverHandshakeState{
65		c: c,
66	}
67	c.in.traceErr = hs.traceErr
68	c.out.traceErr = hs.traceErr
69	isResume, err := hs.readClientHello()
70
71	// [Psiphon]
72	// The ClientHello with the passthrough message is now available. Route the
73	// client to passthrough based on message inspection. This code assumes the
74	// client TCP conn has been wrapped with recordingConn, which has recorded
75	// all bytes sent by the client, which will be replayed, byte-for-byte, to
76	// the passthrough; as a result, passthrough clients will perform their TLS
77	// handshake with the passthrough target, receive its certificate, and in the
78	// case of HTTPS, receive the passthrough target's HTTP responses.
79	//
80	// Passthrough is also triggered if readClientHello fails. E.g., on other
81	// invalid input cases including "tls: handshake message of length..." or if
82	// the ClientHello is otherwise invalid. This ensures that clients sending
83	// random data will be relayed to the passthrough and not receive a
84	// distinguishing error response.
85	//
86	// The `tls` API performs handshakes on demand. E.g., the first call to
87	// tls.Conn.Read will perform a handshake if it's not yet been performed.
88	// Consumers such as `http` may call Read and then Close. To minimize code
89	// changes, in the passthrough case the ownership of Conn.conn, the client
90	// TCP conn, is transferred to the passthrough relay and a closedConn is
91	// substituted for Conn.conn. This allows the remaining `tls` code paths to
92	// continue reference a net.Conn, albeit one that is closed, so Reads and
93	// Writes will fail.
94
95	if c.config.PassthroughAddress != "" {
96
97		doPassthrough := false
98
99		if err != nil {
100			doPassthrough = true
101			err = fmt.Errorf("passthrough: %s", err)
102		}
103
104		clientAddr := c.conn.RemoteAddr().String()
105		clientIP, _, _ := net.SplitHostPort(clientAddr)
106
107		if !doPassthrough {
108			if !obfuscator.VerifyTLSPassthroughMessage(
109				c.config.PassthroughKey, hs.clientHello.random) {
110
111				c.config.PassthroughLogInvalidMessage(clientIP)
112
113				doPassthrough = true
114				err = errors.New("passthrough: invalid client random")
115			}
116		}
117
118		if !doPassthrough {
119			if !c.config.PassthroughHistoryAddNew(
120				clientIP, hs.clientHello.random) {
121
122				doPassthrough = true
123				err = errors.New("passthrough: duplicate client random")
124			}
125		}
126
127		// Call GetReadBuffer, in both passthrough and non-passthrough cases, to
128		// stop buffering all read bytes.
129
130		passthroughReadBuffer := c.conn.(*recorderConn).GetReadBuffer().Bytes()
131
132		if doPassthrough {
133
134			// When performing passthrough, we must exit at the "return err" below.
135			// This is a failsafe to ensure err is always set.
136			if err == nil {
137				err = errors.New("passthrough: missing error")
138			}
139
140			// Modifying c.conn directly is safe only because Conn.Handshake, which
141			// calls Conn.serverHandshake, is holding c.handshakeMutex and c.in locks,
142			// and because of the serial nature of c.conn access during the handshake
143			// sequence.
144			conn := c.conn
145			c.conn = newClosedConn(conn)
146
147			go func() {
148
149				// Perform the passthrough relay.
150				//
151				// Limitations:
152				//
153				// - The local TCP stack may differ from passthrough target in a
154				//   detectable way.
155				//
156				// - There may be detectable timing characteristics due to the network hop
157				//   to the passthrough target.
158				//
159				// - Application-level socket operations may produce detectable
160				//   differences (e.g., CloseWrite/FIN).
161				//
162				// - The dial to the passthrough, or other upstream network operations,
163				//   may fail. These errors are not logged.
164				//
165				// - There's no timeout on the passthrough dial and no time limit on the
166				//   passthrough relay so that the invalid client can't detect a timeout
167				//   shorter than the passthrough target; this may cause additional load.
168
169				defer conn.Close()
170
171				passthroughConn, err := net.Dial("tcp", c.config.PassthroughAddress)
172				if err != nil {
173					return
174				}
175				_, err = passthroughConn.Write(passthroughReadBuffer)
176				if err != nil {
177					return
178				}
179
180				// Allow garbage collection.
181				passthroughReadBuffer = nil
182
183				go func() {
184					_, _ = io.Copy(passthroughConn, conn)
185					passthroughConn.Close()
186				}()
187				_, _ = io.Copy(conn, passthroughConn)
188			}()
189
190		}
191	}
192
193	if err != nil {
194		return err
195	}
196
197	// For an overview of TLS handshaking, see https://tools.ietf.org/html/rfc5246#section-7.3
198	// and https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-2
199	c.buffering = true
200	if c.vers >= VersionTLS13 {
201		if err := hs.doTLS13Handshake(); err != nil {
202			return err
203		}
204		if _, err := c.flush(); err != nil {
205			return err
206		}
207		c.hs = &hs
208		// If the client is sending early data while the server expects
209		// it, delay the Finished check until HandshakeConfirmed() is
210		// called or until all early data is Read(). Otherwise, complete
211		// authenticating the client now (there is no support for
212		// sending 0.5-RTT data to a potential unauthenticated client).
213		if c.phase != readingEarlyData {
214			if err := hs.readClientFinished13(false); err != nil {
215				return err
216			}
217		}
218		atomic.StoreUint32(&c.handshakeStatus, 1)
219		return nil
220	} else if isResume {
221		// The client has included a session ticket and so we do an abbreviated handshake.
222		if err := hs.doResumeHandshake(); err != nil {
223			return err
224		}
225		if err := hs.establishKeys(); err != nil {
226			return err
227		}
228		// ticketSupported is set in a resumption handshake if the
229		// ticket from the client was encrypted with an old session
230		// ticket key and thus a refreshed ticket should be sent.
231		if hs.hello.ticketSupported {
232			if err := hs.sendSessionTicket(); err != nil {
233				return err
234			}
235		}
236		if err := hs.sendFinished(c.serverFinished[:]); err != nil {
237			return err
238		}
239		if _, err := c.flush(); err != nil {
240			return err
241		}
242		c.clientFinishedIsFirst = false
243		if err := hs.readFinished(nil); err != nil {
244			return err
245		}
246		c.didResume = true
247	} else {
248		// The client didn't include a session ticket, or it wasn't
249		// valid so we do a full handshake.
250		if err := hs.doFullHandshake(); err != nil {
251			return err
252		}
253		if err := hs.establishKeys(); err != nil {
254			return err
255		}
256		if err := hs.readFinished(c.clientFinished[:]); err != nil {
257			return err
258		}
259		c.clientFinishedIsFirst = true
260		c.buffering = true
261		if err := hs.sendSessionTicket(); err != nil {
262			return err
263		}
264		if err := hs.sendFinished(nil); err != nil {
265			return err
266		}
267		if _, err := c.flush(); err != nil {
268			return err
269		}
270	}
271	if c.hand.Len() > 0 {
272		return c.sendAlert(alertUnexpectedMessage)
273	}
274	c.phase = handshakeConfirmed
275	atomic.StoreInt32(&c.handshakeConfirmed, 1)
276
277	// [Psiphon]
278	// https://github.com/ooni/psiphon/oopsi/github.com/golang/go/commit/e5b13401c6b19f58a8439f1019a80fe540c0c687
279	atomic.StoreUint32(&c.handshakeStatus, 1)
280
281	return nil
282}
283
284// [Psiphon]
285// recorderConn is a net.Conn which records all bytes read from the wrapped
286// conn until GetReadBuffer is called, which returns the buffered bytes and
287// stops recording. This is used to replay, byte-for-byte, the bytes sent by a
288// client when switching to passthrough.
289//
290// recorderConn operations are not safe for concurrent use and intended only
291// to be used in the initial phase of the TLS handshake, where the order of
292// operations is deterministic.
293type recorderConn struct {
294	net.Conn
295	readBuffer *bytes.Buffer
296}
297
298func newRecorderConn(conn net.Conn) *recorderConn {
299	return &recorderConn{
300		Conn:       conn,
301		readBuffer: new(bytes.Buffer),
302	}
303}
304
305func (c *recorderConn) Read(p []byte) (n int, err error) {
306	n, err = c.Conn.Read(p)
307	if n > 0 && c.readBuffer != nil {
308		_, _ = c.readBuffer.Write(p[:n])
309	}
310	return n, err
311}
312
313func (c *recorderConn) GetReadBuffer() *bytes.Buffer {
314	b := c.readBuffer
315	c.readBuffer = nil
316	return b
317}
318
319func (c *recorderConn) IsRecording() bool {
320	return c.readBuffer != nil
321}
322
323// [Psiphon]
324// closedConn is a net.Conn which behaves as if it were closed: all reads and
325// writes fail. This is used when switching to passthrough mode: ownership of
326// the invalid client conn is taken by the passthrough relay and a closedConn
327// replaces the network conn used by the local TLS server code path.
328type closedConn struct {
329	localAddr  net.Addr
330	remoteAddr net.Addr
331}
332
333var closedClosedError = errors.New("closed")
334
335func newClosedConn(conn net.Conn) *closedConn {
336	return &closedConn{
337		localAddr:  conn.LocalAddr(),
338		remoteAddr: conn.RemoteAddr(),
339	}
340}
341
342func (c *closedConn) Read(_ []byte) (int, error) {
343	return 0, closedClosedError
344}
345
346func (c *closedConn) Write(_ []byte) (int, error) {
347	return 0, closedClosedError
348}
349
350func (c *closedConn) Close() error {
351	return nil
352}
353
354func (c *closedConn) LocalAddr() net.Addr {
355	return c.localAddr
356}
357
358func (c *closedConn) RemoteAddr() net.Addr {
359	return c.remoteAddr
360}
361
362func (c *closedConn) SetDeadline(_ time.Time) error {
363	return closedClosedError
364}
365
366func (c *closedConn) SetReadDeadline(_ time.Time) error {
367	return closedClosedError
368}
369
370func (c *closedConn) SetWriteDeadline(_ time.Time) error {
371	return closedClosedError
372}
373
374// readClientHello reads a ClientHello message from the client and decides
375// whether we will perform session resumption.
376func (hs *serverHandshakeState) readClientHello() (isResume bool, err error) {
377	c := hs.c
378
379	msg, err := c.readHandshake()
380	if err != nil {
381		return false, err
382	}
383	var ok bool
384	hs.clientHello, ok = msg.(*clientHelloMsg)
385	if !ok {
386		c.sendAlert(alertUnexpectedMessage)
387		return false, unexpectedMessageError(hs.clientHello, msg)
388	}
389
390	if c.config.GetConfigForClient != nil {
391		if newConfig, err := c.config.GetConfigForClient(hs.clientHelloInfo()); err != nil {
392			c.out.traceErr, c.in.traceErr = nil, nil // disable tracing
393			c.sendAlert(alertInternalError)
394			return false, err
395		} else if newConfig != nil {
396			newConfig.serverInitOnce.Do(func() { newConfig.serverInit(c.config) })
397			c.config = newConfig
398		}
399	}
400
401	var keyShares []CurveID
402	for _, ks := range hs.clientHello.keyShares {
403		keyShares = append(keyShares, ks.group)
404	}
405
406	if hs.clientHello.supportedVersions != nil {
407		c.vers, ok = c.config.pickVersion(hs.clientHello.supportedVersions)
408		if !ok {
409			c.sendAlert(alertProtocolVersion)
410			return false, fmt.Errorf("tls: none of the client versions (%x) are supported", hs.clientHello.supportedVersions)
411		}
412	} else {
413		c.vers, ok = c.config.mutualVersion(hs.clientHello.vers)
414		if !ok {
415			c.sendAlert(alertProtocolVersion)
416			return false, fmt.Errorf("tls: client offered an unsupported, maximum protocol version of %x", hs.clientHello.vers)
417		}
418	}
419	c.haveVers = true
420
421	preferredCurves := c.config.curvePreferences()
422Curves:
423	for _, curve := range hs.clientHello.supportedCurves {
424		for _, supported := range preferredCurves {
425			if supported == curve {
426				hs.ellipticOk = true
427				break Curves
428			}
429		}
430	}
431
432	// [Psiphon]
433	hasSupportedPoints := false
434
435	// If present, the supported points extension must include uncompressed.
436	// Can be absent. This behavior mirrors BoringSSL.
437	if hs.clientHello.supportedPoints != nil {
438		supportedPointFormat := false
439		for _, pointFormat := range hs.clientHello.supportedPoints {
440			if pointFormat == pointFormatUncompressed {
441				supportedPointFormat = true
442				break
443			}
444		}
445		if !supportedPointFormat {
446			c.sendAlert(alertHandshakeFailure)
447			return false, errors.New("tls: client does not support uncompressed points")
448		}
449		hasSupportedPoints = true
450	}
451
452	foundCompression := false
453	// We only support null compression, so check that the client offered it.
454	for _, compression := range hs.clientHello.compressionMethods {
455		if compression == compressionNone {
456			foundCompression = true
457			break
458		}
459	}
460
461	if !foundCompression {
462		c.sendAlert(alertIllegalParameter)
463		return false, errors.New("tls: client does not support uncompressed connections")
464	}
465	if len(hs.clientHello.compressionMethods) != 1 && c.vers >= VersionTLS13 {
466		c.sendAlert(alertIllegalParameter)
467		return false, errors.New("tls: 1.3 client offered compression")
468	}
469
470	if len(hs.clientHello.secureRenegotiation) != 0 {
471		c.sendAlert(alertHandshakeFailure)
472		return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
473	}
474
475	if c.vers < VersionTLS13 {
476		hs.hello = new(serverHelloMsg)
477		hs.hello.vers = c.vers
478		hs.hello.random = make([]byte, 32)
479		_, err = io.ReadFull(c.config.rand(), hs.hello.random)
480		if err != nil {
481			c.sendAlert(alertInternalError)
482			return false, err
483		}
484		hs.hello.secureRenegotiationSupported = hs.clientHello.secureRenegotiationSupported
485		hs.hello.compressionMethod = compressionNone
486	} else {
487		hs.hello = new(serverHelloMsg)
488		hs.hello13Enc = new(encryptedExtensionsMsg)
489		hs.hello.vers = c.vers
490		hs.hello.random = make([]byte, 32)
491		hs.hello.sessionId = hs.clientHello.sessionId
492		_, err = io.ReadFull(c.config.rand(), hs.hello.random)
493		if err != nil {
494			c.sendAlert(alertInternalError)
495			return false, err
496		}
497	}
498
499	// [Psiphon]
500	// https://github.com/ooni/psiphon/oopsi/github.com/golang/go/commit/02a5502ab8d862309aaec3c5ec293b57b913d01d
501	if hasSupportedPoints && c.vers < VersionTLS13 {
502		// Although omitting the ec_point_formats extension is permitted, some
503		// old OpenSSL versions will refuse to handshake if not present.
504		//
505		// Per RFC 4492, section 5.1.2, implementations MUST support the
506		// uncompressed point format. See github.com/ooni/psiphon/oopsi/golang.org/issue/31943.
507		hs.hello.supportedPoints = []uint8{pointFormatUncompressed}
508	}
509
510	if len(hs.clientHello.serverName) > 0 {
511		c.serverName = hs.clientHello.serverName
512	}
513
514	if len(hs.clientHello.alpnProtocols) > 0 {
515		if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
516			if hs.hello13Enc != nil {
517				hs.hello13Enc.alpnProtocol = selectedProto
518			} else {
519				hs.hello.alpnProtocol = selectedProto
520			}
521			c.clientProtocol = selectedProto
522		}
523	} else {
524		// Although sending an empty NPN extension is reasonable, Firefox has
525		// had a bug around this. Best to send nothing at all if
526		// c.config.NextProtos is empty. See
527		// https://github.com/ooni/psiphon/oopsi/golang.org/issue/5445.
528		if hs.clientHello.nextProtoNeg && len(c.config.NextProtos) > 0 && c.vers < VersionTLS13 {
529			hs.hello.nextProtoNeg = true
530			hs.hello.nextProtos = c.config.NextProtos
531		}
532	}
533
534	hs.cert, err = c.config.getCertificate(hs.clientHelloInfo())
535	if err != nil {
536		c.sendAlert(alertInternalError)
537		return false, err
538	}
539
540	// Set the private key for this handshake to the certificate's secret key.
541	hs.privateKey = hs.cert.PrivateKey
542
543	if hs.clientHello.scts {
544		hs.hello.scts = hs.cert.SignedCertificateTimestamps
545	}
546
547	// Set the private key to the DC private key if the client and server are
548	// willing to negotiate the delegated credential extension.
549	//
550	// Check to see if a DelegatedCredential is available and should be used.
551	// If one is available, the session is using TLS >= 1.2, and the client
552	// accepts the delegated credential extension, then set the handshake
553	// private key to the DC private key.
554	if c.config.GetDelegatedCredential != nil && hs.clientHello.delegatedCredential && c.vers >= VersionTLS12 {
555		dc, sk, err := c.config.GetDelegatedCredential(hs.clientHelloInfo(), c.vers)
556		if err != nil {
557			c.sendAlert(alertInternalError)
558			return false, err
559		}
560
561		// Set the handshake private key.
562		if dc != nil {
563			hs.privateKey = sk
564			hs.delegatedCredential = dc
565		}
566	}
567
568	if priv, ok := hs.privateKey.(crypto.Signer); ok {
569		switch priv.Public().(type) {
570		case *ecdsa.PublicKey:
571			hs.ecdsaOk = true
572		case *rsa.PublicKey:
573			hs.rsaSignOk = true
574		default:
575			c.sendAlert(alertInternalError)
576			return false, fmt.Errorf("tls: unsupported signing key type (%T)", priv.Public())
577		}
578	}
579	if priv, ok := hs.privateKey.(crypto.Decrypter); ok {
580		switch priv.Public().(type) {
581		case *rsa.PublicKey:
582			hs.rsaDecryptOk = true
583		default:
584			c.sendAlert(alertInternalError)
585			return false, fmt.Errorf("tls: unsupported decryption key type (%T)", priv.Public())
586		}
587	}
588
589	if c.vers != VersionTLS13 && hs.checkForResumption() {
590		return true, nil
591	}
592
593	var preferenceList, supportedList []uint16
594	if c.config.PreferServerCipherSuites {
595		preferenceList = c.config.cipherSuites()
596		supportedList = hs.clientHello.cipherSuites
597	} else {
598		preferenceList = hs.clientHello.cipherSuites
599		supportedList = c.config.cipherSuites()
600	}
601
602	for _, id := range preferenceList {
603		if hs.setCipherSuite(id, supportedList, c.vers) {
604			break
605		}
606	}
607
608	if hs.suite == nil {
609		c.sendAlert(alertHandshakeFailure)
610		return false, errors.New("tls: no cipher suite supported by both client and server")
611	}
612
613	// See https://tools.ietf.org/html/rfc7507.
614	for _, id := range hs.clientHello.cipherSuites {
615		if id == TLS_FALLBACK_SCSV {
616			// The client is doing a fallback connection.
617			if c.vers < c.config.maxVersion() {
618				c.sendAlert(alertInappropriateFallback)
619				return false, errors.New("tls: client using inappropriate protocol fallback")
620			}
621			break
622		}
623	}
624
625	return false, nil
626}
627
628// checkForResumption reports whether we should perform resumption on this connection.
629func (hs *serverHandshakeState) checkForResumption() bool {
630	c := hs.c
631
632	if c.config.SessionTicketsDisabled {
633		return false
634	}
635
636	sessionTicket := append([]uint8{}, hs.clientHello.sessionTicket...)
637	serializedState, usedOldKey := c.decryptTicket(sessionTicket)
638	hs.sessionState = &sessionState{usedOldKey: usedOldKey}
639	if hs.sessionState.unmarshal(serializedState) != alertSuccess {
640		return false
641	}
642
643	// Never resume a session for a different TLS version.
644	if c.vers != hs.sessionState.vers {
645		return false
646	}
647
648	// [Psiphon]
649	// When using obfuscated session tickets, the client-generated session ticket
650	// state never uses EMS. ClientHellos vary in EMS support. So, in this mode,
651	// skip this check to ensure the obfuscated session tickets are not
652	// rejected.
653	if !c.config.UseObfuscatedSessionTickets {
654
655		// Do not resume connections where client support for EMS has changed
656		if (hs.clientHello.extendedMSSupported && c.config.UseExtendedMasterSecret) != hs.sessionState.usedEMS {
657			return false
658		}
659	}
660
661	cipherSuiteOk := false
662	// Check that the client is still offering the ciphersuite in the session.
663	for _, id := range hs.clientHello.cipherSuites {
664		if id == hs.sessionState.cipherSuite {
665			cipherSuiteOk = true
666			break
667		}
668	}
669	if !cipherSuiteOk {
670		return false
671	}
672
673	// Check that we also support the ciphersuite from the session.
674	if !hs.setCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers) {
675		return false
676	}
677
678	sessionHasClientCerts := len(hs.sessionState.certificates) != 0
679	needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
680	if needClientCerts && !sessionHasClientCerts {
681		return false
682	}
683	if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
684		return false
685	}
686
687	return true
688}
689
690func (hs *serverHandshakeState) doResumeHandshake() error {
691	c := hs.c
692
693	hs.hello.cipherSuite = hs.suite.id
694	// We echo the client's session ID in the ServerHello to let it know
695	// that we're doing a resumption.
696	hs.hello.sessionId = hs.clientHello.sessionId
697	hs.hello.ticketSupported = hs.sessionState.usedOldKey
698	hs.hello.extendedMSSupported = hs.clientHello.extendedMSSupported && c.config.UseExtendedMasterSecret
699	hs.finishedHash = newFinishedHash(c.vers, hs.suite)
700	hs.finishedHash.discardHandshakeBuffer()
701	hs.finishedHash.Write(hs.clientHello.marshal())
702	hs.finishedHash.Write(hs.hello.marshal())
703	if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
704		return err
705	}
706
707	if len(hs.sessionState.certificates) > 0 {
708		if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
709			return err
710		}
711	}
712
713	hs.masterSecret = hs.sessionState.masterSecret
714	c.useEMS = hs.sessionState.usedEMS
715
716	return nil
717}
718
719func (hs *serverHandshakeState) doFullHandshake() error {
720	c := hs.c
721
722	if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
723		hs.hello.ocspStapling = true
724	}
725
726	hs.hello.ticketSupported = hs.clientHello.ticketSupported && !c.config.SessionTicketsDisabled
727	hs.hello.cipherSuite = hs.suite.id
728	hs.hello.extendedMSSupported = hs.clientHello.extendedMSSupported && c.config.UseExtendedMasterSecret
729
730	hs.finishedHash = newFinishedHash(hs.c.vers, hs.suite)
731	if c.config.ClientAuth == NoClientCert {
732		// No need to keep a full record of the handshake if client
733		// certificates won't be used.
734		hs.finishedHash.discardHandshakeBuffer()
735	}
736	hs.finishedHash.Write(hs.clientHello.marshal())
737	hs.finishedHash.Write(hs.hello.marshal())
738	if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
739		return err
740	}
741
742	certMsg := new(certificateMsg)
743	certMsg.certificates = hs.cert.Certificate
744	hs.finishedHash.Write(certMsg.marshal())
745	if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
746		return err
747	}
748
749	if hs.hello.ocspStapling {
750		certStatus := new(certificateStatusMsg)
751		certStatus.statusType = statusTypeOCSP
752		certStatus.response = hs.cert.OCSPStaple
753		hs.finishedHash.Write(certStatus.marshal())
754		if _, err := c.writeRecord(recordTypeHandshake, certStatus.marshal()); err != nil {
755			return err
756		}
757	}
758
759	keyAgreement := hs.suite.ka(c.vers)
760	skx, err := keyAgreement.generateServerKeyExchange(c.config, hs.privateKey, hs.clientHello, hs.hello)
761	if err != nil {
762		c.sendAlert(alertHandshakeFailure)
763		return err
764	}
765	if skx != nil {
766		hs.finishedHash.Write(skx.marshal())
767		if _, err := c.writeRecord(recordTypeHandshake, skx.marshal()); err != nil {
768			return err
769		}
770	}
771
772	if c.config.ClientAuth >= RequestClientCert {
773		// Request a client certificate
774		certReq := new(certificateRequestMsg)
775		certReq.certificateTypes = []byte{
776			byte(certTypeRSASign),
777			byte(certTypeECDSASign),
778		}
779		if c.vers >= VersionTLS12 {
780			certReq.hasSignatureAndHash = true
781			certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms
782		}
783
784		// An empty list of certificateAuthorities signals to
785		// the client that it may send any certificate in response
786		// to our request. When we know the CAs we trust, then
787		// we can send them down, so that the client can choose
788		// an appropriate certificate to give to us.
789		if c.config.ClientCAs != nil {
790			certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
791		}
792		hs.finishedHash.Write(certReq.marshal())
793		if _, err := c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil {
794			return err
795		}
796	}
797
798	helloDone := new(serverHelloDoneMsg)
799	hs.finishedHash.Write(helloDone.marshal())
800	if _, err := c.writeRecord(recordTypeHandshake, helloDone.marshal()); err != nil {
801		return err
802	}
803
804	if _, err := c.flush(); err != nil {
805		return err
806	}
807
808	var pub crypto.PublicKey // public key for client auth, if any
809
810	msg, err := c.readHandshake()
811	if err != nil {
812		return err
813	}
814
815	var ok bool
816	// If we requested a client certificate, then the client must send a
817	// certificate message, even if it's empty.
818	if c.config.ClientAuth >= RequestClientCert {
819		if certMsg, ok = msg.(*certificateMsg); !ok {
820			c.sendAlert(alertUnexpectedMessage)
821			return unexpectedMessageError(certMsg, msg)
822		}
823		hs.finishedHash.Write(certMsg.marshal())
824
825		if len(certMsg.certificates) == 0 {
826			// The client didn't actually send a certificate
827			switch c.config.ClientAuth {
828			case RequireAnyClientCert, RequireAndVerifyClientCert:
829				c.sendAlert(alertBadCertificate)
830				return errors.New("tls: client didn't provide a certificate")
831			}
832		}
833
834		pub, err = hs.processCertsFromClient(certMsg.certificates)
835		if err != nil {
836			return err
837		}
838
839		msg, err = c.readHandshake()
840		if err != nil {
841			return err
842		}
843	}
844
845	// Get client key exchange
846	ckx, ok := msg.(*clientKeyExchangeMsg)
847	if !ok {
848		c.sendAlert(alertUnexpectedMessage)
849		return unexpectedMessageError(ckx, msg)
850	}
851	hs.finishedHash.Write(ckx.marshal())
852
853	preMasterSecret, err := keyAgreement.processClientKeyExchange(c.config, hs.privateKey, ckx, c.vers)
854	if err != nil {
855		if err == errClientKeyExchange {
856			c.sendAlert(alertDecodeError)
857		} else {
858			c.sendAlert(alertInternalError)
859		}
860		return err
861	}
862	c.useEMS = hs.hello.extendedMSSupported
863	hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random, hs.finishedHash, c.useEMS)
864	if err := c.config.writeKeyLog("CLIENT_RANDOM", hs.clientHello.random, hs.masterSecret); err != nil {
865		c.sendAlert(alertInternalError)
866		return err
867	}
868
869	// If we received a client cert in response to our certificate request message,
870	// the client will send us a certificateVerifyMsg immediately after the
871	// clientKeyExchangeMsg. This message is a digest of all preceding
872	// handshake-layer messages that is signed using the private key corresponding
873	// to the client's certificate. This allows us to verify that the client is in
874	// possession of the private key of the certificate.
875	if len(c.peerCertificates) > 0 {
876		msg, err = c.readHandshake()
877		if err != nil {
878			return err
879		}
880		certVerify, ok := msg.(*certificateVerifyMsg)
881		if !ok {
882			c.sendAlert(alertUnexpectedMessage)
883			return unexpectedMessageError(certVerify, msg)
884		}
885
886		// Determine the signature type.
887		_, sigType, hashFunc, err := pickSignatureAlgorithm(pub, []SignatureScheme{certVerify.signatureAlgorithm}, supportedSignatureAlgorithms, c.vers)
888		if err != nil {
889			c.sendAlert(alertIllegalParameter)
890			return err
891		}
892
893		var digest []byte
894		if digest, err = hs.finishedHash.hashForClientCertificate(sigType, hashFunc, hs.masterSecret); err == nil {
895			err = verifyHandshakeSignature(sigType, pub, hashFunc, digest, certVerify.signature)
896		}
897		if err != nil {
898			c.sendAlert(alertBadCertificate)
899			return errors.New("tls: could not validate signature of connection nonces: " + err.Error())
900		}
901
902		hs.finishedHash.Write(certVerify.marshal())
903	}
904
905	hs.finishedHash.discardHandshakeBuffer()
906
907	return nil
908}
909
910func (hs *serverHandshakeState) establishKeys() error {
911	c := hs.c
912
913	clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
914		keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
915
916	var clientCipher, serverCipher interface{}
917	var clientHash, serverHash macFunction
918
919	if hs.suite.aead == nil {
920		clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
921		clientHash = hs.suite.mac(c.vers, clientMAC)
922		serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
923		serverHash = hs.suite.mac(c.vers, serverMAC)
924	} else {
925		clientCipher = hs.suite.aead(clientKey, clientIV)
926		serverCipher = hs.suite.aead(serverKey, serverIV)
927	}
928
929	c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
930	c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
931
932	return nil
933}
934
935func (hs *serverHandshakeState) readFinished(out []byte) error {
936	c := hs.c
937
938	c.readRecord(recordTypeChangeCipherSpec)
939	if c.in.err != nil {
940		return c.in.err
941	}
942
943	if hs.hello.nextProtoNeg {
944		msg, err := c.readHandshake()
945		if err != nil {
946			return err
947		}
948		nextProto, ok := msg.(*nextProtoMsg)
949		if !ok {
950			c.sendAlert(alertUnexpectedMessage)
951			return unexpectedMessageError(nextProto, msg)
952		}
953		hs.finishedHash.Write(nextProto.marshal())
954		c.clientProtocol = nextProto.proto
955	}
956
957	msg, err := c.readHandshake()
958	if err != nil {
959		return err
960	}
961	clientFinished, ok := msg.(*finishedMsg)
962	if !ok {
963		c.sendAlert(alertUnexpectedMessage)
964		return unexpectedMessageError(clientFinished, msg)
965	}
966
967	verify := hs.finishedHash.clientSum(hs.masterSecret)
968	if len(verify) != len(clientFinished.verifyData) ||
969		subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
970		c.sendAlert(alertDecryptError)
971		return errors.New("tls: client's Finished message is incorrect")
972	}
973
974	hs.finishedHash.Write(clientFinished.marshal())
975	copy(out, verify)
976	return nil
977}
978
979func (hs *serverHandshakeState) sendSessionTicket() error {
980	if !hs.hello.ticketSupported {
981		return nil
982	}
983
984	c := hs.c
985	m := new(newSessionTicketMsg)
986
987	var err error
988	state := sessionState{
989		vers:         c.vers,
990		cipherSuite:  hs.suite.id,
991		masterSecret: hs.masterSecret,
992		certificates: hs.certsFromClient,
993		usedEMS:      c.useEMS,
994	}
995	m.ticket, err = c.encryptTicket(state.marshal())
996	if err != nil {
997		return err
998	}
999
1000	hs.finishedHash.Write(m.marshal())
1001	if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
1002		return err
1003	}
1004
1005	return nil
1006}
1007
1008func (hs *serverHandshakeState) sendFinished(out []byte) error {
1009	c := hs.c
1010
1011	if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
1012		return err
1013	}
1014
1015	finished := new(finishedMsg)
1016	finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
1017	hs.finishedHash.Write(finished.marshal())
1018	if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
1019		return err
1020	}
1021
1022	c.cipherSuite = hs.suite.id
1023	copy(out, finished.verifyData)
1024
1025	return nil
1026}
1027
1028// processCertsFromClient takes a chain of client certificates either from a
1029// Certificates message or from a sessionState and verifies them. It returns
1030// the public key of the leaf certificate.
1031func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
1032	c := hs.c
1033
1034	hs.certsFromClient = certificates
1035	certs := make([]*x509.Certificate, len(certificates))
1036	var err error
1037	for i, asn1Data := range certificates {
1038		if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
1039			c.sendAlert(alertBadCertificate)
1040			return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
1041		}
1042	}
1043
1044	if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
1045		opts := x509.VerifyOptions{
1046			Roots:         c.config.ClientCAs,
1047			CurrentTime:   c.config.time(),
1048			Intermediates: x509.NewCertPool(),
1049			KeyUsages:     []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
1050		}
1051
1052		for _, cert := range certs[1:] {
1053			opts.Intermediates.AddCert(cert)
1054		}
1055
1056		chains, err := certs[0].Verify(opts)
1057		if err != nil {
1058			c.sendAlert(alertBadCertificate)
1059			return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
1060		}
1061
1062		c.verifiedChains = chains
1063	}
1064
1065	if c.config.VerifyPeerCertificate != nil {
1066		if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
1067			c.sendAlert(alertBadCertificate)
1068			return nil, err
1069		}
1070	}
1071
1072	if len(certs) == 0 {
1073		return nil, nil
1074	}
1075
1076	var pub crypto.PublicKey
1077	switch key := certs[0].PublicKey.(type) {
1078	case *ecdsa.PublicKey, *rsa.PublicKey:
1079		pub = key
1080	default:
1081		c.sendAlert(alertUnsupportedCertificate)
1082		return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
1083	}
1084	c.peerCertificates = certs
1085	return pub, nil
1086}
1087
1088// setCipherSuite sets a cipherSuite with the given id as the serverHandshakeState
1089// suite if that cipher suite is acceptable to use.
1090// It returns a bool indicating if the suite was set.
1091func (hs *serverHandshakeState) setCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16) bool {
1092	for _, supported := range supportedCipherSuites {
1093		if id == supported {
1094			var candidate *cipherSuite
1095
1096			for _, s := range cipherSuites {
1097				if s.id == id {
1098					candidate = s
1099					break
1100				}
1101			}
1102			if candidate == nil {
1103				continue
1104			}
1105
1106			if version >= VersionTLS13 && candidate.flags&suiteTLS13 != 0 {
1107				hs.suite = candidate
1108				return true
1109			}
1110			if version < VersionTLS13 && candidate.flags&suiteTLS13 != 0 {
1111				continue
1112			}
1113
1114			// Don't select a ciphersuite which we can't
1115			// support for this client.
1116			if candidate.flags&suiteECDHE != 0 {
1117				if !hs.ellipticOk {
1118					continue
1119				}
1120				if candidate.flags&suiteECDSA != 0 {
1121					if !hs.ecdsaOk {
1122						continue
1123					}
1124				} else if !hs.rsaSignOk {
1125					continue
1126				}
1127			} else if !hs.rsaDecryptOk {
1128				continue
1129			}
1130			if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
1131				continue
1132			}
1133			hs.suite = candidate
1134			return true
1135		}
1136	}
1137	return false
1138}
1139
1140// suppVersArray is the backing array of ClientHelloInfo.SupportedVersions
1141var suppVersArray = [...]uint16{VersionTLS12, VersionTLS11, VersionTLS10, VersionSSL30}
1142
1143func (hs *serverHandshakeState) clientHelloInfo() *ClientHelloInfo {
1144	if hs.cachedClientHelloInfo != nil {
1145		return hs.cachedClientHelloInfo
1146	}
1147
1148	var supportedVersions []uint16
1149	if hs.clientHello.supportedVersions != nil {
1150		supportedVersions = hs.clientHello.supportedVersions
1151	} else if hs.clientHello.vers > VersionTLS12 {
1152		supportedVersions = suppVersArray[:]
1153	} else if hs.clientHello.vers >= VersionSSL30 {
1154		supportedVersions = suppVersArray[VersionTLS12-hs.clientHello.vers:]
1155	}
1156
1157	var pskBinder []byte
1158	if len(hs.clientHello.psks) > 0 {
1159		pskBinder = hs.clientHello.psks[0].binder
1160	}
1161
1162	hs.cachedClientHelloInfo = &ClientHelloInfo{
1163		CipherSuites:               hs.clientHello.cipherSuites,
1164		ServerName:                 hs.clientHello.serverName,
1165		SupportedCurves:            hs.clientHello.supportedCurves,
1166		SupportedPoints:            hs.clientHello.supportedPoints,
1167		SignatureSchemes:           hs.clientHello.supportedSignatureAlgorithms,
1168		SupportedProtos:            hs.clientHello.alpnProtocols,
1169		SupportedVersions:          supportedVersions,
1170		Conn:                       hs.c.conn,
1171		Offered0RTTData:            hs.clientHello.earlyData,
1172		AcceptsDelegatedCredential: hs.clientHello.delegatedCredential,
1173		Fingerprint:                pskBinder,
1174	}
1175
1176	return hs.cachedClientHelloInfo
1177}
1178