The Envoy security model relies on strict validation, zero-trust network boundaries, strongly-typed configuration encapsulation, and fail-closed security filtering to protect downstream clients and upstream services. Developers must assume all external inputs, dynamic extensions, and administrative interfaces are untrusted and enforce rigorous canonicalization, access controls, and explicit cryptographic verification. State-mutating administrative operations, authorization bypasses, and protocol parsing misconfigurations must explicitly fail closed.
Essential implementation rules
Enforce Strict CORS, RBAC, and Administrative Access Controls
Use strict string matchers for allowed origins with filter_enabled active at 100% in production. Configure HTTP RBAC filters using HttpAttributesCelMatchInput and ensure admin listeners are bound strictly to local loopback addresses (127.0.0.1 or ::1) or protected Unix sockets with path normalization enabled.
Secure Administrative State-Modifying Handlers and Endpoints
Explicitly set mutates_server_state = true and enforce HTTP POST semantics for custom administrative handlers or endpoints that alter server state. Populate target path matchers via AdminImpl::addAllowlistedPath and invoke shutdownAdmin() early during server termination.
Validate OAuth2 Authentication, Secrets, and Header Options
Prevent conflicting header flags by selecting only one Authorization header handling option per OAuth2 configuration. Provide valid token secrets when auth_type is not TLS_CLIENT_AUTH, enforce positive assertion lifetimes for PRIVATE_KEY_JWT, and use AES-256-GCM token encryption (oauth2_use_gcm_encryption).
Ensure JWT Audience, Issuer, and Extraction Security
Explicitly configure allowed audiences and issuer fields in every JwtProvider configuration to prevent confused deputy attacks. Declare explicit extraction locations such as from_headers to disable insecure query parameter extraction.
Enforce Upstream and Downstream TLS, SAN, and Certificate Validation
Configure match_typed_subject_alt_names alongside trusted CAs in CertificateValidationContext and UpstreamTlsContext to prevent man-in-the-middle attacks. Ensure certificate fingerprint formats adhere strictly to 64-character hex strings for hashes and base64 digests for SPKI.
Isolate Redis Transactions and Apply Connection Pool Authentication
Isolate dedicated Redis transaction clients, bind transaction keys to hash slots, and explicitly call Transaction::close() upon completion. Pass authentication credentials during connection pool instantiation and ensure transaction states route exclusively to primary cluster nodes.
Verify Signatures, Cryptographic Status, and Dynamic Module Integrity
Always evaluate result.ok() from verifySignature() before trusting signed data payloads. Load dynamic modules and certificate validator shared libraries exclusively from trusted local filesystem paths (module.local.filename), ensuring full ABI compatibility.
Validate Protobuf Deserialization and Percent-Encode AWS STS Parameters
Use TestUtility::validate with recurse_into_any = true to enforce strict message integrity during protobuf deserialization, catching ProtoValidationException and EnvoyException. Percent-encode all parameters using Envoy::Http::Utility::PercentEncoding::encode when constructing AWS STS AssumeRole query strings.
Sanitize HTTP Request Paths, Parameters, and Preserve Pseudo-Headers
Enable ignore_path_parameters_in_path_matching and strip_fragment_from_path to prevent path-based security bypasses and URI fragment pollution. Custom HTTP filters running prior to the router must preserve mandatory HTTP pseudo-headers such as :method.
Harden Protocol Options, Header Rewrites, and Kafka Filtering
Set headers_with_underscores_action to REJECT_REQUEST in header validators to prevent header spoofing. When rewriting or mutating headers, use set(key, value) or configure append: false to prevent duplicate header injection. Restrict Kafka downstream clients using explicit api_keys_allowed rules.
Secure Client IP Trust, Forwarded Headers, and Mitigate SSRF
Evaluate downstream source IPs using envoy.matching.inputs.source_ip rather than unvalidated HTTP headers. Sanitize incoming client certificate headers via SANITIZE or SANITIZE_SET, and enforce resolved address filtering (resolved_address_filter) in dynamic forward proxy caches to block outbound traffic to private IPs and metadata endpoints.
Prevent Resource Exhaustion with Bounded Retries and Buffer Limits
Define absolute global request timeouts, per-try timeouts, and bounded num_retries with retry budget tracking. Set explicit request_body_buffer_limit on virtual hosts and per_connection_buffer_limit_bytes on listeners to prevent memory exhaustion.
Harden Runtime Environments and Automate Secret Discovery Service Rotation
Build Envoy using default BoringSSL or FIPS-compliant BoringSSL/AWS-LC rather than OpenSSL. Run containers with a read-only root filesystem (readOnlyRootFilesystem: true) and non-root users. Configure dynamic TLS contexts and tokens using Secret Discovery Service (SDS) and watched directories with atomic renames.
Enforce Fail-Closed Security Control Integrity
Configure deny_at_disable with a default value of true on external authorization filters (ext_authz) to ensure requests fail closed when disabled. Ensure extension factory creation methods validate configurations and abort initialization via EnvoyException on failure.
envoy: All Security Cards
Approximately 12,816 tokens
On this card
Category: access control
Configure strict CORS origin matching and enforcement
Use when
Configuring route-level or virtual host-level CORS policies in Envoy to manage cross-origin access and protect backend resources from unauthorized third-party requests.
Secure rules
Rule 1: Use strict string matchers for allowed origins and ensure filtering is fully enabled in production environments.
When instantiating CorsPolicyImplBase or configuring Router::CorsPolicy, ensure that allow_origin_string_match rules use explicit exact matchers instead of permissive patterns. Keep filter_enabled active at 100% in production so that CORS checks are fully enforced, and ensure that forwardNotMatchingPreflights() is set to false to block unverified cross-origin preflights from reaching upstream clusters.
Enforce Role-Based Access Control and Authorization Policies
Use when
Configuring Envoy HTTP RBAC filters, destination port ranges, and authorization rules to restrict access and enforce access control policies.
Secure rules
Rule 1: Enforce fine-grained access control using RBAC policies and CEL conditions
Configure Envoy’s HTTP RBAC filter using HttpAttributesCelMatchInput and explicit matchers to enforce access control rules and deny unauthorized requests.
Rule 2: Ensure RBAC port ranges specify valid boundaries
When configuring RBAC policies with port ranges, set valid boundaries where the start is strictly less than the end and within valid port limits to prevent initialization failures.
envoy::config::rbac::v3::Permission permission;auto* range = permission.mutable_destination_port_range();range->set_start(80);range->set_end(443);
Secure Administrative API Endpoints and Restrict Network Exposure
Use when
Configuring, extending, or exposing Envoy administrative interface endpoints, handlers, and listeners.
Secure rules
Rule 1: Explicitly mark state-modifying custom administrative handlers with mutates_server_state set to true.
When registering custom administrative handlers using AdminImpl::addHandler or AdminImpl::addStreamingHandler, set the mutates_server_state parameter to true for any endpoint that modifies server state or configuration. This ensures the admin HTTP connection manager enforces that state-altering administrative operations require HTTP POST requests rather than HTTP GET.
Rule 2: Restrict administrative HTTP listener addresses strictly to loopback interfaces or protected sockets.
When starting the administrative HTTP listener via startHttpListener, ensure the network address passed in is bound strictly to a loopback IP (such as 127.0.0.1 or ::1) or a protected Unix domain socket rather than a wildcard or public interface, preventing remote unauthenticated access.
auto address = Network::Utility::parseInternetAddressAndPortNoThrow("127.0.0.1:9901");admin->startHttpListener(access_logs, address, socket_options);
Rule 3: Restrict administrative endpoint accessibility using path allowlists.
Restrict administrative endpoint accessibility by populating target path matchers with AdminImpl::addAllowlistedPath and checking candidate paths via acceptTargetPath to prevent unauthorized exposure of configuration dumps, sensitive secrets, or profiling endpoints.
auto matcher = std::make_unique<Matchers::ExactStringMatcher>("/stats");admin_impl->addAllowlistedPath(std::move(matcher));if (admin_impl->acceptTargetPath(request_path)) { // Process request}
Secure Envoy Management and Health Endpoints against Unauthorized Access and Mutation
Use when
Configuring, exposing, or extending Envoy management, administrative, and health-checking interfaces such as /config_dump, /healthcheck/fail, or custom admin handlers.
Secure rules
Rule 1: Bind administrative listeners strictly to trusted local loopback interfaces or dedicated management networks and keep path normalization enabled.
Ensure Envoy administration interfaces are never exposed to public or untrusted network interfaces to prevent internal network reconnaissance via /config_dump and sensitive configuration disclosures. Keep shouldNormalizePath() and shouldMergeSlashes() enabled on admin connection managers.
Rule 2: Enforce HTTP POST method and set mutates_server_state to true for administrative endpoints that alter server state.
State-mutating administrative endpoints such as /healthcheck/fail, /healthcheck/ok, or custom mutating handlers registered via addHandler() must explicitly require HTTP POST semantics and set mutates_server_state = true to protect against accidental triggers or cross-site execution.
Rule 3: Order non-terminal health check filters before terminal routing filters and revoke admin access early during shutdown.
Position non-terminal management and health check filters before terminal filters in the http_filters configuration array. Additionally, invoke shutdownAdmin() early during the server shutdown sequence to immediately revoke administrative access before releasing server resources.
Avoid Conflicting Authorization Header Flags in OAuth2 Configuration
Use when
Configuring the OAuth2 HTTP filter in Envoy where multiple request header manipulation flags could be mistakenly enabled simultaneously.
Secure rules
Rule 1: Select only one Authorization header handling flag per OAuth2 configuration to prevent conflicting management of request headers.
Do not combine conflicting HTTP Authorization header manipulation flags in the OAuth2 filter. Enabling more than one of forward_bearer_token, preserve_authorization_header, or forward_id_token is disallowed because they attempt to manage the same request header and cause configuration rejection.
Configure Complete Token Secrets and Client Authentication for OAuth2 Filters
Use when
Setting up Envoy OAuth2 authentication filters and client credentials for token exchange.
Secure rules
Rule 1: Provide valid token secrets and assertion lifetimes for non-TLS client authentication modes.
Ensure a valid token_secret is configured when auth_type is not TLS_CLIENT_AUTH, and explicitly configure a positive assertion_lifetime when using PRIVATE_KEY_JWT.
Rule 2: Configure mTLS upstream transport sockets for token endpoints using TLS client authentication.
Configure the cluster referenced by the token_endpoint with an UpstreamTlsContext containing client certificates and private keys when auth_type is set to TLS_CLIENT_AUTH.
Choose TLS_CLIENT_AUTH or PRIVATE_KEY_JWT for token endpoint communication to avoid transmitting static client secrets in request bodies or headers.
auth_type: TLS_CLIENT_AUTH
Configure Upstream and Downstream Authentication Credentials for Proxies
Use when
Deploying protocol filters and credential injectors that require authentication credentials.
Secure rules
Rule 1: Enforce authentication controls for Redis proxy filters.
Configure downstream authentication passwords and upstream cluster credentials using RedisProtocolOptions to prevent unauthorized command execution against backend clusters.
Rule 2: Configure overwrite behavior explicitly in credential injector filters.
Set the overwrite parameter in the credential_injector filter explicitly to control whether downstream client credentials take precedence or are overridden by injected tokens.
Rule 3: Configure GCP authentication filter metadata on upstream clusters.
Specify the GCP Authn Audience typed filter metadata with a valid service target URL on upstream clusters to ensure identity tokens are correctly requested.
Enforce Audience and Issuer Validation in JWT Configuration
Use when
Configuring the JWT authentication filter to verify identity tokens and prevent confused deputy attacks.
Secure rules
Rule 1: Explicitly configure allowed audiences in every JwtProvider configuration.
Specify the allowed audiences using the audiences field in the JwtProvider configuration to ensure Envoy rejects tokens issued for different applications.
Rule 2: Explicitly specify the issuer field for all JwtProvider configurations.
Always set the issuer field in the JwtProvider configuration to prevent Envoy from treating the provider as permissive and accepting tokens from untrusted issuers.
Declare extraction locations such as from_headers explicitly in the JwtProvider configuration to disable insecure query parameter extraction and prevent credential logging.
Enforce Strict Certificate Validation and Revocation Controls
Use when
Use when configuring downstream and upstream TLS validation contexts, SNI matching, key usage requirements, and revocation checking in Envoy.
Secure rules
Rule 1: Enforce subject alternative name matchers and trusted CAs for TLS server verification.
Configure match_typed_subject_alt_names alongside trusted_ca within CertificateValidationContext to ensure complete server identity verification and prevent man-in-the-middle acceptance of unauthorized certificates.
Rule 2: Configure OCSP stapling and policy enforcement for downstream TLS certificates.
Supply valid OCSP response staple files via ocsp_staple in DownstreamTlsContext and configure ocsp_staple_policy to MUST_STAPLE to ensure clients verify certificate revocation status without fallback risks.
Configure automated PKI tools to issue certificates with standard keyUsage extensions. In Envoy version 1.39.0, keyUsage extension enforcement is unconditionally enabled and the legacy enforce_rsa_key_usage option is deprecated and ignored.
Establish Upstream Destination Trust with Trusted CAs, SANs, and Certificate Revocation
Use when
Configuring Envoy upstream TLS contexts or dynamic Secret Discovery Service (SDS) connections to connect to upstream destination servers securely.
Secure rules
Rule 1: Configure UpstreamTlsContext validation contexts with trusted CA certificates, CRL paths, and explicit SAN matching or auto-validation.
When establishing secure connections with upstream destinations, define a validation_context in UpstreamTlsContext containing both trusted_ca and crl configurations. Additionally, enforce Subject Alternative Name verification using match_typed_subject_alt_names, auto_sni_san_validation, or auto_san_validation to prevent upstream impersonation and Man-in-the-Middle attacks.
When executing Redis database transactions using Envoy’s Redis Transaction and Client interfaces, ensure dedicated upstream transaction connections are isolated per session and explicitly terminated via Transaction::close() upon transaction completion or network failure. Upstream transaction clients created with is_transaction_client set to true must not be returned to shared client pools while a transaction block is active, and transaction keys (key_) must strictly bind transaction commands to the corresponding cluster hash slot.
Rule 2: Authenticate Redis connection pool sessions using database credentials
When instantiating Redis database connection pools, always ensure connection creation passes authentication credentials, including both username and password, to the client factory. Propagating database credentials ensures all pooled upstream connections are properly authenticated before accepting and executing proxy requests.
Rule 3: Enforce read policies to control database query routing
Configure explicit database read policies such as MASTER or REPLICA on Redis connection pool settings. The connection pool relies on these read policies within the load balancer context to safely separate master node operations from read-only replica operations.
auto settings = Common::Redis::Client::createConnPoolSettings( 20, true, true, max_unknown_conns, envoy::extensions::filters::network::redis_proxy::v3::RedisProxy::ConnPoolSettings::MASTER, redis_cx_rate_limit_per_sec);
Rule 4: Enforce Primary Host Selection for Active Redis Transactions
When routing commands through the Redis proxy connection pool, ensure that active database transactions strictly route to primary cluster nodes. The connection pool dynamically evaluates transaction state (transaction.active_) during request creation, switching read policy to ReadPolicy::Primary for both key-based and shard-based requests to preserve database transaction isolation and consistency boundaries.
Rule 5: Maintain Redis Transaction Context Across Upstream Connections
When forwarding Redis database commands through a proxy command splitter, active transaction context (Common::Redis::Client::Transaction) must be preserved across upstream client pool requests and explicitly updated before initiating primary or mirrored requests. Developers must ensure that current_client_idx_ is explicitly reset to index 0 for the primary cluster client and incremented for secondary mirror connections so that transaction state and command execution boundaries remain isolated and bound to the correct connection.
Restrict Envoy Dynamic Modules to Fully Trusted Code
Use when
When loading dynamic modules into Envoy that run in-process and share its full privilege level and memory space.
Secure rules
Rule 1: Only load dynamic modules from fully trusted sources and verify ABI compatibility.
Because dynamic modules run in-process with Envoy without security sandboxing, ensure that you only load binary modules compiled from trusted, code-reviewed source repositories and adhere strictly to memory ownership rules in abi.h.
// Verify ABI compatibility and ensure pointers remain valid for their specified lifetime.typedef const char* envoy_dynamic_module_type_abi_version_module_ptr;// Module-owned buffers must remain allocated and unmodified for the lifetime expected// by the specific event hook or callback.
Category: configuration source integrity
Use Trusted Local File Paths for Dynamic Module Certificate Validators
Use when
Configuring dynamic module TLS certificate validators or shared library paths where configuration source integrity must be maintained.
Secure rules
Rule 1: Specify dynamic module source libraries using trusted local filesystem paths or registered module names.
Ensure that dynamic module shared library paths reference local trusted files using module.local.filename or dynamic_module_config.name, as remote fetching of dynamic module shared libraries is unsupported and can lead to context creation errors or insecure module loading.
Use Authenticated Encryption and Secure Cryptographic Verification in Envoy
Use when
When configuring cryptographic operations, token encryption in filters, and signature verification routines.
Secure rules
Rule 1: Enable AES-256-GCM encryption for OAuth2 cookie token protection
When configuring Envoy’s OAuth2 filter, ensure sensitive tokens stored in cookies are encrypted by setting disable_token_encryption to false and opting in to AES-256-GCM encryption mode via the oauth2_use_gcm_encryption feature flag to replace legacy CBC mode.
Rule 2: Always verify status results from signature verification operations
Envoy’s verifySignature() method returns a status object that evaluates to false on result.ok() when given unsupported hash algorithms, uninitialized key objects, altered data payloads, or corrupted signatures. Callers must evaluate result.ok() before trusting signed data.
auto result = Envoy::Common::Crypto::UtilitySingleton::get().verifySignature("sha256", *key_object, signature_bytes, data_bytes);if (!result.ok()) { ENVOY_LOG(warn, "Signature verification failed: {}", result.message()); return;}
Category: csrf
Configure SameSite Attributes and Expiration for OAuth2 State Cookies
Use when
Configuring OAuth2 authentication filters and cookies in Envoy to protect against cross-site request forgery and authorization state fixation attacks.
Secure rules
Rule 1: Configure explicit SameSite restrictions and short expiration windows for OAuth2 cookies and CSRF state tokens.
Set explicit same_site attributes such as STRICT for bearer, HMAC, and ID token cookies, and define short expiration windows for CSRF state tokens and PKCE code verifiers using csrf_token_expires_in and code_verifier_token_expires_in.
Enforce strict Protobuf message validation during deserialization
Use when
When processing dynamic xDS configurations or local protobuf structures to prevent accepting unvalidated or smuggled fields.
Secure rules
Rule 1: Execute strict downcasting and validation with recursion enabled when processing untrusted protobuf structures.
Use TestUtility::validate with recurse_into_any set to true to enforce strict message integrity. Ensure exceptions such as ProtoValidationException and EnvoyException are caught and handled to prevent structural failures and rule validation bypasses.
Percent-encode parameters in AWS STS AssumeRole query strings
Use when
When constructing query strings for AWS STS AssumeRole requests from user-configurable parameters.
Secure rules
Rule 1: Always percent-encode parameter values when building AWS STS AssumeRole request paths.
Prevent parameter injection and query string structure manipulation by applying Envoy::Http::Utility::PercentEncoding::encode to all parameters such as role_arn, role_session_name, and external_id before embedding them into query strings.
Preserve mandatory HTTP pseudo-headers in custom filters
Use when
Developing or modifying custom HTTP filters placed prior to the Envoy router filter.
Secure rules
Rule 1: Ensure custom filter logic preserves all mandatory HTTP pseudo-headers before passing requests upstream.
Envoy’s router strictly validates required request headers such as :method using Http::HeaderUtility::checkRequiredRequestHeaders. Custom HTTP filters running before the router must not remove or drop these mandatory pseudo-headers, as doing so triggers an immediate local 503 Service Unavailable response.
Ensure that digests adhere strictly to expected encodings when configuring certificate pinning via verify_certificate_hash or public key pinning via verify_certificate_spki. verify_certificate_hash requires a valid 64-character hex-encoded SHA-256 string, while verify_certificate_spki requires a valid base64-encoded SHA-256 digest.
Rule 2: Enable re-verification on session resumption for peer-verifying upstream TLS connections.
Ensure that SSL_CTX_set_reverify_on_resume is enabled during TLS context initialization for peer-verifying connections to re-execute peer certificate validation when resuming a TLS session.
if (verify_mode != SSL_VERIFY_NONE) { SSL_CTX_set_custom_verify(ctx, verify_mode, customVerifyCallback); SSL_CTX_set_reverify_on_resume(ctx, /*reverify_on_resume_enabled=*/1);}
Category: input interpretation safety
Enforce Strict Canonical Host and Authority Parsing
Use when
When configuring host matching, authority validation, or TLS SNI parameters for untrusted network endpoints.
Secure rules
Rule 1: Specify IPv6 allowed domains without brackets for OAuth2 host matching
Configure allowed_domains using domain names, wildcards, or bracketless IPv6 strings such as ::1 because Envoy’s authority parser normalizes IPv6 hostnames by stripping surrounding brackets.
Rule 2: Avoid null bytes in SNI configuration strings
Sanitize and validate string inputs to ensure SNI hostnames do not contain embedded null bytes (\000) before assigning them to transport context settings.
Sanitize and Canonicalize Request Paths and Parameters to Prevent Bypass
Use when
When configuring routing rules, HTTP header validation, or query parameter parsing where untrusted input must be safely interpreted and normalized.
Secure rules
Rule 1: Sanitize path matrix parameters during route matching
Enable ignore_path_parameters_in_path_matching in routing configurations to ensure matrix parameters like ;param=value are removed from the path prior to evaluation, preventing path-based security bypasses.
Rule 2: Decode query parameters safely without unescaping control characters
Use parseAndDecodeQueryString or urlDecodeQueryParameter to ensure percent-encoded sequences are appropriately handled and normalized before making security decisions or inspecting query keys and values.
auto params = Envoy::Http::Utility::QueryParamsMulti::parseAndDecodeQueryString(request_path);auto val = params.getFirstValue("name");if (val.has_value()) { // Perform validation on decoded value}
Rule 3: Strip URI fragments from request path headers
Configure strip_fragment_from_path in HeaderValidatorConfig to ensure URI fragments are safely removed from request paths before route matching and upstream delivery.
Enforce Kafka API Key and Topic Filtering for Messaging Security
Use when
Configuring downstream messaging filters and upstream routing rules for Kafka broker and mesh proxies.
Secure rules
Rule 1: Restrict downstream Kafka client operational capabilities by configuring explicit request filtering via api_keys_allowed.
Prefer an explicit allowlist using api_keys_allowed in the kafka_broker filter to strictly bound acceptable message operation types, preventing unauthorized message consumption or administrative actions.
Rule 2: Define explicit forwarding rules for Kafka mesh topic prefixes to designated upstream clusters.
Configure deterministic forwarding_rules matching all authorized topic prefixes and mapping them to designated upstream clusters to avoid connection termination and unintentional message delivery across boundaries.
Enforce Strict HTTP/2 and QUIC Protocol Options and Stream Limits
Use when
When configuring HTTP/2, HTTP/3, and QUIC options to maintain protocol framing, prevent sequence corruption, and restrict unsupported features.
Secure rules
Rule 1: Validate HTTP/2 protocol options to prevent conflicting settings and unsupported features.
Process and initialize Http2ProtocolOptions using initializeAndValidateOptions to catch parameter collisions, avoid duplicate settings, and ensure server push or raw ENABLE_CONNECT_PROTOCOL parameters are not improperly enabled.
Rule 2: Restrict QPACK settings and configure HTTP/3 protocol options for QUIC clients.
Explicitly set Http3ProtocolOptions parameters such as disable_qpack on Envoy QUIC client connections to disable Huffman encoding, disable cookie crumbling, and zero out the QPACK maximum dynamic table capacity.
Prevent Observability Data and Internal Telemetry Exposure
Use when
Configuring Envoy routers, metric service sinks, and upstream host logging for edge or external-facing listeners.
Secure rules
Rule 1: Suppress internal performance and proxy state headers on untrusted downstream responses.
Set suppress_envoy_headers to true on the router filter (envoy.filters.http.router) for edge listeners to prevent leaking latency telemetry such as x-envoy-upstream-service-time and system health flags like x-envoy-overloaded to downstream clients.
Rule 2: Restrict and sanitize per-endpoint metric generation and host logging.
Ensure per-endpoint stats outputs and host logs generated via HostUtility are restricted to internal telemetry systems and filtered using stats tag extractors or prefix matchers to prevent exposing internal IP addresses, ports, and health failure flags.
HostUtility::forEachHostMetric(cm, [](Stats::PrimitiveCounterSnapshot&& counter) { // Process counter securely or filter sensitive endpoint IP metric names}, [](Stats::PrimitiveGaugeSnapshot&& gauge) { // Filter out host IP-identifying metrics from public endpoints});
Safely Rewrite, Sanitize, and Normalize HTTP Headers
Use when
Use when modifying, rewriting, sanitizing, or transforming HTTP request and response headers in Envoy dynamic modules, external processors, or custom routing filters.
Secure rules
Rule 1: Use set instead of add when modifying HTTP headers in dynamic modules to completely overwrite values and prevent duplicate header injection.
When modifying HTTP headers using the HeaderMap interface in Envoy dynamic modules, invoke set(key, value) rather than add(key, value) when replacing or sanitizing untrusted header inputs. The add method appends duplicate header entries rather than overwriting existing values, which can lead to header interpretation ambiguity or downstream security bypasses.
Rule 2: Explicitly disable append mode when configuring external processor header mutations to ensure untrusted header values are overwritten.
When rewriting request or response headers via Envoy external processing (ext_proc), configure HeaderMutationset_headers with append set to false when replacing untrusted downstream or upstream headers. Disabling header value appending prevents header duplication and ensures untrusted header values are overwritten rather than concatenated.
Rule 3: Normalize bridge header keys when copying them into Envoy header maps
When converting an envoy_headers collection into an Envoy response header map, construct each copied key as a LowerCaseString. Copy both keys and values into the destination map before calling release_envoy_headers, because the source collection may be released after its contents have been copied.
ResponseHeaderMapPtr transformed_headers = ResponseHeaderMapImpl::create();for (envoy_map_size_t i = 0; i < headers.length; i++) { transformed_headers->addCopy( LowerCaseString(Bridge::Utility::copyToString(headers.entries[i].key)), Bridge::Utility::copyToString(headers.entries[i].value));}release_envoy_headers(headers);
Validate and Harden HTTP Headers and Protocol Framing
Use when
When configuring HTTP connection managers, header validators, upgrade handling, and upstream protocol options in Envoy to prevent request smuggling, header spoofing, and protocol desynchronization.
Secure rules
Rule 1: Configure the Envoy Default Header Validator to reject incoming requests with underscores in header names.
Set headers_with_underscores_action to REJECT_REQUEST within the header validator configuration to prevent downstream clients from bypassing security controls or spoofing headers due to backend normalization.
Rule 2: Sanitize and remove unauthorized upgrade tokens using utility helpers.
Use Envoy HTTP utility helpers such as Utility::removeUpgrade with defined string matchers to strip unauthorized upgrade tokens systematically rather than performing manual string manipulation on connection and upgrade headers.
Rule 3: Enforce scheme header transformations for unencrypted mesh connections.
Configure scheme_header_transformation in HttpConnectionManager when receiving HTTP/2 or HTTP/3 traffic over unencrypted mesh networks to overwrite untrusted incoming :scheme pseudo-headers and prevent upstream services from assuming false client security.
Enforce Strict Internal Redirect Policies and Scheme Restrictions
Use when
Configuring Envoy HTTP route internal redirect policies where upstream services may trigger internal redirects.
Secure rules
Rule 1: Disable cross-scheme internal redirects and restrict header copying.
Set allow_cross_scheme_redirect to false in internal redirect policies to prevent silent secure-to-cleartext connection downgrades. Ensure system headers, pseudo-headers, and Host headers are not copied during redirects.
Filter Resolved DNS Addresses in Dynamic Forward Proxies to Mitigate SSRF
Use when
Configuring dynamic forward proxies handling untrusted requests or domains in Envoy v1.39.0 to prevent unauthorized requests to internal networks or cloud metadata APIs.
Secure rules
Rule 1: Enforce resolved address filtering via DnsCacheConfig.resolved_address_filter to block outbound connections to restricted networks, private IP ranges, localhost, link-local addresses, and cloud metadata services.
Configure resolved_address_filter within the DNS cache configuration shared between the dynamic forward proxy filter and cluster to reject unsafe IP destinations. Combine this address filtering mechanism with network firewalls and egress RBAC rules, and monitor the dns_cache.<dns_cache_name>.dns_address_filter_out metric to audit and alert on blocked IP resolution attempts.
Secure Forwarded Headers and Client IP Trust in Envoy Proxies
Use when
Configuring network boundaries, HTTP connection managers, proxy protocol listener filters, or client certificate header forwarding to ensure untrusted downstreams cannot spoof client IPs or identity.
Secure rules
Rule 1: Sanitize incoming client certificate headers from untrusted downstreams before forwarding requests upstream.
Ensure x-forwarded-client-cert headers from untrusted downstreams are sanitized by keeping forward_client_cert_details unset or configuring it to SANITIZE or SANITIZE_SET to prevent backend services from relying on spoofed identity details.
Rule 2: Restrict plain connections and enforce strict validation for PROXY protocol and client IP attributes.
Keep allow_requests_without_proxy_protocol disabled (false) on network boundaries where all incoming traffic must pass through a proxy appending PROXY protocol headers, and ensure connection sockets enforce strict unicast address validation matching declared IP versions.
Rule 3: Explicitly configure trusted internal IP boundaries and original IP detection mechanisms.
Define strict CIDR ranges in internal_address_config and configure use_remote_address or xff_num_trusted_hops to prevent external clients from forging X-Forwarded-For headers and bypassing IP-based access controls or GeoIP filters.
Use envoy.matching.inputs.source_ip (SourceIPInput) instead of unvalidated HTTP headers when enforcing IP-based access rules to evaluate the actual downstream connection source IP and prevent header-spoofing attacks.
Configure Bounded Retries, Timeouts, and Circuit Breakers to Prevent Upstream Exhaustion
Use when
Configuring Envoy routes, virtual hosts, and upstream clusters to handle network retries, timeouts, and request hedging safely.
Secure rules
Rule 1: Enforce explicit global and per-try request timeouts along with bounded retry limits to prevent resource exhaustion and request amplification.
Always define absolute upper bounds using global request timeouts and restrict individual attempts with per-try timeouts. Configure bounded num_retries and use retry budgets or circuit breaker thresholds to prevent retry storms.
Rule 2: Enable timeout budget statistics and track remaining retry circuit breaker metrics to monitor upstream latency and prevent cascading failures.
Set track_timeout_budgets to true in cluster configuration and enable track_remaining on circuit breakers to continuously monitor retry limits and prevent unconstrained traffic spikes.
Configure explicit request body and connection buffer limits to prevent memory exhaustion
Use when
Configuring virtual hosts, connection limits, or listeners in Envoy to handle untrusted incoming client connections and HTTP payloads.
Secure rules
Rule 1: Set explicit request body buffer limits on virtual hosts to bound memory consumption.
Configure request_body_buffer_limit explicitly in the virtual host proto configuration to prevent attacker-controlled requests with large HTTP payloads from exhausting proxy memory resources.
Rule 2: Configure explicit per-connection buffer limits on Envoy listeners.
Specify per_connection_buffer_limit_bytes explicitly in the listener configuration to constrain maximum memory allocated per connection and prevent out-of-memory denial-of-service crashes.
Building and compiling Envoy for production deployment where security policy guarantees and security vulnerability response processes are required.
Secure rules
Rule 1: Build Envoy with default BoringSSL or FIPS-compliant BoringSSL/AWS-LC configurations rather than OpenSSL.
Avoid building Envoy with --config=openssl for production deployments unless strictly required. OpenSSL builds rely on dynamically loaded libraries, disable HTTP/3 (QUIC) support, and are explicitly excluded from the Envoy security policy.
bazel build //source/exe:envoy-static# Or for FIPS compliance:bazel build --config=boringssl-fips //source/exe:envoy-static
Harden Envoy Container Deployments and Runtime Environments
Use when
Configuring container orchestrators, runtime security contexts, and deployment parameters for production Envoy instances.
Secure rules
Rule 1: Run Envoy containers with a read-only root filesystem to prevent runtime modification.
Set readOnlyRootFilesystem: true within the container security context for container orchestrators such as Kubernetes.
Restrict Envoy Privileged Ports and File System Permissions
Use when
Configuring Envoy container execution users, port mappings, and file system paths to restrict access to privileged resources.
Secure rules
Rule 1: Run Envoy as a non-user container and map host privileged ports to unprivileged container ports.
Keep Envoy running as a non-root user such as the default UID/GID 101. Avoid running as root with ENVOY_UID=0, and configure Envoy to listen on unprivileged ports greater than 1024 inside the container while relying on runtime port mapping to forward host privileged ports.
$ docker run -d --name envoy -p 80:8000 envoyproxy/envoy:v1.39.0
Rule 2: Validate file paths to restrict unauthorized access to privileged system directories.
Perform path integrity checks using Filesystem::Instance::illegalPath before attempting filesystem operations to block unauthorized reads from privileged or restricted host directories such as /proc, /sys, and /dev.
Filesystem::InstanceImpl file_system;std::string target_path = "/proc/kallsyms";if (file_system.illegalPath(target_path)) { ENVOY_LOG(warn, "Blocked access to restricted host path: {}", target_path); return;}auto result = file_system.fileReadToEnd(target_path);
Category: secret handling
Automate TLS Certificate Rotation and Secret Discovery
Use when
Use when configuring automated TLS certificate, validation context, and session ticket key lifecycles using dynamic Secret Discovery Service (SDS) providers or filesystem-backed watched directories in Envoy.
Secure rules
Rule 1: Configure Envoy TLS contexts to load certificates dynamically via SDS configurations and watched directories.
Use tls_certificate_sds_secret_configs or validation_context_sds_secret_config in CommonTlsContext to fetch dynamic certificates and CA trust bundles. When using filesystem-backed secrets, specify watched_directory on the parent path to watch for atomic symlink replacements and trigger clean reloads without process restarts.
Rule 2: Secure the communication channel between Envoy proxy and SDS servers.
Protect dynamic certificate channels by using local Unix Domain Sockets or remote TLS connections authenticated with mutual TLS or strict transport security credentials.
Rule 3: Monitor SDS rotation failure metrics and register update callbacks for dynamic updates.
Subscribe to dynamic secret updates using update callbacks such as addUpdateCallback and monitor counter metrics like key_rotation_failed to catch validation errors and prevent silent failures during automated certificate rotations.
auto handle = sds_api->addUpdateCallback([this]() { return secret_callbacks_.onAddOrUpdateSecret();});
Load Dynamic Secrets Securely Using Secret Discovery Service
Use when
Configuring dynamic TLS certificates, session ticket keys, validation contexts, or generic authentication secrets in Envoy using the Secret Discovery Service (SDS).
Secure rules
Rule 1: Use Secret Discovery Service (SDS) generic and TLS secret resources instead of hardcoding sensitive credentials in static configurations.
Configure token_secret and hmac_secret references or transport socket TLS contexts using SDS and file-based or gRPC configuration sources to avoid embedding cleartext credentials in source code and configuration files.
Rule 2: Configure atomic directory-level renames or watched directories for file-backed SDS secrets.
When using file-backed DataSources or SDS secrets, configure watched_directory on the secret proto and perform atomic symlink updates on the host to prevent partial reads and secret loading failures.
Rule 3: Assign unique static secret names within Envoy’s SecretManager.
Ensure that every static secret registered in Envoy’s static resource configuration has a distinct name field to prevent static secret initialization failures and service disruption.
Secure Envoy Administrative Interfaces and Configuration Dumps
Use when
Configuring Envoy bootstrap parameters, setting up administrative endpoints, or managing diagnostic interfaces.
Secure rules
Rule 1: Disable administrative server sockets in bootstrap configurations when administrative endpoints are not required.
Explicitly clear the admin stanza in your envoy::config::bootstrap::v3::Bootstrap configuration to prevent opening administrative ports and exposing internal cluster state.
envoy::config::bootstrap::v3::Bootstrap bootstrap;// Explicitly remove admin server configuration to prevent opening administrative portsbootstrap.clear_admin();
Rule 2: Use strongly-typed configuration messages instead of untyped structs to ensure secrets are redacted in admin config dumps.
Define extension configurations using typed_config with google.protobuf.Any rather than legacy untyped google.protobuf.Struct fields. Strongly-typed protobuf configs allow Envoy to automatically redact secret fields such as private_key and passwords when inspected via /config_dump.
Use dynamic providers such as assume_role_with_web_identity_provider or IAM Roles Anywhere configuration rather than embedding long-lived static keys in Envoy configuration files.
Rule 2: Redact sensitive tokens and signatures from log outputs.
Ensure that sensitive values such as temporary access keys, security tokens, and signature strings are sanitized or overwritten with masks before emitting debug log messages.
Enforce Fail-Closed Behavior and Security Control Integrity Across Filters and Authentication
Use when
Configuring Envoy security filters, authorization hooks, and authentication mechanisms where failing open or bypassing checks could compromise security control integrity.
Secure rules
Rule 1: Configure deny_at_disable on external authorization filters to ensure requests are denied when the filter is disabled.
When setting up the ext_authz filter, configure deny_at_disable with a default value of true to ensure that dynamic runtime overrides or metadata matchers cannot cause requests to bypass authorization checks.
Rule 2: Prevent OAuth2 pass-through matcher evaluation on forward ID token headers.
Ensure that pass_through_matcher rules do not target the header configured in forward_id_token. Envoy rejects configurations where pass-through matchers evaluate the forwarded ID token header to prevent external attackers from bypassing authentication.
Validate extension dependencies and enforce fail-closed factory instantiation
Use when
Developing dynamic extensions using Envoy’s factory registry for dependency injection, such as implementing custom resource detectors.
Secure rules
Rule 1: Ensure extension factory creation methods validate configurations and return non-null pointers or trigger clean initialization failure.
When implementing custom resource detector factories via ResourceDetectorFactory, explicitly validate incoming configurations and ensure components return a valid instance or nullptr to allow Envoy to safely abort initialization via EnvoyException and maintain telemetry context integrity.
class MyDetectorFactory : public ResourceDetectorFactory {public: ResourceDetectorPtr createResourceDetector(const Protobuf::Message& config, Server::Configuration::ServerFactoryContext& context) override { if (!validateConfig(config)) { return nullptr; } return std::make_unique<MyDetector>(); }};
Configure strict CORS origin matching and enforcement
Approximately 1,539 tokens
On this card
Use when
Configuring route-level or virtual host-level CORS policies in Envoy to manage cross-origin access and protect backend resources from unauthorized third-party requests.
Secure rules
Rule 1: Use strict string matchers for allowed origins and ensure filtering is fully enabled in production environments.
When instantiating CorsPolicyImplBase or configuring Router::CorsPolicy, ensure that allow_origin_string_match rules use explicit exact matchers instead of permissive patterns. Keep filter_enabled active at 100% in production so that CORS checks are fully enforced, and ensure that forwardNotMatchingPreflights() is set to false to block unverified cross-origin preflights from reaching upstream clusters.
Enforce Role-Based Access Control and Authorization Policies
Use when
Configuring Envoy HTTP RBAC filters, destination port ranges, and authorization rules to restrict access and enforce access control policies.
Secure rules
Rule 1: Enforce fine-grained access control using RBAC policies and CEL conditions
Configure Envoy’s HTTP RBAC filter using HttpAttributesCelMatchInput and explicit matchers to enforce access control rules and deny unauthorized requests.
Rule 2: Ensure RBAC port ranges specify valid boundaries
When configuring RBAC policies with port ranges, set valid boundaries where the start is strictly less than the end and within valid port limits to prevent initialization failures.
envoy::config::rbac::v3::Permission permission;auto* range = permission.mutable_destination_port_range();range->set_start(80);range->set_end(443);
Secure Administrative API Endpoints and Restrict Network Exposure
Use when
Configuring, extending, or exposing Envoy administrative interface endpoints, handlers, and listeners.
Secure rules
Rule 1: Explicitly mark state-modifying custom administrative handlers with mutates_server_state set to true.
When registering custom administrative handlers using AdminImpl::addHandler or AdminImpl::addStreamingHandler, set the mutates_server_state parameter to true for any endpoint that modifies server state or configuration. This ensures the admin HTTP connection manager enforces that state-altering administrative operations require HTTP POST requests rather than HTTP GET.
Rule 2: Restrict administrative HTTP listener addresses strictly to loopback interfaces or protected sockets.
When starting the administrative HTTP listener via startHttpListener, ensure the network address passed in is bound strictly to a loopback IP (such as 127.0.0.1 or ::1) or a protected Unix domain socket rather than a wildcard or public interface, preventing remote unauthenticated access.
auto address = Network::Utility::parseInternetAddressAndPortNoThrow("127.0.0.1:9901");admin->startHttpListener(access_logs, address, socket_options);
Rule 3: Restrict administrative endpoint accessibility using path allowlists.
Restrict administrative endpoint accessibility by populating target path matchers with AdminImpl::addAllowlistedPath and checking candidate paths via acceptTargetPath to prevent unauthorized exposure of configuration dumps, sensitive secrets, or profiling endpoints.
auto matcher = std::make_unique<Matchers::ExactStringMatcher>("/stats");admin_impl->addAllowlistedPath(std::move(matcher));if (admin_impl->acceptTargetPath(request_path)) { // Process request}
Secure Envoy Management and Health Endpoints against Unauthorized Access and Mutation
Use when
Configuring, exposing, or extending Envoy management, administrative, and health-checking interfaces such as /config_dump, /healthcheck/fail, or custom admin handlers.
Secure rules
Rule 1: Bind administrative listeners strictly to trusted local loopback interfaces or dedicated management networks and keep path normalization enabled.
Ensure Envoy administration interfaces are never exposed to public or untrusted network interfaces to prevent internal network reconnaissance via /config_dump and sensitive configuration disclosures. Keep shouldNormalizePath() and shouldMergeSlashes() enabled on admin connection managers.
Rule 2: Enforce HTTP POST method and set mutates_server_state to true for administrative endpoints that alter server state.
State-mutating administrative endpoints such as /healthcheck/fail, /healthcheck/ok, or custom mutating handlers registered via addHandler() must explicitly require HTTP POST semantics and set mutates_server_state = true to protect against accidental triggers or cross-site execution.
Rule 3: Order non-terminal health check filters before terminal routing filters and revoke admin access early during shutdown.
Position non-terminal management and health check filters before terminal filters in the http_filters configuration array. Additionally, invoke shutdownAdmin() early during the server shutdown sequence to immediately revoke administrative access before releasing server resources.
Avoid Conflicting Authorization Header Flags in OAuth2 Configuration
Approximately 210 tokens
Use when
Configuring the OAuth2 HTTP filter in Envoy where multiple request header manipulation flags could be mistakenly enabled simultaneously.
Secure rules
Rule 1: Select only one Authorization header handling flag per OAuth2 configuration to prevent conflicting management of request headers.
Do not combine conflicting HTTP Authorization header manipulation flags in the OAuth2 filter. Enabling more than one of forward_bearer_token, preserve_authorization_header, or forward_id_token is disallowed because they attempt to manage the same request header and cause configuration rejection.
Configure Complete Token Secrets and Client Authentication for OAuth2 Filters
Approximately 2,705 tokens
On this card
Use when
Setting up Envoy OAuth2 authentication filters and client credentials for token exchange.
Secure rules
Rule 1: Provide valid token secrets and assertion lifetimes for non-TLS client authentication modes.
Ensure a valid token_secret is configured when auth_type is not TLS_CLIENT_AUTH, and explicitly configure a positive assertion_lifetime when using PRIVATE_KEY_JWT.
Rule 2: Configure mTLS upstream transport sockets for token endpoints using TLS client authentication.
Configure the cluster referenced by the token_endpoint with an UpstreamTlsContext containing client certificates and private keys when auth_type is set to TLS_CLIENT_AUTH.
Choose TLS_CLIENT_AUTH or PRIVATE_KEY_JWT for token endpoint communication to avoid transmitting static client secrets in request bodies or headers.
auth_type: TLS_CLIENT_AUTH
Configure Upstream and Downstream Authentication Credentials for Proxies
Use when
Deploying protocol filters and credential injectors that require authentication credentials.
Secure rules
Rule 1: Enforce authentication controls for Redis proxy filters.
Configure downstream authentication passwords and upstream cluster credentials using RedisProtocolOptions to prevent unauthorized command execution against backend clusters.
Rule 2: Configure overwrite behavior explicitly in credential injector filters.
Set the overwrite parameter in the credential_injector filter explicitly to control whether downstream client credentials take precedence or are overridden by injected tokens.
Rule 3: Configure GCP authentication filter metadata on upstream clusters.
Specify the GCP Authn Audience typed filter metadata with a valid service target URL on upstream clusters to ensure identity tokens are correctly requested.
Enforce Audience and Issuer Validation in JWT Configuration
Use when
Configuring the JWT authentication filter to verify identity tokens and prevent confused deputy attacks.
Secure rules
Rule 1: Explicitly configure allowed audiences in every JwtProvider configuration.
Specify the allowed audiences using the audiences field in the JwtProvider configuration to ensure Envoy rejects tokens issued for different applications.
Rule 2: Explicitly specify the issuer field for all JwtProvider configurations.
Always set the issuer field in the JwtProvider configuration to prevent Envoy from treating the provider as permissive and accepting tokens from untrusted issuers.
Declare extraction locations such as from_headers explicitly in the JwtProvider configuration to disable insecure query parameter extraction and prevent credential logging.
Enforce Strict Certificate Validation and Revocation Controls
Use when
Use when configuring downstream and upstream TLS validation contexts, SNI matching, key usage requirements, and revocation checking in Envoy.
Secure rules
Rule 1: Enforce subject alternative name matchers and trusted CAs for TLS server verification.
Configure match_typed_subject_alt_names alongside trusted_ca within CertificateValidationContext to ensure complete server identity verification and prevent man-in-the-middle acceptance of unauthorized certificates.
Rule 2: Configure OCSP stapling and policy enforcement for downstream TLS certificates.
Supply valid OCSP response staple files via ocsp_staple in DownstreamTlsContext and configure ocsp_staple_policy to MUST_STAPLE to ensure clients verify certificate revocation status without fallback risks.
Configure automated PKI tools to issue certificates with standard keyUsage extensions. In Envoy version 1.39.0, keyUsage extension enforcement is unconditionally enabled and the legacy enforce_rsa_key_usage option is deprecated and ignored.
Establish Upstream Destination Trust with Trusted CAs, SANs, and Certificate Revocation
Use when
Configuring Envoy upstream TLS contexts or dynamic Secret Discovery Service (SDS) connections to connect to upstream destination servers securely.
Secure rules
Rule 1: Configure UpstreamTlsContext validation contexts with trusted CA certificates, CRL paths, and explicit SAN matching or auto-validation.
When establishing secure connections with upstream destinations, define a validation_context in UpstreamTlsContext containing both trusted_ca and crl configurations. Additionally, enforce Subject Alternative Name verification using match_typed_subject_alt_names, auto_sni_san_validation, or auto_san_validation to prevent upstream impersonation and Man-in-the-Middle attacks.
When executing Redis database transactions using Envoy’s Redis Transaction and Client interfaces, ensure dedicated upstream transaction connections are isolated per session and explicitly terminated via Transaction::close() upon transaction completion or network failure. Upstream transaction clients created with is_transaction_client set to true must not be returned to shared client pools while a transaction block is active, and transaction keys (key_) must strictly bind transaction commands to the corresponding cluster hash slot.
Rule 2: Authenticate Redis connection pool sessions using database credentials
When instantiating Redis database connection pools, always ensure connection creation passes authentication credentials, including both username and password, to the client factory. Propagating database credentials ensures all pooled upstream connections are properly authenticated before accepting and executing proxy requests.
Rule 3: Enforce read policies to control database query routing
Configure explicit database read policies such as MASTER or REPLICA on Redis connection pool settings. The connection pool relies on these read policies within the load balancer context to safely separate master node operations from read-only replica operations.
auto settings = Common::Redis::Client::createConnPoolSettings( 20, true, true, max_unknown_conns, envoy::extensions::filters::network::redis_proxy::v3::RedisProxy::ConnPoolSettings::MASTER, redis_cx_rate_limit_per_sec);
Rule 4: Enforce Primary Host Selection for Active Redis Transactions
When routing commands through the Redis proxy connection pool, ensure that active database transactions strictly route to primary cluster nodes. The connection pool dynamically evaluates transaction state (transaction.active_) during request creation, switching read policy to ReadPolicy::Primary for both key-based and shard-based requests to preserve database transaction isolation and consistency boundaries.
Rule 5: Maintain Redis Transaction Context Across Upstream Connections
When forwarding Redis database commands through a proxy command splitter, active transaction context (Common::Redis::Client::Transaction) must be preserved across upstream client pool requests and explicitly updated before initiating primary or mirrored requests. Developers must ensure that current_client_idx_ is explicitly reset to index 0 for the primary cluster client and incremented for secondary mirror connections so that transaction state and command execution boundaries remain isolated and bound to the correct connection.
Restrict Envoy Dynamic Modules to Fully Trusted Code
Approximately 190 tokens
Use when
When loading dynamic modules into Envoy that run in-process and share its full privilege level and memory space.
Secure rules
Rule 1: Only load dynamic modules from fully trusted sources and verify ABI compatibility.
Because dynamic modules run in-process with Envoy without security sandboxing, ensure that you only load binary modules compiled from trusted, code-reviewed source repositories and adhere strictly to memory ownership rules in abi.h.
// Verify ABI compatibility and ensure pointers remain valid for their specified lifetime.typedef const char* envoy_dynamic_module_type_abi_version_module_ptr;// Module-owned buffers must remain allocated and unmodified for the lifetime expected// by the specific event hook or callback.
Use Trusted Local File Paths for Dynamic Module Certificate Validators
Approximately 207 tokens
Use when
Configuring dynamic module TLS certificate validators or shared library paths where configuration source integrity must be maintained.
Secure rules
Rule 1: Specify dynamic module source libraries using trusted local filesystem paths or registered module names.
Ensure that dynamic module shared library paths reference local trusted files using module.local.filename or dynamic_module_config.name, as remote fetching of dynamic module shared libraries is unsupported and can lead to context creation errors or insecure module loading.
Use Authenticated Encryption and Secure Cryptographic Verification in Envoy
Approximately 363 tokens
Use when
When configuring cryptographic operations, token encryption in filters, and signature verification routines.
Secure rules
Rule 1: Enable AES-256-GCM encryption for OAuth2 cookie token protection
When configuring Envoy’s OAuth2 filter, ensure sensitive tokens stored in cookies are encrypted by setting disable_token_encryption to false and opting in to AES-256-GCM encryption mode via the oauth2_use_gcm_encryption feature flag to replace legacy CBC mode.
Rule 2: Always verify status results from signature verification operations
Envoy’s verifySignature() method returns a status object that evaluates to false on result.ok() when given unsupported hash algorithms, uninitialized key objects, altered data payloads, or corrupted signatures. Callers must evaluate result.ok() before trusting signed data.
auto result = Envoy::Common::Crypto::UtilitySingleton::get().verifySignature("sha256", *key_object, signature_bytes, data_bytes);if (!result.ok()) { ENVOY_LOG(warn, "Signature verification failed: {}", result.message()); return;}
Configure SameSite Attributes and Expiration for OAuth2 State Cookies
Approximately 231 tokens
Use when
Configuring OAuth2 authentication filters and cookies in Envoy to protect against cross-site request forgery and authorization state fixation attacks.
Secure rules
Rule 1: Configure explicit SameSite restrictions and short expiration windows for OAuth2 cookies and CSRF state tokens.
Set explicit same_site attributes such as STRICT for bearer, HMAC, and ID token cookies, and define short expiration windows for CSRF state tokens and PKCE code verifiers using csrf_token_expires_in and code_verifier_token_expires_in.
Enforce strict Protobuf message validation during deserialization
Approximately 211 tokens
Use when
When processing dynamic xDS configurations or local protobuf structures to prevent accepting unvalidated or smuggled fields.
Secure rules
Rule 1: Execute strict downcasting and validation with recursion enabled when processing untrusted protobuf structures.
Use TestUtility::validate with recurse_into_any set to true to enforce strict message integrity. Ensure exceptions such as ProtoValidationException and EnvoyException are caught and handled to prevent structural failures and rule validation bypasses.
Percent-encode parameters in AWS STS AssumeRole query strings
Approximately 247 tokens
Use when
When constructing query strings for AWS STS AssumeRole requests from user-configurable parameters.
Secure rules
Rule 1: Always percent-encode parameter values when building AWS STS AssumeRole request paths.
Prevent parameter injection and query string structure manipulation by applying Envoy::Http::Utility::PercentEncoding::encode to all parameters such as role_arn, role_session_name, and external_id before embedding them into query strings.
Preserve mandatory HTTP pseudo-headers in custom filters
Approximately 551 tokens
Use when
Developing or modifying custom HTTP filters placed prior to the Envoy router filter.
Secure rules
Rule 1: Ensure custom filter logic preserves all mandatory HTTP pseudo-headers before passing requests upstream.
Envoy’s router strictly validates required request headers such as :method using Http::HeaderUtility::checkRequiredRequestHeaders. Custom HTTP filters running before the router must not remove or drop these mandatory pseudo-headers, as doing so triggers an immediate local 503 Service Unavailable response.
Ensure that digests adhere strictly to expected encodings when configuring certificate pinning via verify_certificate_hash or public key pinning via verify_certificate_spki. verify_certificate_hash requires a valid 64-character hex-encoded SHA-256 string, while verify_certificate_spki requires a valid base64-encoded SHA-256 digest.
Rule 2: Enable re-verification on session resumption for peer-verifying upstream TLS connections.
Ensure that SSL_CTX_set_reverify_on_resume is enabled during TLS context initialization for peer-verifying connections to re-execute peer certificate validation when resuming a TLS session.
if (verify_mode != SSL_VERIFY_NONE) { SSL_CTX_set_custom_verify(ctx, verify_mode, customVerifyCallback); SSL_CTX_set_reverify_on_resume(ctx, /*reverify_on_resume_enabled=*/1);}
Enforce Strict Canonical Host and Authority Parsing
Approximately 575 tokens
Use when
When configuring host matching, authority validation, or TLS SNI parameters for untrusted network endpoints.
Secure rules
Rule 1: Specify IPv6 allowed domains without brackets for OAuth2 host matching
Configure allowed_domains using domain names, wildcards, or bracketless IPv6 strings such as ::1 because Envoy’s authority parser normalizes IPv6 hostnames by stripping surrounding brackets.
Rule 2: Avoid null bytes in SNI configuration strings
Sanitize and validate string inputs to ensure SNI hostnames do not contain embedded null bytes (\000) before assigning them to transport context settings.
Sanitize and Canonicalize Request Paths and Parameters to Prevent Bypass
Use when
When configuring routing rules, HTTP header validation, or query parameter parsing where untrusted input must be safely interpreted and normalized.
Secure rules
Rule 1: Sanitize path matrix parameters during route matching
Enable ignore_path_parameters_in_path_matching in routing configurations to ensure matrix parameters like ;param=value are removed from the path prior to evaluation, preventing path-based security bypasses.
Rule 2: Decode query parameters safely without unescaping control characters
Use parseAndDecodeQueryString or urlDecodeQueryParameter to ensure percent-encoded sequences are appropriately handled and normalized before making security decisions or inspecting query keys and values.
auto params = Envoy::Http::Utility::QueryParamsMulti::parseAndDecodeQueryString(request_path);auto val = params.getFirstValue("name");if (val.has_value()) { // Perform validation on decoded value}
Rule 3: Strip URI fragments from request path headers
Configure strip_fragment_from_path in HeaderValidatorConfig to ensure URI fragments are safely removed from request paths before route matching and upstream delivery.
Enforce Kafka API Key and Topic Filtering for Messaging Security
Approximately 1,807 tokens
On this card
Use when
Configuring downstream messaging filters and upstream routing rules for Kafka broker and mesh proxies.
Secure rules
Rule 1: Restrict downstream Kafka client operational capabilities by configuring explicit request filtering via api_keys_allowed.
Prefer an explicit allowlist using api_keys_allowed in the kafka_broker filter to strictly bound acceptable message operation types, preventing unauthorized message consumption or administrative actions.
Rule 2: Define explicit forwarding rules for Kafka mesh topic prefixes to designated upstream clusters.
Configure deterministic forwarding_rules matching all authorized topic prefixes and mapping them to designated upstream clusters to avoid connection termination and unintentional message delivery across boundaries.
Enforce Strict HTTP/2 and QUIC Protocol Options and Stream Limits
Use when
When configuring HTTP/2, HTTP/3, and QUIC options to maintain protocol framing, prevent sequence corruption, and restrict unsupported features.
Secure rules
Rule 1: Validate HTTP/2 protocol options to prevent conflicting settings and unsupported features.
Process and initialize Http2ProtocolOptions using initializeAndValidateOptions to catch parameter collisions, avoid duplicate settings, and ensure server push or raw ENABLE_CONNECT_PROTOCOL parameters are not improperly enabled.
Rule 2: Restrict QPACK settings and configure HTTP/3 protocol options for QUIC clients.
Explicitly set Http3ProtocolOptions parameters such as disable_qpack on Envoy QUIC client connections to disable Huffman encoding, disable cookie crumbling, and zero out the QPACK maximum dynamic table capacity.
Prevent Observability Data and Internal Telemetry Exposure
Use when
Configuring Envoy routers, metric service sinks, and upstream host logging for edge or external-facing listeners.
Secure rules
Rule 1: Suppress internal performance and proxy state headers on untrusted downstream responses.
Set suppress_envoy_headers to true on the router filter (envoy.filters.http.router) for edge listeners to prevent leaking latency telemetry such as x-envoy-upstream-service-time and system health flags like x-envoy-overloaded to downstream clients.
Rule 2: Restrict and sanitize per-endpoint metric generation and host logging.
Ensure per-endpoint stats outputs and host logs generated via HostUtility are restricted to internal telemetry systems and filtered using stats tag extractors or prefix matchers to prevent exposing internal IP addresses, ports, and health failure flags.
HostUtility::forEachHostMetric(cm, [](Stats::PrimitiveCounterSnapshot&& counter) { // Process counter securely or filter sensitive endpoint IP metric names}, [](Stats::PrimitiveGaugeSnapshot&& gauge) { // Filter out host IP-identifying metrics from public endpoints});
Safely Rewrite, Sanitize, and Normalize HTTP Headers
Use when
Use when modifying, rewriting, sanitizing, or transforming HTTP request and response headers in Envoy dynamic modules, external processors, or custom routing filters.
Secure rules
Rule 1: Use set instead of add when modifying HTTP headers in dynamic modules to completely overwrite values and prevent duplicate header injection.
When modifying HTTP headers using the HeaderMap interface in Envoy dynamic modules, invoke set(key, value) rather than add(key, value) when replacing or sanitizing untrusted header inputs. The add method appends duplicate header entries rather than overwriting existing values, which can lead to header interpretation ambiguity or downstream security bypasses.
Rule 2: Explicitly disable append mode when configuring external processor header mutations to ensure untrusted header values are overwritten.
When rewriting request or response headers via Envoy external processing (ext_proc), configure HeaderMutationset_headers with append set to false when replacing untrusted downstream or upstream headers. Disabling header value appending prevents header duplication and ensures untrusted header values are overwritten rather than concatenated.
Rule 3: Normalize bridge header keys when copying them into Envoy header maps
When converting an envoy_headers collection into an Envoy response header map, construct each copied key as a LowerCaseString. Copy both keys and values into the destination map before calling release_envoy_headers, because the source collection may be released after its contents have been copied.
ResponseHeaderMapPtr transformed_headers = ResponseHeaderMapImpl::create();for (envoy_map_size_t i = 0; i < headers.length; i++) { transformed_headers->addCopy( LowerCaseString(Bridge::Utility::copyToString(headers.entries[i].key)), Bridge::Utility::copyToString(headers.entries[i].value));}release_envoy_headers(headers);
Validate and Harden HTTP Headers and Protocol Framing
Use when
When configuring HTTP connection managers, header validators, upgrade handling, and upstream protocol options in Envoy to prevent request smuggling, header spoofing, and protocol desynchronization.
Secure rules
Rule 1: Configure the Envoy Default Header Validator to reject incoming requests with underscores in header names.
Set headers_with_underscores_action to REJECT_REQUEST within the header validator configuration to prevent downstream clients from bypassing security controls or spoofing headers due to backend normalization.
Rule 2: Sanitize and remove unauthorized upgrade tokens using utility helpers.
Use Envoy HTTP utility helpers such as Utility::removeUpgrade with defined string matchers to strip unauthorized upgrade tokens systematically rather than performing manual string manipulation on connection and upgrade headers.
Rule 3: Enforce scheme header transformations for unencrypted mesh connections.
Configure scheme_header_transformation in HttpConnectionManager when receiving HTTP/2 or HTTP/3 traffic over unencrypted mesh networks to overwrite untrusted incoming :scheme pseudo-headers and prevent upstream services from assuming false client security.
Enforce Strict Internal Redirect Policies and Scheme Restrictions
Approximately 1,103 tokens
Use when
Configuring Envoy HTTP route internal redirect policies where upstream services may trigger internal redirects.
Secure rules
Rule 1: Disable cross-scheme internal redirects and restrict header copying.
Set allow_cross_scheme_redirect to false in internal redirect policies to prevent silent secure-to-cleartext connection downgrades. Ensure system headers, pseudo-headers, and Host headers are not copied during redirects.
Filter Resolved DNS Addresses in Dynamic Forward Proxies to Mitigate SSRF
Use when
Configuring dynamic forward proxies handling untrusted requests or domains in Envoy v1.39.0 to prevent unauthorized requests to internal networks or cloud metadata APIs.
Secure rules
Rule 1: Enforce resolved address filtering via DnsCacheConfig.resolved_address_filter to block outbound connections to restricted networks, private IP ranges, localhost, link-local addresses, and cloud metadata services.
Configure resolved_address_filter within the DNS cache configuration shared between the dynamic forward proxy filter and cluster to reject unsafe IP destinations. Combine this address filtering mechanism with network firewalls and egress RBAC rules, and monitor the dns_cache.<dns_cache_name>.dns_address_filter_out metric to audit and alert on blocked IP resolution attempts.
Secure Forwarded Headers and Client IP Trust in Envoy Proxies
Use when
Configuring network boundaries, HTTP connection managers, proxy protocol listener filters, or client certificate header forwarding to ensure untrusted downstreams cannot spoof client IPs or identity.
Secure rules
Rule 1: Sanitize incoming client certificate headers from untrusted downstreams before forwarding requests upstream.
Ensure x-forwarded-client-cert headers from untrusted downstreams are sanitized by keeping forward_client_cert_details unset or configuring it to SANITIZE or SANITIZE_SET to prevent backend services from relying on spoofed identity details.
Rule 2: Restrict plain connections and enforce strict validation for PROXY protocol and client IP attributes.
Keep allow_requests_without_proxy_protocol disabled (false) on network boundaries where all incoming traffic must pass through a proxy appending PROXY protocol headers, and ensure connection sockets enforce strict unicast address validation matching declared IP versions.
Rule 3: Explicitly configure trusted internal IP boundaries and original IP detection mechanisms.
Define strict CIDR ranges in internal_address_config and configure use_remote_address or xff_num_trusted_hops to prevent external clients from forging X-Forwarded-For headers and bypassing IP-based access controls or GeoIP filters.
Use envoy.matching.inputs.source_ip (SourceIPInput) instead of unvalidated HTTP headers when enforcing IP-based access rules to evaluate the actual downstream connection source IP and prevent header-spoofing attacks.
Configure Bounded Retries, Timeouts, and Circuit Breakers to Prevent Upstream Exhaustion
Approximately 607 tokens
Use when
Configuring Envoy routes, virtual hosts, and upstream clusters to handle network retries, timeouts, and request hedging safely.
Secure rules
Rule 1: Enforce explicit global and per-try request timeouts along with bounded retry limits to prevent resource exhaustion and request amplification.
Always define absolute upper bounds using global request timeouts and restrict individual attempts with per-try timeouts. Configure bounded num_retries and use retry budgets or circuit breaker thresholds to prevent retry storms.
Rule 2: Enable timeout budget statistics and track remaining retry circuit breaker metrics to monitor upstream latency and prevent cascading failures.
Set track_timeout_budgets to true in cluster configuration and enable track_remaining on circuit breakers to continuously monitor retry limits and prevent unconstrained traffic spikes.
Configure explicit request body and connection buffer limits to prevent memory exhaustion
Use when
Configuring virtual hosts, connection limits, or listeners in Envoy to handle untrusted incoming client connections and HTTP payloads.
Secure rules
Rule 1: Set explicit request body buffer limits on virtual hosts to bound memory consumption.
Configure request_body_buffer_limit explicitly in the virtual host proto configuration to prevent attacker-controlled requests with large HTTP payloads from exhausting proxy memory resources.
Rule 2: Configure explicit per-connection buffer limits on Envoy listeners.
Specify per_connection_buffer_limit_bytes explicitly in the listener configuration to constrain maximum memory allocated per connection and prevent out-of-memory denial-of-service crashes.
Building and compiling Envoy for production deployment where security policy guarantees and security vulnerability response processes are required.
Secure rules
Rule 1: Build Envoy with default BoringSSL or FIPS-compliant BoringSSL/AWS-LC configurations rather than OpenSSL.
Avoid building Envoy with --config=openssl for production deployments unless strictly required. OpenSSL builds rely on dynamically loaded libraries, disable HTTP/3 (QUIC) support, and are explicitly excluded from the Envoy security policy.
bazel build //source/exe:envoy-static# Or for FIPS compliance:bazel build --config=boringssl-fips //source/exe:envoy-static
Harden Envoy Container Deployments and Runtime Environments
Use when
Configuring container orchestrators, runtime security contexts, and deployment parameters for production Envoy instances.
Secure rules
Rule 1: Run Envoy containers with a read-only root filesystem to prevent runtime modification.
Set readOnlyRootFilesystem: true within the container security context for container orchestrators such as Kubernetes.
Restrict Envoy Privileged Ports and File System Permissions
Use when
Configuring Envoy container execution users, port mappings, and file system paths to restrict access to privileged resources.
Secure rules
Rule 1: Run Envoy as a non-user container and map host privileged ports to unprivileged container ports.
Keep Envoy running as a non-root user such as the default UID/GID 101. Avoid running as root with ENVOY_UID=0, and configure Envoy to listen on unprivileged ports greater than 1024 inside the container while relying on runtime port mapping to forward host privileged ports.
docker run -d --name envoy -p 80:8000 envoyproxy/envoy:v1.39.0
Rule 2: Validate file paths to restrict unauthorized access to privileged system directories.
Perform path integrity checks using Filesystem::Instance::illegalPath before attempting filesystem operations to block unauthorized reads from privileged or restricted host directories such as /proc, /sys, and /dev.
Filesystem::InstanceImpl file_system;std::string target_path = "/proc/kallsyms";if (file_system.illegalPath(target_path)) { ENVOY_LOG(warn, "Blocked access to restricted host path: {}", target_path); return;}auto result = file_system.fileReadToEnd(target_path);
Automate TLS Certificate Rotation and Secret Discovery
Approximately 1,449 tokens
On this card
Use when
Use when configuring automated TLS certificate, validation context, and session ticket key lifecycles using dynamic Secret Discovery Service (SDS) providers or filesystem-backed watched directories in Envoy.
Secure rules
Rule 1: Configure Envoy TLS contexts to load certificates dynamically via SDS configurations and watched directories.
Use tls_certificate_sds_secret_configs or validation_context_sds_secret_config in CommonTlsContext to fetch dynamic certificates and CA trust bundles. When using filesystem-backed secrets, specify watched_directory on the parent path to watch for atomic symlink replacements and trigger clean reloads without process restarts.
Rule 2: Secure the communication channel between Envoy proxy and SDS servers.
Protect dynamic certificate channels by using local Unix Domain Sockets or remote TLS connections authenticated with mutual TLS or strict transport security credentials.
Rule 3: Monitor SDS rotation failure metrics and register update callbacks for dynamic updates.
Subscribe to dynamic secret updates using update callbacks such as addUpdateCallback and monitor counter metrics like key_rotation_failed to catch validation errors and prevent silent failures during automated certificate rotations.
auto handle = sds_api->addUpdateCallback([this]() { return secret_callbacks_.onAddOrUpdateSecret();});
Load Dynamic Secrets Securely Using Secret Discovery Service
Use when
Configuring dynamic TLS certificates, session ticket keys, validation contexts, or generic authentication secrets in Envoy using the Secret Discovery Service (SDS).
Secure rules
Rule 1: Use Secret Discovery Service (SDS) generic and TLS secret resources instead of hardcoding sensitive credentials in static configurations.
Configure token_secret and hmac_secret references or transport socket TLS contexts using SDS and file-based or gRPC configuration sources to avoid embedding cleartext credentials in source code and configuration files.
Rule 2: Configure atomic directory-level renames or watched directories for file-backed SDS secrets.
When using file-backed DataSources or SDS secrets, configure watched_directory on the secret proto and perform atomic symlink updates on the host to prevent partial reads and secret loading failures.
Rule 3: Assign unique static secret names within Envoy’s SecretManager.
Ensure that every static secret registered in Envoy’s static resource configuration has a distinct name field to prevent static secret initialization failures and service disruption.
Secure Envoy Administrative Interfaces and Configuration Dumps
Use when
Configuring Envoy bootstrap parameters, setting up administrative endpoints, or managing diagnostic interfaces.
Secure rules
Rule 1: Disable administrative server sockets in bootstrap configurations when administrative endpoints are not required.
Explicitly clear the admin stanza in your envoy::config::bootstrap::v3::Bootstrap configuration to prevent opening administrative ports and exposing internal cluster state.
envoy::config::bootstrap::v3::Bootstrap bootstrap;// Explicitly remove admin server configuration to prevent opening administrative portsbootstrap.clear_admin();
Rule 2: Use strongly-typed configuration messages instead of untyped structs to ensure secrets are redacted in admin config dumps.
Define extension configurations using typed_config with google.protobuf.Any rather than legacy untyped google.protobuf.Struct fields. Strongly-typed protobuf configs allow Envoy to automatically redact secret fields such as private_key and passwords when inspected via /config_dump.
Use dynamic providers such as assume_role_with_web_identity_provider or IAM Roles Anywhere configuration rather than embedding long-lived static keys in Envoy configuration files.
Rule 2: Redact sensitive tokens and signatures from log outputs.
Ensure that sensitive values such as temporary access keys, security tokens, and signature strings are sanitized or overwritten with masks before emitting debug log messages.
Enforce Fail-Closed Behavior and Security Control Integrity Across Filters and Authentication
Approximately 504 tokens
Use when
Configuring Envoy security filters, authorization hooks, and authentication mechanisms where failing open or bypassing checks could compromise security control integrity.
Secure rules
Rule 1: Configure deny_at_disable on external authorization filters to ensure requests are denied when the filter is disabled.
When setting up the ext_authz filter, configure deny_at_disable with a default value of true to ensure that dynamic runtime overrides or metadata matchers cannot cause requests to bypass authorization checks.
Rule 2: Prevent OAuth2 pass-through matcher evaluation on forward ID token headers.
Ensure that pass_through_matcher rules do not target the header configured in forward_id_token. Envoy rejects configurations where pass-through matchers evaluate the forwarded ID token header to prevent external attackers from bypassing authentication.
Validate extension dependencies and enforce fail-closed factory instantiation
Use when
Developing dynamic extensions using Envoy’s factory registry for dependency injection, such as implementing custom resource detectors.
Secure rules
Rule 1: Ensure extension factory creation methods validate configurations and return non-null pointers or trigger clean initialization failure.
When implementing custom resource detector factories via ResourceDetectorFactory, explicitly validate incoming configurations and ensure components return a valid instance or nullptr to allow Envoy to safely abort initialization via EnvoyException and maintain telemetry context integrity.
class MyDetectorFactory : public ResourceDetectorFactory {public: ResourceDetectorPtr createResourceDetector(const Protobuf::Message& config, Server::Configuration::ServerFactoryContext& context) override { if (!validateConfig(config)) { return nullptr; } return std::make_unique<MyDetector>(); }};