Handle unsigned constants for module I/O.
[official-gcc.git] / libgo / go / crypto / tls / tls.go
blobb529c705237bbd8df526d6549583dda34b6232d0
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.
5 // Package tls partially implements TLS 1.2, as specified in RFC 5246,
6 // and TLS 1.3, as specified in RFC 8446.
7 package tls
9 // BUG(agl): The crypto/tls package only implements some countermeasures
10 // against Lucky13 attacks on CBC-mode encryption, and only on SHA1
11 // variants. See http://www.isg.rhul.ac.uk/tls/TLStiming.pdf and
12 // https://www.imperialviolet.org/2013/02/04/luckythirteen.html.
14 import (
15 "bytes"
16 "context"
17 "crypto"
18 "crypto/ecdsa"
19 "crypto/ed25519"
20 "crypto/rsa"
21 "crypto/x509"
22 "encoding/pem"
23 "errors"
24 "fmt"
25 "net"
26 "os"
27 "strings"
30 // Server returns a new TLS server side connection
31 // using conn as the underlying transport.
32 // The configuration config must be non-nil and must include
33 // at least one certificate or else set GetCertificate.
34 func Server(conn net.Conn, config *Config) *Conn {
35 c := &Conn{
36 conn: conn,
37 config: config,
39 c.handshakeFn = c.serverHandshake
40 return c
43 // Client returns a new TLS client side connection
44 // using conn as the underlying transport.
45 // The config cannot be nil: users must set either ServerName or
46 // InsecureSkipVerify in the config.
47 func Client(conn net.Conn, config *Config) *Conn {
48 c := &Conn{
49 conn: conn,
50 config: config,
51 isClient: true,
53 c.handshakeFn = c.clientHandshake
54 return c
57 // A listener implements a network listener (net.Listener) for TLS connections.
58 type listener struct {
59 net.Listener
60 config *Config
63 // Accept waits for and returns the next incoming TLS connection.
64 // The returned connection is of type *Conn.
65 func (l *listener) Accept() (net.Conn, error) {
66 c, err := l.Listener.Accept()
67 if err != nil {
68 return nil, err
70 return Server(c, l.config), nil
73 // NewListener creates a Listener which accepts connections from an inner
74 // Listener and wraps each connection with Server.
75 // The configuration config must be non-nil and must include
76 // at least one certificate or else set GetCertificate.
77 func NewListener(inner net.Listener, config *Config) net.Listener {
78 l := new(listener)
79 l.Listener = inner
80 l.config = config
81 return l
84 // Listen creates a TLS listener accepting connections on the
85 // given network address using net.Listen.
86 // The configuration config must be non-nil and must include
87 // at least one certificate or else set GetCertificate.
88 func Listen(network, laddr string, config *Config) (net.Listener, error) {
89 if config == nil || len(config.Certificates) == 0 &&
90 config.GetCertificate == nil && config.GetConfigForClient == nil {
91 return nil, errors.New("tls: neither Certificates, GetCertificate, nor GetConfigForClient set in Config")
93 l, err := net.Listen(network, laddr)
94 if err != nil {
95 return nil, err
97 return NewListener(l, config), nil
100 type timeoutError struct{}
102 func (timeoutError) Error() string { return "tls: DialWithDialer timed out" }
103 func (timeoutError) Timeout() bool { return true }
104 func (timeoutError) Temporary() bool { return true }
106 // DialWithDialer connects to the given network address using dialer.Dial and
107 // then initiates a TLS handshake, returning the resulting TLS connection. Any
108 // timeout or deadline given in the dialer apply to connection and TLS
109 // handshake as a whole.
111 // DialWithDialer interprets a nil configuration as equivalent to the zero
112 // configuration; see the documentation of Config for the defaults.
114 // DialWithDialer uses context.Background internally; to specify the context,
115 // use Dialer.DialContext with NetDialer set to the desired dialer.
116 func DialWithDialer(dialer *net.Dialer, network, addr string, config *Config) (*Conn, error) {
117 return dial(context.Background(), dialer, network, addr, config)
120 func dial(ctx context.Context, netDialer *net.Dialer, network, addr string, config *Config) (*Conn, error) {
121 if netDialer.Timeout != 0 {
122 var cancel context.CancelFunc
123 ctx, cancel = context.WithTimeout(ctx, netDialer.Timeout)
124 defer cancel()
127 if !netDialer.Deadline.IsZero() {
128 var cancel context.CancelFunc
129 ctx, cancel = context.WithDeadline(ctx, netDialer.Deadline)
130 defer cancel()
133 rawConn, err := netDialer.DialContext(ctx, network, addr)
134 if err != nil {
135 return nil, err
138 colonPos := strings.LastIndex(addr, ":")
139 if colonPos == -1 {
140 colonPos = len(addr)
142 hostname := addr[:colonPos]
144 if config == nil {
145 config = defaultConfig()
147 // If no ServerName is set, infer the ServerName
148 // from the hostname we're connecting to.
149 if config.ServerName == "" {
150 // Make a copy to avoid polluting argument or default.
151 c := config.Clone()
152 c.ServerName = hostname
153 config = c
156 conn := Client(rawConn, config)
157 if err := conn.HandshakeContext(ctx); err != nil {
158 rawConn.Close()
159 return nil, err
161 return conn, nil
164 // Dial connects to the given network address using net.Dial
165 // and then initiates a TLS handshake, returning the resulting
166 // TLS connection.
167 // Dial interprets a nil configuration as equivalent to
168 // the zero configuration; see the documentation of Config
169 // for the defaults.
170 func Dial(network, addr string, config *Config) (*Conn, error) {
171 return DialWithDialer(new(net.Dialer), network, addr, config)
174 // Dialer dials TLS connections given a configuration and a Dialer for the
175 // underlying connection.
176 type Dialer struct {
177 // NetDialer is the optional dialer to use for the TLS connections'
178 // underlying TCP connections.
179 // A nil NetDialer is equivalent to the net.Dialer zero value.
180 NetDialer *net.Dialer
182 // Config is the TLS configuration to use for new connections.
183 // A nil configuration is equivalent to the zero
184 // configuration; see the documentation of Config for the
185 // defaults.
186 Config *Config
189 // Dial connects to the given network address and initiates a TLS
190 // handshake, returning the resulting TLS connection.
192 // The returned Conn, if any, will always be of type *Conn.
194 // Dial uses context.Background internally; to specify the context,
195 // use DialContext.
196 func (d *Dialer) Dial(network, addr string) (net.Conn, error) {
197 return d.DialContext(context.Background(), network, addr)
200 func (d *Dialer) netDialer() *net.Dialer {
201 if d.NetDialer != nil {
202 return d.NetDialer
204 return new(net.Dialer)
207 // DialContext connects to the given network address and initiates a TLS
208 // handshake, returning the resulting TLS connection.
210 // The provided Context must be non-nil. If the context expires before
211 // the connection is complete, an error is returned. Once successfully
212 // connected, any expiration of the context will not affect the
213 // connection.
215 // The returned Conn, if any, will always be of type *Conn.
216 func (d *Dialer) DialContext(ctx context.Context, network, addr string) (net.Conn, error) {
217 c, err := dial(ctx, d.netDialer(), network, addr, d.Config)
218 if err != nil {
219 // Don't return c (a typed nil) in an interface.
220 return nil, err
222 return c, nil
225 // LoadX509KeyPair reads and parses a public/private key pair from a pair
226 // of files. The files must contain PEM encoded data. The certificate file
227 // may contain intermediate certificates following the leaf certificate to
228 // form a certificate chain. On successful return, Certificate.Leaf will
229 // be nil because the parsed form of the certificate is not retained.
230 func LoadX509KeyPair(certFile, keyFile string) (Certificate, error) {
231 certPEMBlock, err := os.ReadFile(certFile)
232 if err != nil {
233 return Certificate{}, err
235 keyPEMBlock, err := os.ReadFile(keyFile)
236 if err != nil {
237 return Certificate{}, err
239 return X509KeyPair(certPEMBlock, keyPEMBlock)
242 // X509KeyPair parses a public/private key pair from a pair of
243 // PEM encoded data. On successful return, Certificate.Leaf will be nil because
244 // the parsed form of the certificate is not retained.
245 func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (Certificate, error) {
246 fail := func(err error) (Certificate, error) { return Certificate{}, err }
248 var cert Certificate
249 var skippedBlockTypes []string
250 for {
251 var certDERBlock *pem.Block
252 certDERBlock, certPEMBlock = pem.Decode(certPEMBlock)
253 if certDERBlock == nil {
254 break
256 if certDERBlock.Type == "CERTIFICATE" {
257 cert.Certificate = append(cert.Certificate, certDERBlock.Bytes)
258 } else {
259 skippedBlockTypes = append(skippedBlockTypes, certDERBlock.Type)
263 if len(cert.Certificate) == 0 {
264 if len(skippedBlockTypes) == 0 {
265 return fail(errors.New("tls: failed to find any PEM data in certificate input"))
267 if len(skippedBlockTypes) == 1 && strings.HasSuffix(skippedBlockTypes[0], "PRIVATE KEY") {
268 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"))
270 return fail(fmt.Errorf("tls: failed to find \"CERTIFICATE\" PEM block in certificate input after skipping PEM blocks of the following types: %v", skippedBlockTypes))
273 skippedBlockTypes = skippedBlockTypes[:0]
274 var keyDERBlock *pem.Block
275 for {
276 keyDERBlock, keyPEMBlock = pem.Decode(keyPEMBlock)
277 if keyDERBlock == nil {
278 if len(skippedBlockTypes) == 0 {
279 return fail(errors.New("tls: failed to find any PEM data in key input"))
281 if len(skippedBlockTypes) == 1 && skippedBlockTypes[0] == "CERTIFICATE" {
282 return fail(errors.New("tls: found a certificate rather than a key in the PEM for the private key"))
284 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))
286 if keyDERBlock.Type == "PRIVATE KEY" || strings.HasSuffix(keyDERBlock.Type, " PRIVATE KEY") {
287 break
289 skippedBlockTypes = append(skippedBlockTypes, keyDERBlock.Type)
292 // We don't need to parse the public key for TLS, but we so do anyway
293 // to check that it looks sane and matches the private key.
294 x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
295 if err != nil {
296 return fail(err)
299 cert.PrivateKey, err = parsePrivateKey(keyDERBlock.Bytes)
300 if err != nil {
301 return fail(err)
304 switch pub := x509Cert.PublicKey.(type) {
305 case *rsa.PublicKey:
306 priv, ok := cert.PrivateKey.(*rsa.PrivateKey)
307 if !ok {
308 return fail(errors.New("tls: private key type does not match public key type"))
310 if pub.N.Cmp(priv.N) != 0 {
311 return fail(errors.New("tls: private key does not match public key"))
313 case *ecdsa.PublicKey:
314 priv, ok := cert.PrivateKey.(*ecdsa.PrivateKey)
315 if !ok {
316 return fail(errors.New("tls: private key type does not match public key type"))
318 if pub.X.Cmp(priv.X) != 0 || pub.Y.Cmp(priv.Y) != 0 {
319 return fail(errors.New("tls: private key does not match public key"))
321 case ed25519.PublicKey:
322 priv, ok := cert.PrivateKey.(ed25519.PrivateKey)
323 if !ok {
324 return fail(errors.New("tls: private key type does not match public key type"))
326 if !bytes.Equal(priv.Public().(ed25519.PublicKey), pub) {
327 return fail(errors.New("tls: private key does not match public key"))
329 default:
330 return fail(errors.New("tls: unknown public key algorithm"))
333 return cert, nil
336 // Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates
337 // PKCS #1 private keys by default, while OpenSSL 1.0.0 generates PKCS #8 keys.
338 // OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three.
339 func parsePrivateKey(der []byte) (crypto.PrivateKey, error) {
340 if key, err := x509.ParsePKCS1PrivateKey(der); err == nil {
341 return key, nil
343 if key, err := x509.ParsePKCS8PrivateKey(der); err == nil {
344 switch key := key.(type) {
345 case *rsa.PrivateKey, *ecdsa.PrivateKey, ed25519.PrivateKey:
346 return key, nil
347 default:
348 return nil, errors.New("tls: found unknown private key type in PKCS#8 wrapping")
351 if key, err := x509.ParseECPrivateKey(der); err == nil {
352 return key, nil
355 return nil, errors.New("tls: failed to parse private key")