Source file src/crypto/tls/tls.go

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package tls partially implements TLS 1.2, as specified in RFC 5246,
     6  // and TLS 1.3, as specified in RFC 8446.
     7  //
     8  // # FIPS 140-3 mode
     9  //
    10  // When the program is in [FIPS 140-3 mode], this package behaves as if only
    11  // SP 800-140C and SP 800-140D approved protocol versions, cipher suites,
    12  // signature algorithms, certificate public key types and sizes, and key
    13  // exchange and derivation algorithms were implemented. Others are silently
    14  // ignored and not negotiated, or rejected. This set may depend on the
    15  // algorithms supported by the FIPS 140-3 Go Cryptographic Module selected with
    16  // GOFIPS140, and may change across Go versions.
    17  //
    18  // [FIPS 140-3 mode]: https://go.dev/doc/security/fips140
    19  package tls
    20  
    21  // BUG(agl): The crypto/tls package only implements some countermeasures
    22  // against Lucky13 attacks on CBC-mode encryption, and only on SHA1
    23  // variants. See http://www.isg.rhul.ac.uk/tls/TLStiming.pdf and
    24  // https://www.imperialviolet.org/2013/02/04/luckythirteen.html.
    25  
    26  import (
    27  	"bytes"
    28  	"context"
    29  	"crypto"
    30  	"crypto/ecdsa"
    31  	"crypto/ed25519"
    32  	"crypto/rsa"
    33  	"crypto/x509"
    34  	"encoding/pem"
    35  	"errors"
    36  	"fmt"
    37  	"internal/godebug"
    38  	"net"
    39  	"os"
    40  	"strings"
    41  )
    42  
    43  // Server returns a new TLS server side connection
    44  // using conn as the underlying transport.
    45  // The configuration config must be non-nil and must include
    46  // at least one certificate or else set GetCertificate.
    47  func Server(conn net.Conn, config *Config) *Conn {
    48  	c := &Conn{
    49  		conn:   conn,
    50  		config: config,
    51  	}
    52  	c.handshakeFn = c.serverHandshake
    53  	return c
    54  }
    55  
    56  // Client returns a new TLS client side connection
    57  // using conn as the underlying transport.
    58  // The config cannot be nil: users must set either ServerName or
    59  // InsecureSkipVerify in the config.
    60  func Client(conn net.Conn, config *Config) *Conn {
    61  	c := &Conn{
    62  		conn:     conn,
    63  		config:   config,
    64  		isClient: true,
    65  	}
    66  	c.handshakeFn = c.clientHandshake
    67  	return c
    68  }
    69  
    70  // A listener implements a network listener (net.Listener) for TLS connections.
    71  type listener struct {
    72  	net.Listener
    73  	config *Config
    74  }
    75  
    76  // Accept waits for and returns the next incoming TLS connection.
    77  // The returned connection is of type *Conn.
    78  func (l *listener) Accept() (net.Conn, error) {
    79  	c, err := l.Listener.Accept()
    80  	if err != nil {
    81  		return nil, err
    82  	}
    83  	return Server(c, l.config), nil
    84  }
    85  
    86  // NewListener creates a Listener which accepts connections from an inner
    87  // Listener and wraps each connection with [Server].
    88  // The configuration config must be non-nil and must include
    89  // at least one certificate or else set GetCertificate.
    90  func NewListener(inner net.Listener, config *Config) net.Listener {
    91  	l := new(listener)
    92  	l.Listener = inner
    93  	l.config = config
    94  	return l
    95  }
    96  
    97  // Listen creates a TLS listener accepting connections on the
    98  // given network address using net.Listen.
    99  // The configuration config must be non-nil and must include
   100  // at least one certificate or else set GetCertificate.
   101  func Listen(network, laddr string, config *Config) (net.Listener, error) {
   102  	// If this condition changes, consider updating http.Server.ServeTLS too.
   103  	if config == nil || len(config.Certificates) == 0 &&
   104  		config.GetCertificate == nil && config.GetConfigForClient == nil {
   105  		return nil, errors.New("tls: neither Certificates, GetCertificate, nor GetConfigForClient set in Config")
   106  	}
   107  	l, err := net.Listen(network, laddr)
   108  	if err != nil {
   109  		return nil, err
   110  	}
   111  	return NewListener(l, config), nil
   112  }
   113  
   114  type timeoutError struct{}
   115  
   116  func (timeoutError) Error() string   { return "tls: DialWithDialer timed out" }
   117  func (timeoutError) Timeout() bool   { return true }
   118  func (timeoutError) Temporary() bool { return true }
   119  
   120  // DialWithDialer connects to the given network address using dialer.Dial and
   121  // then initiates a TLS handshake, returning the resulting TLS connection. Any
   122  // timeout or deadline given in the dialer apply to connection and TLS
   123  // handshake as a whole.
   124  //
   125  // DialWithDialer interprets a nil configuration as equivalent to the zero
   126  // configuration; see the documentation of [Config] for the defaults.
   127  //
   128  // DialWithDialer uses context.Background internally; to specify the context,
   129  // use [Dialer.DialContext] with NetDialer set to the desired dialer.
   130  func DialWithDialer(dialer *net.Dialer, network, addr string, config *Config) (*Conn, error) {
   131  	return dial(context.Background(), dialer, network, addr, config)
   132  }
   133  
   134  func dial(ctx context.Context, netDialer *net.Dialer, network, addr string, config *Config) (*Conn, error) {
   135  	if netDialer.Timeout != 0 {
   136  		var cancel context.CancelFunc
   137  		ctx, cancel = context.WithTimeout(ctx, netDialer.Timeout)
   138  		defer cancel()
   139  	}
   140  
   141  	if !netDialer.Deadline.IsZero() {
   142  		var cancel context.CancelFunc
   143  		ctx, cancel = context.WithDeadline(ctx, netDialer.Deadline)
   144  		defer cancel()
   145  	}
   146  
   147  	rawConn, err := netDialer.DialContext(ctx, network, addr)
   148  	if err != nil {
   149  		return nil, err
   150  	}
   151  
   152  	colonPos := strings.LastIndex(addr, ":")
   153  	if colonPos == -1 {
   154  		colonPos = len(addr)
   155  	}
   156  	hostname := addr[:colonPos]
   157  
   158  	if config == nil {
   159  		config = defaultConfig()
   160  	}
   161  	// If no ServerName is set, infer the ServerName
   162  	// from the hostname we're connecting to.
   163  	if config.ServerName == "" {
   164  		// Make a copy to avoid polluting argument or default.
   165  		c := config.Clone()
   166  		c.ServerName = hostname
   167  		config = c
   168  	}
   169  
   170  	conn := Client(rawConn, config)
   171  	if err := conn.HandshakeContext(ctx); err != nil {
   172  		rawConn.Close()
   173  		return nil, err
   174  	}
   175  	return conn, nil
   176  }
   177  
   178  // Dial connects to the given network address using net.Dial
   179  // and then initiates a TLS handshake, returning the resulting
   180  // TLS connection.
   181  // Dial interprets a nil configuration as equivalent to
   182  // the zero configuration; see the documentation of Config
   183  // for the defaults.
   184  func Dial(network, addr string, config *Config) (*Conn, error) {
   185  	return DialWithDialer(new(net.Dialer), network, addr, config)
   186  }
   187  
   188  // Dialer dials TLS connections given a configuration and a Dialer for the
   189  // underlying connection.
   190  type Dialer struct {
   191  	// NetDialer is the optional dialer to use for the TLS connections'
   192  	// underlying TCP connections.
   193  	// A nil NetDialer is equivalent to the net.Dialer zero value.
   194  	NetDialer *net.Dialer
   195  
   196  	// Config is the TLS configuration to use for new connections.
   197  	// A nil configuration is equivalent to the zero
   198  	// configuration; see the documentation of Config for the
   199  	// defaults.
   200  	Config *Config
   201  }
   202  
   203  // Dial connects to the given network address and initiates a TLS
   204  // handshake, returning the resulting TLS connection.
   205  //
   206  // The returned [Conn], if any, will always be of type *[Conn].
   207  //
   208  // Dial uses context.Background internally; to specify the context,
   209  // use [Dialer.DialContext].
   210  func (d *Dialer) Dial(network, addr string) (net.Conn, error) {
   211  	return d.DialContext(context.Background(), network, addr)
   212  }
   213  
   214  func (d *Dialer) netDialer() *net.Dialer {
   215  	if d.NetDialer != nil {
   216  		return d.NetDialer
   217  	}
   218  	return new(net.Dialer)
   219  }
   220  
   221  // DialContext connects to the given network address and initiates a TLS
   222  // handshake, returning the resulting TLS connection.
   223  //
   224  // The provided Context must be non-nil. If the context expires before
   225  // the connection is complete, an error is returned. Once successfully
   226  // connected, any expiration of the context will not affect the
   227  // connection.
   228  //
   229  // The returned [Conn], if any, will always be of type *[Conn].
   230  func (d *Dialer) DialContext(ctx context.Context, network, addr string) (net.Conn, error) {
   231  	c, err := dial(ctx, d.netDialer(), network, addr, d.Config)
   232  	if err != nil {
   233  		// Don't return c (a typed nil) in an interface.
   234  		return nil, err
   235  	}
   236  	return c, nil
   237  }
   238  
   239  // LoadX509KeyPair reads and parses a public/private key pair from a pair of
   240  // files. The files must contain PEM encoded data. The certificate file may
   241  // contain intermediate certificates following the leaf certificate to form a
   242  // certificate chain. On successful return, Certificate.Leaf will be populated.
   243  //
   244  // Before Go 1.23 Certificate.Leaf was left nil, and the parsed certificate was
   245  // discarded. This behavior can be re-enabled by setting "x509keypairleaf=0"
   246  // in the GODEBUG environment variable.
   247  func LoadX509KeyPair(certFile, keyFile string) (Certificate, error) {
   248  	certPEMBlock, err := os.ReadFile(certFile)
   249  	if err != nil {
   250  		return Certificate{}, err
   251  	}
   252  	keyPEMBlock, err := os.ReadFile(keyFile)
   253  	if err != nil {
   254  		return Certificate{}, err
   255  	}
   256  	return X509KeyPair(certPEMBlock, keyPEMBlock)
   257  }
   258  
   259  var x509keypairleaf = godebug.New("x509keypairleaf")
   260  
   261  // X509KeyPair parses a public/private key pair from a pair of
   262  // PEM encoded data. On successful return, Certificate.Leaf will be populated.
   263  //
   264  // Before Go 1.23 Certificate.Leaf was left nil, and the parsed certificate was
   265  // discarded. This behavior can be re-enabled by setting "x509keypairleaf=0"
   266  // in the GODEBUG environment variable.
   267  func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (Certificate, error) {
   268  	fail := func(err error) (Certificate, error) { return Certificate{}, err }
   269  
   270  	var cert Certificate
   271  	var skippedBlockTypes []string
   272  	for {
   273  		var certDERBlock *pem.Block
   274  		certDERBlock, certPEMBlock = pem.Decode(certPEMBlock)
   275  		if certDERBlock == nil {
   276  			break
   277  		}
   278  		if certDERBlock.Type == "CERTIFICATE" {
   279  			cert.Certificate = append(cert.Certificate, certDERBlock.Bytes)
   280  		} else {
   281  			skippedBlockTypes = append(skippedBlockTypes, certDERBlock.Type)
   282  		}
   283  	}
   284  
   285  	if len(cert.Certificate) == 0 {
   286  		if len(skippedBlockTypes) == 0 {
   287  			return fail(errors.New("tls: failed to find any PEM data in certificate input"))
   288  		}
   289  		if len(skippedBlockTypes) == 1 && strings.HasSuffix(skippedBlockTypes[0], "PRIVATE KEY") {
   290  			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"))
   291  		}
   292  		return fail(fmt.Errorf("tls: failed to find \"CERTIFICATE\" PEM block in certificate input after skipping PEM blocks of the following types: %v", skippedBlockTypes))
   293  	}
   294  
   295  	skippedBlockTypes = skippedBlockTypes[:0]
   296  	var keyDERBlock *pem.Block
   297  	for {
   298  		keyDERBlock, keyPEMBlock = pem.Decode(keyPEMBlock)
   299  		if keyDERBlock == nil {
   300  			if len(skippedBlockTypes) == 0 {
   301  				return fail(errors.New("tls: failed to find any PEM data in key input"))
   302  			}
   303  			if len(skippedBlockTypes) == 1 && skippedBlockTypes[0] == "CERTIFICATE" {
   304  				return fail(errors.New("tls: found a certificate rather than a key in the PEM for the private key"))
   305  			}
   306  			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))
   307  		}
   308  		if keyDERBlock.Type == "PRIVATE KEY" || strings.HasSuffix(keyDERBlock.Type, " PRIVATE KEY") {
   309  			break
   310  		}
   311  		skippedBlockTypes = append(skippedBlockTypes, keyDERBlock.Type)
   312  	}
   313  
   314  	// We don't need to parse the public key for TLS, but we so do anyway
   315  	// to check that it looks sane and matches the private key.
   316  	x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
   317  	if err != nil {
   318  		return fail(err)
   319  	}
   320  
   321  	if x509keypairleaf.Value() != "0" {
   322  		cert.Leaf = x509Cert
   323  	} else {
   324  		x509keypairleaf.IncNonDefault()
   325  	}
   326  
   327  	cert.PrivateKey, err = parsePrivateKey(keyDERBlock.Bytes)
   328  	if err != nil {
   329  		return fail(err)
   330  	}
   331  
   332  	switch pub := x509Cert.PublicKey.(type) {
   333  	case *rsa.PublicKey:
   334  		priv, ok := cert.PrivateKey.(*rsa.PrivateKey)
   335  		if !ok {
   336  			return fail(errors.New("tls: private key type does not match public key type"))
   337  		}
   338  		if pub.N.Cmp(priv.N) != 0 {
   339  			return fail(errors.New("tls: private key does not match public key"))
   340  		}
   341  	case *ecdsa.PublicKey:
   342  		priv, ok := cert.PrivateKey.(*ecdsa.PrivateKey)
   343  		if !ok {
   344  			return fail(errors.New("tls: private key type does not match public key type"))
   345  		}
   346  		if pub.X.Cmp(priv.X) != 0 || pub.Y.Cmp(priv.Y) != 0 {
   347  			return fail(errors.New("tls: private key does not match public key"))
   348  		}
   349  	case ed25519.PublicKey:
   350  		priv, ok := cert.PrivateKey.(ed25519.PrivateKey)
   351  		if !ok {
   352  			return fail(errors.New("tls: private key type does not match public key type"))
   353  		}
   354  		if !bytes.Equal(priv.Public().(ed25519.PublicKey), pub) {
   355  			return fail(errors.New("tls: private key does not match public key"))
   356  		}
   357  	default:
   358  		return fail(errors.New("tls: unknown public key algorithm"))
   359  	}
   360  
   361  	return cert, nil
   362  }
   363  
   364  // Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates
   365  // PKCS #1 private keys by default, while OpenSSL 1.0.0 generates PKCS #8 keys.
   366  // OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three.
   367  func parsePrivateKey(der []byte) (crypto.PrivateKey, error) {
   368  	if key, err := x509.ParsePKCS1PrivateKey(der); err == nil {
   369  		return key, nil
   370  	}
   371  	if key, err := x509.ParsePKCS8PrivateKey(der); err == nil {
   372  		switch key := key.(type) {
   373  		case *rsa.PrivateKey, *ecdsa.PrivateKey, ed25519.PrivateKey:
   374  			return key, nil
   375  		default:
   376  			return nil, errors.New("tls: found unknown private key type in PKCS#8 wrapping")
   377  		}
   378  	}
   379  	if key, err := x509.ParseECPrivateKey(der); err == nil {
   380  		return key, nil
   381  	}
   382  
   383  	return nil, errors.New("tls: failed to parse private key")
   384  }
   385  

View as plain text