Sub topic 7
Controlling network access and egress
This chapter assumes you can run Docker containers, read a Compose file, and know what a TCP connection and a DNS lookup are. It also assumes you have read the earlier chapters on container hardening and filesystem scoping. Here you decide what an agent running in a sandbox can reach over the network.
Why egress matters
Egress is traffic that leaves your sandbox. A hardened container with a read-only root filesystem and no capabilities can still do damage if it can open a connection to the internet. Three things can go wrong:
- Exfiltration. The agent reads your project files, including any secret that ended up in them, and sends them to a server an attacker controls. A prompt injection hidden in a README or web page can trigger this.
- Payload download. The agent fetches and runs code from an arbitrary host, which defeats the review you did of the agent's own actions.
- Lateral movement. The agent reaches services you never meant to expose: a database on the host, other containers, or the cloud metadata service at
169.254.169.254, which hands out instance credentials.
Network control is the layer that limits the damage when the agent's decisions go wrong. File and process limits do not do this.
The options, from strict to loose
| Mode | What the agent can reach | Typical use |
|---|---|---|
| `--network none` | Only the loopback interface inside the container | Running tests, linters, and code that needs no packages |
| Internal network | Other containers on the same network, nothing external | Agent plus a local database or a proxy |
| Internal network plus allowlist proxy | Only the hostnames the proxy permits | Agents that must install packages or call one API |
| Default bridge | The whole internet and the host's other interfaces | Avoid for untrusted agent work |
Start with none and loosen only when a real task fails. Each step down the table adds a path an attacker could use.
Mode 1: no network
The simplest control is --network none, which you saw in the hardened container example. The container gets a loopback interface and nothing else. Any pip install, git clone, or API call fails immediately.
docker run --rm --network none python:3.12-slim \
python -c "import urllib.request as u; u.urlopen('https://example.com', timeout=3)"This prints a traceback ending in a name resolution or connection error. That failure is the result you want. If the agent's workflow can be prepared in advance (dependencies baked into the image, for example), prefer this mode.
Mode 2: internal networks
Docker can create a user-defined network marked internal. Containers on it can reach each other by name, but Docker does not attach a route to the outside world.
docker network create --internal agent-net
docker run --rm -it --network agent-net python:3.12-slim bashThis is useful when the agent needs a helper service, such as a test database, but must not call out. Note that an internal network does not isolate the agent from the other containers on it. Put only the containers the agent should talk to on that network.
Mode 3: an allowlist proxy
Many agents need a small set of outside hosts, for example a package index. Opening the whole internet for that is too much. The standard pattern uses two networks and a proxy:
- The agent sits only on an internal network.
- A proxy container sits on both the internal network and an ordinary network with internet access.
- The proxy forwards a request only if the destination hostname is on an allowlist.
Here is a working setup using Squid. First, the proxy configuration, saved as squid.conf:
http_port 3128
acl allowed_domains dstdomain .pypi.org .pythonhosted.org
acl SSL_ports port 443
acl Safe_ports port 80 443
acl CONNECT method CONNECT
http_access deny !Safe_ports
http_access deny CONNECT !SSL_ports
http_access allow allowed_domains
http_access deny allThe leading dot in .pypi.org matches the domain and all of its subdomains. Squid evaluates http_access rules in order and stops at the first match, so the final deny all makes the list a true allowlist.
Now the Compose file:
services:
proxy:
image: ubuntu/squid:latest
volumes:
- ./squid.conf:/etc/squid/squid.conf:ro
networks:
- sandbox
- egress
agent:
image: python:3.12-slim
user: "1000:1000"
working_dir: /workspace
command: ["sleep", "infinity"]
read_only: true
tmpfs:
- /tmp
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
pids_limit: 256
mem_limit: 2g
volumes:
- ./project:/workspace
environment:
HTTP_PROXY: http://proxy:3128
HTTPS_PROXY: http://proxy:3128
NO_PROXY: proxy
networks:
- sandbox
networks:
sandbox:
internal: true
egress: {}The proxy variables only tell well-behaved tools where to send traffic. They are not the security control. The security control is that the sandbox network is internal, so a program that ignores the variables simply cannot connect.
Test the boundary
Never assume a network policy works. Save this as project/check_egress.py and run it inside the agent container:
import socket
import urllib.request
def direct_connect(host: str, port: int) -> bool:
try:
with socket.create_connection((host, port), timeout=3):
return True
except OSError:
return False
def via_proxy(url: str) -> str:
# urllib reads HTTP_PROXY and HTTPS_PROXY from the environment.
try:
with urllib.request.urlopen(url, timeout=10) as response:
return f"allowed ({response.status})"
except Exception as exc:
return f"blocked ({exc})"
print("direct to 1.1.1.1:443:", "REACHABLE" if direct_connect("1.1.1.1", 443) else "blocked")
print("pypi.org via proxy: ", via_proxy("https://pypi.org/simple/"))
print("example.com via proxy:", via_proxy("https://example.com/"))Run it with docker compose exec agent python check_egress.py. The expected result is that the direct connection is blocked, PyPI is allowed, and example.com is blocked with a 403 error from the proxy. If the direct connection says REACHABLE, your agent is on the wrong network.
Gotchas and common errors
DNS is a data channel
Even with no HTTP access, a container that can resolve names can leak data by encoding it in lookups, such as c2VjcmV0.attacker.example. The resolver forwards the query to the attacker's DNS server. On an internal Docker network, the embedded resolver only answers for container names in this setup, but if you point the container at an external resolver with --dns, you reopen the channel. Do not give an isolated agent a general-purpose resolver.
Allowlisting a domain trusts everything on it
Allowing github.com lets the agent read any public repository and also push to any repository for which it finds a token. Allowing a cloud storage domain can allow uploads to an attacker's bucket on the same domain. Prefer narrow hostnames and read-only access, and avoid broad shared-hosting domains.
Host and metadata access
From a default container, host.docker.internal (where configured) and the bridge gateway address reach services bound on the host. The cloud metadata address 169.254.169.254 is a separate concern. If you must run the agent on a cloud VM with a default bridge, block it on the host:
sudo iptables -I DOCKER-USER -d 169.254.169.254 -j DROPAn internal network avoids the problem, because the route does not exist.
HTTPS hides the path
A forward proxy that does not decrypt traffic sees only the hostname in the CONNECT request, not the URL or body. You can allow or deny by host, but you cannot filter by path or inspect uploads. Decrypting traffic requires installing a custom certificate authority in the container, which adds its own risk and is rarely worth it for this purpose.
Package installs can run code
An allowlisted package index is not harmless. Installing a package can execute arbitrary build scripts, and a malicious or typosquatted package gets the same permissions as the agent. Pin versions, use a lockfile, or pre-build the image and drop the network afterward.
A practical decision procedure
- Try the task with
--network none. If it passes, stop. - If it fails because of dependencies, bake them into the image or install them in a separate, supervised step, then return to step 1.
- If the agent needs a local service, use an internal network and attach only that service.
- If the agent needs specific external hosts, add the allowlist proxy and list the narrowest hostnames that work.
- Run the egress test script after every change to the network layout.
Exercise
In the Compose file, the agent has HTTPPROXY and HTTPSPROXY set, and the sandbox network is internal. A tool inside the agent container ignores the proxy variables and tries to connect directly to an external IP address. What happens, and which setting is responsible for that outcome?
Show answer
The connection fails because there is no route out of the internal network. The internal: true setting on the sandbox network is responsible. The proxy variables are only a convenience for tools that honor them. The agent can reach the outside only through the proxy, because the proxy is the one container that also sits on the egress network.
Exercise
You add .github.com to the proxy allowlist so the agent can clone one public repository. Name one risk this creates and one way to reduce it.
Show answer
The allowlist now permits traffic to every GitHub subdomain and repository, so an agent steered by a prompt injection could push data to an attacker's repository if it finds a token, or fetch code you did not intend. To reduce the risk, allow only the narrowest hostname that works, keep tokens out of the sandbox, or clone the repository outside the sandbox and mount it read-only instead of allowing GitHub at all.