pinning + new version of backups
This commit is contained in:
@@ -0,0 +1,106 @@
|
||||
package tlsconfig
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Options struct {
|
||||
InsecureSkipVerify bool
|
||||
CAPath string
|
||||
SPKIPins []string
|
||||
ClientCertPath string
|
||||
ClientKeyPath string
|
||||
}
|
||||
|
||||
func Build(options Options) (*tls.Config, error) {
|
||||
pins, err := decodePins(options.SPKIPins)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tlsConfig := &tls.Config{
|
||||
MinVersion: tls.VersionTLS12,
|
||||
}
|
||||
|
||||
if strings.TrimSpace(options.CAPath) != "" {
|
||||
caCert, err := os.ReadFile(options.CAPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read TLS CA: %w", err)
|
||||
}
|
||||
caCertPool := x509.NewCertPool()
|
||||
if !caCertPool.AppendCertsFromPEM(caCert) {
|
||||
return nil, errors.New("parse TLS CA: no certificates found")
|
||||
}
|
||||
tlsConfig.RootCAs = caCertPool
|
||||
}
|
||||
|
||||
if strings.TrimSpace(options.ClientCertPath) != "" || strings.TrimSpace(options.ClientKeyPath) != "" {
|
||||
if strings.TrimSpace(options.ClientCertPath) == "" || strings.TrimSpace(options.ClientKeyPath) == "" {
|
||||
return nil, errors.New("both TLS client certificate and key are required")
|
||||
}
|
||||
certificate, err := tls.LoadX509KeyPair(options.ClientCertPath, options.ClientKeyPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load TLS client certificate: %w", err)
|
||||
}
|
||||
tlsConfig.Certificates = []tls.Certificate{certificate}
|
||||
}
|
||||
|
||||
if len(pins) > 0 {
|
||||
// Verification is performed below against an embedded application pin.
|
||||
// This intentionally supports self-signed certificates without trusting
|
||||
// arbitrary certificates from the network or host trust store.
|
||||
tlsConfig.InsecureSkipVerify = true //nolint:gosec
|
||||
tlsConfig.VerifyConnection = func(state tls.ConnectionState) error {
|
||||
return verifyPinnedConnection(state, pins, time.Now())
|
||||
}
|
||||
return tlsConfig, nil
|
||||
}
|
||||
|
||||
tlsConfig.InsecureSkipVerify = options.InsecureSkipVerify //nolint:gosec
|
||||
return tlsConfig, nil
|
||||
}
|
||||
|
||||
func decodePins(values []string) ([][]byte, error) {
|
||||
result := make([][]byte, 0, len(values))
|
||||
for _, value := range values {
|
||||
value = strings.TrimSpace(strings.TrimPrefix(value, "sha256/"))
|
||||
if value == "" {
|
||||
continue
|
||||
}
|
||||
decoded, err := base64.StdEncoding.DecodeString(value)
|
||||
if err != nil || len(decoded) != sha256.Size {
|
||||
return nil, fmt.Errorf("invalid TLS SPKI pin %q", value)
|
||||
}
|
||||
result = append(result, decoded)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func verifyPinnedConnection(state tls.ConnectionState, pins [][]byte, now time.Time) error {
|
||||
if len(state.PeerCertificates) == 0 {
|
||||
return errors.New("TLS peer did not provide a certificate")
|
||||
}
|
||||
leaf := state.PeerCertificates[0]
|
||||
if now.Before(leaf.NotBefore) || now.After(leaf.NotAfter) {
|
||||
return fmt.Errorf("TLS peer certificate is not valid at %s", now.UTC().Format(time.RFC3339))
|
||||
}
|
||||
sum := sha256.Sum256(leaf.RawSubjectPublicKeyInfo)
|
||||
for _, pin := range pins {
|
||||
if bytes.Equal(sum[:], pin) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf(
|
||||
"TLS server identity pin mismatch (received sha256/%s)",
|
||||
base64.StdEncoding.EncodeToString(sum[:]),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package tlsconfig
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"encoding/base64"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func pinForCertificate(certificate *tls.Certificate) string {
|
||||
sum := sha256.Sum256(certificate.Leaf.RawSubjectPublicKeyInfo)
|
||||
return base64.StdEncoding.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func clientForConfig(config *tls.Config) *http.Client {
|
||||
return &http.Client{
|
||||
Transport: &http.Transport{TLSClientConfig: config},
|
||||
}
|
||||
}
|
||||
|
||||
func TestPinnedServerIdentity(t *testing.T) {
|
||||
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = io.WriteString(w, "ok")
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
correctPin := pinForCertificate(&server.TLS.Certificates[0])
|
||||
config, err := Build(Options{SPKIPins: []string{correctPin}})
|
||||
if err != nil {
|
||||
t.Fatalf("Build failed: %v", err)
|
||||
}
|
||||
|
||||
response, err := clientForConfig(config).Get(server.URL)
|
||||
if err != nil {
|
||||
t.Fatalf("pinned request failed: %v", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
t.Fatalf("unexpected status: %d", response.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPinnedServerRejectsRogueKey(t *testing.T) {
|
||||
server := httptest.NewTLSServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
|
||||
defer server.Close()
|
||||
|
||||
roguePin := base64.StdEncoding.EncodeToString(bytesOf(sha256.Size, 0x42))
|
||||
config, err := Build(Options{SPKIPins: []string{roguePin}})
|
||||
if err != nil {
|
||||
t.Fatalf("Build failed: %v", err)
|
||||
}
|
||||
|
||||
_, err = clientForConfig(config).Get(server.URL)
|
||||
if err == nil || !strings.Contains(err.Error(), "identity pin mismatch") {
|
||||
t.Fatalf("expected pin mismatch, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidPinFailsClosed(t *testing.T) {
|
||||
if _, err := Build(Options{SPKIPins: []string{"not-a-pin"}}); err == nil {
|
||||
t.Fatal("expected invalid pin to be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExplicitInsecureModeRemainsOptIn(t *testing.T) {
|
||||
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
secureConfig, err := Build(Options{})
|
||||
if err != nil {
|
||||
t.Fatalf("Build secure config failed: %v", err)
|
||||
}
|
||||
if _, err := clientForConfig(secureConfig).Get(server.URL); err == nil {
|
||||
t.Fatal("untrusted self-signed certificate unexpectedly succeeded")
|
||||
}
|
||||
|
||||
insecureConfig, err := Build(Options{InsecureSkipVerify: true})
|
||||
if err != nil {
|
||||
t.Fatalf("Build insecure config failed: %v", err)
|
||||
}
|
||||
response, err := clientForConfig(insecureConfig).Get(server.URL)
|
||||
if err != nil {
|
||||
t.Fatalf("explicit insecure request failed: %v", err)
|
||||
}
|
||||
response.Body.Close()
|
||||
}
|
||||
|
||||
func bytesOf(count int, value byte) []byte {
|
||||
result := make([]byte, count)
|
||||
for i := range result {
|
||||
result[i] = value
|
||||
}
|
||||
return result
|
||||
}
|
||||
Reference in New Issue
Block a user