github.com/bigzoro/my_simplechain@v0.0.0-20240315012955-8ad0a2a29bb9/core/access_contoller/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 "chainmaker.org/chainmaker/common/v2/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  
   112  	if !dialer.Deadline.IsZero() {
   113  		deadlineTimeout := time.Until(dialer.Deadline)
   114  		if timeout == 0 || deadlineTimeout < timeout {
   115  			timeout = deadlineTimeout
   116  		}
   117  	}
   118  
   119  	var errChannel chan error
   120  
   121  	if timeout != 0 {
   122  		errChannel = make(chan error, 2)
   123  		timer := time.AfterFunc(timeout, func() {
   124  			errChannel <- timeoutError{}
   125  		})
   126  		defer timer.Stop()
   127  	}
   128  
   129  	rawConn, err := dialer.Dial(network, addr)
   130  	if err != nil {
   131  		return nil, err
   132  	}
   133  
   134  	colonPos := strings.LastIndex(addr, ":")
   135  	if colonPos == -1 {
   136  		colonPos = len(addr)
   137  	}
   138  	hostname := addr[:colonPos]
   139  
   140  	if config == nil {
   141  		config = defaultConfig()
   142  	}
   143  	// If no ServerName is set, infer the ServerName
   144  	// from the hostname we're connecting to.
   145  	if config.ServerName == "" {
   146  		// Make a copy to avoid polluting argument or default.
   147  		c := config.Clone()
   148  		c.ServerName = hostname
   149  		config = c
   150  	}
   151  
   152  	conn := Client(rawConn, config)
   153  
   154  	if timeout == 0 {
   155  		err = conn.Handshake()
   156  	} else {
   157  		go func() {
   158  			errChannel <- conn.Handshake()
   159  		}()
   160  
   161  		err = <-errChannel
   162  	}
   163  
   164  	if err != nil {
   165  		rawConn.Close()
   166  		return nil, err
   167  	}
   168  
   169  	return conn, nil
   170  }
   171  
   172  // Dial connects to the given network address using net.Dial
   173  // and then initiates a TLS handshake, returning the resulting
   174  // TLS connection.
   175  // Dial interprets a nil configuration as equivalent to
   176  // the zero configuration; see the documentation of Config
   177  // for the defaults.
   178  func Dial(network, addr string, config *Config) (*Conn, error) {
   179  	return DialWithDialer(new(net.Dialer), network, addr, config)
   180  }
   181  
   182  // LoadX509KeyPair reads and parses a public/private key pair from a pair
   183  // of files. The files must contain PEM encoded data. The certificate file
   184  // may contain intermediate certificates following the leaf certificate to
   185  // form a certificate chain. On successful return, Certificate.Leaf will
   186  // be nil because the parsed form of the certificate is not retained.
   187  func LoadX509KeyPair(certFile, keyFile string) (Certificate, error) {
   188  	certPEMBlock, err := ioutil.ReadFile(certFile)
   189  	if err != nil {
   190  		return Certificate{}, err
   191  	}
   192  	keyPEMBlock, err := ioutil.ReadFile(keyFile)
   193  	if err != nil {
   194  		return Certificate{}, err
   195  	}
   196  	return X509KeyPair(certPEMBlock, keyPEMBlock)
   197  }
   198  
   199  // X509KeyPair parses a public/private key pair from a pair of
   200  // PEM encoded data. On successful return, Certificate.Leaf will be nil because
   201  // the parsed form of the certificate is not retained.
   202  func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (Certificate, error) {
   203  	fail := func(err error) (Certificate, error) { return Certificate{}, err }
   204  
   205  	var cert Certificate
   206  	var skippedBlockTypes []string
   207  	for {
   208  		var certDERBlock *pem.Block
   209  		certDERBlock, certPEMBlock = pem.Decode(certPEMBlock)
   210  		if certDERBlock == nil {
   211  			break
   212  		}
   213  		if certDERBlock.Type == "CERTIFICATE" {
   214  			cert.Certificate = append(cert.Certificate, certDERBlock.Bytes)
   215  		} else {
   216  			skippedBlockTypes = append(skippedBlockTypes, certDERBlock.Type)
   217  		}
   218  	}
   219  
   220  	if len(cert.Certificate) == 0 {
   221  		if len(skippedBlockTypes) == 0 {
   222  			return fail(errors.New("tls: failed to find any PEM data in certificate input"))
   223  		}
   224  		if len(skippedBlockTypes) == 1 && strings.HasSuffix(skippedBlockTypes[0], "PRIVATE KEY") {
   225  			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"))
   226  		}
   227  		return fail(fmt.Errorf("tls: failed to find \"CERTIFICATE\" PEM block in certificate input after skipping PEM blocks of the following types: %v", skippedBlockTypes))
   228  	}
   229  
   230  	skippedBlockTypes = skippedBlockTypes[:0]
   231  	var keyDERBlock *pem.Block
   232  	for {
   233  		keyDERBlock, keyPEMBlock = pem.Decode(keyPEMBlock)
   234  		if keyDERBlock == nil {
   235  			if len(skippedBlockTypes) == 0 {
   236  				return fail(errors.New("tls: failed to find any PEM data in key input"))
   237  			}
   238  			if len(skippedBlockTypes) == 1 && skippedBlockTypes[0] == "CERTIFICATE" {
   239  				return fail(errors.New("tls: found a certificate rather than a key in the PEM for the private key"))
   240  			}
   241  			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))
   242  		}
   243  		if keyDERBlock.Type == "PRIVATE KEY" || strings.HasSuffix(keyDERBlock.Type, " PRIVATE KEY") {
   244  			break
   245  		}
   246  		skippedBlockTypes = append(skippedBlockTypes, keyDERBlock.Type)
   247  	}
   248  
   249  	// We don't need to parse the public key for TLS, but we so do anyway
   250  	// to check that it looks sane and matches the private key.
   251  	x509Cert, err := cmx509.ParseCertificate(cert.Certificate[0])
   252  	if err != nil {
   253  		return fail(err)
   254  	}
   255  
   256  	cmx509Cert, _ := cmx509.ChainMakerCertToX509Cert(x509Cert)
   257  
   258  	cert.PrivateKey, err = parsePrivateKey(keyDERBlock.Bytes)
   259  	if err != nil {
   260  		return fail(err)
   261  	}
   262  
   263  	switch pub := cmx509Cert.PublicKey.(type) {
   264  	case *rsa.PublicKey:
   265  		priv, ok := cert.PrivateKey.(*rsa.PrivateKey)
   266  		if !ok {
   267  			return fail(errors.New("tls: private key type does not match public key type"))
   268  		}
   269  		if pub.N.Cmp(priv.N) != 0 {
   270  			return fail(errors.New("tls: private key does not match public key"))
   271  		}
   272  	case *ecdsa.PublicKey:
   273  		priv, ok := cert.PrivateKey.(*ecdsa.PrivateKey)
   274  		if !ok {
   275  			return fail(errors.New("tls: private key type does not match public key type"))
   276  		}
   277  		if pub.X.Cmp(priv.X) != 0 || pub.Y.Cmp(priv.Y) != 0 {
   278  			return fail(errors.New("tls: private key does not match public key"))
   279  		}
   280  	case *sm2.PublicKey:
   281  		priv, ok := cert.PrivateKey.(*sm2.PrivateKey)
   282  		if !ok {
   283  			return fail(errors.New("tls: private key type does not match public key type"))
   284  		}
   285  		if pub.X.Cmp(priv.X) != 0 || pub.Y.Cmp(priv.Y) != 0 {
   286  			return fail(errors.New("tls: private key does not match public key"))
   287  		}
   288  	case ed25519.PublicKey:
   289  		priv, ok := cert.PrivateKey.(ed25519.PrivateKey)
   290  		if !ok {
   291  			return fail(errors.New("tls: private key type does not match public key type"))
   292  		}
   293  		if !bytes.Equal(priv.Public().(ed25519.PublicKey), pub) {
   294  			return fail(errors.New("tls: private key does not match public key"))
   295  		}
   296  	default:
   297  		return fail(errors.New("tls: unknown public key algorithm"))
   298  	}
   299  	return cert, nil
   300  }
   301  
   302  // Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates
   303  // PKCS#1 private keys by default, while OpenSSL 1.0.0 generates PKCS#8 keys.
   304  // OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three.
   305  func parsePrivateKey(der []byte) (crypto.PrivateKey, error) {
   306  	if key, err := cmx509.ParsePKCS1PrivateKey(der); err == nil {
   307  		return key, nil
   308  	}
   309  	if key, err := cmx509.ParsePKCS8PrivateKey(der); err == nil {
   310  		switch key := key.(type) {
   311  		case *rsa.PrivateKey, *ecdsa.PrivateKey, ed25519.PrivateKey, *sm2.PrivateKey:
   312  			return key, nil
   313  		default:
   314  			return nil, errors.New("tls: found unknown private key type in PKCS#8 wrapping")
   315  		}
   316  	}
   317  	if key, err := x509.ParseECPrivateKey(der); err == nil {
   318  		oid, ok := oidFromNamedCurve(key.Curve)
   319  		if ok && !oid.Equal(oidNamedCurveSm2) {
   320  			return key, nil
   321  		}
   322  	}
   323  
   324  	//sm2
   325  	if key, err := tjx509.ParseSm2PrivateKey(der); err == nil {
   326  		return key, nil
   327  	}
   328  
   329  	return nil, errors.New("tls: failed to parse private key")
   330  }