> For the complete documentation index, see [llms.txt](https://docs.bluerock.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.bluerock.io/bluerock-documentation-2.7.0-beta/bluerock-sandbox/bluewarden-egress-security.md).

# BlueWarden Egress Security

BlueWarden operates as a per-sandbox egress security proxy designed for AI coding agents running inside the BlueRock Sandbox environment. Every outbound TCP connection initiated by a sandboxed agent passes through BlueWarden, where configured security policies dictate accessible destinations and permissible Large Language Models (LLMs) before data leaves the host.

### Prerequisite

BlueWarden must be enabled in the host configuration file (`/etc/bluedev/bouncer.toml`) before policy rules in `bru_policy.json` can take effect. If BlueWarden is disabled in `bouncer.toml`, all `warden` policy rules will be ignored.

{% code title="bouncer.toml" lineNumbers="true" %}

```toml
[warden]
enable = true
```

{% endcode %}

## Connection Handling & Enforcement Architecture

### First-Byte Traffic Inspection

BlueWarden inspects the initial bytes of every connection opened by the sandbox to classify and handle traffic based on content rather than port numbers. No policy field names a port for protocol classification, ensuring that internal services or gateways running on non-standard ports receive deep packet inspection.

| **Initial Bytes Observed**                    | **Routing & Handling Protocol**                                                                                                    |
| --------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| TLS Handshake (any port)                      | Decrypted and inspected using a certificate minted for the sandbox, unless the target server is listed in `tls.passthrough.hosts`. |
| HTTP Request Line / HTTP/2 Preface (any port) | Parsed as cleartext HTTP and evaluated against `http` and `llm` policy rules.                                                      |
| DNS Query (port 53 UDP/TCP, port 853 TCP)     | Handled or proxied according to the `dns` block configuration.                                                                     |
| Unrecognized / Non-Web Data                   | Relayed byte-for-byte unread, subject exclusively to Layer 4 destination checks in `egress.destinations.allow_to`.                 |

* **Port-Agnostic Processing**: \
  An LLM gateway on port 3000 undergoes identical application-layer inspection to standard public endpoints. Non-web protocols (such as database connections or SSH) running on port 443 are carried unread rather than reset.
* **Datagram & Protocol Floor**: \
  All TCP traffic is forced through BlueWarden. UDP traffic is filtered at the kernel layer via `egress.destinations.allow_to` rather than proxied. Non-TCP/UDP protocols (such as ICMP) pass without proxy filtering.

### Two-Tiered Enforcement Model

To prevent accidental disruption during deployment, every enforcement mechanism in BlueWarden operates under a two-tiered control model:

1. **Module `enable` Switch**: \
   Controls whether a mechanism actively inspects traffic and generates telemetry.
2. **Module `remediate` Switch**: \
   Controls whether policy violations trigger traffic blocking (`true`) or operate in watch-and-record mode (`false`).

Model pinning requires three active remediation switches (`options.remediate: true`, `llm.remediate: true`, and `llm.model.remediate: true`).

## Configuration Reference

All BlueWarden configurations reside within the `bru_policy.json` file, defined under `app_policies.default.warden` for default policies or `app_policies.<policy_name>.warden` for custom, user-defined policies.

### Global Options (`options`)

The `options` block defines proxy-wide enforcement toggles and failure behavior.

* **`remediate` (boolean, default: `false`)**: \
  Master enforcement toggle. While `false`, BlueWarden inspects and records all traffic without blocking any connections. When `true`, individually armed modules begin enforcing denials.
* **`fail_closed` (boolean, default: `false`)**: \
  Controls sandbox network behavior if the BlueWarden proxy process terminates or restarts. When `false`, temporary proxy failures bypass inspection. If proxy crash-looping trips the circuit breaker (5 restarts within 300 seconds), network egress is permanently isolated while the workload remains running. When `true`, temporary failures pause egress; if the circuit breaker trips, the sandbox container is terminated immediately via SIGKILL.

{% hint style="info" icon="notes" %}
**Note:**&#x20;

* Unspecified/broadcast addresses, documentation ranges, and connections directed back to BlueWarden's own listeners are refused regardless of enforcement settings.
* If BlueWarden loses its connection to `bluerockd`, for example while `bluerockd` restarts, BlueWarden exits and is restarted like any other BlueWarden failure. A restart succeeds once bluerockd is available again, and enforcement resumes. If `bluerockd` is still unavailable when the circuit breaker trips, the sandbox is left without network access (`fail_closed: false`) or terminated (`fail_closed: true`).
  {% endhint %}

### TLS Configuration (`tls`)

Governs TLS termination and pass-through exemptions.

* `passthrough.hosts` (array of strings, default: `[]`): \
  Explicit list of FQDN hostnames that bypass TLS decryption (e.g., `["pinned-sdk.vendor.com"]`). Wildcards are prohibited. Passthrough traffic is relayed without decryption (retaining end-to-end TLS). Host allow/deny rules are still enforced by SNI inspection. Path scoping, model pinning, and MCP filtering are bypassed..
* `require_server_name` (boolean, default: `enable: true, remediate: false`): \
  Refuses TLS handshakes that omit the Server Name Indication (SNI) extension.

### HTTP & Web Endpoint Filtering (`http`)

Evaluates all decrypted web traffic, inference calls, and MCP exchanges. Host filtering is configured within the `endpoint` sub-block using host pattern entries and optional path scopes.

* `endpoint.allow_list` (array of strings or objects, default: `[]`): \
  Denies outbound HTTP traffic from the sandbox to external endpoints by default, permitting only the web hostnames and path objects explicitly specified in the list.
* `endpoint.deny_list` (array of strings or objects, default: `[]`): \
  Permits outbound HTTP traffic from the sandbox to external endpoints by default, blocking only the web hostnames and path objects explicitly specified in the list.

{% hint style="info" icon="notes" %}
**Note:**&#x20;

`allow_list` and `deny_list` are mutually exclusive. Populating both parameters within the same policy causes compilation failure.
{% endhint %}

#### Host Patterns

* `api.example.com`: \
  Matches the exact hostname.
* `.example.com`: \
  Matches the apex domain and all subdomains.
* `*.example.com`: \
  Matches subdomains only (excluding apex).

#### **Path Scoping**&#x20;

Host entries can be expanded into objects to restrict path prefixes:

```json
{ "host": "<website>.com", "only_paths": ["/bedrocksystems"] }
```

`only_paths` and `except_paths` are mutually exclusive and segment-anchored.

#### **Request Invariants**

* `require_host`: Refuses requests missing a valid Host header.
* `sni_mismatch`: Refuses requests where the HTTP Host header contradicts the TLS SNI server name (domain fronting).
* `protocol_upgrade`: Refuses switches to uninspectable protocols (such as `h2c` or `CONNECT` tunnels). Standard WebSockets are permitted as frame payloads remain inspected.

### LLM Inference Recognition & Model Pinning (`llm`)

BlueWarden inspects JSON request payloads on the wire to enforce model selection rules.

{% code title="bru\_policy\_json" lineNumbers="true" %}

```json
"llm": {
  "enable": true,
  "remediate": true,
  "model": {
    "remediate": true,
    "allow_list": ["claude-3-5-*", "gpt-4o*"],
    "deny_list": []
  }
}
```

{% endcode %}

* `model.allow_list` / `deny_list` (array of strings, default: `[]`): \
  Glob-matched lists defining permitted or blocked model names (e.g., `["claude-*"]`, `["gpt-4*"]`).
* `model.remediate` (boolean, default: `false`): \
  Controls enforcement for model pinning. Blocking an unauthorized model call requires `options.remediate: true`, `llm.remediate: true`, and `llm.model.remediate: true`.

#### Provider Independence&#x20;

BlueWarden automatically recognizes known endpoints (Anthropic, OpenAI, ChatGPT backend), but also evaluates any HTTP request body containing a top-level `model` field regardless of the destination host.

#### Unreadable Payloads&#x20;

Requests with obfuscated, corrupted, or non-decodable model fields trigger an automatic policy violation if either list is active.

#### Client Refusal Emulation&#x20;

When a request names a model blocked by policy, BlueWarden returns a single unified provider-native JSON response directly to the client with HTTP Status 400 Bad Request. This prevents LLM SDKs (such as Anthropic or OpenAI) from mistaking policy denials for credential failures or triggering continuous authentication retry loops:

```json
{
  "type": "error",
  "error": {
    "type": "policy_blocked",
    "message": "blocked by warden policy: Requested model 'gpt-4o' is denied by warden model policy"
  },
  "request_id": "<exchange_id>"
}
```

#### Response Telemetry&#x20;

Decodes reply streams to emit telemetry regarding token outputs and tool-call requests without altering response content.

### DNS Control (`dns`)

BlueWarden captures all sandbox DNS lookups on port `53` by default. Upstream resolvers are configured via `nameservers` (array of strings, default `[]`), falling back to `/etc/resolv.conf` when empty.

#### Transport Controls

* `allow_over_udp_tcp` (default: `true`): \
  Resolves standard DNS queries via configured nameservers.
* `allow_over_https` (default: `true`): \
  Answers DNS-over-HTTPS queries transparently within web traffic.
* `enable` (boolean, default: `true`): \
  Controls whether the DNS proxy module actively processes lookups.
* `remediate` (boolean, default: `false`): \
  Master switch for DNS transport enforcement. Requires `options.remediate: true` and `dns.remediate: true` to refuse non-permitted DNS transports.
* `allow_over_tls` (boolean, default: `false`): \
  Controls DNS-over-TLS (port 853). When `dns.remediate` is `false`, DoT traffic is observed and forwarded; when `true`, DoT traffic is dropped.

{% hint style="success" icon="lightbulb-exclamation-on" %}
**Important:**

Setting `dns.enable: true` and `egress.block_dns_over_tls: true` simultaneously triggers a policy compilation error due to mutual exclusion.
{% endhint %}

### Egress Controls (`egress`)

The `egress` block governs non-web TCP/UDP routing, protocol classification requirements, and network boundary security.

* `remediate` (boolean, default: `false`): \
  Parent enforcement arm for destination lists (`allow_to`/`deny_to`), UDP controls, `block_quic`, and `block_dns_over_tls`. Address guards (`deny_private_addresses`, `deny_link_local_addresses`) and `require_known_protocol` operate independently of `egress.remediate`, responding to `options.remediate` and their own `remediate` flags.
* `destinations.allow_to` / `deny_to` (array of objects, default: `[]`): \
  Rules defining non-web destinations. Entries require three attributes:
  * `addr`: \
    Destination CIDR block or IP address (e.g., `"10.0.5.10/32"`). Hostnames are accepted only for UDP rules (`proto: ["udp"]`) and are resolved once upon policy installation. TCP rules must use explicit IP addresses or CIDR blocks.
  * `ports`: \
    Array of permitted/denied port integers (e.g., `[22, 5432]`).
  * `proto`: \
    Array of protocols (e.g., `["tcp"]`, `["udp"]`). Omission applies the rule to both TCP and UDP.
* `block_quic` (boolean, default: `true`): \
  Drops UDP traffic on port 443. This forces browsers and tools to fall back from HTTP/3 to inspectable TCP.
* `require_known_protocol` (boolean, default: `enable: true, remediate: false`): \
  Refuses connections whose initial bytes are neither a TLS handshake nor an HTTP request line. Arms directly with `options.remediate`.

#### Address Guards

* `deny_private_addresses`: \
  Blocks cleartext HTTP and `tls.passthrough` dials targeting RFC1918, loopback, and carrier-grade NAT space. (Inspected HTTPS traffic is governed by `http.endpoint`, and raw TCP is governed by `egress.destinations`). Exceptions are defined via `allowed_private_destinations` (e.g., `["172.31.0.0/16"]`).
* `deny_link_local_addresses`: \
  Blocks access to `169.254.0.0/16`, protecting cloud metadata endpoints (e.g., `169.254.169.254`). Exceptions are set via `allowed_link_local_destinations`.

{% hint style="success" icon="lightbulb-exclamation-on" %}
**Important:**&#x20;

Entries in `allowed_private_destinations` can never grant access to link-local metadata addresses, regardless of CIDR breadth.
{% endhint %}

## Telemetry & Observability Events

BlueWarden emits structured telemetry events for every processed flow and policy violation. Enabling a module automatically activates its corresponding telemetry stream.

<table data-search="false"><thead><tr><th>Telemetry Record / Event</th><th>Description &#x26; Triggering Mechanism</th></tr></thead><tbody><tr><td><code>warden_connect</code></td><td>Connection acceptance record containing target address, dialled port, TLS SNI, and classification branch.</td></tr><tr><td><code>warden_http_request</code></td><td>Decrypted HTTP request record capturing host, path, HTTP method, and invariant flags.</td></tr><tr><td><code>warden_llm_request</code></td><td>Inference exchange record capturing target model ID and provider endpoint.</td></tr><tr><td><code>warden_llm_response</code></td><td>Inference response telemetry capturing completion status and token counts (tool-call intents recorded separately in <code>warden_llm_tool_call</code>).</td></tr><tr><td><code>warden_dns</code></td><td>Name resolution record containing queried hostname, query type, resolved IP addresses, and TTL.</td></tr><tr><td><code>warden_flow</code></td><td>Completed flow summary record emitted ~2 minutes after TCP termination, detailing total bytes transferred and <code>policy_verdict</code> (<code>would_deny</code>, <code>allowed</code>, <code>denied</code>).</td></tr><tr><td><code>warden_endpoint_violation</code></td><td>Refusals by <code>http.endpoint</code> host and path rules.</td></tr><tr><td><code>warden_model_violation</code></td><td>Refusals by model pinning.</td></tr><tr><td><code>warden_dns_violation</code></td><td>DNS queries and transports refused by the <code>dns</code> block.</td></tr><tr><td><code>warden_invalid_protocol</code></td><td>Raised on refusals by <code>tls.require_server_name</code> (<code>no_sni</code>), <code>http.require_host</code> (<code>missing_host</code>), and <code>http.protocol_upgrade</code> (<code>upgrade_refused</code>).</td></tr><tr><td><code>warden_sni_host_mismatch</code></td><td>Raised on domain-fronting refusals by <code>http.sni_mismatch</code>.</td></tr><tr><td><code>warden_ssrf_blocked</code></td><td>Raised when cleartext HTTP requests are blocked by <code>deny_private_addresses</code> or <code>deny_link_local_addresses</code>.</td></tr><tr><td><code>warden_egress_violation</code></td><td>Raised on non-web TCP/UDP layer-4 refusals (destination lists, link-local guards, <code>require_known_protocol</code>).</td></tr></tbody></table>

## Complete Annotated Policy Configuration

Below is a reference JSON configuration illustrating an active, fully configured `warden` block populated with representative production policies. Configure this object under `app_policies.<policy_name>.warden` within `bru_policy.json`:

{% code title="bru\_policy.json" lineNumbers="true" %}

```json
"warden": {
  "options": {
    "remediate": true,
    "fail_closed": false
  },
  "tls": {
    "passthrough": {
      "hosts": ["pinned-sdk.example.com"]
    },
    "require_server_name": {
      "enable": true,
      "remediate": true
    }
  },
  "http": {
    "endpoint": {
      "enable": true,
      "remediate": true,
      "allow_list": [
        "api.example-provider-1.com",
        "api.example-provider-2.com",
        { "host": "example.com", "only_paths": ["/my-org"] }
      ],
      "deny_list": []
    },
    "require_host": {
      "enable": true,
      "remediate": true
    },
    "sni_mismatch": {
      "enable": true,
      "remediate": true
    },
    "protocol_upgrade": {
      "enable": true,
      "remediate": true
    }
  },
  "llm": {
    "remediate": true,
    "model": {
      "remediate": true,
      "allow_list": ["model-family-1-*", "model-family-2*"],
      "deny_list": []
    }
  },
  "dns": {
    "enable": true,
    "remediate": true,
    "nameservers": ["192.0.2.1", "192.0.2.2"],
    "allow_over_udp_tcp": true,
    "allow_over_https": true,
    "allow_over_tls": false
  },
  "egress": {
    "remediate": true,
    "block_quic": true,
    "block_dns_over_tls": false,
    "destinations": {
      "allow_to": [
        {
          "addr": "192.0.2.10/32",
          "ports": [22, 5432],
          "proto": ["tcp"]
        }
      ],
      "deny_to": []
    },
    "require_known_protocol": {
      "enable": true,
      "remediate": false
    },
    "deny_private_addresses": {
      "enable": true,
      "remediate": true,
      "allowed_private_destinations": ["192.168.0.0/16"]
    },
    "deny_link_local_addresses": {
      "enable": true,
      "remediate": true,
      "allowed_link_local_destinations": []
    }
  }
}
```

{% endcode %}

## Phased Rollout Workflow

To prevent service disruption, operators must deploy BlueWarden using a structured six-stage workflow:

1. **Observation Posture (**`Watch`**)**: \
   Deploy BlueWarden with default settings (`options.remediate: false`). All module inspection engines remain active, recording traffic flows without blocking any connections.
2. **Traffic Analysis**: \
   Review `warden_llm_request` (for model IDs and hosts), and `warden_http_request` (for web destinations). Use `verdict_reason` on `warden_flow` records exclusively to identify connection-level blocks.
3. **Content Rules**: \
   Set `options.remediate: true`. Enable `remediate: true` selectively on `http.endpoint`, `llm` (setting both `llm.remediate` and `llm.model.remediate`).
4. **Integrity Guards:** \
   Set `remediate: true` on `tls.require_server_name`, `http.require_host`, `http.sni_mismatch`, `http.protocol_upgrade`, `deny_private_addresses`, and `deny_link_local_addresses`.
5. **Configure Fail-Closed Availability**: \
   Evaluate operational requirements and set `options.fail_closed: true` for sensitive production workloads. Note: If BlueWarden crash-loops, `fail_closed: true` will terminate the sandbox container via SIGKILL.
6. **Lock Layer 4 Datapath:** \
   Enable `egress.remediate: true`. Non-web TCP/UDP traffic not explicitly listed in `egress.destinations.allow_to` is dropped.

{% hint style="info" icon="notes" %}
**Note:**&#x20;

Policy updates apply immediately without requiring a sandbox container restart or interrupting existing connections. Setting `options.remediate: false` instantly reverts the entire proxy to observation posture.
{% endhint %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.bluerock.io/bluerock-documentation-2.7.0-beta/bluerock-sandbox/bluewarden-egress-security.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
