DEV Community

Ishant Singh
Ishant Singh

Posted on Fully Autonomous

Can your proxy read your passwords? I logged what it gets for http:// and https://

If your scraper or your login script goes through a proxy someone else runs, that proxy sits in the middle of every request. So can it read the password you post, the API token in your header, the session cookie?

For https:// URLs, a normal HTTP proxy can't. It gets the host name and port, sometimes your client's User-Agent, and a count of encrypted bytes. For http:// URLs it gets all of it in plain text. And I found two ways an https:// setup still hands it everything.

What my test proxy logged

I put four fake secrets into one request: a password in a form body, a bearer token, a session cookie and an api_key in the query string. Then I sent it through a small logging proxy and checked whether any of the four strings showed up in the bytes the proxy received, encrypted tunnel bytes included.

Request What the proxy logged Secrets it saw
http:// POST Full URL, every header, the body 4 of 4
https:// POST CONNECT httpbin.org:443, the SNI, byte counts 0 of 4
http:// URL that redirects to https:// The first request in full token and cookie
https:// with verification off, through a proxy that intercepts TLS Full URL, every header, the body 4 of 4
https:// with verification on, same intercepting proxy The CONNECT line, then the client refused its certificate and sent nothing 0 of 4

curl and Python requests gave the same answer in every row.

Why https:// hides it

For an https:// URL the client doesn't send its request to the proxy. It sends CONNECT httpbin.org:443, the proxy opens a TCP connection to that host, and from then on it just copies bytes both ways. The TLS handshake happens between your client and the site, through that tunnel. The path, the query string, the headers, the cookies and the body are all inside TLS.

For an http:// URL there's nothing to decrypt. The client sends the whole request to the proxy, POST http://httpbin.org/post?api_key=... HTTP/1.1 and every header after it, because that's how plain HTTP proxying works.

The test

I ran this on my Mac (macOS 26.7.1) with curl 8.7.1, Python 3.9.6, requests 2.32.5 and urllib3 2.6.3, against httpbin.org. No proxy account needed. The proxy prints every request line and header it can read. For tunnels it pulls the server name (SNI) out of the TLS ClientHello and counts the bytes. With --mitm it does what an intercepting proxy does and answers the TLS handshake itself, with a certificate signed by its own CA.

peek_proxy.py
# peek_proxy.py: an HTTP proxy that writes down everything it can read.
# Usage: python3 peek_proxy.py [--mitm]
# Each connection ends with one line: which of the SECRETS showed up in the
# bytes this proxy received from the client.
import http.client, os, socket, ssl, subprocess, sys, threading

SECRETS = ["hunter2", "tok_live_9f8e7d", "sess_4b3a21", "key_77aa"]
MITM = "--mitm" in sys.argv
lock = threading.Lock()

def log(conn_id, text):
    with lock:
        print(f"[{conn_id}] {text}", flush=True)

def read_head(f):
    lines = []
    while (line := f.readline()) not in (b"\r\n", b"\n", b""):
        lines.append(line.decode("latin-1").rstrip("\r\n"))
    return lines

def sni_from_client_hello(data):
    # TLS record (5 bytes) + handshake header (4) + version (2) + random (32)
    try:
        i = 5 + 4 + 2 + 32
        i += 1 + data[i]                                   # session id
        i += 2 + int.from_bytes(data[i:i + 2], "big")      # cipher suites
        i += 1 + data[i]                                   # compression
        end = i + 2 + int.from_bytes(data[i:i + 2], "big")
        i += 2
        while i < end:
            ext, size = int.from_bytes(data[i:i + 2], "big"), int.from_bytes(data[i + 2:i + 4], "big")
            if ext == 0:                                   # server_name
                n = int.from_bytes(data[i + 7:i + 9], "big")
                return data[i + 9:i + 9 + n].decode()
            i += 4 + size
    except (IndexError, UnicodeDecodeError):
        pass
    return None

