vendor: remove dep and use vndr

Signed-off-by: Antonio Murdaca <runcom@redhat.com>
This commit is contained in:
Antonio Murdaca 2017-06-06 09:19:04 +02:00
parent 16f44674a4
commit 148e72d81e
No known key found for this signature in database
GPG key ID: B2BEAD150DE936B9
16131 changed files with 73815 additions and 4235138 deletions

View file

@ -14,7 +14,7 @@ import (
func SystemCertPool() (*x509.CertPool, error) {
certpool, err := x509.SystemCertPool()
if err != nil && runtime.GOOS == "windows" {
logrus.Warnf("Unable to use system certificate pool: %v", err)
logrus.Infof("Unable to use system certificate pool: %v", err)
return x509.NewCertPool(), nil
}
return certpool, err

View file

@ -8,11 +8,13 @@ package tlsconfig
import (
"crypto/tls"
"crypto/x509"
"encoding/pem"
"fmt"
"io/ioutil"
"os"
"github.com/Sirupsen/logrus"
"github.com/pkg/errors"
)
// Options represents the information needed to create client and server TLS configurations.
@ -29,6 +31,14 @@ type Options struct {
InsecureSkipVerify bool
// server-only option
ClientAuth tls.ClientAuthType
// If ExclusiveRootPools is set, then if a CA file is provided, the root pool used for TLS
// creds will include exclusively the roots in that CA file. If no CA file is provided,
// the system pool will be used.
ExclusiveRootPools bool
MinVersion uint16
// If Passphrase is set, it will be used to decrypt a TLS private key
// if the key is encrypted
Passphrase string
}
// Extra (server-side) accepted CBC cipher suites - will phase out in the future
@ -46,6 +56,15 @@ var acceptedCBCCiphers = []uint16{
// known weak algorithms removed.
var DefaultServerAcceptedCiphers = append(clientCipherSuites, acceptedCBCCiphers...)
// allTLSVersions lists all the TLS versions and is used by the code that validates
// a uint16 value as a TLS version.
var allTLSVersions = map[uint16]struct{}{
tls.VersionSSL30: {},
tls.VersionTLS10: {},
tls.VersionTLS11: {},
tls.VersionTLS12: {},
}
// ServerDefault returns a secure-enough TLS configuration for the server TLS configuration.
func ServerDefault() *tls.Config {
return &tls.Config{
@ -66,11 +85,19 @@ func ClientDefault() *tls.Config {
}
// certPool returns an X.509 certificate pool from `caFile`, the certificate file.
func certPool(caFile string) (*x509.CertPool, error) {
func certPool(caFile string, exclusivePool bool) (*x509.CertPool, error) {
// If we should verify the server, we need to load a trusted ca
certPool, err := SystemCertPool()
if err != nil {
return nil, fmt.Errorf("failed to read system certificates: %v", err)
var (
certPool *x509.CertPool
err error
)
if exclusivePool {
certPool = x509.NewCertPool()
} else {
certPool, err = SystemCertPool()
if err != nil {
return nil, fmt.Errorf("failed to read system certificates: %v", err)
}
}
pem, err := ioutil.ReadFile(caFile)
if err != nil {
@ -83,24 +110,109 @@ func certPool(caFile string) (*x509.CertPool, error) {
return certPool, nil
}
// isValidMinVersion checks that the input value is a valid tls minimum version
func isValidMinVersion(version uint16) bool {
_, ok := allTLSVersions[version]
return ok
}
// adjustMinVersion sets the MinVersion on `config`, the input configuration.
// It assumes the current MinVersion on the `config` is the lowest allowed.
func adjustMinVersion(options Options, config *tls.Config) error {
if options.MinVersion > 0 {
if !isValidMinVersion(options.MinVersion) {
return fmt.Errorf("Invalid minimum TLS version: %x", options.MinVersion)
}
if options.MinVersion < config.MinVersion {
return fmt.Errorf("Requested minimum TLS version is too low. Should be at-least: %x", config.MinVersion)
}
config.MinVersion = options.MinVersion
}
return nil
}
// IsErrEncryptedKey returns true if the 'err' is an error of incorrect
// password when tryin to decrypt a TLS private key
func IsErrEncryptedKey(err error) bool {
return errors.Cause(err) == x509.IncorrectPasswordError
}
// getPrivateKey returns the private key in 'keyBytes', in PEM-encoded format.
// If the private key is encrypted, 'passphrase' is used to decrypted the
// private key.
func getPrivateKey(keyBytes []byte, passphrase string) ([]byte, error) {
// this section makes some small changes to code from notary/tuf/utils/x509.go
pemBlock, _ := pem.Decode(keyBytes)
if pemBlock == nil {
return nil, fmt.Errorf("no valid private key found")
}
var err error
if x509.IsEncryptedPEMBlock(pemBlock) {
keyBytes, err = x509.DecryptPEMBlock(pemBlock, []byte(passphrase))
if err != nil {
return nil, errors.Wrap(err, "private key is encrypted, but could not decrypt it")
}
keyBytes = pem.EncodeToMemory(&pem.Block{Type: pemBlock.Type, Bytes: keyBytes})
}
return keyBytes, nil
}
// getCert returns a Certificate from the CertFile and KeyFile in 'options',
// if the key is encrypted, the Passphrase in 'options' will be used to
// decrypt it.
func getCert(options Options) ([]tls.Certificate, error) {
if options.CertFile == "" && options.KeyFile == "" {
return nil, nil
}
errMessage := "Could not load X509 key pair"
cert, err := ioutil.ReadFile(options.CertFile)
if err != nil {
return nil, errors.Wrap(err, errMessage)
}
prKeyBytes, err := ioutil.ReadFile(options.KeyFile)
if err != nil {
return nil, errors.Wrap(err, errMessage)
}
prKeyBytes, err = getPrivateKey(prKeyBytes, options.Passphrase)
if err != nil {
return nil, errors.Wrap(err, errMessage)
}
tlsCert, err := tls.X509KeyPair(cert, prKeyBytes)
if err != nil {
return nil, errors.Wrap(err, errMessage)
}
return []tls.Certificate{tlsCert}, nil
}
// Client returns a TLS configuration meant to be used by a client.
func Client(options Options) (*tls.Config, error) {
tlsConfig := ClientDefault()
tlsConfig.InsecureSkipVerify = options.InsecureSkipVerify
if !options.InsecureSkipVerify && options.CAFile != "" {
CAs, err := certPool(options.CAFile)
CAs, err := certPool(options.CAFile, options.ExclusiveRootPools)
if err != nil {
return nil, err
}
tlsConfig.RootCAs = CAs
}
if options.CertFile != "" || options.KeyFile != "" {
tlsCert, err := tls.LoadX509KeyPair(options.CertFile, options.KeyFile)
if err != nil {
return nil, fmt.Errorf("Could not load X509 key pair: %v. Make sure the key is not encrypted", err)
}
tlsConfig.Certificates = []tls.Certificate{tlsCert}
tlsCerts, err := getCert(options)
if err != nil {
return nil, err
}
tlsConfig.Certificates = tlsCerts
if err := adjustMinVersion(options, tlsConfig); err != nil {
return nil, err
}
return tlsConfig, nil
@ -118,12 +230,17 @@ func Server(options Options) (*tls.Config, error) {
return nil, fmt.Errorf("Error reading X509 key pair (cert: %q, key: %q): %v. Make sure the key is not encrypted.", options.CertFile, options.KeyFile, err)
}
tlsConfig.Certificates = []tls.Certificate{tlsCert}
if options.ClientAuth >= tls.VerifyClientCertIfGiven {
CAs, err := certPool(options.CAFile)
if options.ClientAuth >= tls.VerifyClientCertIfGiven && options.CAFile != "" {
CAs, err := certPool(options.CAFile, options.ExclusiveRootPools)
if err != nil {
return nil, err
}
tlsConfig.ClientCAs = CAs
}
if err := adjustMinVersion(options, tlsConfig); err != nil {
return nil, err
}
return tlsConfig, nil
}

View file

@ -1,391 +0,0 @@
package tlsconfig
import (
"bytes"
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"io"
"io/ioutil"
"math/big"
"os"
"path/filepath"
"reflect"
"testing"
"time"
)
var certTemplate = x509.Certificate{
SerialNumber: big.NewInt(199999),
Subject: pkix.Name{
CommonName: "test",
},
NotBefore: time.Now().AddDate(-1, 1, 1),
NotAfter: time.Now().AddDate(1, 1, 1),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageCodeSigning},
BasicConstraintsValid: true,
}
func generateCertificate(t *testing.T, signer crypto.Signer, out io.Writer) {
derBytes, err := x509.CreateCertificate(rand.Reader, &certTemplate, &certTemplate, signer.Public(), signer)
if err != nil {
t.Fatal("Unable to generate a certificate", err.Error())
}
if err = pem.Encode(out, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil {
t.Fatal("Unable to write cert to file", err.Error())
}
}
// generates a multiple-certificate file with both RSA and ECDSA certs and
// returns the filename so that cleanup can be deferred.
func generateMultiCert(t *testing.T, tempDir string) string {
certOut, err := os.Create(filepath.Join(tempDir, "multi"))
if err != nil {
t.Fatal("Unable to create file to write multi-cert to", err.Error())
}
defer certOut.Close()
rsaKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatal("Unable to generate RSA key for multi-cert", err.Error())
}
ecKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal("Unable to generate ECDSA key for multi-cert", err.Error())
}
for _, signer := range []crypto.Signer{rsaKey, ecKey} {
generateCertificate(t, signer, certOut)
}
return certOut.Name()
}
func generateCertAndKey(t *testing.T, tempDir string) (string, string) {
rsaKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatal("Unable to generate RSA key", err.Error())
}
keyBytes := x509.MarshalPKCS1PrivateKey(rsaKey)
keyOut, err := os.Create(filepath.Join(tempDir, "key"))
if err != nil {
t.Fatal("Unable to create file to write key to", err.Error())
}
defer keyOut.Close()
if err = pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: keyBytes}); err != nil {
t.Fatal("Unable to write key to file", err.Error())
}
certOut, err := os.Create(filepath.Join(tempDir, "cert"))
if err != nil {
t.Fatal("Unable to create file to write cert to", err.Error())
}
defer certOut.Close()
generateCertificate(t, rsaKey, certOut)
return keyOut.Name(), certOut.Name()
}
func makeTempDir(t *testing.T) string {
tempDir, err := ioutil.TempDir("", "tlsconfig-test")
if err != nil {
t.Fatal("Could not make a temporary directory", err.Error())
}
return tempDir
}
// If the cert files and directory are provided but are invalid, an error is
// returned.
func TestConfigServerTLSFailsIfUnableToLoadCerts(t *testing.T) {
tempDir := makeTempDir(t)
defer os.RemoveAll(tempDir)
key, cert := generateCertAndKey(t, tempDir)
ca := generateMultiCert(t, tempDir)
tempFile, err := ioutil.TempFile("", "cert-test")
if err != nil {
t.Fatal("Unable to create temporary empty file")
}
defer os.RemoveAll(tempFile.Name())
tempFile.Close()
for _, badFile := range []string{"not-a-file", tempFile.Name()} {
for i := 0; i < 3; i++ {
files := []string{cert, key, ca}
files[i] = badFile
result, err := Server(Options{
CertFile: files[0],
KeyFile: files[1],
CAFile: files[2],
ClientAuth: tls.VerifyClientCertIfGiven,
})
if err == nil || result != nil {
t.Fatal("Expected a non-real file to error and return a nil TLS config")
}
}
}
}
// If server cert and key are provided and client auth and client CA are not
// set, a tls config with only the server certs will be returned.
func TestConfigServerTLSServerCertsOnly(t *testing.T) {
tempDir := makeTempDir(t)
defer os.RemoveAll(tempDir)
key, cert := generateCertAndKey(t, tempDir)
keypair, err := tls.LoadX509KeyPair(cert, key)
if err != nil {
t.Fatal("Unable to load the generated cert and key")
}
tlsConfig, err := Server(Options{
CertFile: cert,
KeyFile: key,
})
if err != nil || tlsConfig == nil {
t.Fatal("Unable to configure server TLS", err)
}
if len(tlsConfig.Certificates) != 1 {
t.Fatal("Unexpected server certificates")
}
if len(tlsConfig.Certificates[0].Certificate) != len(keypair.Certificate) {
t.Fatal("Unexpected server certificates")
}
for i, cert := range tlsConfig.Certificates[0].Certificate {
if !bytes.Equal(cert, keypair.Certificate[i]) {
t.Fatal("Unexpected server certificates")
}
}
if !reflect.DeepEqual(tlsConfig.CipherSuites, DefaultServerAcceptedCiphers) {
t.Fatal("Unexpected server cipher suites")
}
if !tlsConfig.PreferServerCipherSuites {
t.Fatal("Expected server to prefer cipher suites")
}
if tlsConfig.MinVersion != tls.VersionTLS10 {
t.Fatal("Unexpected server TLS version")
}
}
// If client CA is provided, it will only be used if the client auth is >=
// VerifyClientCertIfGiven
func TestConfigServerTLSClientCANotSetIfClientAuthTooLow(t *testing.T) {
tempDir := makeTempDir(t)
defer os.RemoveAll(tempDir)
key, cert := generateCertAndKey(t, tempDir)
ca := generateMultiCert(t, tempDir)
tlsConfig, err := Server(Options{
CertFile: cert,
KeyFile: key,
ClientAuth: tls.RequestClientCert,
CAFile: ca,
})
if err != nil || tlsConfig == nil {
t.Fatal("Unable to configure server TLS", err)
}
if len(tlsConfig.Certificates) != 1 {
t.Fatal("Unexpected server certificates")
}
if tlsConfig.ClientAuth != tls.RequestClientCert {
t.Fatal("ClientAuth was not set to what was in the options")
}
if tlsConfig.ClientCAs != nil {
t.Fatalf("Client CAs should never have been set")
}
}
// If client CA is provided, it will only be used if the client auth is >=
// VerifyClientCertIfGiven
func TestConfigServerTLSClientCASet(t *testing.T) {
tempDir := makeTempDir(t)
defer os.RemoveAll(tempDir)
key, cert := generateCertAndKey(t, tempDir)
ca := generateMultiCert(t, tempDir)
tlsConfig, err := Server(Options{
CertFile: cert,
KeyFile: key,
ClientAuth: tls.VerifyClientCertIfGiven,
CAFile: ca,
})
if err != nil || tlsConfig == nil {
t.Fatal("Unable to configure server TLS", err)
}
if len(tlsConfig.Certificates) != 1 {
t.Fatal("Unexpected server certificates")
}
if tlsConfig.ClientAuth != tls.VerifyClientCertIfGiven {
t.Fatal("ClientAuth was not set to what was in the options")
}
if tlsConfig.ClientCAs == nil || len(tlsConfig.ClientCAs.Subjects()) != 2 {
t.Fatalf("Client CAs were never set correctly")
}
}
// The root CA is never set if InsecureSkipBoolean is set to true, but the
// default client options are set
func TestConfigClientTLSNoVerify(t *testing.T) {
tempDir := makeTempDir(t)
defer os.RemoveAll(tempDir)
ca := generateMultiCert(t, tempDir)
tlsConfig, err := Client(Options{CAFile: ca, InsecureSkipVerify: true})
if err != nil || tlsConfig == nil {
t.Fatal("Unable to configure client TLS", err)
}
if tlsConfig.RootCAs != nil {
t.Fatal("Should not have set Root CAs", err)
}
if !reflect.DeepEqual(tlsConfig.CipherSuites, clientCipherSuites) {
t.Fatal("Unexpected client cipher suites")
}
if tlsConfig.MinVersion != tls.VersionTLS12 {
t.Fatal("Unexpected client TLS version")
}
if tlsConfig.Certificates != nil {
t.Fatal("Somehow client certificates were set")
}
}
// The root CA is never set if InsecureSkipBoolean is set to false and root CA
// is not provided.
func TestConfigClientTLSNoRoot(t *testing.T) {
tlsConfig, err := Client(Options{})
if err != nil || tlsConfig == nil {
t.Fatal("Unable to configure client TLS", err)
}
if tlsConfig.RootCAs != nil {
t.Fatal("Should not have set Root CAs", err)
}
if !reflect.DeepEqual(tlsConfig.CipherSuites, clientCipherSuites) {
t.Fatal("Unexpected client cipher suites")
}
if tlsConfig.MinVersion != tls.VersionTLS12 {
t.Fatal("Unexpected client TLS version")
}
if tlsConfig.Certificates != nil {
t.Fatal("Somehow client certificates were set")
}
}
// The RootCA is set if the file is provided and InsecureSkipVerify is false
func TestConfigClientTLSRootCAFileWithOneCert(t *testing.T) {
tempDir := makeTempDir(t)
defer os.RemoveAll(tempDir)
ca := generateMultiCert(t, tempDir)
tlsConfig, err := Client(Options{CAFile: ca})
if err != nil || tlsConfig == nil {
t.Fatal("Unable to configure client TLS", err)
}
if tlsConfig.RootCAs == nil || len(tlsConfig.RootCAs.Subjects()) != 2 {
t.Fatal("Root CAs not set properly", err)
}
if tlsConfig.Certificates != nil {
t.Fatal("Somehow client certificates were set")
}
}
// An error is returned if a root CA is provided but the file doesn't exist.
func TestConfigClientTLSNonexistentRootCAFile(t *testing.T) {
tlsConfig, err := Client(Options{CAFile: "nonexistent"})
if err == nil || tlsConfig != nil {
t.Fatal("Should not have been able to configure client TLS", err)
}
}
// An error is returned if either the client cert or the key are provided
// but invalid or blank.
func TestConfigClientTLSClientCertOrKeyInvalid(t *testing.T) {
tempDir := makeTempDir(t)
defer os.RemoveAll(tempDir)
key, cert := generateCertAndKey(t, tempDir)
tempFile, err := ioutil.TempFile("", "cert-test")
if err != nil {
t.Fatal("Unable to create temporary empty file")
}
defer os.Remove(tempFile.Name())
tempFile.Close()
for i := 0; i < 2; i++ {
for _, invalid := range []string{"not-a-file", "", tempFile.Name()} {
files := []string{cert, key}
files[i] = invalid
tlsConfig, err := Client(Options{CertFile: files[0], KeyFile: files[1]})
if err == nil || tlsConfig != nil {
t.Fatal("Should not have been able to configure client TLS", err)
}
}
}
}
// The certificate is set if the client cert and client key are provided and
// valid.
func TestConfigClientTLSValidClientCertAndKey(t *testing.T) {
tempDir := makeTempDir(t)
defer os.RemoveAll(tempDir)
key, cert := generateCertAndKey(t, tempDir)
keypair, err := tls.LoadX509KeyPair(cert, key)
if err != nil {
t.Fatal("Unable to load the generated cert and key")
}
tlsConfig, err := Client(Options{CertFile: cert, KeyFile: key})
if err != nil || tlsConfig == nil {
t.Fatal("Unable to configure client TLS", err)
}
if len(tlsConfig.Certificates) != 1 {
t.Fatal("Unexpected client certificates")
}
if len(tlsConfig.Certificates[0].Certificate) != len(keypair.Certificate) {
t.Fatal("Unexpected client certificates")
}
for i, cert := range tlsConfig.Certificates[0].Certificate {
if !bytes.Equal(cert, keypair.Certificate[i]) {
t.Fatal("Unexpected client certificates")
}
}
if tlsConfig.RootCAs != nil {
t.Fatal("Root CAs should not have been set", err)
}
}