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 qtls partially implements TLS 1.2, as specified in RFC 5246,
6// and TLS 1.3, as specified in RFC 8446.
7
8package qtls
9
10// BUG(agl): The crypto/tls package only implements some countermeasures
11// against Lucky13 attacks on CBC-mode encryption, and only on SHA1
12// variants. See http://www.isg.rhul.ac.uk/tls/TLStiming.pdf and
13// https://www.imperialviolet.org/2013/02/04/luckythirteen.html.
14
15import (
16	"bytes"
17	"crypto"
18	"crypto/ecdsa"
19	"crypto/ed25519"
20	"crypto/rsa"
21	"crypto/x509"
22	"encoding/pem"
23	"errors"
24	"fmt"
25	"io/ioutil"
26	"net"
27	"strings"
28	"time"
29)
30
31// Server returns a new TLS server side connection
32// using conn as the underlying transport.
33// The configuration config must be non-nil and must include
34// at least one certificate or else set GetCertificate.
35func Server(conn net.Conn, config *Config) *Conn {
36	return &Conn{conn: conn, config: config}
37}
38
39// Client returns a new TLS client side connection
40// using conn as the underlying transport.
41// The config cannot be nil: users must set either ServerName or
42// InsecureSkipVerify in the config.
43func Client(conn net.Conn, config *Config) *Conn {
44	return &Conn{conn: conn, config: config, isClient: true}
45}
46
47// A listener implements a network listener (net.Listener) for TLS connections.
48type listener struct {
49	net.Listener
50	config *Config
51}
52
53// Accept waits for and returns the next incoming TLS connection.
54// The returned connection is of type *Conn.
55func (l *listener) Accept() (net.Conn, error) {
56	c, err := l.Listener.Accept()
57	if err != nil {
58		return nil, err
59	}
60	return Server(c, l.config), nil
61}
62
63// NewListener creates a Listener which accepts connections from an inner
64// Listener and wraps each connection with Server.
65// The configuration config must be non-nil and must include
66// at least one certificate or else set GetCertificate.
67func NewListener(inner net.Listener, config *Config) net.Listener {
68	l := new(listener)
69	l.Listener = inner
70	l.config = config
71	return l
72}
73
74// Listen creates a TLS listener accepting connections on the
75// given network address using net.Listen.
76// The configuration config must be non-nil and must include
77// at least one certificate or else set GetCertificate.
78func Listen(network, laddr string, config *Config) (net.Listener, error) {
79	if config == nil || len(config.Certificates) == 0 &&
80		config.GetCertificate == nil && config.GetConfigForClient == nil {
81		return nil, errors.New("tls: neither Certificates, GetCertificate, nor GetConfigForClient set in Config")
82	}
83	l, err := net.Listen(network, laddr)
84	if err != nil {
85		return nil, err
86	}
87	return NewListener(l, config), nil
88}
89
90type timeoutError struct{}
91
92func (timeoutError) Error() string   { return "tls: DialWithDialer timed out" }
93func (timeoutError) Timeout() bool   { return true }
94func (timeoutError) Temporary() bool { return true }
95
96// DialWithDialer connects to the given network address using dialer.Dial and
97// then initiates a TLS handshake, returning the resulting TLS connection. Any
98// timeout or deadline given in the dialer apply to connection and TLS
99// handshake as a whole.
100//
101// DialWithDialer interprets a nil configuration as equivalent to the zero
102// configuration; see the documentation of Config for the defaults.
103func DialWithDialer(dialer *net.Dialer, network, addr string, config *Config) (*Conn, error) {
104	// We want the Timeout and Deadline values from dialer to cover the
105	// whole process: TCP connection and TLS handshake. This means that we
106	// also need to start our own timers now.
107	timeout := dialer.Timeout
108
109	if !dialer.Deadline.IsZero() {
110		deadlineTimeout := time.Until(dialer.Deadline)
111		if timeout == 0 || deadlineTimeout < timeout {
112			timeout = deadlineTimeout
113		}
114	}
115
116	var errChannel chan error
117
118	if timeout != 0 {
119		errChannel = make(chan error, 2)
120		timer := time.AfterFunc(timeout, func() {
121			errChannel <- timeoutError{}
122		})
123		defer timer.Stop()
124	}
125
126	rawConn, err := dialer.Dial(network, addr)
127	if err != nil {
128		return nil, err
129	}
130
131	colonPos := strings.LastIndex(addr, ":")
132	if colonPos == -1 {
133		colonPos = len(addr)
134	}
135	hostname := addr[:colonPos]
136
137	if config == nil {
138		config = defaultConfig()
139	}
140	// If no ServerName is set, infer the ServerName
141	// from the hostname we're connecting to.
142	if config.ServerName == "" {
143		// Make a copy to avoid polluting argument or default.
144		c := config.Clone()
145		c.ServerName = hostname
146		config = c
147	}
148
149	conn := Client(rawConn, config)
150
151	if timeout == 0 {
152		err = conn.Handshake()
153	} else {
154		go func() {
155			errChannel <- conn.Handshake()
156		}()
157
158		err = <-errChannel
159	}
160
161	if err != nil {
162		rawConn.Close()
163		return nil, err
164	}
165
166	return conn, nil
167}
168
169// Dial connects to the given network address using net.Dial
170// and then initiates a TLS handshake, returning the resulting
171// TLS connection.
172// Dial interprets a nil configuration as equivalent to
173// the zero configuration; see the documentation of Config
174// for the defaults.
175func Dial(network, addr string, config *Config) (*Conn, error) {
176	return DialWithDialer(new(net.Dialer), network, addr, config)
177}
178
179// LoadX509KeyPair reads and parses a public/private key pair from a pair
180// of files. The files must contain PEM encoded data. The certificate file
181// may contain intermediate certificates following the leaf certificate to
182// form a certificate chain. On successful return, Certificate.Leaf will
183// be nil because the parsed form of the certificate is not retained.
184func LoadX509KeyPair(certFile, keyFile string) (Certificate, error) {
185	certPEMBlock, err := ioutil.ReadFile(certFile)
186	if err != nil {
187		return Certificate{}, err
188	}
189	keyPEMBlock, err := ioutil.ReadFile(keyFile)
190	if err != nil {
191		return Certificate{}, err
192	}
193	return X509KeyPair(certPEMBlock, keyPEMBlock)
194}
195
196// X509KeyPair parses a public/private key pair from a pair of
197// PEM encoded data. On successful return, Certificate.Leaf will be nil because
198// the parsed form of the certificate is not retained.
199func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (Certificate, error) {
200	fail := func(err error) (Certificate, error) { return Certificate{}, err }
201
202	var cert Certificate
203	var skippedBlockTypes []string
204	for {
205		var certDERBlock *pem.Block
206		certDERBlock, certPEMBlock = pem.Decode(certPEMBlock)
207		if certDERBlock == nil {
208			break
209		}
210		if certDERBlock.Type == "CERTIFICATE" {
211			cert.Certificate = append(cert.Certificate, certDERBlock.Bytes)
212		} else {
213			skippedBlockTypes = append(skippedBlockTypes, certDERBlock.Type)
214		}
215	}
216
217	if len(cert.Certificate) == 0 {
218		if len(skippedBlockTypes) == 0 {
219			return fail(errors.New("tls: failed to find any PEM data in certificate input"))
220		}
221		if len(skippedBlockTypes) == 1 && strings.HasSuffix(skippedBlockTypes[0], "PRIVATE KEY") {
222			return fail(errors.New("tls: failed to find certificate PEM data in certificate input, but did find a private key; PEM inputs may have been switched"))
223		}
224		return fail(fmt.Errorf("tls: failed to find \"CERTIFICATE\" PEM block in certificate input after skipping PEM blocks of the following types: %v", skippedBlockTypes))
225	}
226
227	skippedBlockTypes = skippedBlockTypes[:0]
228	var keyDERBlock *pem.Block
229	for {
230		keyDERBlock, keyPEMBlock = pem.Decode(keyPEMBlock)
231		if keyDERBlock == nil {
232			if len(skippedBlockTypes) == 0 {
233				return fail(errors.New("tls: failed to find any PEM data in key input"))
234			}
235			if len(skippedBlockTypes) == 1 && skippedBlockTypes[0] == "CERTIFICATE" {
236				return fail(errors.New("tls: found a certificate rather than a key in the PEM for the private key"))
237			}
238			return fail(fmt.Errorf("tls: failed to find PEM block with type ending in \"PRIVATE KEY\" in key input after skipping PEM blocks of the following types: %v", skippedBlockTypes))
239		}
240		if keyDERBlock.Type == "PRIVATE KEY" || strings.HasSuffix(keyDERBlock.Type, " PRIVATE KEY") {
241			break
242		}
243		skippedBlockTypes = append(skippedBlockTypes, keyDERBlock.Type)
244	}
245
246	// We don't need to parse the public key for TLS, but we so do anyway
247	// to check that it looks sane and matches the private key.
248	x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
249	if err != nil {
250		return fail(err)
251	}
252
253	cert.PrivateKey, err = parsePrivateKey(keyDERBlock.Bytes)
254	if err != nil {
255		return fail(err)
256	}
257
258	switch pub := x509Cert.PublicKey.(type) {
259	case *rsa.PublicKey:
260		priv, ok := cert.PrivateKey.(*rsa.PrivateKey)
261		if !ok {
262			return fail(errors.New("tls: private key type does not match public key type"))
263		}
264		if pub.N.Cmp(priv.N) != 0 {
265			return fail(errors.New("tls: private key does not match public key"))
266		}
267	case *ecdsa.PublicKey:
268		priv, ok := cert.PrivateKey.(*ecdsa.PrivateKey)
269		if !ok {
270			return fail(errors.New("tls: private key type does not match public key type"))
271		}
272		if pub.X.Cmp(priv.X) != 0 || pub.Y.Cmp(priv.Y) != 0 {
273			return fail(errors.New("tls: private key does not match public key"))
274		}
275	case ed25519.PublicKey:
276		priv, ok := cert.PrivateKey.(ed25519.PrivateKey)
277		if !ok {
278			return fail(errors.New("tls: private key type does not match public key type"))
279		}
280		if !bytes.Equal(priv.Public().(ed25519.PublicKey), pub) {
281			return fail(errors.New("tls: private key does not match public key"))
282		}
283	default:
284		return fail(errors.New("tls: unknown public key algorithm"))
285	}
286
287	return cert, nil
288}
289
290// Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates
291// PKCS#1 private keys by default, while OpenSSL 1.0.0 generates PKCS#8 keys.
292// OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three.
293func parsePrivateKey(der []byte) (crypto.PrivateKey, error) {
294	if key, err := x509.ParsePKCS1PrivateKey(der); err == nil {
295		return key, nil
296	}
297	if key, err := x509.ParsePKCS8PrivateKey(der); err == nil {
298		switch key := key.(type) {
299		case *rsa.PrivateKey, *ecdsa.PrivateKey, ed25519.PrivateKey:
300			return key, nil
301		default:
302			return nil, errors.New("tls: found unknown private key type in PKCS#8 wrapping")
303		}
304	}
305	if key, err := x509.ParseECPrivateKey(der); err == nil {
306		return key, nil
307	}
308
309	return nil, errors.New("tls: failed to parse private key")
310}
311