TExcelTAD
Home › Programming for Security: Python, Bash, PowerShell & C Tools › Project: A Logging HTTP Proxy for Local Testing

Project: A Logging HTTP Proxy for Local Testing

When you test a web application you own, you want to see every request your browser or client sends and every response it gets: the exact headers, cookies, redirects and bodies. Intercepting proxies such as Burp Suite and OWASP ZAP do this (they appear as lab sessions in Web Application Security), and writing a tiny one yourself is the best way to understand what they do and what can go wrong with them. A proxy is also a security-sensitive program in its own right: one that forwards anything to anywhere is an open proxy, and attackers use those to hide their origin or to reach internal services.

This project builds a logging forward proxy that listens on 127.0.0.1, forwards only to an allowlisted upstream, and writes a JSON log with secrets redacted. Everything runs in your sandbox: a client (curl), the proxy and a lab web server (python3 -m http.server), all on loopback.

curl -xclient proxy127.0.0.1:8080allowlist + log lab server127.0.0.1:8000 other host: 403 proxy.log (JSON lines) requestforwarded

Definitions

  • Forward proxy: the client sends the whole URL in the request line (GET http://127.0.0.1:8000/hello.txt HTTP/1.1, the "absolute form" of RFC 9112) and the proxy makes the request on its behalf. curl -x http://127.0.0.1:8080 uses one.
  • Hop-by-hop headers: Connection, Keep-Alive, Proxy-Authorization, Proxy-Connection, TE, Trailer, Transfer-Encoding, Upgrade belong to one connection and must not be forwarded (RFC 9110 §7.6.1).
  • Open proxy: a proxy that forwards to any destination for any client. Upstream allowlist: the set of destinations the proxy may reach.
  • CONNECT: the method a client uses to tunnel HTTPS through a proxy; an intercepting proxy then needs its own CA certificate trusted by the client. This project refuses CONNECT and handles plain HTTP only.

The proxy

bash · try it yourself
mkdir -p site && printf 'hello from the lab server\n' > site/hello.txt
python3 -m http.server 8000 --bind 127.0.0.1 --directory site >upstream.log 2>&1 &

cat > proxy.py <<'PY'
import json, urllib.error, urllib.parse, urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

ALLOWED = {("127.0.0.1", 8000)}            # the only upstream this proxy may reach
HOP = {"connection", "keep-alive", "proxy-authorization", "proxy-connection",
       "te", "trailer", "transfer-encoding", "upgrade"}
REDACT = {"authorization", "cookie", "set-cookie"}
MAX_BODY = 64 * 1024
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))   # ignore *_proxy env vars

def log(entry):
    with open("proxy.log", "a") as f:
        f.write(json.dumps(entry, sort_keys=True) + "\n")

def redacted(headers):
    return {k: ("<redacted>" if k.lower() in REDACT else v) for k, v in headers.items()}

class Proxy(BaseHTTPRequestHandler):
    def log_message(self, *args):          # silence the default stderr log; we write our own
        pass

    def refuse(self, code, why):
        log({"method": self.command, "url": self.path, "status": code, "refused": why})
        self.send_response(code)
        self.send_header("Content-Length", "0")
        self.end_headers()

    def do_CONNECT(self):
        self.refuse(405, "CONNECT tunnels not supported")

    def do_GET(self):
        self.forward()

    def do_POST(self):
        self.forward()

    def forward(self):
        u = urllib.parse.urlsplit(self.path)
        if u.scheme != "http" or (u.hostname, u.port or 80) not in ALLOWED:
            return self.refuse(403, "destination not in allowlist")
        length = int(self.headers.get("Content-Length") or 0)
        if length > MAX_BODY:
            return self.refuse(413, "body too large")
        body = self.rfile.read(length) if length else None
        fwd = {k: v for k, v in self.headers.items() if k.lower() not in HOP}
        req = urllib.request.Request(self.path, data=body, headers=fwd, method=self.command)
        try:
            with opener.open(req, timeout=5) as r:
                status, data, rh = r.status, r.read(), r.headers
        except urllib.error.HTTPError as e:
            status, data, rh = e.code, e.read(), e.headers
        self.send_response(status)
        for k, v in rh.items():
            if k.lower() not in HOP | {"content-length", "date", "server"}:
                self.send_header(k, v)
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)
        log({"method": self.command, "url": self.path, "status": status, "bytes": len(data),
             "req_headers": redacted({k: v for k, v in fwd.items() if k.lower() != "user-agent"})})

ThreadingHTTPServer(("127.0.0.1", 8080), Proxy).serve_forever()
PY
python3 proxy.py &
for i in $(seq 50); do curl -s -o /dev/null http://127.0.0.1:8000/ && curl -s -o /dev/null -x http://127.0.0.1:8080 http://127.0.0.1:8000/ && break; sleep 0.1; done
: > proxy.log

