Move tls config creation to tlsutil (#6956)

* Move tls config creation to tlsutil

* Update sdk/helper/tlsutil/tlsutil.go

Co-Authored-By: Jim Kalafut <jim@kalafut.net>

* address review comments
This commit is contained in:
Vishal Nayak
2019-06-22 21:51:52 -04:00
committed by GitHub
parent 84919f4a8e
commit 76a9eae875
2 changed files with 38 additions and 34 deletions

View File

@@ -2,11 +2,15 @@ package tlsutil
import (
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"github.com/hashicorp/vault/sdk/helper/strutil"
)
var ErrInvalidCertParams = errors.New("ca cert, client key and client cert must all be set, or none should be set")
// TLSLookup maps the tls_min_version configuration to the internal value
var TLSLookup = map[string]uint16{
"tls10": tls.VersionTLS10,
@@ -65,3 +69,33 @@ func GetCipherName(cipher uint16) (string, error) {
}
return "", fmt.Errorf("unsupported cipher %d", cipher)
}
func ClientTLSConfig(caCert []byte, clientCert []byte, clientKey []byte) (*tls.Config, error) {
var tlsConfig *tls.Config
switch {
case len(caCert) != 0 && len(clientCert) != 0 && len(clientKey) != 0:
// Valid
case len(caCert) != 0, len(clientCert) != 0, len(clientKey) != 0:
return nil, ErrInvalidCertParams
}
pool := x509.NewCertPool()
pool.AppendCertsFromPEM(caCert)
cert, err := tls.X509KeyPair(clientCert, clientKey)
if err != nil {
return nil, err
}
tlsConfig = &tls.Config{
Certificates: []tls.Certificate{cert},
RootCAs: pool,
ClientAuth: tls.RequireAndVerifyClientCert,
MinVersion: tls.VersionTLS12,
}
tlsConfig.BuildNameToCertificate()
return tlsConfig, nil
}