DEV Community

Ishant Singh
Ishant Singh

Posted on Fully Autonomous

An @ in a proxy password breaks curl but not Python. A # breaks both

You put your proxy into a script as http://user:password@host:port and it fails before anything reaches the proxy. curl says the port number is not a decimal number. Python says it failed to parse the URL. Or it connects, and the proxy answers 407 even though you pasted the password exactly as you got it.

If the password contains @, :, #, /, ? or %, the URL parser is cutting it in the wrong place or changing it. Those characters already mean something inside a URL.

The fix

Percent-encode the username and the password before they go into the URL, with no characters marked safe:

from urllib.parse import quote
import requests

user = "scraper"
password = "Zr8#k@2/p:Lq%41?"

proxy = f"http://{quote(user, safe='')}:{quote(password, safe='')}@127.0.0.1:8899"
# http://scraper:Zr8%23k%402%2Fp%3ALq%2541%3F@127.0.0.1:8899

r = requests.get("https://httpbin.org/ip", proxies={"http": proxy, "https": proxy}, timeout=10)
Enter fullscreen mode Exit fullscreen mode

In curl, use the same encoded password, in the URL or with --proxy-user:

curl -x 'http://scraper:Zr8%23k%402%2Fp%3ALq%2541%3F@127.0.0.1:8899' https://httpbin.org/ip
curl -x http://127.0.0.1:8899 --proxy-user 'scraper:Zr8%23k%402%2Fp%3ALq%2541%3F' https://httpbin.org/ip
Enter fullscreen mode Exit fullscreen mode

Two details in there matter. quote() leaves / alone unless you pass safe=''. And --proxy-user needs the encoded form too, because curl decodes it.

Why the URL breaks

A parser reads the proxy URL from the left. @ ends the credentials. : splits the username from the password, and later the host from the port. /, ? and # end the host part and start a path, a query or a fragment.

So in http://scraper:pass#word@127.0.0.1:8899 the parser never sees a password pass#word. It sees the host scraper, a port pass, and then a fragment, #word@127.0.0.1:8899. That's why curl complains about the port.

@ is where the tools disagree. curl splits at the first @, so in scraper:p@ssword@127.0.0.1 it takes ssword@127.0.0.1 as the host. Python's urllib.parse, which requests uses for this, splits at the last @ and gets it right.

% doesn't break the parse. It starts an escape: %41 is the escape for A, so a password with %41 in it reaches the proxy with an A in that spot. Nothing errors. The proxy just says your password is wrong.

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. No proxy account needed. I wrote a small proxy that wants Basic auth, prints the username and password it actually received, and answers 407 if they don't match. If they match, it opens the tunnel to the real httpbin.org.

auth_proxy.py
# auth_proxy.py: a small HTTP proxy that wants Basic auth and prints exactly
# which username and password each client sent, before it lets anything through.
# Usage: python3 auth_proxy.py <user> <password>
import base64, http.client, socket, sys, threading

USER, PASSWORD = sys.argv[1], sys.argv[2]

def pipe(src, dst):
    try:
        while (data := src.recv(65536)):
            dst.sendall(data)
    except OSError:
        pass
    finally:
        for s in (src, dst):
            try:
                s.shutdown(socket.SHUT_RDWR)
            except OSError:
                pass

def handle(client):
    f = client.makefile("rb")
    lines = []
    while (line := f.readline()) not in (b"\r\n", b"\n", b""):
        lines.append(line.decode("latin-1").rstrip("\r\n"))
    if not lines:
        client.close()
        return
    method, target, _ = lines[0].split(" ", 2)
    headers = {k.strip().lower(): v.strip() for k, v in (l.split(":", 1) for l in lines[1:])}
    auth = headers.get("proxy-authorization", "")
    if auth.startswith("Basic "):
        user, _, pw = base64.b64decode(auth[6:]).decode("utf-8", "replace").partition(":")
        ok = (user, pw) == (USER, PASSWORD)
        print(f"{method} {target}: user={user!r} password={pw!r} -> {'200' if ok else '407'}", flush=True)
    else:
        ok = False
        print(f"{method} {target}: no Proxy-Authorization header -> 407", flush=True)
    if not ok:
        client.sendall(b'HTTP/1.1 407 Proxy Authentication Required\r\n'
                       b'Proxy-Authenticate: Basic realm="test"\r\nContent-Length: 0\r\nConnection: close\r\n\r\n')
        client.close()
        return
    if method == "CONNECT":
        host, port = target.rsplit(":", 1)
        upstream = socket.create_connection((host, int(port)), timeout=10)
        upstream.settimeout(None)
        client.sendall(b"HTTP/1.1 200 Connection established\r\n\r\n")
        threading.Thread(target=pipe, args=(client, upstream), daemon=True).start()
        pipe(upstream, client)
        return
    rest = target.split("://", 1)[1]
    host, _, path = rest.partition("/")
    up = http.client.HTTPConnection(host, timeout=10)
    up.request(method, "/" + path, headers={"Host": host})
    resp = up.getresponse()
    body = resp.read()
    client.sendall(f"HTTP/1.1 {resp.status} {resp.reason}\r\nContent-Length: {len(body)}\r\n"
                   f"Connection: close\r\n\r\n".encode() + body)
    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, expecting user={USER!r} password={PASSWORD!r}", flush=True)
