Add glide.yaml and vendor deps

This commit is contained in:
Dalton Hubble 2016-12-03 22:43:32 -08:00
parent db918f12ad
commit 5b3d5e81bd
18880 changed files with 5166045 additions and 1 deletions

View file

@ -0,0 +1,21 @@
// +build go1.7
package tlsconfig
import (
"crypto/x509"
"runtime"
"github.com/Sirupsen/logrus"
)
// SystemCertPool returns a copy of the system cert pool,
// returns an error if failed to load or empty pool on windows.
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)
return x509.NewCertPool(), nil
}
return certpool, err
}

View file

@ -0,0 +1,16 @@
// +build !go1.7
package tlsconfig
import (
"crypto/x509"
"github.com/Sirupsen/logrus"
)
// SystemCertPool returns an new empty cert pool,
// accessing system cert pool is supported in go 1.7
func SystemCertPool() (*x509.CertPool, error) {
logrus.Warn("Unable to use system certificate pool: requires building with go 1.7 or later")
return x509.NewCertPool(), nil
}

View file

@ -0,0 +1,129 @@
// Package tlsconfig provides primitives to retrieve secure-enough TLS configurations for both clients and servers.
//
// As a reminder from https://golang.org/pkg/crypto/tls/#Config:
// A Config structure is used to configure a TLS client or server. After one has been passed to a TLS function it must not be modified.
// A Config may be reused; the tls package will also not modify it.
package tlsconfig
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"os"
"github.com/Sirupsen/logrus"
)
// Options represents the information needed to create client and server TLS configurations.
type Options struct {
CAFile string
// If either CertFile or KeyFile is empty, Client() will not load them
// preventing the client from authenticating to the server.
// However, Server() requires them and will error out if they are empty.
CertFile string
KeyFile string
// client-only option
InsecureSkipVerify bool
// server-only option
ClientAuth tls.ClientAuthType
}
// Extra (server-side) accepted CBC cipher suites - will phase out in the future
var acceptedCBCCiphers = []uint16{
tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
tls.TLS_RSA_WITH_AES_256_CBC_SHA,
tls.TLS_RSA_WITH_AES_128_CBC_SHA,
}
// DefaultServerAcceptedCiphers should be uses by code which already has a crypto/tls
// options struct but wants to use a commonly accepted set of TLS cipher suites, with
// known weak algorithms removed.
var DefaultServerAcceptedCiphers = append(clientCipherSuites, acceptedCBCCiphers...)
// ServerDefault returns a secure-enough TLS configuration for the server TLS configuration.
func ServerDefault() *tls.Config {
return &tls.Config{
// Avoid fallback to SSL protocols < TLS1.0
MinVersion: tls.VersionTLS10,
PreferServerCipherSuites: true,
CipherSuites: DefaultServerAcceptedCiphers,
}
}
// ClientDefault returns a secure-enough TLS configuration for the client TLS configuration.
func ClientDefault() *tls.Config {
return &tls.Config{
// Prefer TLS1.2 as the client minimum
MinVersion: tls.VersionTLS12,
CipherSuites: clientCipherSuites,
}
}
// certPool returns an X.509 certificate pool from `caFile`, the certificate file.
func certPool(caFile string) (*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)
}
pem, err := ioutil.ReadFile(caFile)
if err != nil {
return nil, fmt.Errorf("could not read CA certificate %q: %v", caFile, err)
}
if !certPool.AppendCertsFromPEM(pem) {
return nil, fmt.Errorf("failed to append certificates from PEM file: %q", caFile)
}
logrus.Debugf("Trusting %d certs", len(certPool.Subjects()))
return certPool, 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)
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}
}
return tlsConfig, nil
}
// Server returns a TLS configuration meant to be used by a server.
func Server(options Options) (*tls.Config, error) {
tlsConfig := ServerDefault()
tlsConfig.ClientAuth = options.ClientAuth
tlsCert, err := tls.LoadX509KeyPair(options.CertFile, options.KeyFile)
if err != nil {
if os.IsNotExist(err) {
return nil, fmt.Errorf("Could not load X509 key pair (cert: %q, key: %q): %v", options.CertFile, options.KeyFile, err)
}
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 err != nil {
return nil, err
}
tlsConfig.ClientCAs = CAs
}
return tlsConfig, nil
}

View file

@ -0,0 +1,17 @@
// +build go1.5
// Package tlsconfig provides primitives to retrieve secure-enough TLS configurations for both clients and servers.
//
package tlsconfig
import (
"crypto/tls"
)
// Client TLS cipher suites (dropping CBC ciphers for client preferred suite set)
var clientCipherSuites = []uint16{
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
}

View file

@ -0,0 +1,15 @@
// +build !go1.5
// Package tlsconfig provides primitives to retrieve secure-enough TLS configurations for both clients and servers.
//
package tlsconfig
import (
"crypto/tls"
)
// Client TLS cipher suites (dropping CBC ciphers for client preferred suite set)
var clientCipherSuites = []uint16{
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
}

View file

@ -0,0 +1,391 @@
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)
}
}