def leaf_cert(host):
    # A certificate for `host`, signed by our own test CA (ca.key / ca.crt).
    crt, key = f"certs/{host}.crt", f"certs/{host}.key"
    if not os.path.exists(crt):
        os.makedirs("certs", exist_ok=True)
        subprocess.run(["openssl", "req", "-new", "-newkey", "rsa:2048", "-nodes", "-keyout", key,
                        "-subj", f"/CN={host}", "-out", f"certs/{host}.csr"], check=True, capture_output=True)
        with open(f"certs/{host}.ext", "w") as ext:
            ext.write(f"subjectAltName=DNS:{host}\n")
        subprocess.run(["openssl", "x509", "-req", "-in", f"certs/{host}.csr", "-CA", "ca.crt", "-CAkey", "ca.key",
                        "-CAcreateserial", "-days", "2", "-extfile", f"certs/{host}.ext", "-out", crt],
                       check=True, capture_output=True)
    return crt, key

def forward_http(conn_id, f, client, head, scheme, host):
    method, target, _ = head[0].split(" ", 2)
    headers = [tuple(x.strip() for x in l.split(":", 1)) for l in head[1:]]
    body = f.read(int(dict((k.lower(), v) for k, v in headers).get("content-length", 0)))
    log(conn_id, head[0])
    for k, v in headers:
        log(conn_id, f"  {k}: {v}")
    if body:
        log(conn_id, f"  body: {body.decode('latin-1')}")
    path = target if target.startswith("/") else "/" + target.split("://", 1)[1].partition("/")[2]
    if scheme == "https":
        up = http.client.HTTPSConnection(host, timeout=10)
    else:
        up = http.client.HTTPConnection(target.split("://", 1)[1].split("/", 1)[0], timeout=10)
    send = {k: v for k, v in headers if not k.lower().startswith("proxy-") and k.lower() != "connection"}
    up.request(method, path, body=body or None, headers=send)
    resp = up.getresponse()
    data = resp.read()
    extra = "".join(f"{k}: {v}\r\n" for k, v in resp.getheaders()
                    if k.lower() not in ("content-length", "connection", "transfer-encoding"))
    client.sendall(f"HTTP/1.1 {resp.status} {resp.reason}\r\n{extra}Content-Length: {len(data)}\r\n"
                   f"Connection: close\r\n\r\n".encode() + data)
    return " ".join(head).encode() + body

def handle(client, conn_id):
    f = client.makefile("rb")
    head = read_head(f)
    if not head:
        return client.close()
    seen = b""
    if not head[0].startswith("CONNECT "):
        seen = forward_http(conn_id, f, client, head, "http", None)
    else:
        target = head[0].split(" ")[1]
        host, port = target.rsplit(":", 1)
        log(conn_id, head[0])
        for line in head[1:]:
            log(conn_id, f"  {line}")
        seen = " ".join(head).encode()
        client.sendall(b"HTTP/1.1 200 Connection established\r\n\r\n")
        if MITM:
            ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
            ctx.load_cert_chain(*leaf_cert(host))
            try:
                tls = ctx.wrap_socket(client, server_side=True)
            except (ssl.SSLError, OSError) as e:
                log(conn_id, f"  client refused our certificate: {e.__class__.__name__}")
                return client.close()
            tf = tls.makefile("rb")
            inner = read_head(tf)
            seen += forward_http(conn_id, tf, tls, inner, "https", host)
            tls.close()
        else:
            upstream = socket.create_connection((host, int(port)), timeout=10)
            got = {"up": 0, "down": 0}
            def pipe(src, dst, key, keep):
                nonlocal seen
                try:
                    while (data := src.recv(65536)):
                        got[key] += len(data)
                        if keep:
                            seen += data
                        dst.sendall(data)
                except OSError:
                    pass
                finally:
                    for s in (src, dst):
                        try:
                            s.shutdown(socket.SHUT_RDWR)
                        except OSError:
                            pass
            t = threading.Thread(target=pipe, args=(upstream, client, "down", False))
            t.start()
            pipe(client, upstream, "up", True)
            t.join()
            log(conn_id, f"  tunnel: SNI={sni_from_client_hello(seen[len(' '.join(head)):])!r}, "
                         f"{got['up']} bytes up, {got['down']} bytes down, all of it TLS")
    found = [s for s in SECRETS if s.encode() in seen]
    log(conn_id, f"  SECRETS THE PROXY SAW: {found or 'none'}")
    client.close()

