// A bounded TLS boundary; cleartext targets must bind only to loopback. package main import ( "bytes" "context" "crypto/tls" "crypto/x509" "encoding/binary" "encoding/json" "errors" "fmt" "io" "log" "net" "net/http" "net/http/httputil" "net/url" "os" "os/signal" "path/filepath" "strconv" "strings" "sync" "syscall" "time" ) type Boundary struct { Listen string `json:"listen"` Target string `json:"target"` Protocol string `json:"protocol"` // Identity -> allowed HTTP method/path prefixes; an empty list denies HTTP. Allow map[string][]string `json:"allow"` Public bool `json:"public"` } type Outbound struct { Listen string `json:"listen"` Target string `json:"target"` Identity string `json:"server_identity"` } type Config struct { Outbounds []Outbound `json:"outbounds"` ServeOnly bool `json:"serve_only"` ReloadPIDOne bool `json:"reload_pid_one"` Role string `json:"role"` DNS []string `json:"dns"` IP []string `json:"ip"` Bao string `json:"bao"` Trust string `json:"trust"` Bootstrap string `json:"bootstrap"` Identity string `json:"identity"` Revoked string `json:"revoked"` TTL string `json:"ttl"` KV bool `json:"kv"` Servers []Boundary `json:"servers"` } type Agent struct { c Config mu sync.Mutex token string tokenUntil time.Time } func event(name string) { log.Print("{\"event\":\"" + name + "\"}") } func trust(c Config) (*x509.CertPool, error) { raw, e := os.ReadFile(c.Trust) if e != nil { return nil, e } pool := x509.NewCertPool() if !pool.AppendCertsFromPEM(raw) { return nil, errors.New("invalid trust bundle") } return pool, nil } func material(c Config) (tls.Certificate, error) { base := filepath.Join(c.Identity, "current") if real, e := filepath.EvalSymlinks(base); e == nil { base = real } else { base = c.Bootstrap } return tls.LoadX509KeyPair(filepath.Join(base, "cert.pem"), filepath.Join(base, "key.pem")) } func revoked(c Config, cert *x509.Certificate) bool { raw, e := os.ReadFile(c.Revoked) if e != nil { return true } // missing policy fails closed var entries map[string]bool if json.Unmarshal(raw, &entries) != nil { return true } return entries[strings.ToLower(cert.SerialNumber.Text(16))] } func peer(c Config, state tls.ConnectionState, b Boundary) (string, error) { if b.Public { return "", nil } if len(state.VerifiedChains) == 0 || len(state.PeerCertificates) == 0 { return "", errors.New("client certificate required") } cert := state.PeerCertificates[0] roots, err := trust(c) if err != nil { return "", err } intermediates := x509.NewCertPool() for _, item := range state.PeerCertificates[1:] { intermediates.AddCert(item) } if _, err = cert.Verify(x509.VerifyOptions{Roots: roots, Intermediates: intermediates, KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}}); err != nil { return "", errors.New("current trust denies client") } if time.Now().Before(cert.NotBefore) || !time.Now().Before(cert.NotAfter) || revoked(c, cert) { return "", errors.New("client certificate unavailable") } for _, identity := range cert.URIs { if _, ok := b.Allow[identity.String()]; ok { return identity.String(), nil } } return "", errors.New("client identity denied") } func serverTLS(c Config, b Boundary) *tls.Config { return &tls.Config{MinVersion: tls.VersionTLS13, SessionTicketsDisabled: true, GetConfigForClient: func(_ *tls.ClientHelloInfo) (*tls.Config, error) { cert, e := material(c) if e != nil { return nil, e } roots, e := trust(c) if e != nil { return nil, e } conf := &tls.Config{MinVersion: tls.VersionTLS13, Certificates: []tls.Certificate{cert}, ClientCAs: roots, SessionTicketsDisabled: true} if !b.Public { conf.ClientAuth = tls.RequireAndVerifyClientCert conf.VerifyConnection = func(s tls.ConnectionState) error { _, e := peer(c, s, b); return e } } return conf, nil }} } func atomicFile(path string, raw []byte) error { temp := path + ".new" if e := os.WriteFile(temp, raw, 0600); e != nil { return e } return os.Rename(temp, path) } func (a *Agent) request(method, path string, body any, authenticated bool) (map[string]any, error) { cert, e := material(a.c) if e != nil { return nil, e } roots, e := trust(a.c) if e != nil { return nil, e } transport := &http.Transport{TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS13, RootCAs: roots, Certificates: []tls.Certificate{cert}}, DisableKeepAlives: true, ResponseHeaderTimeout: 4 * time.Second} defer transport.CloseIdleConnections() client := &http.Client{Transport: transport, Timeout: 5 * time.Second} var encoded []byte if body != nil { encoded, e = json.Marshal(body) if e != nil { return nil, e } } request, e := http.NewRequest(method, a.c.Bao+"/v1/"+path, bytes.NewReader(encoded)) if e != nil { return nil, e } request.Header.Set("Content-Type", "application/json") if authenticated { request.Header.Set("X-Vault-Token", a.token) } response, e := client.Do(request) if e != nil { return nil, errors.New("identity service unavailable") } defer response.Body.Close() if response.StatusCode >= 300 { return nil, fmt.Errorf("identity service status %d", response.StatusCode) } var data map[string]any e = json.NewDecoder(io.LimitReader(response.Body, 1024*1024)).Decode(&data) return data, e } func (a *Agent) refresh() error { a.mu.Lock() defer a.mu.Unlock() now := time.Now() if a.token != "" && time.Until(a.tokenUntil) < 95*time.Second { result, err := a.request("POST", "auth/token/renew-self", map[string]string{"increment": "120s"}, true) if err == nil { auth, ok := result["auth"].(map[string]any) if !ok { return errors.New("invalid renewal response") } ttl, ok := auth["lease_duration"].(float64) if !ok || ttl < 1 { return errors.New("invalid renewed lease") } a.tokenUntil = now.Add(time.Duration(ttl * float64(time.Second))) event("identity.token_renewed") } else { a.token = "" } } if a.token == "" { // The exact CN+URI constraints select the correct role. Omitting name // permits old/new CA roles to coexist safely during trust rollover. result, err := a.request("POST", "auth/cert/login", map[string]string{}, false) if err != nil { return err } auth, ok := result["auth"].(map[string]any) if !ok { return errors.New("invalid auth response") } a.token, ok = auth["client_token"].(string) if !ok { return errors.New("missing service token") } ttl, ok := auth["lease_duration"].(float64) if !ok || ttl < 1 { return errors.New("invalid service lease") } a.tokenUntil = now.Add(time.Duration(ttl * float64(time.Second))) event("identity.authenticated") } cert, e := material(a.c) _, currentErr := os.Stat(filepath.Join(a.c.Identity, "current")) _, initializedErr := os.Stat(filepath.Join(a.c.Identity, "agent.json")) renew := initializedErr != nil || currentErr != nil || e != nil || cert.Leaf == nil || time.Until(cert.Leaf.NotAfter) < 80*time.Second if renew { request := map[string]any{"common_name": a.c.Role, "alt_names": strings.Join(a.c.DNS, ","), "uri_sans": "spiffe://messenger/" + a.c.Role, "ttl": a.c.TTL} if len(a.c.IP) > 0 { request["ip_sans"] = strings.Join(a.c.IP, ",") } result, e := a.request("POST", "pki/issue/"+a.c.Role, request, true) if e != nil { return e } data, ok := result["data"].(map[string]any) if !ok { return errors.New("invalid PKI response") } crt, ok := data["certificate"].(string) if !ok { return errors.New("missing certificate") } key, ok := data["private_key"].(string) if !ok { return errors.New("missing private key") } if chain, ok := data["ca_chain"].([]any); ok { for _, item := range chain { crt += "\n" + item.(string) } } parsed, e := tls.X509KeyPair([]byte(crt), []byte(key)) if e != nil { return e } dir, e := os.MkdirTemp(a.c.Identity, "generation-") if e != nil { return e } if e = os.WriteFile(filepath.Join(dir, "cert.pem"), []byte(crt), 0600); e != nil { return e } if e = os.WriteFile(filepath.Join(dir, "key.pem"), []byte(key), 0600); e != nil { return e } if e = os.WriteFile(filepath.Join(dir, "bundle.pem"), []byte(crt+"\n"+key), 0600); e != nil { return e } link := filepath.Join(a.c.Identity, "next") os.Remove(link) if e = os.Symlink(filepath.Base(dir), link); e != nil { return e } if e = os.Rename(link, filepath.Join(a.c.Identity, "current")); e != nil { return e } // Retain only the current and immediately previous generations, bounding tmpfs. entries, _ := os.ReadDir(a.c.Identity) for _, entry := range entries { if entry.IsDir() && strings.HasPrefix(entry.Name(), "generation-") && entry.Name() != filepath.Base(dir) { info, _ := entry.Info() if info != nil && now.Sub(info.ModTime()) > 3*time.Minute { os.RemoveAll(filepath.Join(a.c.Identity, entry.Name())) } } } if parsed.Leaf == nil { return errors.New("unparsed certificate") } event("identity.certificate_issued") if a.c.ReloadPIDOne { if e = syscall.Kill(1, syscall.SIGUSR2); e != nil { return errors.New("certificate reload failed") } } } if a.c.KV { result, e := a.request("GET", "secret/data/"+a.c.Role, nil, true) if e != nil { return e } outer, ok := result["data"].(map[string]any) if !ok { return errors.New("invalid secret response") } values, ok := outer["data"].(map[string]any) if !ok { return errors.New("invalid secret values") } expiry := now.Add(60 * time.Second) if a.tokenUntil.Before(expiry) { expiry = a.tokenUntil } data, e := json.Marshal(map[string]any{"fetched_at": now.Unix(), "valid_until": expiry.Unix(), "values": values}) if e != nil { return e } if e = atomicFile(filepath.Join(a.c.Identity, "secrets.json"), data); e != nil { return e } } return atomicFile(filepath.Join(a.c.Identity, "agent.json"), []byte(`{"refreshed_at":`+strconv.FormatInt(now.Unix(), 10)+`}`)) } type boundedListener struct { net.Listener slots chan struct{} } type boundedConn struct { net.Conn once sync.Once release func() } func (c *boundedConn) Close() error { e := c.Conn.Close(); c.once.Do(c.release); return e } func (l *boundedListener) Accept() (net.Conn, error) { for { c, e := l.Listener.Accept() if e != nil { return nil, e } select { case l.slots <- struct{}{}: return &boundedConn{Conn: c, release: func() { <-l.slots }}, nil default: c.Close() } } } func loopbackProxy(c Config, target *url.URL) *httputil.ReverseProxy { proxy := httputil.NewSingleHostReverseProxy(target) if c.Role == "api" { // Deliver the application's early error before request-body teardown. // Otherwise a large upload can close the hop before buffered JSON drains. proxy.FlushInterval = -1 } director := proxy.Director proxy.Director = func(r *http.Request) { director(r) if c.Role == "api" && r.Body != nil && r.Body != http.NoBody { // Uvicorn sends 100 only when ASGI receives the body. Preserve an // early JSON 4xx without racing an unnecessary large body write. r.Header.Set("Expect", "100-continue") } } proxy.Transport = &http.Transport{MaxIdleConns: 32, MaxIdleConnsPerHost: 16, ResponseHeaderTimeout: 8 * time.Second, IdleConnTimeout: 30 * time.Second, ExpectContinueTimeout: time.Second} proxy.ErrorLog = log.New(io.Discard, "", 0) proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, e error) { w.Header().Set("Connection", "close") http.Error(w, "Protected service unavailable", 503) } return proxy } func runHTTP(c Config, b Boundary) error { target, e := url.Parse("http://" + b.Target) if e != nil { return e } proxy := loopbackProxy(c, target) handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Force a fresh handshake after each response: no indefinitely cached // certificate identity across rollover, expiry or serial revocation. w.Header().Set("Connection", "close") identity, e := peer(c, *r.TLS, b) if e != nil { w.Header().Set("Connection", "close") http.Error(w, "Client identity denied", 403) return } allowed := b.Public for _, rule := range b.Allow[identity] { parts := strings.SplitN(rule, " ", 2) if len(parts) == 2 && (parts[0] == "*" || parts[0] == r.Method) && strings.HasPrefix(r.URL.Path, parts[1]) { allowed = true } } if !allowed { if c.Role == "s3" { w.Header().Set("Content-Type", "application/xml") w.WriteHeader(http.StatusForbidden) io.WriteString(w, "AccessDeniedOperation deniedtls-boundarylocal") } else { http.Error(w, "Operation denied", http.StatusForbidden) } return } r.Header.Del("X-Forwarded-Client-Cert") r.Header.Del("X-TLS-Identity") proxy.ServeHTTP(w, r) }) listener, e := net.Listen("tcp", b.Listen) if e != nil { return e } listener = &boundedListener{Listener: listener, slots: make(chan struct{}, 128)} server := &http.Server{Handler: handler, TLSConfig: serverTLS(c, b), ReadHeaderTimeout: 5 * time.Second, IdleTimeout: 30 * time.Second, MaxHeaderBytes: 32768, ErrorLog: log.New(io.Discard, "", 0)} return server.Serve(tls.NewListener(listener, server.TLSConfig)) } // Native clients use a private loopback endpoint when their certificate // reload behavior cannot meet the short credential lifetime. Every network // connection is verified mTLS; configuration cannot publish this HTTP hop. func runOutbound(c Config, b Outbound) error { target, e := url.Parse(b.Target) if e != nil || target.Scheme != "https" || target.Hostname() == "" { return errors.New("outbound TLS target required") } host, _, e := net.SplitHostPort(b.Listen) if e != nil || host != "127.0.0.1" { return errors.New("outbound listener must be loopback") } proxy := httputil.NewSingleHostReverseProxy(target) proxy.Transport = &http.Transport{ DisableKeepAlives: true, MaxConnsPerHost: 32, ResponseHeaderTimeout: 8 * time.Second, DialTLSContext: func(ctx context.Context, network, address string) (net.Conn, error) { cert, e := material(c) if e != nil { return nil, e } roots, e := trust(c) if e != nil { return nil, e } config := &tls.Config{MinVersion: tls.VersionTLS13, RootCAs: roots, Certificates: []tls.Certificate{cert}, ServerName: target.Hostname(), VerifyConnection: func(state tls.ConnectionState) error { if len(state.VerifiedChains) == 0 || len(state.PeerCertificates) == 0 { return errors.New("unverified protected server") } leaf := state.PeerCertificates[0] if revoked(c, leaf) { return errors.New("protected server revoked") } if b.Identity != "" { found := false for _, identity := range leaf.URIs { if identity.String() == b.Identity { found = true } } if !found { return errors.New("protected server identity denied") } } return nil }} dialer := tls.Dialer{NetDialer: &net.Dialer{Timeout: 2 * time.Second}, Config: config} return dialer.DialContext(ctx, network, address) }, } proxy.ErrorLog = log.New(io.Discard, "", 0) proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, e error) { w.Header().Set("Connection", "close") http.Error(w, "Protected destination unavailable", 503) } listener, e := net.Listen("tcp", b.Listen) if e != nil { return e } listener = &boundedListener{Listener: listener, slots: make(chan struct{}, 64)} handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Connection", "close") proxy.ServeHTTP(w, r) }) server := &http.Server{Handler: handler, ReadHeaderTimeout: 5 * time.Second, IdleTimeout: 10 * time.Second, MaxHeaderBytes: 32768, ErrorLog: log.New(io.Discard, "", 0)} return server.Serve(listener) } func runTCP(c Config, b Boundary) error { listener, e := net.Listen("tcp", b.Listen) if e != nil { return e } slots := make(chan struct{}, 128) for { raw, e := listener.Accept() if e != nil { return e } select { case slots <- struct{}{}: default: raw.Close() continue } go func() { defer func() { <-slots }() defer raw.Close() raw.SetDeadline(time.Now().Add(5 * time.Second)) if b.Protocol == "postgres" { request := make([]byte, 8) if _, e := io.ReadFull(raw, request); e != nil { return } if binary.BigEndian.Uint32(request[:4]) != 8 || binary.BigEndian.Uint32(request[4:]) != 80877103 { return } if _, e := raw.Write([]byte{'S'}); e != nil { return } } client := tls.Server(raw, serverTLS(c, b)) if e := client.Handshake(); e != nil { return } target, e := net.DialTimeout("tcp", b.Target, 2*time.Second) if e != nil { return } defer target.Close() // Bound a previously authenticated connection even after expiry/revocation. deadline := time.Now().Add(45 * time.Second) state := client.ConnectionState() if len(state.PeerCertificates) > 0 && state.PeerCertificates[0].NotAfter.Before(deadline) { deadline = state.PeerCertificates[0].NotAfter } client.SetDeadline(deadline) target.SetDeadline(deadline) done := make(chan struct{}, 1) go func() { io.Copy(target, client); done <- struct{}{} }() io.Copy(client, target) client.Close() target.Close() <-done }() } } func main() { if len(os.Args) != 2 { event("gateway.invalid_configuration") os.Exit(2) } raw, e := os.ReadFile(os.Args[1]) if e != nil { event("gateway.invalid_configuration") os.Exit(2) } var c Config if json.Unmarshal(raw, &c) != nil || c.Role == "" { event("gateway.invalid_configuration") os.Exit(2) } if c.TTL == "" { c.TTL = "120s" } if e = os.MkdirAll(c.Identity, 0700); e != nil { event("gateway.identity_directory_unavailable") os.Exit(2) } for _, b := range c.Servers { host, _, err := net.SplitHostPort(b.Target) if err != nil || (host != "127.0.0.1" && host != "[::1]" && host != "::1") { event("gateway.nonlocal_target_denied") os.Exit(2) } } agent := &Agent{c: c} ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT) defer stop() // Bootstrap failures never start a cleartext fallback listener. if !c.ServeOnly { for { if e = agent.refresh(); e == nil { break } event("identity.refresh_failed") select { case <-ctx.Done(): return case <-time.After(3 * time.Second): } } go func() { ticker := time.NewTicker(15 * time.Second) defer ticker.Stop() for { select { case <-ctx.Done(): return case <-ticker.C: if agent.refresh() != nil { event("identity.refresh_failed") } } } }() } else { for { cert, err := material(c) if err == nil && cert.Leaf != nil && time.Now().Before(cert.Leaf.NotAfter) { break } select { case <-ctx.Done(): return case <-time.After(time.Second): } } } for _, boundary := range c.Servers { go func(b Boundary) { var e error if b.Protocol == "http" { e = runHTTP(c, b) } else { e = runTCP(c, b) } if e != nil { event("gateway.listener_failed") stop() } }(boundary) } for _, outbound := range c.Outbounds { go func(b Outbound) { if e := runOutbound(c, b); e != nil { event("gateway.outbound_failed") stop() } }(outbound) } event("gateway.ready") <-ctx.Done() }