HUB
Sign inSign up

sebcvm/mtls-sidecar

By sebcvm

•Updated about 1 year ago

A minimal Rust-based sidecar proxy for enforcing inbound mTLS in Kubernetes pods

Image
0

1.5K

sebcvm/mtls-sidecar repository overview

⁠mtls-sidecar

Tests Docker Build Docker Pulls Docker Image Size

A minimal Rust-based sidecar proxy for enforcing inbound mTLS in Kubernetes pods. It terminates mTLS connections, verifies client certificates against trusted CAs, and forwards validated HTTP requests to an upstream application in the same pod. The sidecar monitors mounted certificate files for updates (e.g., from Vault Secrets Operator) and reloads TLS configuration without restarts.

⁠Source

See https://github.com/value-medical/mtls-sidecar⁠ for source code and examples.

⁠Purpose

This component provides a lightweight layer for securing HTTP services with mutual TLS, integrating seamlessly with Kubernetes Secret mounts. It focuses on inbound termination and proxying, avoiding broader features like routing or outbound connections.

⁠Key Features

  • Enforces mTLS with client certificate verification against a CA bundle.
  • Hot-reloads TLS configuration on file changes.
  • Simple reverse proxy to a single upstream endpoint.
  • Optional injection of client certificate details into upstream headers.
  • Dedicated monitoring port for health probes (including server certificate expiry validation) and optional Prometheus metrics.
  • Supports both kubernetes.io/tls and VSO Opaque Secret formats via file auto-detection.
  • Supports HTTP/1.1 and HTTP/2 proxying, enabling mTLS termination for gRPC services.
  • Low overhead: <17MB RAM, <15.0% CPU at 1k req/s (avg 15.3MB RAM, peak 16.4MB RAM, avg 11.6% CPU, peak 14.1% CPU)
  • Graceful shutdown.
  • Structured JSON logging for requests, reloads, and errors.

⁠Non-Features

  • No multi-port or advanced routing support.
  • No outbound mTLS or service discovery.
  • No rate limiting, caching, or additional authentication.
  • Minimal logging and metrics for simplicity (upstream is expected to provide these).

⁠Configuration

Configuration is via environment variables only, with sensible defaults for common setups. All vars are optional strings unless noted.

VariableDefault ValueDescription
TLS_LISTEN_PORT8443TCP port for inbound mTLS listener.
UPSTREAM_URLhttp://localhost:8080Full URL for the proxy target.
UPSTREAM_READINESS_URLhttp://localhost:8080/readyURL for upstream readiness check.
CERT_DIR/etc/certsDirectory containing server cert/key files.
CA_DIR/etc/caDirectory containing the CA bundle file.
INJECT_CLIENT_HEADERSfalseIf true, inject X-Client-TLS-Info header.
MONITOR_PORT8081Port for health probes and metrics.
ENABLE_METRICSfalseIf true, expose Prometheus /metrics on the monitor port.

⁠Deployment Assumptions

  • Deployed as a Kubernetes sidecar container alongside the main application.
  • Secrets are mounted as read-only volumes to CERT_DIR and CA_DIR.
  • Upstream is HTTP-only, accessible via localhost.
  • Runs as non-root user (UID 1000).
  • Supports HTTP/1.1 and HTTP/2; TLS 1.2+ with secure ciphers.
  • Certificates are PEM-encoded PKCS#1, PKCS#8, or SEC1 formats.

⁠Secret Handling

Mount entire Secrets to directories; the sidecar auto-detects files:

  • Server cert: Prefers tls.crt + tls.key in CERT_DIR; falls back to certificate + private_key.
  • CA bundle: Prefers ca-bundle.pem or ca.crt in CA_DIR; merges ca.crt or issuing_ca if found in CERT_DIR.
  • Ignores unused keys (e.g., _raw, expiration).

On load/reload failure, logs an error and retains the previous configuration.

⁠Client Certificate Header Injection

When INJECT_CLIENT_HEADERS is set to true, the sidecar extracts key details from the validated client certificate during mTLS termination and injects them into the forwarded HTTP request via a single custom header: X-Client-TLS-Info. This provides the upstream application with lightweight, pre-parsed x509 information (e.g., subject, SANs, hash) without requiring it to handle TLS or certificate parsing. All extraction occurs in the sidecar using Rust's rustls and x509-parser crates, ensuring containment of TLS concerns.

The header value is a base64-encoded JSON object (for single-hop scenarios, which is the default in this minimal sidecar). This format avoids parsing complexities like quoting or delimiters in traditional schemes, relying only on universal base64 decoding followed by JSON parsing. The payload is compact (~200-500 bytes pre-encoding) and includes only authentication-relevant fields.

⁠Header Format
  • Header Name: X-Client-TLS-Info (case-insensitive; value is opaque to intermediaries).
  • Value: Base64 (standard RFC 4648) of a compact JSON string. No line breaks or extra whitespace.
  • Structure: JSON object with string keys and values/arrays as shown below. Fields are derived directly from the client certificate's leaf (end-entity) after validation.
⁠Extracted Fields
FieldTypeDescriptionExample Value
subjectstringFull distinguished name (DN) as RFC 2253 string, normalized by sidecar."CN=client.example.com,O=Acme"
uri_sansarrayURI subject alternative names (SANs), e.g., for SPIFFE identities.["spiffe://cluster/ns/default/sa/client"]
dns_sansarrayDNS subject alternative names (SANs).["client.example.com"]
hashstringSHA-256 hex digest of the certificate DER, prefixed with "sha256:"."sha256:abc123def456..."
not_beforestringIssuance timestamp in ISO 8601 format."2025-01-01T00:00:00Z"
not_afterstringExpiry timestamp in ISO 8601 format."2026-01-01T00:00:00Z"
serialstringCertificate serial number as hex string."0x1234567890abcdef"
⁠Upstream Examples

The format is designed for easy integration in common web service languages. Upstream code should validate the header presence and decode/parse safely (e.g., handle missing/invalid values gracefully). For minimal upstream examples, refer to the examples/ directory.

⁠Security Considerations
  • Trust Model: Upstream should treat the header as trusted (sidecar validates the cert), verifying hash against a known trust store if required.
  • Chain of Custody: Suitable for single-hop scenarios; avoid forwarding to untrusted parties.
  • Spoofing Prevention: The sidecar strips this header on inbound requests to prevent client tampering.

This feature unburdens upstream services while exposing just enough cert info for auth/audit.

⁠License

MIT License. See LICENSE file.

Tag summary

Content type

Image

Digest

sha256:5d1df52df…

Size

14.7 MB

Last updated

about 1 year ago

docker pull sebcvm/mtls-sidecar