server = socket.socket()
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(("127.0.0.1", 8899))
server.listen()
print(f"listening on 127.0.0.1:8899{' (intercepting TLS)' if MITM else ''}", flush=True)
n = 0
while True:
    conn, _ = server.accept()
    n += 1
    threading.Thread(target=handle, args=(conn, n), daemon=True).start()
Enter fullscreen mode Exit fullscreen mode

The curl side:

python3 peek_proxy.py

curl -sS -o /dev/null -w '%{http_code}\n' -x http://127.0.0.1:8899 \
  -H 'Authorization: Bearer tok_live_9f8e7d' -b 'session=sess_4b3a21' \
  -d 'user=ishant&password=hunter2' 'http://httpbin.org/post?api_key=key_77aa'
# then the same command with https://httpbin.org/post?api_key=key_77aa
Enter fullscreen mode Exit fullscreen mode

The Python side, python3 clients.py http://httpbin.org/post https://httpbin.org/post:

# clients.py: the same login-style request through the proxy, as http:// and https://
import sys, requests

proxy = "http://127.0.0.1:8899"
proxies = {"http": proxy, "https": proxy}
verify = "--insecure" not in sys.argv

for url in sys.argv[1:]:
    if url.startswith("--"):
        continue
    try:
        r = requests.post(
            url,
            params={"api_key": "key_77aa"},
            data={"user": "ishant", "password": "hunter2"},
            headers={"Authorization": "Bearer tok_live_9f8e7d"},
            cookies={"session": "sess_4b3a21"},
            proxies=proxies, timeout=15, verify=verify,
        )
        print(url, "->", r.status_code)
    except requests.exceptions.SSLError as e:
        print(url, "->", "SSLError:", str(e)[:160])
Enter fullscreen mode Exit fullscreen mode

Here's what the proxy logged for curl, first http:// and then https://:

[1] POST http://httpbin.org/post?api_key=key_77aa HTTP/1.1
[1]   Host: httpbin.org
[1]   User-Agent: curl/8.7.1
[1]   Accept: */*
[1]   Proxy-Connection: Keep-Alive
[1]   Cookie: session=sess_4b3a21
[1]   Authorization: Bearer tok_live_9f8e7d
[1]   Content-Length: 28
[1]   Content-Type: application/x-www-form-urlencoded
[1]   body: user=ishant&password=hunter2
[1]   SECRETS THE PROXY SAW: ['hunter2', 'tok_live_9f8e7d', 'sess_4b3a21', 'key_77aa']
[2] CONNECT httpbin.org:443 HTTP/1.1
[2]   Host: httpbin.org:443
[2]   User-Agent: curl/8.7.1
[2]   Proxy-Connection: Keep-Alive
[2]   tunnel: SNI='httpbin.org', 706 bytes up, 4597 bytes down, all of it TLS
[2]   SECRETS THE PROXY SAW: none
Enter fullscreen mode Exit fullscreen mode

One small difference between the clients: curl puts its User-Agent on the CONNECT line, and if you set one with -A, the proxy gets that one. requests sent a bare CONNECT httpbin.org:443 HTTP/1.0 with no headers at all.

Leak 1: an http:// URL that redirects to https://

Lots of sites redirect http:// to https://, so an http:// URL in a config file keeps working and nobody notices. But the first request goes out before the redirect, in plain text, with your headers on it:

[8] GET http://httpbin.org/redirect-to?url=https%3A%2F%2Fhttpbin.org%2Fheaders HTTP/1.1
[8]   Host: httpbin.org
[8]   User-Agent: python-requests/2.32.5
[8]   Accept-Encoding: gzip, deflate
[8]   Accept: */*
[8]   Connection: keep-alive
[8]   Authorization: Bearer tok_live_9f8e7d
[8]   Cookie: session=sess_4b3a21
[8]   SECRETS THE PROXY SAW: ['tok_live_9f8e7d', 'sess_4b3a21']
[9] CONNECT httpbin.org:443 HTTP/1.0
[9]   tunnel: SNI='httpbin.org', 534 bytes up, 4302 bytes down, all of it TLS
[9]   SECRETS THE PROXY SAW: none
Enter fullscreen mode Exit fullscreen mode

