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

View as plain text