DEV Community

Alessio
Alessio

Posted on Originally published at py-forge.com

How to Find Docker Ports That Bypass Your Host Firewall

When you publish a container port, the engine inserts its own packet-filter rules ahead of the host firewall. A bind that looks locked down in UFW or firewalld can still be reachable from the network. The usual surprises are a Compose file that publishes 5432:5432 on every interface, a service running with network_mode: host, or an IPv4 bind of 127.0.0.1 sitting next to an IPv6 wildcard ::.

PortExpose is a single-file Python auditor for that gap. It reads Compose files and docker inspect JSON, classifies each published binding, and prints a report. It does not change firewall rules and it does not talk to a running daemon on its own.


Install & Usage

The script uses only the Python standard library (argparse, ipaddress, json, re, subprocess, unittest, and related modules). Python 3.8 or newer is enough. There is nothing to install with pip.

Save the file locally as portexpose_docker_firewall_auditor.py.

List the real flags:

python portexpose_docker_firewall_auditor.py --help
Enter fullscreen mode Exit fullscreen mode

Run the built-in checks (IP classification, short-syntax port ranges, and bracketed IPv6 bindings):

python portexpose_docker_firewall_auditor.py --self-test
Enter fullscreen mode Exit fullscreen mode

A passing run exits 0. A failure exits 1.

Audit one or more Compose files

Pass -f / --compose-file once, or several times. Multiple files are merged in order, the same way a base Compose file and an override file are combined: mappings merge recursively, and later values replace earlier ones for the same key.

python portexpose_docker_firewall_auditor.py -f docker-compose.yml -f docker-compose.override.yml
Enter fullscreen mode Exit fullscreen mode

Add --json when you want a structured findings array instead of the text report.

Audit live bindings from inspect JSON

The tool does not call the engine for you. You export inspect JSON and pass it with -i / --inspect-json. Use - to read stdin:

python portexpose_docker_firewall_auditor.py --inspect-json inspect.json
Enter fullscreen mode Exit fullscreen mode
docker inspect $(docker ps -q) | python portexpose_docker_firewall_auditor.py --inspect-json -
Enter fullscreen mode Exit fullscreen mode

A malformed JSON file or a read error prints a message to stderr and exits 1. A successful audit exits 0 even when the report contains CRITICAL or HIGH rows, so treat the report contents as the result, not the process status.


How It Works

Parsing published ports, including ranges and IPv6

parse_port_entry accepts both Compose forms: the short string ("5432:5432", "127.0.0.1:5432:5432", "8000-8002:8000-8002/tcp", "[::]:5432:5432") and the long mapping (published, target, host_ip, protocol, mode). A host port range is expanded to one record per port. A lone value such as "5432" is treated as published on all interfaces, using that port as the host port for the audit.

Bracketed IPv6 addresses are stripped out before the remaining host:port pieces are read, which is what makes [::]:5432:5432 and [::1]:8080:80 parse correctly:

    # Bracketed IPv6 host IP, e.g. "[::]:5432:5432" or "[::1]:8080:80"
    if elem_str.startswith("["):
        close = elem_str.find("]")
        if close == -1:
            return []
        host_ip = elem_str[1:close]
        rest = elem_str[close + 1:].lstrip(":")
        parts = ["__ip__"] + rest.split(":")
Enter fullscreen mode Exit fullscreen mode

Services with network_mode: host never get a single published port. They are recorded as sharing the host network stack on 0.0.0.0, with protocol all.

Classifying exposure

Each binding goes through classify_binding_risk, which returns CRITICAL, HIGH, MEDIUM, LOW, or SAFE:

    if dual_stack_leak:
        severity = "CRITICAL"
        description = f"Dual-stack IPv6 wildcard leak: IPv4 is restricted but IPv6 is exposed on port {host_port} ({service_label})"
    elif host_mode:
        severity = "HIGH"
        description = "Service runs in network_mode: host (bypasses Docker NAT entirely, exposes all listening sockets)"
    elif is_wildcard_binding(host_ip):
        if is_sensitive:
            severity = "CRITICAL"
            description = f"Sensitive service ({service_label}) exposed publicly on wildcard {host_ip}:{host_port}"
        else:
            severity = "HIGH"
            description = f"Port {host_port} exposed publicly on wildcard {host_ip}"
    elif is_loopback_binding(host_ip):
        severity = "SAFE"
        description = f"Bound strictly to loopback {host_ip}:{host_port}"
    elif is_private_or_vpn(host_ip):
        severity = "LOW"
        description = f"Bound to private/VPN interface {host_ip}:{host_port}"
    else:
        severity = "HIGH" if is_sensitive else "MEDIUM"
        description = f"Bound to specific external IP {host_ip}:{host_port}"
