Secure messenger with TLS identities, scoped OpenBao secrets and worker compromise experiments
This commit is contained in:
@@ -0,0 +1,133 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Rule struct {
|
||||
Identity string `json:"identity"`
|
||||
Methods []string `json:"methods"`
|
||||
Prefixes []string `json:"prefixes"`
|
||||
}
|
||||
type Listener struct {
|
||||
Listen string `json:"listen"`
|
||||
Target string `json:"target"`
|
||||
Raw bool `json:"raw"`
|
||||
Identities []string `json:"identities"`
|
||||
Rules []Rule `json:"rules"`
|
||||
}
|
||||
|
||||
// The plaintext upstream is always loopback in the SAME network namespace.
|
||||
// Services have no native listener on the container network or published port.
|
||||
func Gateway(ctx context.Context, path string) error {
|
||||
b, e := os.ReadFile(path)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
var configs []Listener
|
||||
if e = json.Unmarshal(b, &configs); e != nil {
|
||||
return e
|
||||
}
|
||||
errors := make(chan error, len(configs))
|
||||
for _, cfg := range configs {
|
||||
cfg := cfg
|
||||
host, _, e := net.SplitHostPort(cfg.Target)
|
||||
if e != nil || host != "127.0.0.1" {
|
||||
return fmt.Errorf("gateway upstream must be loopback")
|
||||
}
|
||||
tc, e := ServerTLS(cfg.Identities)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
ln, e := tls.Listen("tcp", cfg.Listen, tc)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
go func() { <-ctx.Done(); ln.Close() }()
|
||||
if cfg.Raw {
|
||||
go func() {
|
||||
for {
|
||||
c, e := ln.Accept()
|
||||
if e != nil {
|
||||
errors <- e
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
defer c.Close()
|
||||
c.SetDeadline(time.Now().Add(30 * time.Second))
|
||||
if e := c.(*tls.Conn).Handshake(); e != nil {
|
||||
return
|
||||
}
|
||||
up, e := net.DialTimeout("tcp", cfg.Target, time.Second)
|
||||
if e != nil {
|
||||
return
|
||||
}
|
||||
defer up.Close()
|
||||
up.SetDeadline(time.Now().Add(30 * time.Second))
|
||||
go io.Copy(up, c)
|
||||
io.Copy(c, up)
|
||||
}()
|
||||
}
|
||||
}()
|
||||
continue
|
||||
}
|
||||
u, _ := url.Parse("http://" + cfg.Target)
|
||||
proxy := httputil.NewSingleHostReverseProxy(u)
|
||||
proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, e error) { http.Error(w, "upstream unavailable", 503) }
|
||||
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if len(cfg.Rules) > 0 {
|
||||
allowed := false
|
||||
for _, rule := range cfg.Rules {
|
||||
if r.TLS == nil || len(r.TLS.PeerCertificates) == 0 {
|
||||
continue
|
||||
}
|
||||
identity := false
|
||||
for _, san := range r.TLS.PeerCertificates[0].DNSNames {
|
||||
if san == rule.Identity+".client.lab" {
|
||||
identity = true
|
||||
}
|
||||
}
|
||||
method := false
|
||||
for _, v := range rule.Methods {
|
||||
if v == r.Method {
|
||||
method = true
|
||||
}
|
||||
}
|
||||
if identity && method {
|
||||
for _, p := range rule.Prefixes {
|
||||
if strings.HasPrefix(r.URL.Path, p) {
|
||||
allowed = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !allowed {
|
||||
http.Error(w, "service action forbidden", 403)
|
||||
return
|
||||
}
|
||||
}
|
||||
proxy.ServeHTTP(w, r)
|
||||
})
|
||||
srv := &http.Server{Handler: AuthorizeHTTP(tc, handler), ReadHeaderTimeout: 3 * time.Second, ReadTimeout: 35 * time.Second, WriteTimeout: 35 * time.Second, IdleTimeout: 2 * time.Second, MaxHeaderBytes: 16 << 10,
|
||||
ErrorLog: slog.NewLogLogger(slog.NewTextHandler(io.Discard, nil), slog.LevelError)}
|
||||
go func() { errors <- srv.Serve(ln) }()
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
case e := <-errors:
|
||||
return e
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
// Operator-only verifier. Inputs arrive on stdin; private values never appear
|
||||
// in argv or output. SQL outputs only allow/deny, never returned row contents.
|
||||
func Probe() error {
|
||||
var in struct {
|
||||
Kind, Role, Cert, URL, Method, Body, Query, Key, CredentialsFile, ServerName, Auth string
|
||||
NoCert, WrongCA, ReturnBody bool
|
||||
Command []string
|
||||
}
|
||||
if json.NewDecoder(io.LimitReader(os.Stdin, 65536)).Decode(&in) != nil {
|
||||
return fmt.Errorf("invalid probe input")
|
||||
}
|
||||
if in.Cert == "" {
|
||||
in.Cert = "operator"
|
||||
}
|
||||
os.Setenv("TLS_CERT_FILE", "/fixtures/"+in.Cert+"/cert.crt")
|
||||
os.Setenv("TLS_KEY_FILE", "/fixtures/"+in.Cert+"/key.key")
|
||||
tc, e := ClientTLS()
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if in.NoCert {
|
||||
tc.GetClientCertificate = nil
|
||||
}
|
||||
if in.ServerName != "" {
|
||||
tc.ServerName = in.ServerName
|
||||
}
|
||||
if in.WrongCA {
|
||||
b, _ := os.ReadFile("/operator/alien-ca/ca.crt")
|
||||
p := x509.NewCertPool()
|
||||
p.AppendCertsFromPEM(b)
|
||||
tc.RootCAs = p
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 6*time.Second)
|
||||
defer cancel()
|
||||
result := map[string]any{"ok": false}
|
||||
var creds map[string]json.RawMessage
|
||||
path := in.CredentialsFile
|
||||
if path == "" {
|
||||
path = "/operator/credentials.json"
|
||||
}
|
||||
raw, _ := os.ReadFile(path)
|
||||
json.Unmarshal(raw, &creds)
|
||||
var role struct {
|
||||
DBPassword string `json:"db_password"`
|
||||
BrokerPassword string `json:"broker_password"`
|
||||
CachePassword string `json:"cache_password"`
|
||||
Access string `json:"s3_access_key_id"`
|
||||
Secret string `json:"s3_secret_access_key"`
|
||||
}
|
||||
json.Unmarshal(creds[in.Role], &role)
|
||||
switch in.Kind {
|
||||
case "http":
|
||||
if in.Method == "" {
|
||||
in.Method = "GET"
|
||||
}
|
||||
r, e2 := http.NewRequestWithContext(ctx, in.Method, in.URL, strings.NewReader(in.Body))
|
||||
if e2 != nil {
|
||||
return fmt.Errorf("invalid probe URL")
|
||||
}
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
if in.Auth == "grafana" {
|
||||
var password string
|
||||
json.Unmarshal(creds["grafana_password"], &password)
|
||||
r.SetBasicAuth("admin", password)
|
||||
}
|
||||
tr := &http.Transport{TLSClientConfig: tc, DisableKeepAlives: true}
|
||||
defer tr.CloseIdleConnections()
|
||||
client := &http.Client{Transport: tr, Timeout: 6 * time.Second}
|
||||
resp, err := client.Do(r)
|
||||
e = err
|
||||
if e == nil {
|
||||
defer resp.Body.Close()
|
||||
b, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
result["status"] = resp.StatusCode
|
||||
result["ok"] = resp.StatusCode >= 200 && resp.StatusCode < 300
|
||||
result["tls"] = resp.TLS != nil && resp.TLS.Version >= tls.VersionTLS12
|
||||
if in.ReturnBody {
|
||||
result["body"] = string(b)
|
||||
}
|
||||
}
|
||||
case "postgres":
|
||||
cfg, err := pgx.ParseConfig("postgres://messenger_" + in.Role + ":" + role.DBPassword + "@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/run/tls/ca.crt")
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid probe role")
|
||||
}
|
||||
cfg.TLSConfig = tc.Clone()
|
||||
if cfg.TLSConfig.ServerName == "" {
|
||||
cfg.TLSConfig.ServerName = "postgres"
|
||||
}
|
||||
cfg.Fallbacks = nil
|
||||
var conn *pgx.Conn
|
||||
conn, e = pgx.ConnectConfig(ctx, cfg)
|
||||
if e == nil {
|
||||
defer conn.Close(ctx)
|
||||
_, e = conn.Exec(ctx, in.Query)
|
||||
result["ok"] = e == nil
|
||||
}
|
||||
case "redis":
|
||||
pass := role.BrokerPassword
|
||||
user := in.Role
|
||||
host := "broker"
|
||||
if in.URL == "cache" {
|
||||
pass = role.CachePassword
|
||||
host = "cache"
|
||||
}
|
||||
rc := redis.NewClient(&redis.Options{Addr: host + ":6379", Username: user, Password: pass, TLSConfig: tc, MaxRetries: -1, DialTimeout: time.Second, ReadTimeout: time.Second, WriteTimeout: time.Second})
|
||||
defer rc.Close()
|
||||
args := make([]any, len(in.Command))
|
||||
for i, v := range in.Command {
|
||||
args[i] = v
|
||||
}
|
||||
_, e = rc.Do(ctx, args...).Result()
|
||||
result["ok"] = e == nil
|
||||
case "s3":
|
||||
tr := &http.Transport{TLSClientConfig: tc}
|
||||
defer tr.CloseIdleConnections()
|
||||
client, err := minio.New("s3:9000", &minio.Options{Secure: true, Creds: credentials.NewStaticV4(role.Access, role.Secret, ""), Region: "us-east-1", Transport: tr, MaxRetries: 1})
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid probe object client")
|
||||
}
|
||||
switch in.Method {
|
||||
case "PUT":
|
||||
_, e = client.PutObject(ctx, "messenger-attachments", in.Key, strings.NewReader(in.Body), int64(len(in.Body)), minio.PutObjectOptions{})
|
||||
case "DELETE":
|
||||
e = client.RemoveObject(ctx, "messenger-attachments", in.Key, minio.RemoveObjectOptions{})
|
||||
case "LIST_BUCKETS":
|
||||
_, e = client.ListBuckets(ctx)
|
||||
default:
|
||||
_, e = client.StatObject(ctx, "messenger-attachments", in.Key, minio.StatObjectOptions{})
|
||||
}
|
||||
result["ok"] = e == nil
|
||||
default:
|
||||
return fmt.Errorf("unknown probe kind")
|
||||
}
|
||||
if e != nil {
|
||||
category := "connection_or_action_denied"
|
||||
if strings.Contains(e.Error(), "NOPERM") || strings.Contains(e.Error(), "permission denied") || strings.Contains(e.Error(), "Access Denied") {
|
||||
category = "permission_denied"
|
||||
}
|
||||
var authority x509.UnknownAuthorityError
|
||||
var hostname x509.HostnameError
|
||||
var pg *pgconn.PgError
|
||||
switch {
|
||||
case errors.As(e, &authority):
|
||||
category = "ca_verification_failed"
|
||||
case errors.As(e, &hostname):
|
||||
category = "hostname_verification_failed"
|
||||
case errors.As(e, &pg):
|
||||
if pg.Code == "42501" {
|
||||
category = "permission_denied"
|
||||
} else if pg.Code == "28P01" {
|
||||
category = "credential_denied"
|
||||
}
|
||||
case strings.Contains(e.Error(), "tls:") || strings.Contains(e.Error(), "certificate"):
|
||||
category = "tls_handshake_denied"
|
||||
case strings.Contains(e.Error(), "timeout") || strings.Contains(e.Error(), "deadline exceeded"):
|
||||
category = "timeout"
|
||||
}
|
||||
// Generic category only: upstream errors can contain SQL/user names/keys.
|
||||
result["error_category"] = category
|
||||
}
|
||||
return json.NewEncoder(os.Stdout).Encode(result)
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"reflect"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
func baoRequest(ctx context.Context, client *http.Client, method, path, token string, body any) (map[string]any, error) {
|
||||
if !strings.HasPrefix(os.Getenv("BAO_ADDR"), "https://") {
|
||||
return nil, fmt.Errorf("secret service requires HTTPS")
|
||||
}
|
||||
b, _ := json.Marshal(body)
|
||||
r, e := http.NewRequestWithContext(ctx, method, os.Getenv("BAO_ADDR")+"/v1/"+path, bytes.NewReader(b))
|
||||
if e != nil {
|
||||
return nil, fmt.Errorf("invalid secret endpoint")
|
||||
}
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
if token != "" {
|
||||
r.Header.Set("X-Vault-Token", token)
|
||||
}
|
||||
resp, e := client.Do(r)
|
||||
if e != nil {
|
||||
return nil, fmt.Errorf("secret service unavailable")
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
return nil, fmt.Errorf("secret service denied or sealed")
|
||||
}
|
||||
var out map[string]any
|
||||
if json.NewDecoder(io.LimitReader(resp.Body, 65536)).Decode(&out) != nil {
|
||||
return nil, fmt.Errorf("invalid secret response")
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Short-lived certificate auth replaces a permanent bootstrap token. Values
|
||||
// live only in this process and a tmpfs snapshot consumed by the child.
|
||||
func fetch(ctx context.Context) (map[string]string, time.Time, error) {
|
||||
tc, e := ClientTLS()
|
||||
if e != nil {
|
||||
return nil, time.Time{}, e
|
||||
}
|
||||
transport := &http.Transport{TLSClientConfig: tc}
|
||||
defer transport.CloseIdleConnections()
|
||||
client := &http.Client{Transport: transport, Timeout: 3 * time.Second}
|
||||
login, e := baoRequest(ctx, client, "POST", "auth/cert/login", "", map[string]string{"name": os.Getenv("SERVICE_ID")})
|
||||
if e != nil {
|
||||
return nil, time.Time{}, e
|
||||
}
|
||||
auth, ok := login["auth"].(map[string]any)
|
||||
if !ok {
|
||||
return nil, time.Time{}, fmt.Errorf("missing service auth")
|
||||
}
|
||||
token, _ := auth["client_token"].(string)
|
||||
ttl, _ := auth["lease_duration"].(float64)
|
||||
if ttl <= 0 || ttl > 120 {
|
||||
return nil, time.Time{}, fmt.Errorf("invalid service TTL")
|
||||
}
|
||||
defer baoRequest(context.WithoutCancel(ctx), client, "POST", "auth/token/revoke-self", token, map[string]any{})
|
||||
data, e := baoRequest(ctx, client, "GET", "kv/data/"+os.Getenv("SERVICE_ID"), token, nil)
|
||||
if e != nil {
|
||||
return nil, time.Time{}, e
|
||||
}
|
||||
outer, _ := data["data"].(map[string]any)
|
||||
raw, _ := outer["data"].(map[string]any)
|
||||
values := map[string]string{}
|
||||
for k, v := range raw {
|
||||
if s, ok := v.(string); ok {
|
||||
values[k] = s
|
||||
}
|
||||
}
|
||||
if values["database_url"] == "" {
|
||||
return nil, time.Time{}, fmt.Errorf("incomplete service secrets")
|
||||
}
|
||||
return values, time.Now().Add(time.Duration(ttl) * time.Second), nil
|
||||
}
|
||||
func stopChild(cmd *exec.Cmd, done <-chan error) {
|
||||
cmd.Process.Signal(syscall.SIGTERM)
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(6 * time.Second):
|
||||
cmd.Process.Kill()
|
||||
<-done
|
||||
}
|
||||
}
|
||||
|
||||
func Supervise(ctx context.Context, args []string) error {
|
||||
var values map[string]string
|
||||
var expiry time.Time
|
||||
var child *exec.Cmd
|
||||
var done chan error
|
||||
ticker := time.NewTicker(5 * time.Second)
|
||||
defer ticker.Stop()
|
||||
defer func() {
|
||||
if child != nil {
|
||||
stopChild(child, done)
|
||||
}
|
||||
}()
|
||||
for {
|
||||
fresh, until, e := fetch(ctx)
|
||||
if e == nil {
|
||||
expiry = until
|
||||
if child == nil || !reflect.DeepEqual(values, fresh) {
|
||||
if child != nil {
|
||||
stopChild(child, done)
|
||||
child = nil
|
||||
}
|
||||
values = fresh
|
||||
b, _ := json.Marshal(values)
|
||||
if e = os.WriteFile("/run/runtime/active.json", b, 0600); e != nil {
|
||||
return fmt.Errorf("runtime secret storage unavailable")
|
||||
}
|
||||
executable, _ := os.Executable()
|
||||
child = exec.Command(executable, args...)
|
||||
child.Env = append(os.Environ(), "RUNTIME_SECRET_FILE=/run/runtime/active.json")
|
||||
child.Stdout = os.Stdout
|
||||
child.Stderr = os.Stderr
|
||||
if e = child.Start(); e != nil {
|
||||
return fmt.Errorf("child unavailable")
|
||||
}
|
||||
done = make(chan error, 1)
|
||||
go func(c *exec.Cmd, ch chan error) { ch <- c.Wait() }(child, done)
|
||||
slog.Info("service credentials installed", "event", "credentials_installed")
|
||||
}
|
||||
} else if child != nil && !time.Now().Before(expiry) {
|
||||
stopChild(child, done)
|
||||
child = nil
|
||||
os.Remove("/run/runtime/active.json")
|
||||
slog.Warn("service authorization expired", "event", "authorization_expired")
|
||||
}
|
||||
if child != nil {
|
||||
select {
|
||||
case <-done:
|
||||
child = nil
|
||||
default:
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func RuntimeSecret(name string) (string, bool) {
|
||||
path := os.Getenv("RUNTIME_SECRET_FILE")
|
||||
if path == "" {
|
||||
return "", false
|
||||
}
|
||||
b, e := os.ReadFile(path)
|
||||
if e != nil {
|
||||
return "", true
|
||||
}
|
||||
var data map[string]string
|
||||
if json.Unmarshal(b, &data) != nil {
|
||||
return "", true
|
||||
}
|
||||
key := map[string]string{"DATABASE_URL_FILE": "database_url", "CACHE_URL_FILE": "cache_url", "BROKER_URL_FILE": "broker_url", "CURSOR_KEY_FILE": "cursor_key", "S3_ACCESS_KEY_ID_FILE": "s3_access_key_id", "S3_SECRET_ACCESS_KEY_FILE": "s3_secret_access_key"}[name]
|
||||
return data[key], true
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
// Package security implements the lab's explicit trust boundaries.
|
||||
package security
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func roots() (*x509.CertPool, error) {
|
||||
b, e := os.ReadFile(os.Getenv("TLS_CA_FILE"))
|
||||
if e != nil {
|
||||
return nil, fmt.Errorf("TLS CA unavailable")
|
||||
}
|
||||
p := x509.NewCertPool()
|
||||
if !p.AppendCertsFromPEM(b) {
|
||||
return nil, fmt.Errorf("invalid TLS CA")
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// Recheck revocation on EVERY HTTP request, including an already-open TLS
|
||||
// connection. An in-flight request remains bounded by the HTTP deadlines.
|
||||
func AuthorizeHTTP(c *tls.Config, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if c.VerifyConnection != nil && (r.TLS == nil || c.VerifyConnection(*r.TLS) != nil) {
|
||||
w.Header().Set("Connection", "close")
|
||||
http.Error(w, "service identity forbidden", 403)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
func pair() (*tls.Certificate, error) {
|
||||
c, e := tls.LoadX509KeyPair(os.Getenv("TLS_CERT_FILE"), os.Getenv("TLS_KEY_FILE"))
|
||||
if e != nil {
|
||||
return nil, fmt.Errorf("TLS identity unavailable")
|
||||
}
|
||||
return &c, nil
|
||||
}
|
||||
func ClientTLS() (*tls.Config, error) {
|
||||
p, e := roots()
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
return &tls.Config{MinVersion: tls.VersionTLS12, RootCAs: p, GetClientCertificate: func(*tls.CertificateRequestInfo) (*tls.Certificate, error) { return pair() }}, nil
|
||||
}
|
||||
|
||||
// VerifyConnection runs even on resumed handshakes. Current CA-validated chain,
|
||||
// exact DNS SAN and serial denylist all matter, not the certificate CN alone.
|
||||
func ServerTLS(identities []string) (*tls.Config, error) {
|
||||
p, e := roots()
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
c := &tls.Config{MinVersion: tls.VersionTLS12, ClientCAs: p, GetCertificate: func(*tls.ClientHelloInfo) (*tls.Certificate, error) { return pair() }, SessionTicketsDisabled: true}
|
||||
if len(identities) == 0 {
|
||||
return c, nil
|
||||
}
|
||||
c.ClientAuth = tls.RequireAndVerifyClientCert
|
||||
c.VerifyConnection = func(s tls.ConnectionState) error {
|
||||
if len(s.VerifiedChains) == 0 || len(s.PeerCertificates) == 0 {
|
||||
return fmt.Errorf("unverified peer")
|
||||
}
|
||||
leaf := s.PeerCertificates[0]
|
||||
now := time.Now()
|
||||
if now.Before(leaf.NotBefore) || !now.Before(leaf.NotAfter) {
|
||||
return fmt.Errorf("identity expired")
|
||||
}
|
||||
b, e := os.ReadFile(os.Getenv("TLS_REVOCATIONS_FILE"))
|
||||
if e != nil {
|
||||
return fmt.Errorf("revocation state unavailable")
|
||||
}
|
||||
var revoked []string
|
||||
if json.Unmarshal(b, &revoked) != nil {
|
||||
return fmt.Errorf("invalid revocation state")
|
||||
}
|
||||
for _, serial := range revoked {
|
||||
if strings.EqualFold(serial, leaf.SerialNumber.Text(16)) {
|
||||
return fmt.Errorf("identity revoked")
|
||||
}
|
||||
}
|
||||
for _, allowed := range identities {
|
||||
for _, name := range leaf.DNSNames {
|
||||
if name == allowed+".client.lab" {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("identity not allowed")
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
Reference in New Issue
Block a user