P=(-s -x http://127.0.0.1:8080 -w '[%{http_code}]\n')
curl "${P[@]}" http://127.0.0.1:8000/hello.txt
curl "${P[@]}" -H 'Authorization: Bearer lab-token-123' -H 'Cookie: sid=lab-session' http://127.0.0.1:8000/hello.txt
curl "${P[@]}" -o /dev/null http://127.0.0.1:8000/missing.txt
curl "${P[@]}" http://192.0.2.10/admin
curl "${P[@]}" http://127.0.0.1:22/
curl -s -o /dev/null -w '[%{http_connect}] via CONNECT\n' -p -x http://127.0.0.1:8080 http://127.0.0.1:8000/ || true
echo "== proxy.log"
cat proxy.log
echo "== upstream saw"
grep -E '"GET /[a-z]' upstream.log | sed -E 's/^.*"(GET [^"]*)" ([0-9]+).*/\1 -> \2/'
kill %1 %2
hello from the lab server
[200]
hello from the lab server
[200]
[404]
[403]
[403]
[405] via CONNECT
== proxy.log
{"bytes": 26, "method": "GET", "req_headers": {"Accept": "*/*", "Host": "127.0.0.1:8000"}, "status": 200, "url": "http://127.0.0.1:8000/hello.txt"}
{"bytes": 26, "method": "GET", "req_headers": {"Accept": "*/*", "Authorization": "<redacted>", "Cookie": "<redacted>", "Host": "127.0.0.1:8000"}, "status": 200, "url": "http://127.0.0.1:8000/hello.txt"}
{"bytes": 335, "method": "GET", "req_headers": {"Accept": "*/*", "Host": "127.0.0.1:8000"}, "status": 404, "url": "http://127.0.0.1:8000/missing.txt"}
{"method": "GET", "refused": "destination not in allowlist", "status": 403, "url": "http://192.0.2.10/admin"}
{"method": "GET", "refused": "destination not in allowlist", "status": 403, "url": "http://127.0.0.1:22/"}
{"method": "CONNECT", "refused": "CONNECT tunnels not supported", "status": 405, "url": "127.0.0.1:8000"}
== upstream saw
GET /hello.txt HTTP/1.1 -> 200
GET /hello.txt HTTP/1.1 -> 200
GET /missing.txt HTTP/1.1 -> 404

Read the log against the requests. The two allowed requests and the 404 were forwarded and logged with their headers, and the Authorization and Cookie values were replaced by <redacted>, so the log can be shared with a colleague without leaking a session. The request to 192.0.2.10 and the one to port 22 on loopback were refused with 403 before any connection was attempted, because neither destination is on the allowlist; the upstream server's own log confirms it saw only the three allowed requests. The CONNECT tunnel (curl -p) was refused with 405.

Why the allowlist matters (detection)

An open proxy on a server inside a network is a door: anyone who can reach it can make requests from that server, to internal admin panels, cloud metadata services (169.254.169.254) or other hosts that trust the server's address. This is the same mechanism as server-side request forgery (SSRF), and both are found the same way:

  • Test the proxy as an attacker would, in your lab: absolute URLs to other hosts and ports, localhost spelled differently (127.1, [::1], 0x7f000001), redirects from the allowed upstream to a forbidden one.
  • Look for unexpected destinations in proxy logs and egress firewall logs: a proxy that suddenly talks to 169.254.169.254 or to port 22 is being abused.
  • Scan for listening proxies on your own hosts (ss -tlnp; a process bound to 0.0.0.0:8080 that answers absolute-form requests).

How to keep a proxy safe (prevention)

  1. Bind to 127.0.0.1, never 0.0.0.0, for a testing proxy.
  2. Allowlist destinations by parsed host and port, and compare the address the connection actually uses. Don't follow redirects to other destinations (urllib follows redirects by default; this proxy only talks to one host, so a redirect elsewhere would still be blocked when the client requests the new URL through the proxy).
  3. Strip hop-by-hop headers and refuse CONNECT unless you implement interception deliberately.
  4. Limit body sizes and set timeouts, so the proxy can't be used to exhaust memory or hold connections.
  5. Redact secrets in logs, protect the log file, and delete it after testing.

Pitfalls

  • Inheriting http_proxy: urllib honours the environment's proxy variables; without ProxyHandler({}) the proxy might forward through another proxy, or to itself.
  • Host-header confusion: the request line and the Host header may disagree. Decide which one you route on (here: the URL) and log both.
  • HTTP/1.1 keep-alive and chunked bodies are not handled by this teaching proxy; real proxies are much larger for a reason. Use mitmproxy, ZAP or Burp for real work.

Practice

1. Add a rule that refuses requests whose URL host is a name rather than an address. Why might that be wise for a testing proxy?

Check ipaddress.ip_address(u.hostname) in a try; on ValueError, refuse with 403. Names can resolve to different addresses over time (DNS rebinding), so an allowlist of addresses is only reliable if the proxy never resolves names itself.

2. The proxy logs req_headers without User-Agent. Why was it removed here, and would you remove it in a real test log?

Here it was dropped so the recorded output does not depend on the curl version. In a real test log keep it: the client identity is useful evidence.

3. An attacker sends GET http://127.0.0.1:8000@192.0.2.10/ HTTP/1.1. Which host does urlsplit return, and is the request allowed?

urlsplit treats 127.0.0.1:8000 as user-info and returns hostname 192.0.2.10, so the allowlist refuses it. A proxy that checked the URL with a naive string test such as startswith("http://127.0.0.1:8000") would have let it through. Always check the parsed components.

Test yourself

What makes a proxy an "open proxy"?

  1. It uses HTTP
  2. It forwards requests to any destination for any client
  3. It logs requests
  4. It listens on 127.0.0.1

Why did the request to 192.0.2.10 never leave the sandbox?

  1. curl blocked it
  2. The proxy refused it with 403 because the destination is not on the allowlist, before connecting
  3. The lab server refused it
  4. DNS failed

Which header is hop-by-hop and must not be forwarded?

  1. Authorization
  2. Content-Type
  3. Connection
  4. Accept

Why does the log show <redacted> for the Cookie header?

  1. Cookies are always empty
  2. So the log can be shared without leaking a live session
  3. urllib removes cookies
  4. The server sent no cookie