We are going to design a system for secure transport using mTLS, SPIFFE identities, and policies.
The system will have the following components:
A Certificate Authority (CA) that issues certificates for services. We'll use SPIFFE CA.
Services that will communicate using mTLS, with their identities provided by SPIFFE.
A policy engine that enforces access control based on SPIFFE identities.
Steps:
Set up a SPIFFE CA (or use an existing one). We'll assume we have a CA that can issue SVIDs (SPIFFE Verifiable Identities) for our services.
Each service must have a SPIFFE identity. This identity is typically in the form of a SPIFFE ID (e.g., spiffe://example.org/service-name) and is encoded in an X.509 certificate (SVID) issued by the SPIFFE CA.
Services will use mTLS for authentication. This means both client and server present their SVIDs during the TLS handshake.
After the mTLS handshake, the server (or a sidecar/proxy) will extract the client's SPIFFE ID from the client's certificate.
The server will then check the client's SPIFFE ID against a set of policies to decide if the client is allowed to perform the requested action.
Policies are defined in terms of allowed SPIFFE IDs (or patterns) and the actions they are allowed to perform (e.g., which RPC methods, which HTTP paths, etc.).
Implementation Considerations:
We can use a library that supports mTLS and SPIFFE, such as the SPIFFE libraries (e.g., spiffe-go, spiffe-java) or use a sidecar like Envoy with SPIFFE integration.
For the policy engine, we can have a centralized policy server or distribute policies to the services. We'll assume a simple policy file per service for now.
Example Policy Format (per service):
The server service has a policy that says:
allow:
- spiffe://example.org/client-service-1 to call GET /resource1
- spiffe://example.org/client-service-2 to call POST /resource2
We can use a more expressive language (like Rego for Open Policy Agent) if needed.
The server must validate the client's certificate against the CA (which is part of mTLS) and then check the policy.
Steps in code (for a server):
a. Set up a TLS server that requires client certificates (mTLS) and uses a CA to verify the client's certificate.
b. In the TLS handshake, the client's certificate is verified by the TLS library (using the CA). We then extract the SPIFFE ID from the client's certificate. This is typically in the Subject Alternative Name (SAN) extension as a URI.
c. Once the connection is established, for each request (if we are doing HTTP, for example) we can get the client's SPIFFE ID from the TLS connection state.
d. We then look up the policy for the requested resource (HTTP path and method) and see if the client's SPIFFE ID is allowed.
e. If allowed, process the request; else, return 403.
For the client, we need to obtain an SVID (a certificate and key) from the SPIFFE CA and use it when connecting to the server.
We assume that the SPIFFE CA is set up and that services are registered and can get their SVIDs (via the SPIFFE Workload API or by fetching from a CA).
Example using Go (with spiffe-go library):
Server:
go
Client:
go
package main
import (
"crypto/tls"
"crypto/x509"
"io/ioutil"
"log"
"net/http"
"github.com/spiffe/go-spiffe/v2/spiffe"
)
func main() {
// Get the client's SVID (cert and key) - similarly from SPIFFE Workload API or file.
clientCert, clientKey, err := getClientSVID()
if err != nil {
log.Fatalf("failed to get client SVID: %v", err)
}
// Create a TLS config for the client
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{{Certificate: [][]byte{clientCert}, PrivateKey: clientKey}},
// The client should verify the server's certificate. We need the server's CA.
RootCAs: getTrustedCABundle(),
}
// Create an HTTP client with the TLS config
client := &http.Client{
Transport: &http.Transport{
TLSClientConfig: tlsConfig,
},
}
resp, err := client.Get("https://server:8443/resource1")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
log.Printf("Response: %s", body)
}
// getTrustedCABundle and getClientSVID are similar to the server but for the client.
Policy Management:
We can have a separate policy service that the server queries, or we can load policies from a file and watch for changes.
Example of a more advanced policy using OPA (Open Policy Agent):
We can define policies in Rego and have the server evaluate them using the OPA client.
func policyAllows(spiffeID, method, path string) bool {
// Prepare input for OPA
input := map[string]interface{}{
"client_id": spiffeID,
"method": method,
"path": path,
}
// Query OPA
// We assume OPA is running and we have a client for it.
result, err := opaClient.Evaluate("data.authz.allow", input)
if err != nil {
log.Printf("error evaluating policy: %v", err)
return false
}
// The result is a boolean. We assume the policy returns a single boolean.
if allow, ok := result.(bool); ok {
return allow
}
return false
}
Security Considerations:
The server must have the correct CA bundle to verify the client's certificate. In a SPIFFE setup, the CA bundle is typically provided by the SPIFFE CA.
The server must also have its own certificate and key, and the client must trust the server's CA.
The policy engine must be protected from unauthorized modifications.
The SPIFFE IDs must be unique and properly assigned to services.
The system must handle certificate rotation. In SPIFFE, the Workload API can provide updated SVIDs.
Scalability:
For a large number of services, we might want a centralized policy server that caches policies and does evaluation.
We might also want to use a sidecar pattern (like Envoy) that handles mTLS and policy enforcement, so that the application code is not burdened.
Using Envoy with SPIFFE:
Envoy can be configured to do mTLS and extract the SPIFFE ID from the client certificate. Then we can use Envoy's external authorization filter to check with a policy server.
Example Envoy configuration for mTLS:
yaml
static_resources:
listeners:
- name: listener_0
address:
socket_address: { address: 0.0.0.0, port_value: 8443 }
filter_chains:
- filters:
- name: envoy.filters.network.http_connection_manager
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
stat_prefix: ingress_http
route_config:
name: local_route
virtual_hosts:
- name: backend
domains: ["*"]
routes:
- match: { prefix: "/" }
route:
cluster: some_service
http_filters:
- name: envoy.filters.http.jwt_authn
# ... for JWT if needed
- name: envoy.filters.http.ext_authz
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthz
http_service:
server_uri:
uri: http://policy-server:9191
cluster: policy-server
timeout: 0.5s
authorization_request:
allowed_headers:
patterns:
- exact: "x-spiffe-id"
authorization_response:
allowed_upstream_headers:
patterns:
- exact: "x-spiffe-id"
- name: envoy.filters.http.router
transport_socket:
name: envoy.transport_sockets.tls
typed_config:
"@type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.DownstreamTlsContext
common_tls_context:
tls_certificates:
- certificate_chain:
filename: /etc/envoy/server-cert.pem
private_key:
filename: /etc/envoy/server-key.pem
validation_context:
trusted_ca:
filename: /etc/envoy/ca.pem
match_subject_alt_name_ports:
- port: 8443
# For SPIFFE, we might need to configure the validation context to allow SPIFFE IDs.
# However, Envoy does not natively understand SPIFFE IDs. We can use the `verify_subject_alt_name`
# to check the SPIFFE ID in the SAN, but we would have to configure the allowed SPIFFE IDs in the validation context?
# Actually, for mTLS, we typically just verify the certificate chain and then let the application (or ext_authz) check the SPIFFE ID.
# So we set `allow_renegotiation` and `verify_certificate_hash`? Not exactly.
clusters:
- name: some_service
connect_timeout: 0.25s
type: LOGICAL_DNS
lb_policy: ROUND_ROBIN
load_assignment:
cluster_name: some_service
endpoints:
- lb_endpoints:
- endpoint:
address:
socket_address:
address: some_service
port_value: 8080
In this setup, Envoy does the mTLS and then sends the client's SPIFFE ID (extracted from the certificate) to the external authorization server (policy server) in the x-spiffe-id header. The policy server then decides.
The policy server would then have the same kind of policy logic as above.
Summary:
We have several options:
Option 1: Application handles mTLS and policy (as in the first code example).
Option 2: Use a sidecar (Envoy) for mTLS and policy enforcement via external authorization.
Option 3: Use a service mesh (like Istio, Linkerd) that has built-in mTLS and policy enforcement (with SPIFFE support).
The choice depends on the complexity and requirements.
For a simple setup, Option 1 might be enough. For a large microservices architecture, Option 2 or 3 might be better.
In any case, the core components are:
SPIFFE CA for issuing identities.
mTLS for transport security and authentication.
Policy engine for authorization.
We must also consider how to distribute and rotate the SVIDs (using the SPIFFE Workload API is the standard way).
Let me know if you need more details on a specific part.
I'll help you design a comprehensive secure transport system using mTLS, SPIFFE identities, and policy-based authorization. This is a production-grade pattern for zero-trust architectures.
# Using SPIFFE CA (spire-server)
server:
spire_server:
data_dir: "/var/lib/spire"
trust_domain: "example.org"
ca:
cert_ttl: "86400h" # 10 years for CA
intermediate_ca:
cert_ttl: "2160h" # 90 days for intermediates
Graceful rotation with overlapping validity periods
Defense in Depth
mTLS at transport layer
Policy enforcement at application layer
Mutual authentication before authorization
Audit Trail
Log all SPIFFE ID exchanges
Record policy evaluation results
Immutable audit logs
Implementation Checklist
Deploy SPIFFE CA (SPIRE or other)
Configure Workload API endpoints
Issue initial SVIDs for all services
Configure mTLS in services/sidecars
Define initial authorization policies
Set up policy distribution mechanism
Implement monitoring for:
Certificate expirations
Policy violations
mTLS handshake failures
Test certificate rotation
Document SPIFFE ID allocation scheme
Set up automated testing for policy changes
Common Pitfalls to Avoid
Don't use long-lived certificates (>7 days)
Don't disable certificate validation in development
Don't grant overly broad SPIFFE ID selectors
Don't hardcode SPIFFE IDs in application code
Don't mix SPIFFE with traditional CA-based trust
This architecture provides:
Strong identity: SPIFFE IDs as universal service identity
Transport security: mTLS with automatic certificate rotation
Fine-grained authorization: Policy-based access control
Scalability: Works from 2 services to thousands
Multi-language: SPIFFE libraries available for all major languages
Would you like me to elaborate on any specific component or provide implementation details for a particular platform (Kubernetes, VMs, bare metal)?
package main
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"log"
"net/http"
"github.com/spiffe/go-spiffe/v2/spiffe"
"github.com/spiffe/go-spiffe/v2/workloadapi"
)
func main() {
// Set up the server's own SVID (server certificate and key) - we assume we have them from SPIFFE
serverCert, serverKey, err := getServerSVID()
if err != nil {
log.Fatalf("failed to get server SVID: %v", err)
}
// Create a TLS config for the server
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{{Certificate: [][]byte{serverCert}, PrivateKey: serverKey}},
ClientAuth: tls.RequireAndVerifyClientCert,
// We'll use the SPIFFE CA to verify client certificates. In practice, we might have a set of trusted CAs.
// For SPIFFE, we can use the SPIFFE CA bundle.
ClientCAs: getTrustedCABundle(), // returns an x509.CertPool with the SPIFFE CA and any others
VerifyPeerCertificate: func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
// We can do additional verification here if needed, but the standard verification is done by the TLS library.
return nil
},
}
// We'll use an HTTP server with the TLS config
server := &http.Server{
Addr: ":8443",
TLSConfig: tlsConfig,
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// Get the client's SPIFFE ID from the TLS connection state
if r.TLS == nil || len(r.TLS.PeerCertificates) == 0 {
http.Error(w, "no client certificate", http.StatusForbidden)
return
}
// The client's certificate is r.TLS.PeerCertificates[0] (the leaf)
clientCert := r.TLS.PeerCertificates[0]
// Extract the SPIFFE ID from the certificate's SAN
spiffeID, err := spiffe.IDFromCert(clientCert)
if err != nil {
http.Error(w, "invalid client certificate", http.StatusForbidden)
return
}
// Now check the policy for this request (path and method)
if !policyAllows(spiffeID.String(), r.Method, r.URL.Path) {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
fmt.Fprintf(w, "Hello, %s!", spiffeID.String())
})
log.Fatal(server.ListenAndServeTLS("", ""))
}
func policyAllows(spiffeID, method, path string) bool {
// This is a simple example. In reality, we would load policies from a config or a policy server.
// Let's say we have a policy that only allows spiffe://example.org/client-service-1 to do GET /resource1
if spiffeID == "spiffe://example.org/client-service-1" && method == "GET" && path == "/resource1" {
return true
}
return false
}
func getTrustedCABundle() *x509.CertPool {
// Load the SPIFFE CA bundle (from file or from the workload API)
// For simplicity, we assume we have a file with the CA certificate.
// In a real setup, we might use the SPIFFE Workload API to get the CA bundle.
pool := x509.NewCertPool()
caCert, err := os.ReadFile("spiffe-ca.pem")
if err != nil {
log.Fatal(err)
}
pool.AppendCertsFromPEM(caCert)
return pool
}
func getServerSVID() ([]byte, crypto.Signer, error) {
// In a real setup, we would get the server's SVID from the SPIFFE Workload API or from a file.
// For example, using the workload API:
// client, err := workloadapi.NewX509Source(context.Background(), workloadapi.WithAddr("unix:///tmp/agent.sock"))
// if err != nil { ... }
// defer client.Close()
// id, cert, key, err := client.FetchX509SVIDForPath(context.Background(), "spiffe://example.org/server")
// ...
// For simplicity, we read from files.
cert, err := tls.LoadX509KeyPair("server-cert.pem", "server-key.pem")
if err != nil {
return nil, nil, err
}
// The cert.Certificate is a [][]byte, we take the first (leaf) certificate.
leaf := cert.Leaf
// We need the raw certificate and the private key as a crypto.Signer.
// The private key is already a crypto.Signer in cert.PrivateKey.
return leaf.Raw, cert.PrivateKey, nil
}