github.com/JimmyHuang454/JLS-go@v0.0.0-20230831150107-90d536585ba0/tls/tls.go (about)

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