Source file src/crypto/tls/tls.go

Documentation: crypto/tls

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

View as plain text