2010-12-03 04:34:57 +00:00
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
2019-01-18 19:04:36 +00:00
// Package tls partially implements TLS 1.2, as specified in RFC 5246,
// and TLS 1.3, as specified in RFC 8446.
2010-12-03 04:34:57 +00:00
package tls
2017-01-14 00:05:42 +00:00
// BUG(agl): The crypto/tls package only implements some countermeasures
2017-01-23 22:18:42 +00:00
// against Lucky13 attacks on CBC-mode encryption, and only on SHA1
// variants. See http://www.isg.rhul.ac.uk/tls/TLStiming.pdf and
2016-02-03 21:58:02 +00:00
// https://www.imperialviolet.org/2013/02/04/luckythirteen.html.
2010-12-03 04:34:57 +00:00
import (
2019-09-06 18:12:46 +00:00
"bytes"
2020-07-27 22:27:54 -07:00
"context"
2012-11-21 07:03:38 +00:00
"crypto"
"crypto/ecdsa"
2019-09-06 18:12:46 +00:00
"crypto/ed25519"
2010-12-03 04:34:57 +00:00
"crypto/rsa"
"crypto/x509"
"encoding/pem"
2011-12-03 02:17:34 +00:00
"errors"
2016-02-03 21:58:02 +00:00
"fmt"
2010-12-03 04:34:57 +00:00
"net"
2020-12-23 09:57:37 -08:00
"os"
2010-12-03 04:34:57 +00:00
"strings"
)
2011-01-21 18:19:03 +00:00
// Server returns a new TLS server side connection
// using conn as the underlying transport.
2016-02-03 21:58:02 +00:00
// The configuration config must be non-nil and must include
// at least one certificate or else set GetCertificate.
2010-12-03 04:34:57 +00:00
func Server ( conn net . Conn , config * Config ) * Conn {
2020-07-27 22:27:54 -07:00
c := & Conn {
conn : conn ,
config : config ,
}
c . handshakeFn = c . serverHandshake
return c
2010-12-03 04:34:57 +00:00
}
2011-01-21 18:19:03 +00:00
// Client returns a new TLS client side connection
// using conn as the underlying transport.
2014-07-19 08:53:52 +00:00
// The config cannot be nil: users must set either ServerName or
2014-06-06 22:37:27 +00:00
// InsecureSkipVerify in the config.
2010-12-03 04:34:57 +00:00
func Client ( conn net . Conn , config * Config ) * Conn {
2020-07-27 22:27:54 -07:00
c := & Conn {
conn : conn ,
config : config ,
isClient : true ,
}
c . handshakeFn = c . clientHandshake
return c
2010-12-03 04:34:57 +00:00
}
2012-02-09 08:19:58 +00:00
// A listener implements a network listener (net.Listener) for TLS connections.
type listener struct {
net . Listener
config * Config
2010-12-03 04:34:57 +00:00
}
2011-01-21 18:19:03 +00:00
// Accept waits for and returns the next incoming TLS connection.
2016-07-22 18:15:38 +00:00
// The returned connection is of type *Conn.
func ( l * listener ) Accept ( ) ( net . Conn , error ) {
c , err := l . Listener . Accept ( )
2010-12-03 04:34:57 +00:00
if err != nil {
2016-07-22 18:15:38 +00:00
return nil , err
2010-12-03 04:34:57 +00:00
}
2016-07-22 18:15:38 +00:00
return Server ( c , l . config ) , nil
2010-12-03 04:34:57 +00:00
}
// NewListener creates a Listener which accepts connections from an inner
// Listener and wraps each connection with Server.
2016-02-03 21:58:02 +00:00
// The configuration config must be non-nil and must include
// at least one certificate or else set GetCertificate.
2012-02-09 08:19:58 +00:00
func NewListener ( inner net . Listener , config * Config ) net . Listener {
l := new ( listener )
l . Listener = inner
2010-12-03 04:34:57 +00:00
l . config = config
2012-02-09 08:19:58 +00:00
return l
2010-12-03 04:34:57 +00:00
}
2011-01-21 18:19:03 +00:00
// Listen creates a TLS listener accepting connections on the
// given network address using net.Listen.
2016-02-03 21:58:02 +00:00
// The configuration config must be non-nil and must include
// at least one certificate or else set GetCertificate.
2012-02-09 08:19:58 +00:00
func Listen ( network , laddr string , config * Config ) ( net . Listener , error ) {
2020-01-02 15:05:27 -08:00
if config == nil || len ( config . Certificates ) == 0 &&
config . GetCertificate == nil && config . GetConfigForClient == nil {
return nil , errors . New ( "tls: neither Certificates, GetCertificate, nor GetConfigForClient set in Config" )
2010-12-03 04:34:57 +00:00
}
l , err := net . Listen ( network , laddr )
if err != nil {
return nil , err
}
return NewListener ( l , config ) , nil
}
2014-07-19 08:53:52 +00:00
type timeoutError struct { }
func ( timeoutError ) Error ( ) string { return "tls: DialWithDialer timed out" }
func ( timeoutError ) Timeout ( ) bool { return true }
func ( timeoutError ) Temporary ( ) bool { return true }
// DialWithDialer connects to the given network address using dialer.Dial and
// then initiates a TLS handshake, returning the resulting TLS connection. Any
// timeout or deadline given in the dialer apply to connection and TLS
// handshake as a whole.
//
// DialWithDialer interprets a nil configuration as equivalent to the zero
// configuration; see the documentation of Config for the defaults.
2021-07-30 14:28:58 -07:00
//
// DialWithDialer uses context.Background internally; to specify the context,
// use Dialer.DialContext with NetDialer set to the desired dialer.
2014-07-19 08:53:52 +00:00
func DialWithDialer ( dialer * net . Dialer , network , addr string , config * Config ) ( * Conn , error ) {
2020-07-27 22:27:54 -07:00
return dial ( context . Background ( ) , dialer , network , addr , config )
}
func dial ( ctx context . Context , netDialer * net . Dialer , network , addr string , config * Config ) ( * Conn , error ) {
2021-07-30 14:28:58 -07:00
if netDialer . Timeout != 0 {
var cancel context . CancelFunc
ctx , cancel = context . WithTimeout ( ctx , netDialer . Timeout )
defer cancel ( )
2021-01-27 17:55:50 -08:00
}
2021-07-30 14:28:58 -07:00
if ! netDialer . Deadline . IsZero ( ) {
var cancel context . CancelFunc
ctx , cancel = context . WithDeadline ( ctx , netDialer . Deadline )
defer cancel ( )
2014-07-19 08:53:52 +00:00
}
2020-07-27 22:27:54 -07:00
rawConn , err := netDialer . DialContext ( ctx , network , addr )
2010-12-03 04:34:57 +00:00
if err != nil {
return nil , err
}
2014-07-19 08:53:52 +00:00
colonPos := strings . LastIndex ( addr , ":" )
2010-12-03 04:34:57 +00:00
if colonPos == - 1 {
2014-07-19 08:53:52 +00:00
colonPos = len ( addr )
2010-12-03 04:34:57 +00:00
}
2014-07-19 08:53:52 +00:00
hostname := addr [ : colonPos ]
2010-12-03 04:34:57 +00:00
2011-01-21 18:19:03 +00:00
if config == nil {
config = defaultConfig ( )
}
2012-03-30 21:27:11 +00:00
// If no ServerName is set, infer the ServerName
// from the hostname we're connecting to.
if config . ServerName == "" {
2011-01-21 18:19:03 +00:00
// Make a copy to avoid polluting argument or default.
2017-01-14 00:05:42 +00:00
c := config . Clone ( )
2011-01-21 18:19:03 +00:00
c . ServerName = hostname
2016-07-22 18:15:38 +00:00
config = c
2011-01-21 18:19:03 +00:00
}
2014-07-19 08:53:52 +00:00
conn := Client ( rawConn , config )
2021-07-30 14:28:58 -07:00
if err := conn . HandshakeContext ( ctx ) ; err != nil {
2014-07-19 08:53:52 +00:00
rawConn . Close ( )
2011-01-21 18:19:03 +00:00
return nil , err
2010-12-03 04:34:57 +00:00
}
2011-01-21 18:19:03 +00:00
return conn , nil
2010-12-03 04:34:57 +00:00
}
2014-07-19 08:53:52 +00:00
// Dial connects to the given network address using net.Dial
// and then initiates a TLS handshake, returning the resulting
// TLS connection.
// Dial interprets a nil configuration as equivalent to
// the zero configuration; see the documentation of Config
// for the defaults.
func Dial ( network , addr string , config * Config ) ( * Conn , error ) {
return DialWithDialer ( new ( net . Dialer ) , network , addr , config )
}
2020-07-27 22:27:54 -07:00
// Dialer dials TLS connections given a configuration and a Dialer for the
// underlying connection.
type Dialer struct {
// NetDialer is the optional dialer to use for the TLS connections'
// underlying TCP connections.
// A nil NetDialer is equivalent to the net.Dialer zero value.
NetDialer * net . Dialer
// Config is the TLS configuration to use for new connections.
// A nil configuration is equivalent to the zero
// configuration; see the documentation of Config for the
// defaults.
Config * Config
}
// Dial connects to the given network address and initiates a TLS
// handshake, returning the resulting TLS connection.
//
// The returned Conn, if any, will always be of type *Conn.
2021-07-30 14:28:58 -07:00
//
// Dial uses context.Background internally; to specify the context,
// use DialContext.
2020-07-27 22:27:54 -07:00
func ( d * Dialer ) Dial ( network , addr string ) ( net . Conn , error ) {
return d . DialContext ( context . Background ( ) , network , addr )
}
func ( d * Dialer ) netDialer ( ) * net . Dialer {
if d . NetDialer != nil {
return d . NetDialer
}
return new ( net . Dialer )
}
// DialContext connects to the given network address and initiates a TLS
// handshake, returning the resulting TLS connection.
//
// The provided Context must be non-nil. If the context expires before
// the connection is complete, an error is returned. Once successfully
// connected, any expiration of the context will not affect the
// connection.
//
// The returned Conn, if any, will always be of type *Conn.
func ( d * Dialer ) DialContext ( ctx context . Context , network , addr string ) ( net . Conn , error ) {
c , err := dial ( ctx , d . netDialer ( ) , network , addr , d . Config )
if err != nil {
// Don't return c (a typed nil) in an interface.
return nil , err
}
return c , nil
}
2016-07-22 18:15:38 +00:00
// LoadX509KeyPair reads and parses a public/private key pair from a pair
// of files. The files must contain PEM encoded data. The certificate file
// may contain intermediate certificates following the leaf certificate to
// form a certificate chain. On successful return, Certificate.Leaf will
// be nil because the parsed form of the certificate is not retained.
2015-10-31 00:59:47 +00:00
func LoadX509KeyPair ( certFile , keyFile string ) ( Certificate , error ) {
2020-12-23 09:57:37 -08:00
certPEMBlock , err := os . ReadFile ( certFile )
2010-12-03 04:34:57 +00:00
if err != nil {
2015-10-31 00:59:47 +00:00
return Certificate { } , err
2010-12-03 04:34:57 +00:00
}
2020-12-23 09:57:37 -08:00
keyPEMBlock , err := os . ReadFile ( keyFile )
2011-04-07 17:09:10 +00:00
if err != nil {
2015-10-31 00:59:47 +00:00
return Certificate { } , err
2011-04-07 17:09:10 +00:00
}
return X509KeyPair ( certPEMBlock , keyPEMBlock )
}
2010-12-03 04:34:57 +00:00
2011-04-07 17:09:10 +00:00
// X509KeyPair parses a public/private key pair from a pair of
2016-02-03 21:58:02 +00:00
// PEM encoded data. On successful return, Certificate.Leaf will be nil because
// the parsed form of the certificate is not retained.
2015-10-31 00:59:47 +00:00
func X509KeyPair ( certPEMBlock , keyPEMBlock [ ] byte ) ( Certificate , error ) {
fail := func ( err error ) ( Certificate , error ) { return Certificate { } , err }
2016-02-03 21:58:02 +00:00
var cert Certificate
var skippedBlockTypes [ ] string
2011-03-16 23:05:44 +00:00
for {
2016-02-03 21:58:02 +00:00
var certDERBlock * pem . Block
2011-03-16 23:05:44 +00:00
certDERBlock , certPEMBlock = pem . Decode ( certPEMBlock )
if certDERBlock == nil {
break
}
if certDERBlock . Type == "CERTIFICATE" {
cert . Certificate = append ( cert . Certificate , certDERBlock . Bytes )
2016-02-03 21:58:02 +00:00
} else {
skippedBlockTypes = append ( skippedBlockTypes , certDERBlock . Type )
2011-03-16 23:05:44 +00:00
}
}
if len ( cert . Certificate ) == 0 {
2016-02-03 21:58:02 +00:00
if len ( skippedBlockTypes ) == 0 {
2016-07-22 18:15:38 +00:00
return fail ( errors . New ( "tls: failed to find any PEM data in certificate input" ) )
}
if len ( skippedBlockTypes ) == 1 && strings . HasSuffix ( skippedBlockTypes [ 0 ] , "PRIVATE KEY" ) {
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" ) )
2016-02-03 21:58:02 +00:00
}
2016-07-22 18:15:38 +00:00
return fail ( fmt . Errorf ( "tls: failed to find \"CERTIFICATE\" PEM block in certificate input after skipping PEM blocks of the following types: %v" , skippedBlockTypes ) )
2010-12-03 04:34:57 +00:00
}
2016-02-03 21:58:02 +00:00
skippedBlockTypes = skippedBlockTypes [ : 0 ]
2012-10-23 04:31:11 +00:00
var keyDERBlock * pem . Block
for {
keyDERBlock , keyPEMBlock = pem . Decode ( keyPEMBlock )
if keyDERBlock == nil {
2016-02-03 21:58:02 +00:00
if len ( skippedBlockTypes ) == 0 {
2016-07-22 18:15:38 +00:00
return fail ( errors . New ( "tls: failed to find any PEM data in key input" ) )
2016-02-03 21:58:02 +00:00
}
2016-07-22 18:15:38 +00:00
if len ( skippedBlockTypes ) == 1 && skippedBlockTypes [ 0 ] == "CERTIFICATE" {
return fail ( errors . New ( "tls: found a certificate rather than a key in the PEM for the private key" ) )
}
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 ) )
2012-10-23 04:31:11 +00:00
}
2012-12-12 23:13:29 +00:00
if keyDERBlock . Type == "PRIVATE KEY" || strings . HasSuffix ( keyDERBlock . Type , " PRIVATE KEY" ) {
2012-10-23 04:31:11 +00:00
break
}
2016-02-03 21:58:02 +00:00
skippedBlockTypes = append ( skippedBlockTypes , keyDERBlock . Type )
2010-12-03 04:34:57 +00:00
}
2018-09-24 21:46:21 +00:00
// We don't need to parse the public key for TLS, but we so do anyway
// to check that it looks sane and matches the private key.
x509Cert , err := x509 . ParseCertificate ( cert . Certificate [ 0 ] )
2012-11-21 07:03:38 +00:00
if err != nil {
2015-10-31 00:59:47 +00:00
return fail ( err )
2010-12-03 04:34:57 +00:00
}
2018-09-24 21:46:21 +00:00
cert . PrivateKey , err = parsePrivateKey ( keyDERBlock . Bytes )
2010-12-03 04:34:57 +00:00
if err != nil {
2015-10-31 00:59:47 +00:00
return fail ( err )
2010-12-03 04:34:57 +00:00
}
2012-11-21 07:03:38 +00:00
switch pub := x509Cert . PublicKey . ( type ) {
case * rsa . PublicKey :
priv , ok := cert . PrivateKey . ( * rsa . PrivateKey )
if ! ok {
2016-07-22 18:15:38 +00:00
return fail ( errors . New ( "tls: private key type does not match public key type" ) )
2012-11-21 07:03:38 +00:00
}
if pub . N . Cmp ( priv . N ) != 0 {
2016-07-22 18:15:38 +00:00
return fail ( errors . New ( "tls: private key does not match public key" ) )
2012-11-21 07:03:38 +00:00
}
case * ecdsa . PublicKey :
priv , ok := cert . PrivateKey . ( * ecdsa . PrivateKey )
if ! ok {
2016-07-22 18:15:38 +00:00
return fail ( errors . New ( "tls: private key type does not match public key type" ) )
2012-11-21 07:03:38 +00:00
}
if pub . X . Cmp ( priv . X ) != 0 || pub . Y . Cmp ( priv . Y ) != 0 {
2016-07-22 18:15:38 +00:00
return fail ( errors . New ( "tls: private key does not match public key" ) )
2012-11-21 07:03:38 +00:00
}
2019-09-06 18:12:46 +00:00
case ed25519 . PublicKey :
priv , ok := cert . PrivateKey . ( ed25519 . PrivateKey )
if ! ok {
return fail ( errors . New ( "tls: private key type does not match public key type" ) )
}
if ! bytes . Equal ( priv . Public ( ) . ( ed25519 . PublicKey ) , pub ) {
return fail ( errors . New ( "tls: private key does not match public key" ) )
}
2012-11-21 07:03:38 +00:00
default :
2016-07-22 18:15:38 +00:00
return fail ( errors . New ( "tls: unknown public key algorithm" ) )
2010-12-03 04:34:57 +00:00
}
2015-10-31 00:59:47 +00:00
return cert , nil
2010-12-03 04:34:57 +00:00
}
2012-11-21 07:03:38 +00:00
// Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates
2020-07-27 22:27:54 -07:00
// PKCS #1 private keys by default, while OpenSSL 1.0.0 generates PKCS #8 keys.
2012-11-21 07:03:38 +00:00
// OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three.
func parsePrivateKey ( der [ ] byte ) ( crypto . PrivateKey , error ) {
if key , err := x509 . ParsePKCS1PrivateKey ( der ) ; err == nil {
return key , nil
}
if key , err := x509 . ParsePKCS8PrivateKey ( der ) ; err == nil {
switch key := key . ( type ) {
2019-09-06 18:12:46 +00:00
case * rsa . PrivateKey , * ecdsa . PrivateKey , ed25519 . PrivateKey :
2012-11-21 07:03:38 +00:00
return key , nil
default :
2016-07-22 18:15:38 +00:00
return nil , errors . New ( "tls: found unknown private key type in PKCS#8 wrapping" )
2012-11-21 07:03:38 +00:00
}
}
if key , err := x509 . ParseECPrivateKey ( der ) ; err == nil {
return key , nil
}
2016-07-22 18:15:38 +00:00
return nil , errors . New ( "tls: failed to parse private key" )
2012-11-21 07:03:38 +00:00
}