The request ended in a 200 over https://, and requests kept the Authorization header on the second hop because it was the same host, so nothing looked wrong. curl with -L sent the token and cookie in plain text on that first hop as well. The fix is to write https:// yourself. To find out whether a URL was upgraded under you, check r.history in requests or %{num_redirects} in curl.

Leak 2: verify=False

Then I ran the proxy with --mitm. It answers the CONNECT with a 200, then does the TLS handshake with the client itself, using a certificate for httpbin.org that my own test CA signed (openssl req -x509 -new -newkey rsa:2048 -nodes -keyout ca.key -out ca.crt -days 2 -subj "/CN=peek test CA"). It reads the request and sends it on to the real site over its own TLS connection.

With certificate checks on, both clients refused, and nothing was sent:

curl: (60) SSL certificate problem: unable to get local issuer certificate
SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1129)'))
Enter fullscreen mode Exit fullscreen mode

With curl -k and verify=False, both got a normal 200 and the proxy logged everything. That's the part that bothered me: from the client's side, the run looked exactly like a good one.

[4] CONNECT httpbin.org:443 HTTP/1.0
[4] POST /post?api_key=key_77aa HTTP/1.1
[4]   Host: httpbin.org
[4]   User-Agent: python-requests/2.32.5
[4]   Accept-Encoding: gzip, deflate
[4]   Accept: */*
[4]   Connection: keep-alive
[4]   Authorization: Bearer tok_live_9f8e7d
[4]   Cookie: session=sess_4b3a21
[4]   Content-Length: 28
[4]   Content-Type: application/x-www-form-urlencoded
[4]   body: user=ishant&password=hunter2
[4]   SECRETS THE PROXY SAW: ['hunter2', 'tok_live_9f8e7d', 'sess_4b3a21', 'key_77aa']
Enter fullscreen mode Exit fullscreen mode

People add verify=False to make a certificate error go away. Through a proxy, that error can be the only sign that something in the middle is reading your traffic. If a proxy you trust really needs its own CA, as some company proxies do, pass that CA with verify="/path/to/ca.pem" or curl --cacert and leave verification on.

Where this stops

  • The proxy's own password is a different story. With an http:// proxy URL, the link from you to the proxy is plain TCP, and the login rides on it as base64. My proxy logged Proxy-Authorization: Basic c2NyYXBlcjpzM2NyZXQtcHJveHktcHc=, and base64 -d turns that into scraper:s3cret-proxy-pw. Anyone on the network between you and the proxy can read that, even though the site login in the same request stayed inside TLS.
  • The SNI was readable for both clients. Encrypted Client Hello would hide it, but neither client in my test used it.
  • Byte counts and timing are always visible. 706 bytes up and 4,597 down doesn't show what I sent, but the proxy still knows a request of about that size went to that host at that moment.
  • I tested an HTTP proxy only. A SOCKS5 proxy gets the destination in its own handshake instead of a CONNECT line; I didn't test that here.

I work on BuyProxy, a proxy service. None of the tests above used it; every request went through the small proxy in this post.

Top comments (0)