2012-03-27 23:13:14 +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.
2014-09-21 17:33:12 +00:00
// Package tls partially implements TLS 1.2, as specified in RFC 5246.
2012-03-27 23:13:14 +00:00
package tls
2017-04-10 11:32:00 +00:00
// BUG(agl): The crypto/tls package does not implement countermeasures
// against Lucky13 attacks on CBC-mode encryption. See
// http://www.isg.rhul.ac.uk/tls/TLStiming.pdf and
// https://www.imperialviolet.org/2013/02/04/luckythirteen.html.
2012-03-27 23:13:14 +00:00
import (
2014-09-21 17:33:12 +00:00
"crypto"
"crypto/ecdsa"
2012-03-27 23:13:14 +00:00
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
2017-04-10 11:32:00 +00:00
"fmt"
2012-03-27 23:13:14 +00:00
"io/ioutil"
"net"
"strings"
2015-08-28 15:33:40 +00:00
"time"
2012-03-27 23:13:14 +00:00
)
// Server returns a new TLS server side connection
// using conn as the underlying transport.
2017-04-10 11:32:00 +00:00
// The configuration config must be non-nil and must include
// at least one certificate or else set GetCertificate.
2012-03-27 23:13:14 +00:00
func Server ( conn net . Conn , config * Config ) * Conn {
return & Conn { conn : conn , config : config }
}
// Client returns a new TLS client side connection
// using conn as the underlying transport.
2015-08-28 15:33:40 +00:00
// The config cannot be nil: users must set either ServerName or
// InsecureSkipVerify in the config.
2012-03-27 23:13:14 +00:00
func Client ( conn net . Conn , config * Config ) * Conn {
return & Conn { conn : conn , config : config , isClient : true }
}
// A listener implements a network listener (net.Listener) for TLS connections.
type listener struct {
net . Listener
config * Config
}
// Accept waits for and returns the next incoming TLS connection.
// The returned connection c is a *tls.Conn.
func ( l * listener ) Accept ( ) ( c net . Conn , err error ) {
c , err = l . Listener . Accept ( )
if err != nil {
return
}
c = Server ( c , l . config )
return
}
// NewListener creates a Listener which accepts connections from an inner
// Listener and wraps each connection with Server.
2017-04-10 11:32:00 +00:00
// The configuration config must be non-nil and must include
// at least one certificate or else set GetCertificate.
2012-03-27 23:13:14 +00:00
func NewListener ( inner net . Listener , config * Config ) net . Listener {
l := new ( listener )
l . Listener = inner
l . config = config
return l
}
// Listen creates a TLS listener accepting connections on the
// given network address using net.Listen.
2017-04-10 11:32:00 +00:00
// The configuration config must be non-nil and must include
// at least one certificate or else set GetCertificate.
2012-03-27 23:13:14 +00:00
func Listen ( network , laddr string , config * Config ) ( net . Listener , error ) {
2017-04-10 11:32:00 +00:00
if config == nil || ( len ( config . Certificates ) == 0 && config . GetCertificate == nil ) {
return nil , errors . New ( "tls: neither Certificates nor GetCertificate set in Config" )
2012-03-27 23:13:14 +00:00
}
l , err := net . Listen ( network , laddr )
if err != nil {
return nil , err
}
return NewListener ( l , config ) , nil
}
2015-08-28 15:33:40 +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.
func DialWithDialer ( dialer * net . Dialer , network , addr string , config * Config ) ( * Conn , error ) {
// We want the Timeout and Deadline values from dialer to cover the
// whole process: TCP connection and TLS handshake. This means that we
// also need to start our own timers now.
timeout := dialer . Timeout
if ! dialer . Deadline . IsZero ( ) {
deadlineTimeout := dialer . Deadline . Sub ( time . Now ( ) )
if timeout == 0 || deadlineTimeout < timeout {
timeout = deadlineTimeout
}
}
var errChannel chan error
if timeout != 0 {
errChannel = make ( chan error , 2 )
time . AfterFunc ( timeout , func ( ) {
errChannel <- timeoutError { }
} )
}
rawConn , err := dialer . Dial ( network , addr )
2012-03-27 23:13:14 +00:00
if err != nil {
return nil , err
}
2015-08-28 15:33:40 +00:00
colonPos := strings . LastIndex ( addr , ":" )
2012-03-27 23:13:14 +00:00
if colonPos == - 1 {
2015-08-28 15:33:40 +00:00
colonPos = len ( addr )
2012-03-27 23:13:14 +00:00
}
2015-08-28 15:33:40 +00:00
hostname := addr [ : colonPos ]
2012-03-27 23:13:14 +00:00
if config == nil {
config = defaultConfig ( )
}
2014-09-21 17:33:12 +00:00
// If no ServerName is set, infer the ServerName
// from the hostname we're connecting to.
if config . ServerName == "" {
2012-03-27 23:13:14 +00:00
// Make a copy to avoid polluting argument or default.
c := * config
c . ServerName = hostname
config = & c
}
2015-08-28 15:33:40 +00:00
conn := Client ( rawConn , config )
if timeout == 0 {
err = conn . Handshake ( )
} else {
go func ( ) {
errChannel <- conn . Handshake ( )
} ( )
err = <- errChannel
}
if err != nil {
rawConn . Close ( )
2012-03-27 23:13:14 +00:00
return nil , err
}
2015-08-28 15:33:40 +00:00
2012-03-27 23:13:14 +00:00
return conn , nil
}
2015-08-28 15:33:40 +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 )
}
2012-03-27 23:13:14 +00:00
// LoadX509KeyPair reads and parses a public/private key pair from a pair of
2017-04-10 11:32:00 +00:00
// files. The files must contain PEM encoded data. On successful return,
// Certificate.Leaf will be nil because the parsed form of the certificate is
// not retained.
func LoadX509KeyPair ( certFile , keyFile string ) ( Certificate , error ) {
2012-03-27 23:13:14 +00:00
certPEMBlock , err := ioutil . ReadFile ( certFile )
if err != nil {
2017-04-10 11:32:00 +00:00
return Certificate { } , err
2012-03-27 23:13:14 +00:00
}
keyPEMBlock , err := ioutil . ReadFile ( keyFile )
if err != nil {
2017-04-10 11:32:00 +00:00
return Certificate { } , err
2012-03-27 23:13:14 +00:00
}
return X509KeyPair ( certPEMBlock , keyPEMBlock )
}
// X509KeyPair parses a public/private key pair from a pair of
2017-04-10 11:32:00 +00:00
// PEM encoded data. On successful return, Certificate.Leaf will be nil because
// the parsed form of the certificate is not retained.
func X509KeyPair ( certPEMBlock , keyPEMBlock [ ] byte ) ( Certificate , error ) {
fail := func ( err error ) ( Certificate , error ) { return Certificate { } , err }
var cert Certificate
var skippedBlockTypes [ ] string
2012-03-27 23:13:14 +00:00
for {
2017-04-10 11:32:00 +00:00
var certDERBlock * pem . Block
2012-03-27 23:13:14 +00:00
certDERBlock , certPEMBlock = pem . Decode ( certPEMBlock )
if certDERBlock == nil {
break
}
if certDERBlock . Type == "CERTIFICATE" {
cert . Certificate = append ( cert . Certificate , certDERBlock . Bytes )
2017-04-10 11:32:00 +00:00
} else {
skippedBlockTypes = append ( skippedBlockTypes , certDERBlock . Type )
2012-03-27 23:13:14 +00:00
}
}
if len ( cert . Certificate ) == 0 {
2017-04-10 11:32:00 +00:00
if len ( skippedBlockTypes ) == 0 {
return fail ( errors . New ( "crypto/tls: failed to find any PEM data in certificate input" ) )
} else if len ( skippedBlockTypes ) == 1 && strings . HasSuffix ( skippedBlockTypes [ 0 ] , "PRIVATE KEY" ) {
return fail ( errors . New ( "crypto/tls: failed to find certificate PEM data in certificate input, but did find a private key; PEM inputs may have been switched" ) )
} else {
return fail ( fmt . Errorf ( "crypto/tls: failed to find \"CERTIFICATE\" PEM block in certificate input after skipping PEM blocks of the following types: %v" , skippedBlockTypes ) )
}
2012-03-27 23:13:14 +00:00
}
2017-04-10 11:32:00 +00:00
skippedBlockTypes = skippedBlockTypes [ : 0 ]
2014-09-21 17:33:12 +00:00
var keyDERBlock * pem . Block
for {
keyDERBlock , keyPEMBlock = pem . Decode ( keyPEMBlock )
if keyDERBlock == nil {
2017-04-10 11:32:00 +00:00
if len ( skippedBlockTypes ) == 0 {
return fail ( errors . New ( "crypto/tls: failed to find any PEM data in key input" ) )
} else if len ( skippedBlockTypes ) == 1 && skippedBlockTypes [ 0 ] == "CERTIFICATE" {
return fail ( errors . New ( "crypto/tls: found a certificate rather than a key in the PEM for the private key" ) )
} else {
return fail ( fmt . Errorf ( "crypto/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-03-27 23:13:14 +00:00
}
2014-09-21 17:33:12 +00:00
if keyDERBlock . Type == "PRIVATE KEY" || strings . HasSuffix ( keyDERBlock . Type , " PRIVATE KEY" ) {
break
2012-03-27 23:13:14 +00:00
}
2017-04-10 11:32:00 +00:00
skippedBlockTypes = append ( skippedBlockTypes , keyDERBlock . Type )
2012-03-27 23:13:14 +00:00
}
2017-04-10 11:32:00 +00:00
var err error
2014-09-21 17:33:12 +00:00
cert . PrivateKey , err = parsePrivateKey ( keyDERBlock . Bytes )
if err != nil {
2017-04-10 11:32:00 +00:00
return fail ( err )
2014-09-21 17:33:12 +00:00
}
2012-03-27 23:13:14 +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 ] )
if err != nil {
2017-04-10 11:32:00 +00:00
return fail ( err )
2012-03-27 23:13:14 +00:00
}
2014-09-21 17:33:12 +00:00
switch pub := x509Cert . PublicKey . ( type ) {
case * rsa . PublicKey :
priv , ok := cert . PrivateKey . ( * rsa . PrivateKey )
if ! ok {
2017-04-10 11:32:00 +00:00
return fail ( errors . New ( "crypto/tls: private key type does not match public key type" ) )
2014-09-21 17:33:12 +00:00
}
if pub . N . Cmp ( priv . N ) != 0 {
2017-04-10 11:32:00 +00:00
return fail ( errors . New ( "crypto/tls: private key does not match public key" ) )
2014-09-21 17:33:12 +00:00
}
case * ecdsa . PublicKey :
priv , ok := cert . PrivateKey . ( * ecdsa . PrivateKey )
if ! ok {
2017-04-10 11:32:00 +00:00
return fail ( errors . New ( "crypto/tls: private key type does not match public key type" ) )
2014-09-21 17:33:12 +00:00
}
if pub . X . Cmp ( priv . X ) != 0 || pub . Y . Cmp ( priv . Y ) != 0 {
2017-04-10 11:32:00 +00:00
return fail ( errors . New ( "crypto/tls: private key does not match public key" ) )
2014-09-21 17:33:12 +00:00
}
default :
2017-04-10 11:32:00 +00:00
return fail ( errors . New ( "crypto/tls: unknown public key algorithm" ) )
2012-03-27 23:13:14 +00:00
}
2017-04-10 11:32:00 +00:00
return cert , nil
2012-03-27 23:13:14 +00:00
}
2014-09-21 17:33:12 +00:00
// Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates
// PKCS#1 private keys by default, while OpenSSL 1.0.0 generates PKCS#8 keys.
// 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 ) {
case * rsa . PrivateKey , * ecdsa . PrivateKey :
return key , nil
default :
return nil , errors . New ( "crypto/tls: found unknown private key type in PKCS#8 wrapping" )
}
}
if key , err := x509 . ParseECPrivateKey ( der ) ; err == nil {
return key , nil
}
return nil , errors . New ( "crypto/tls: failed to parse private key" )
}