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