Outbound Policies
An Outbound Policy allows you to control how traffic from a Sandbox to destinations outside of Modal is handled by specifying a set of routes. A route matches traffic based on destination address or host and decides what happens to that traffic.
When using Modal Sandboxes to run untrusted code, an Outbound Policy allows you to restrict outbound traffic to a limited set of destinations, as well as to inject API secrets into HTTP headers without ever making the secret visible to the untrusted workload. See Security for additional security benefits of using an Outbound Policy.
For full reference documentation on the modal.OutboundPolicy interface, visit our SDK
docs (Python, JavaScript, Go).
import modal
app = modal.App.lookup("sandbox-outbound-policy", create_if_missing=True)
policy = modal.OutboundPolicy(
routes=[
# Allow TLS connections to these domains.
modal.OutboundRoute.tls(domains=["pypi.org", "files.pythonhosted.org"]),
# Block everything else.
modal.OutboundRoute.any().block(),
],
)
sb = modal.Sandbox.create("sleep", "infinity", app=app, outbound_policy=policy)import { ModalClient, OutboundPolicy, OutboundRoute } from "modal";
const modal = new ModalClient();
const app = await modal.apps.fromName("sandbox-outbound-policy", {
createIfMissing: true,
});
const image = modal.images.fromRegistry("python:3.13-slim");
const policy = new OutboundPolicy({
routes: [
// Allow TLS connections to these domains.
OutboundRoute.tls({
domains: ["pypi.org", "files.pythonhosted.org"],
}),
// Block everything else.
OutboundRoute.any().block(),
],
});
const sb = await modal.sandboxes.create(app, image, {
command: ["sleep", "infinity"],
outboundPolicy: policy,
});policy := &modal.OutboundPolicy{
Routes: []modal.OutboundRoute{
// Allow TLS connections to these domains.
modal.OutboundRouteTLS{Domains: []string{"pypi.org", "files.pythonhosted.org"}},
// Block everything else.
modal.OutboundRouteAny{Redirect: modal.OutboundBlock{}},
},
}
sb, err := mc.Sandboxes.Create(ctx, app, image, &modal.SandboxCreateParams{
Command: []string{"sleep", "infinity"},
OutboundPolicy: policy,
})
if err != nil {
return err
}How routes are evaluated
The list of routes is evaluated against outgoing traffic in order. The first matching route handles the traffic, and no later route has any effect.
The last route must be the special any route, which matches all traffic not
already matched by a previous route. An OutboundRoute.any() route means that
this traffic is allowed, and OutboundRoute.any().block() means that it’s
blocked, i.e., only traffic matched by the previous routes is allowed.
Route types
In addition to the any route, there are three route types with different characteristics.
| Route | Matches | Decrypts traffic |
|---|---|---|
OutboundRoute.ip(cidrs=[...]) | All traffic to the listed IP ranges, on any transport and port. | No |
OutboundRoute.tls(domains=[...]) | TLS connections on tcp/443, by the domain the client requests (SNI). | No |
OutboundRoute.https(domains=[...]) | HTTPS connections on tcp/443, by the domain the client requests (SNI). | Yes |
OutboundRoute.any() / OutboundRoute.any().block() | Everything no earlier route matched. | No |
IP routes are suitable for allowing traffic to services addressed by IP, and for non-TLS traffic, including UDP.
TLS routes match traffic based on domain, without intercepting or decrypting connections. This has known limitations.
Use HTTPS routes to have Modal decrypt and inspect HTTPS traffic to matching
domains. They require the Outbound Policy to set allow_tls_decryption=True when the Sandbox is created. HTTPS routes enable additional security features and support header replacement with Secret injection.
DNS lookups
Malicious DNS requests can be used to leak data from Sandboxes by encoding data in lookups of names under a controlled domain. No explicit connection is needed.
To protect against such DNS exfiltration, ending a policy with OutboundRoute.any().block() blocks (returns NXDOMAIN) for DNS lookups, except for names matching domains in TLS or HTTPS routes.
When a policy ends in OutboundRoute.any(), every name resolves.
Two cases are not protected, even under a policy ending in OutboundRoute.any().block():
- A TLS or HTTPS route with the domain
*lets every name resolve. - Lookups sent directly to an address allowed by an IP route, such as a public
resolver like
8.8.8.8, are not filtered.
Matching IP ranges
OutboundRoute.ip() takes a list of IPv4 CIDRs and allows matching destination IPv4
addresses. This is transport and port agnostic. IPv6 CIDRs are rejected, and IPv6
traffic is dropped. Private, link-local and other reserved ranges stay blocked,
whatever the routes say.
Under a policy ending in any().block(), DNS resolution is off by default. Destinations can’t be resolved by name unless there’s also a TLS or HTTPS route mentioning it by name.
policy = modal.OutboundPolicy(
routes=[
# Allow all traffic to a public IP range, on any port.
modal.OutboundRoute.ip(cidrs=["52.0.0.0/8"]),
# Block everything else.
modal.OutboundRoute.any().block(),
],
)const policy = new OutboundPolicy({
routes: [
// Allow all traffic to a public IP range, on any port.
OutboundRoute.ip({ cidrs: ["52.0.0.0/8"] }),
// Block everything else.
OutboundRoute.any().block(),
],
});policy := &modal.OutboundPolicy{
Routes: []modal.OutboundRoute{
// Allow all traffic to a public IP range, on any port.
modal.OutboundRouteIP{CIDRs: []string{"52.0.0.0/8"}},
// Block everything else.
modal.OutboundRouteAny{Redirect: modal.OutboundBlock{}},
},
}Matching and validating outbound domains
TLS and HTTPS routes match the specified domain against the SNI in the TLS
handshake, and Modal resolves that hostname itself rather than trusting the
destination IP the Sandbox picked. Connections without an SNI do not match
these routes, not even a route with a "*". HTTPS routes do additional validation.
Encrypted Client Hello (ECH) is not supported. Modal only sees the outer public name, not the real hostname inside it, so an ECH connection is matched against that public name and is blocked unless the public name is matched by a route.
| Domain entry | Matches | Does not match |
|---|---|---|
example.com | example.com | a.example.com |
*.example.com | a.example.com, a.b.example.com | example.com, evilexample.com |
* | any domain |
policy = modal.OutboundPolicy(
routes=[
# Allow TLS connections to GitHub, without decrypting them.
modal.OutboundRoute.tls(domains=["github.com", "*.github.com"]),
# Allow all traffic to a public IP range, on any port.
modal.OutboundRoute.ip(cidrs=["52.0.0.0/8"]),
# Block everything else.
modal.OutboundRoute.any().block(),
],
)const policy = new OutboundPolicy({
routes: [
// Allow TLS connections to GitHub, without decrypting them.
OutboundRoute.tls({ domains: ["github.com", "*.github.com"] }),
// Allow all traffic to a public IP range, on any port.
OutboundRoute.ip({ cidrs: ["52.0.0.0/8"] }),
// Block everything else.
OutboundRoute.any().block(),
],
});policy := &modal.OutboundPolicy{
Routes: []modal.OutboundRoute{
// Allow TLS connections to GitHub, without decrypting them.
modal.OutboundRouteTLS{Domains: []string{"github.com", "*.github.com"}},
// Allow all traffic to a public IP range, on any port.
modal.OutboundRouteIP{CIDRs: []string{"52.0.0.0/8"}},
// Block everything else.
modal.OutboundRouteAny{Redirect: modal.OutboundBlock{}},
},
}TLS routes
TLS routes are not decrypted (unlike HTTPS routes below), so the Host header, URL path,
and body are never inspected.
HTTPS routes with TLS decryption
Modal can also verify Host headers, by decrypting the TLS connection for
HTTPS. These HTTPS routes can additionally have
header replacements specified to e.g. perform secret injection.
To use HTTPS routes, the policy must set allow_tls_decryption=True when the Sandbox is created, and
it can’t be changed at any later point. With it set, Modal attaches a local proxy that
sits on the Sandbox’s outbound network path, and generates a certificate authority
(CA) unique to the Sandbox. The CA’s certificate is installed into the Sandbox’s trust store at creation.
If the SNI domain of a request matches an HTTPS route, the proxy terminates the
TLS connection using a certificate minted by the Sandbox’s CA. The proxy refuses requests with mismatched SNI/Host headers, and forwards any matching request to the destination
over a separate TLS
connection. Modal verifies these upstream destinations against a Modal-managed
trust store.
- Only HTTPS on port 443 is decrypted.
- Plain HTTP, other ports, and non-TLS protocols are never terminated.
- The proxy speaks HTTP/1.1 or HTTP/2 to the Sandbox, whichever the destination chose from the protocols the client offered over ALPN. gRPC and other HTTP/2-only clients work as long as the destination supports HTTP/2. A client and destination that share no protocol fail the TLS handshake.
- Upgrade requests, such as WebSocket, go through.
policy = modal.OutboundPolicy(
allow_tls_decryption=True,
routes=[
# Decrypt connections to the API, so requests whose Host header doesn't
# match api.example.com are refused.
modal.OutboundRoute.https(domains=["api.example.com"]),
modal.OutboundRoute.any().block(),
],
)const policy = new OutboundPolicy({
allowTlsDecryption: true,
routes: [
// Decrypt connections to the API, so requests whose Host header doesn't
// match api.example.com are refused.
OutboundRoute.https({ domains: ["api.example.com"] }),
OutboundRoute.any().block(),
],
});policy := &modal.OutboundPolicy{
AllowTLSDecryption: true,
Routes: []modal.OutboundRoute{
// Decrypt connections to the API, so requests whose Host header doesn't
// match api.example.com are refused.
modal.OutboundRouteHTTPS{Domains: []string{"api.example.com"}},
modal.OutboundRouteAny{Redirect: modal.OutboundBlock{}},
},
}TLS trust inside the Sandbox
TLS termination on HTTPS routes only works if the workload trusts the
certificate authority used in the proxy. At creation time, Modal installs the CA certificate in the root filesystem at /etc/modal/sandbox-egress-ca.crt. Modal
also appends this to any existing system CA bundle the image has if we
can recognize it.
Modal also sets common environment variables in the Sandbox pointing to a CA bundle containing the Sandbox CA certificate:
SSL_CERT_FILEREQUESTS_CA_BUNDLECURL_CA_BUNDLENODE_EXTRA_CA_CERTSGRPC_DEFAULT_SSL_ROOTS_FILE_PATH
If your chosen HTTP client does not recognize these environment variables, or
if your system CA bundle is in a location where we don’t append the CA
certificate, configure the client to read the
certificate from /etc/modal/sandbox-egress-ca.crt.
Secret injection
Passing Secrets as environment variables to untrusted code is risky: any process in the Sandbox can read its own environment and leak the keys. Secret injection avoids this by declaring header replacements on outbound HTTPS requests to given domains. This replacement happens outside the Sandbox, so the secret never appears in the Sandbox’s environment.
For a complete working demonstration, see the Secret injection example.
secret = modal.Secret.from_name("api-token")
outbound_policy = modal.OutboundPolicy(
allow_tls_decryption=True,
routes=[
# Inject a secret-backed Authorization header.
modal.OutboundRoute.https(
domains=["example.com"],
header_replacements=[
{"secret": secret, "headers": {"Authorization": "Bearer $API_TOKEN"}},
],
),
# Inject a static header into requests to another domain.
modal.OutboundRoute.https(
domains=["modal.com"],
header_replacements=[{"headers": {"X-Trace-Token": "trace_abcd"}}],
),
# Allow all other traffic, without decrypting it.
modal.OutboundRoute.any(),
],
)
sb = modal.Sandbox.create(
"python", "agent.py", app=app, outbound_policy=outbound_policy
)const secret = await modal.secrets.fromName("api-token");
const outboundPolicy = new OutboundPolicy({
allowTlsDecryption: true,
routes: [
// Inject a secret-backed Authorization header.
OutboundRoute.https({
domains: ["example.com"],
headerReplacements: [
{ secret, headers: { Authorization: "Bearer $API_TOKEN" } },
],
}),
// Inject a static header into requests to another domain.
OutboundRoute.https({
domains: ["modal.com"],
headerReplacements: [{ headers: { "X-Trace-Token": "trace_abcd" } }],
}),
// Allow all other traffic, without decrypting it.
OutboundRoute.any(),
],
});
const sb = await modal.sandboxes.create(app, image, {
command: ["python", "agent.py"],
outboundPolicy,
});secret, err := mc.Secrets.FromName(ctx, "api-token", nil)
if err != nil {
return err
}
outboundPolicy := &modal.OutboundPolicy{
AllowTLSDecryption: true,
Routes: []modal.OutboundRoute{
// Inject a secret-backed Authorization header.
modal.OutboundRouteHTTPS{
Domains: []string{"example.com"},
HeaderReplacements: []modal.OutboundHeaderReplacement{
{Secret: secret, Headers: map[string]string{"Authorization": "Bearer $API_TOKEN"}},
},
},
// Inject a static header into requests to another domain.
modal.OutboundRouteHTTPS{
Domains: []string{"modal.com"},
HeaderReplacements: []modal.OutboundHeaderReplacement{
{Headers: map[string]string{"X-Trace-Token": "trace_abcd"}},
},
},
// Allow all other traffic, without decrypting it.
modal.OutboundRouteAny{},
},
}
sb, err := mc.Sandboxes.Create(ctx, app, image, &modal.SandboxCreateParams{
Command: []string{"python", "agent.py"},
OutboundPolicy: outboundPolicy,
})
if err != nil {
return err
}Each HTTPS route can set headers on the requests it matches, as in the example above. A header the request doesn’t have is added, and any existing copies are replaced, whatever their case. A route can set each header name only once.
Header replacements support templating against the keys of a supplied Secret.
A $-prefixed key name is replaced with the secret value at request time.
To write a literal $, escape it as $$.
A replacement without a secret is static, and its header values are used
verbatim when injected into the request.
Security
| Protection | What it does | Applies to |
|---|---|---|
| Pinned destinations | Connects to the address Modal resolves for the domain, not the one the Sandbox picked. | tls and https routes |
| Domain fronting protection | Refuses requests whose Host header doesn’t match the requested domain. | https routes |
| Secrets kept out of the Sandbox | Adds credentials to requests without the workload ever seeing them. | https routes with header replacements |
| DNS exfiltration protection | Stops data leaking out through DNS lookups. | Policies ending in any().block() with no * domain, for lookups through the Sandbox’s resolver |
Changing the policy of a running Sandbox
Outbound Policies can be changed while the Sandbox is running. For example: allow broad access while installing dependencies, then restrict it before an agent runs.
Setting a new policy with set_outbound_policy() replaces the existing
policy in full. It takes effect immediately; established connections that
are no longer allowed are terminated. It can change which DNS names resolve, but already cached answers are
not revoked.
- Policy updates are available for all Sandboxes, unless they’re created with
block_network=True. - The
allow_tls_decryptionflag must stay the same as it was on creation.
# Start with outbound traffic allowed, for example to install dependencies.
sb = modal.Sandbox.create("sleep", "infinity", app=app)
# ... later, allow only the domains the workload needs.
sb.set_outbound_policy(
modal.OutboundPolicy(
routes=[
modal.OutboundRoute.tls(domains=["api.openai.com"]),
modal.OutboundRoute.any().block(),
],
)
)
# Or block all outbound traffic.
sb.set_outbound_policy(modal.OutboundPolicy(routes=[modal.OutboundRoute.any().block()]))
# Allow all outbound traffic again.
sb.set_outbound_policy(modal.OutboundPolicy(routes=[modal.OutboundRoute.any()]))// Start with outbound traffic allowed, for example to install dependencies.
const sb = await modal.sandboxes.create(app, image, {
command: ["sleep", "infinity"],
});
// ... later, allow only the domains the workload needs.
await sb.setOutboundPolicy(
new OutboundPolicy({
routes: [
OutboundRoute.tls({ domains: ["api.openai.com"] }),
OutboundRoute.any().block(),
],
}),
);
// Or block all outbound traffic.
await sb.setOutboundPolicy(
new OutboundPolicy({ routes: [OutboundRoute.any().block()] }),
);
// Allow all outbound traffic again.
await sb.setOutboundPolicy(
new OutboundPolicy({ routes: [OutboundRoute.any()] }),
);// Start with outbound traffic allowed, for example to install dependencies.
sb, err := mc.Sandboxes.Create(ctx, app, image, &modal.SandboxCreateParams{
Command: []string{"sleep", "infinity"},
})
if err != nil {
return err
}
// ... later, allow only the domains the workload needs.
err = sb.SetOutboundPolicy(ctx, &modal.OutboundPolicy{
Routes: []modal.OutboundRoute{
modal.OutboundRouteTLS{Domains: []string{"api.openai.com"}},
modal.OutboundRouteAny{Redirect: modal.OutboundBlock{}},
},
})
// Or block all outbound traffic.
err = sb.SetOutboundPolicy(ctx, &modal.OutboundPolicy{
Routes: []modal.OutboundRoute{modal.OutboundRouteAny{Redirect: modal.OutboundBlock{}}},
})
// Allow all outbound traffic again.
err = sb.SetOutboundPolicy(ctx, &modal.OutboundPolicy{
Routes: []modal.OutboundRoute{modal.OutboundRouteAny{}},
})Combining with other Sandbox options
block_network=Truecan’t be used with Outbound Policies. A policy of onlyOutboundRoute.any().block()also blocks all outgoing traffic (though inbound is unaffected), and can later be updated.inbound_cidr_allowlistis unaffected by any Outbound Policy.outbound_cidr_allowlist,outbound_domain_allowlistand_experimental_outbound_policyare replaced byoutbound_policy. See the migration guide.- Modal Proxies apply to traffic after it has been allowed by the Outbound Policy.
proxy_traffic_via_sidecaralso applies to outbound traffic on port 443, and is disallowed withallow_tls_decryption=True(required for HTTPS routes). For Outbound Policies without HTTPS routes, the traffic is redirected to the proxy sidecar after it has been allowed by the Outbound Policy.
Limitations
- Limits across one
OutboundPolicy: 100 total routes, of which 32 IP routes. One Outbound Policy HTTPS route can contain up to 25 header values. One policy can access a maximum of 25 Secrets across all its header replacements. - A Sandbox with
allow_tls_decryption=Trueor where Outbound Policy has been updated can no longer have its memory state captured with a memory snapshot. - Sidecars still use the
outbound_cidr_allowlistandoutbound_domain_allowlistoptions, for now. - For HTTPS routes, there is no way to manage or add to the trust store used for upstream requests.
- Only the first matching HTTPS route applies its header replacements, if two routes cover the same domain.
- Only named Secrets are allowed in header replacements;
Secret.from_dictand other ephemeral Secrets are rejected. - Secret values in header replacements are resolved at creation and on each
set_outbound_policycall; a running Sandbox will not pick up later changes to the Secret.