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