Enter fullscreen mode Exit fullscreen mode

A few details that matter in practice:

  • Wildcard means IPv4 0.0.0.0, IPv6 ::, *, or an empty host IP. Those bindings are CRITICAL when the host port is in a built-in list of sensitive services (for example 5432 PostgreSQL, 3306 MySQL/MariaDB, 6379 Redis, 27017 MongoDB, 2375 unencrypted engine API, 9090 Prometheus, 3000 Grafana/Gitea), and HIGH otherwise.
  • Loopback (127.0.0.1, ::1, localhost) is SAFE.
  • RFC1918, IPv6 ULA (fc00::/7), and CGNAT 100.64.0.0/10 (often used by overlays such as WireGuard or Tailscale) are LOW. Documentation and benchmark ranges such as 192.0.2.0/24 and 2001:db8::/32 are not treated as private.
  • A bind to a specific non-private address is HIGH if the port is sensitive, otherwise MEDIUM.

The dual-stack leak in inspect JSON

When the input comes from docker inspect, PortExpose looks at every host binding for the same container port. If IPv4 is locked to 127.0.0.1 (or localhost) and IPv6 is published on ::, it flags a dual-stack leak and forces CRITICAL:

                is_dual_stack_leak = False
                note = ""
                if h_ip in ("::", "[::]") and has_ipv4_loopback:
                    is_dual_stack_leak = True
                    note = "CRITICAL: IPv4 is locked to 127.0.0.1 but IPv6 is exposed via wildcard ::"
Enter fullscreen mode Exit fullscreen mode

This is easy to miss in a dashboard that only shows the IPv4 bind.

The text report looks like this:

======================================================================
 PortExpose: Docker Firewall Auditor Report
======================================================================
[CRITICAL] postgres           -> 0.0.0.0:5432  | Sensitive service (PostgreSQL Database) exposed publicly on wildcard 0.0.0.0:5432
======================================================================
Enter fullscreen mode Exit fullscreen mode

Limitations

These limits are visible in the current code:

  • The Compose reader is a small standard-library YAML subset. It handles nested mappings, lists, scalars, and comments. It does not implement anchors, aliases, merge keys, or multiline block scalars, and it does not expand Compose ${VAR} interpolation.
  • The tool reads ports and network_mode. Compose expose: entries (container-only ports, not published on the host) are not treated as host bindings.
  • --check-iptables is declared on the command line, and inspect_docker_user_chain can parse iptables -S DOCKER-USER, but the entrypoint does not call that helper yet. Passing the flag alone does not add iptables findings to the report.
  • Helpers exist to read /etc/docker/daemon.json and to detect a rootless environment, but they are not used in the audit path, so those facts do not appear in the report.
  • The sensitive-port list is a fixed dictionary of well-known ports. An unusual port that happens to serve a database will be classified only by how it is bound, not by the process behind it.
  • A successful run always exits 0, including when findings are CRITICAL. Wire CI on the report (or the JSON) rather than on the exit status.

FAQ

Does this replace UFW, firewalld, or a review of DOCKER-USER?

No. It reports how Compose files and inspect JSON publish ports, and how risky each bind looks. It does not install rules and, in this version, it does not yet attach the DOCKER-USER inspector to the CLI.

Will a bind to 127.0.0.1 always be marked safe?

The IPv4 loopback bind itself is SAFE. If the same container port is also published on IPv6 ::, the inspect path flags a dual-stack leak and that IPv6 binding is CRITICAL.

Can I point it at a running daemon without a JSON file?

Not directly. Export inspect JSON first, or pipe it on stdin with --inspect-json -. For Compose, pass the files with --compose-file.


Full version and the rest of the toolkit: PortExpose Docker firewall auditor on PyForge. Product page: https://py-forge.com/products/portexpose-docker-firewall-auditor

Top comments (0)