← 输入框|github.com|刷新
Skip to content

Add support for the PROXY protocol - #581

Merged
rofl0r merged 7 commits into
tinyproxy:masterfrom
Tey:client_proxy
Nov 11, 2026
Merged

rofl0r merged 7 commits into
tinyproxy:masterfrom
Tey:client_proxy

Conversation

@Tey

@Tey Tey commented Sep 21, 2025

Copy link
Copy Markdown
Contributor

When there is a proxy in front of tinyproxy, the latter does not see the actual IP address of the client. This is a problem when using tools like fail2ban that parse the tinyproxy log to find and ban clients that try to break the authentication using brute force. Some proxies like stunnel or HAProxy support the PROXY protocol to overcome that issue, so that the next proxy in the chain can tell what the IP address of the original client is.

See https://www.haproxy.org/download/1.8/doc/proxy-protocol.txt

This commit adds support for clients that use the PROXY protocol to extract the real client IP address and report it in the logs. This is only implemented when the new ClientUsesProxyProtocol parameter is set to Yes. It should only be enabled when the client is trusted and known to be a proxy that support that protocol.

@rofl0r

rofl0r commented Sep 21, 2025

Copy link
Copy Markdown
Contributor

reading the document, it appears the protocol is widely enough supported so it may make sense to support it too. however, some questions arise:

  • should acl and loop checks be done before or after the peer address is rewritten?
  • should conn_init_contents be called after the PROXY line is already retrieved?

as for the implementation presented:

  • only the client ip string seems to be updated in the current impl, but not the port
  • read_request_line is being repurposed to do 2 different things at once. imo there should be a separate function called specifically when the PROXY protocol is enabled, called from handle_request.
  • from code flow it would appear that the "Connect (file descriptor %d): %s" is currently printed with the frontend proxy's address, not the one passed in the PROXY line.
  • while efficient, the current implementation modifies the original string twice (adding and removing nul terminators), which is kinda frail and requires some cognitive load to decipher for correctness. also it raises the basically same error message in 2 places.
    so imo, the checking should be done once and the error raised immediately before modifying the string. we can for example compare whether it starts with "PROXY TCP" and then check the next char for '4' or '6' and scan the string for the right amount of spaces (eventually making a list of pointers or offsets of them) and only after it's checked proceed to the ip address field (and port, if it's needed) and only insert a NUL there.

also it needs to be documented that only v1 of the protocol is supported.

@Tey

Tey commented Sep 21, 2025 •

Copy link
Copy Markdown
Contributor Author

My main goal was the authentication failure log message, so I didn't think about the other things like ACL. What do you think of applying these changes:

  1. Move the PROXY line parsing logic into a new function like read_proxy_line().
  2. Call it just before the call to getpeer_information() in handle_connection(), so that it updates addr with the reported IP address of the client. That way, getpeer_information() will set peer_ipaddr to the reported IP address so all the log messages will use it and the ACL will be checked against it too.

I'm not sure it is useful to update the client port too. Is it ever used anywhere in the code?

I agree with the remarks about the implementation and will change it accordingly.

Comment thread src/reqs.c Resolved
Comment thread etc/tinyproxy.conf.in Resolved
Comment thread src/reqs.c Resolved
Comment thread src/reqs.c Resolved
Comment thread src/reqs.c Resolved
@Tey

Tey commented Sep 25, 2025

Copy link
Copy Markdown
Contributor Author

All of the review comments have been addressed in the latest commits.

@Tey

Tey commented Nov 17, 2025

Copy link
Copy Markdown
Contributor Author

@rofl0r Let me know if you need anything else from me to accept this PR.

@rofl0r

rofl0r commented Nov 19, 2025

Copy link
Copy Markdown
Contributor

looks mostly good now, but i still have no setup to test it. can you confirm whether the current impl here works in your setup ?

@Tey

Tey commented Nov 19, 2025

Copy link
Copy Markdown
Contributor Author

OK, take your time.

It works well on my 2 tinyproxy servers.

With fail2ban, I do see brute force bots getting banned from time to time, using the following configuration (based on that message):

/etc/fail2ban/filter.d/tinyproxy.conf
[Definition]
failregex = .* Failed auth attempt .*, ip <HOST>
/etc/fail2ban/jail.d/tinyproxy.conf
[tinyproxy]
enabled = true
#port = 8888
# stunnel+tinyproxy
port = 3128
filter = tinyproxy
logpath = /var/log/tinyproxy/tinyproxy.log
maxretry = 10
findtime = 60
bantime = 300
backend = auto

@rofl0r

rofl0r commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

sorry for the long wait. i had an agent review and test your code with real PROXY protocol clients. the following are its findings.

PR #581: Review findings and proposed fixes

1. Apply the connection timeout before reading the PROXY header
Location: src/reqs.c, handle_connection(), around the read_proxy_line() call.