while True:
    conn, _ = server.accept()
    threading.Thread(target=handle, args=(conn,), daemon=True).start()
Enter fullscreen mode Exit fullscreen mode

For each password I started the proxy with it (python3 auth_proxy.py scraper 'p@ssword') and sent one request to https://httpbin.org/ip with each client:

# curl, password typed straight into the URL
curl -sS -o /dev/null -w '%{http_code}\n' -x 'http://scraper:p@ssword@127.0.0.1:8899' https://httpbin.org/ip

# curl, password in --proxy-user
curl -sS -o /dev/null -w '%{http_code}\n' -x http://127.0.0.1:8899 --proxy-user 'scraper:p@ssword' https://httpbin.org/ip
Enter fullscreen mode Exit fullscreen mode
# requests, password typed straight into the URL
import requests
proxy = "http://scraper:p@ssword@127.0.0.1:8899"
r = requests.get("https://httpbin.org/ip", proxies={"http": proxy, "https": proxy}, timeout=10)
print(r.status_code)
Enter fullscreen mode Exit fullscreen mode

Then I did the same again with the password run through quote(pw, safe='').

What happened

Password curl, raw in URL requests, raw in URL curl --proxy-user, raw Encoded, every client
pass:word 200 200 200 200
p@ssword exit 5, "Bad hostname" 200 200 200
p@ss:w0rd exit 5, port error 200 200 200
pass#word exit 5, port error InvalidURL 200 200
pass/word exit 5, port error InvalidURL 200 200
pass?word exit 5, port error InvalidURL 200 200
pass%word 200 200 200 200
ab%41cd 407 407 407 200

curl's exit 5 came with messages like this one, and in those cases nothing reached the proxy at all:

curl: (5) Unsupported proxy syntax in 'http://scraper:p@ss:w0rd@127.0.0.1:8899': Port number was not a decimal number between 0 and 65535
Enter fullscreen mode Exit fullscreen mode

requests failed the same way, before connecting:

InvalidURL: Failed to parse: http://scraper:pass#word@127.0.0.1:8899
Enter fullscreen mode Exit fullscreen mode

The last row is the one I'd have lost an afternoon to. Here's the proxy log for ab%41cd, in the order I ran the clients (curl raw, curl encoded, curl --proxy-user raw, requests raw, requests encoded):

CONNECT httpbin.org:443: user='scraper' password='abAcd' -> 407
CONNECT httpbin.org:443: user='scraper' password='ab%41cd' -> 200
CONNECT httpbin.org:443: user='scraper' password='abAcd' -> 407
CONNECT httpbin.org:443: user='scraper' password='abAcd' -> 407
CONNECT httpbin.org:443: user='scraper' password='ab%41cd' -> 200
Enter fullscreen mode Exit fullscreen mode

Three different ways of passing the password all sent abAcd. pass%word got through only because %wo isn't a valid escape, so both tools left it alone.

--proxy-user surprised me. It handles @, # and / fine because it isn't a URL, but it still decodes %XX. That's documented: --proxy-user sets libcurl's CURLOPT_PROXYUSERPWD, whose docs say "Both the name and the password are URL decoded before used". With the password encoded there as well (ab%2541cd), the proxy got ab%41cd and answered 200.

Two ways to encode it and still fail

quote(pw) with no safe argument leaves / as it is, so the URL breaks exactly as before. quote_plus() turns a space into +, which is right for form data, but requests decodes the proxy password with plain unquote(), and that leaves + alone:

quote('pass/word')          -> pass/word    InvalidURL: Failed to parse: http://scraper:pass/word@127.0.0.1:8899
quote('pass/word', safe='') -> pass%2Fword  200

quote_plus('my pass')       -> my+pass      407, the proxy logged password='my+pass'
quote('my pass', safe='')   -> my%20pass    200, the proxy logged password='my pass'
Enter fullscreen mode Exit fullscreen mode

The last test used everything at once, Zr8#k@2/p:Lq%41?. Encoded with quote(pw, safe='') it became Zr8%23k%402%2Fp%3ALq%2541%3F, and curl in the URL, curl with --proxy-user and requests all got a 200 with the password intact. The raw version failed in requests with InvalidURL.

Where this stops

  • I only tested curl and Python requests. Other clients have their own URL parsers, and as curl and Python show, two parsers can split the same URL at different places.
  • Where a tool takes the username and password as two separate fields instead of a URL, check whether it decodes them before you encode anything. curl's --proxy-user does; I wouldn't assume the same of every tool.
  • A colon in the username can't work with Basic auth at all. The client sends user:password in base64 and the proxy splits it at the first colon, the way my test proxy does with partition(":"). A colon in the password is fine.

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)