The PROXY header is read before set_socket_timeout(). A peer can therefore hold a worker indefinitely without sending a header, even when Timeout is configured. Move the existing timeout setup before the optional PROXY read:

        set_socket_timeout(fd);

        if (config->client_uses_proxyproto && read_proxy_line (connptr, addr)) {
                close (fd);
                return;
        }

        /* ... */

        if(!conn_init_contents (connptr, peer_ipaddr,
                                config->bindsame ? sock_ipaddr : NULL)) {
                close (fd);
                return;
        }

        /* Remove the later set_socket_timeout(fd); */

This uses the existing receive timeout for the header read. SO_RCVTIMEO is an inactivity timeout, not a total deadline; if the header must have a strict wall-clock limit, enforce a deadline in the bounded reader as well.

2. Validate the complete PROXY v1 line
Location: src/reqs.c, read_proxy_line(), around lines 116–145.

The parser currently checks the protocol marker and source IP, then accepts the rest of the line without checking it. I confirmed that invalid destination and port fields are accepted. PROXY v1 requires a complete CRLF-terminated line, at most 107 bytes, and valid address and port fields.

Use a PROXY-specific bounded read, maximum 107 bytes including CRLF, then validate the whole line before updating addr:

- Require the final bytes to be CRLF; reject LF-only or incomplete lines.
- For TCP4 and TCP6, require exactly the source address, destination address, source port, and destination port fields.
- Validate both addresses with inet_pton().
- Parse each port with a small digit loop, rejecting non-digits, empty values, and values greater than 65535.
- Only clear and update addr after every field validates.

Rejecting only after the existing generic readline() returns would still let it buffer lines much larger than the PROXY protocol permits.

3. Accept the valid UNKNOWN command
Location: src/reqs.c, read_proxy_line(), around lines 116–119.

PROXY UNKNOWN followed by CRLF is a valid PROXY v1 header. The specification says to accept it and continue using the actual socket peer address. The current parser rejects it.

After validating the CRLF, check for UNKNOWN before modifying addr:

        line[len - 2] = '\0';

        if (!strncmp (line, "PROXY UNKNOWN", 13)
            && (line[13] == '\0' || line[13] == ' '))
                return 0;

For this case, leave addr unchanged. The accepted connection already has the proxy’s socket address there. Continue parsing TCP4 and TCP6 headers as usual, and reject other protocol markers.

Verification notes

The PR head compiled and make check passed, though the check target ran no tests. A local protocol-client test returned HTTP 200 for valid IPv4 and IPv6 headers and showed their advertised source addresses in the logs. It also reproduced the timeout behavior, confirmed acceptance of invalid address/port fields, and confirmed rejection of PROXY UNKNOWN.

Keep the tinyproxy listener restricted to trusted proxy senders: PROXY headers are not authenticated, so any sender that can reach the listener can otherwise claim a source address.

if you implement changes, please add them as new commits on top of the old ones, no rebasing or squashing.

@Tey

Tey commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor Author

I disagree with point 2: the goal of this PR is not to support the full PROXY protocol, but to use it as a way to extract the real client IP address. We don't care of the other fields in the PROXY line, and don't even care if they are present and valid, as we don't use them (and never will). The PROXY protocol will only be used when tinyproxy is behind another proxy that the user controls, so there is no attack vector here. Adding extra checks on the PROXY line is just complexifying the code and burning extra CPU cycles for nothing.

I'll make the changes for points 1 and 3. Let me know your thoughts about point 2 please.

@rofl0r

rofl0r commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

ok, agree on 2.

@Tey

Tey commented Nov 11, 2026

Copy link
Copy Markdown
Contributor Author

I've implemented the 2 changes and tested them on my server.

I'm not sure about the need to support the PROXY UNKNOWN feature though, as the IP address that will appear in the logs when this happens is the address of the upstream proxy, which might end up being banned instead of the real client then😕

A merge/rebase with the current master will probably be needed to merge that PR.

Tey added 7 commits November 11, 2026 23:12
When there is a proxy in front of tinyproxy, the latter does not see the
actual IP address of the client. This is a problem when using tools like
fail2ban that parse the tinyproxy log to find and ban clients that try
to break the authentication using brute force. Some proxies like stunnel
or HAProxy support the PROXY protocol to overcome that issue, so that
the next proxy in the chain can tell what the IP address of the original
client is.

See https://www.haproxy.org/download/1.8/doc/proxy-protocol.txt

This commit adds support for clients that use the PROXY protocol to
extract the real client IP address and report it in the logs. This is
only implemented when the new ClientUsesProxyProtocol parameter is set
to Yes. It should only be enabled when the client is trusted and known
to be a proxy that support that protocol.
Reading the PROXY line is the first thing done in handle_connection() so that
the client IP address is updated before it is needed by the rest of the code
(ACL, logging, etc.).

The parsing implementation is now less generic and updates the sockaddr_union
structure directly.
This prevents a peer to hold a worker indefinitely without sending
a header, even when Timeout is configured.
@rofl0r
rofl0r merged commit eca64f0 into tinyproxy:master Nov 11, 2026
@rofl0r

rofl0r commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

minor issue is detected: "UNKNOWNwhatever" would be successfully parsed too. ideally we'd compare "UNKNOWN " with a trailing space. but i went ahead and merged anyway. if you like you can fix that in a follow up PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants