Skip to content

Commit 7b37b9b

Browse files
committed
properly handle and interpret X-Forwarded-For header
1 parent 0ea100e commit 7b37b9b

File tree

2 files changed

+52
-14
lines changed

2 files changed

+52
-14
lines changed

src/server/_common.py

+21-6
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from werkzeug.local import LocalProxy
99

1010
from delphi.epidata.common.logger import get_structured_logger
11-
from ._config import SECRET, REVERSE_PROXIED
11+
from ._config import SECRET, REVERSE_PROXY_DEPTH
1212
from ._db import engine
1313
from ._exceptions import DatabaseErrorException, EpiDataException
1414
from ._security import current_user, _is_public_route, resolve_auth_token, show_no_api_key_warning, update_key_last_time_used, ERROR_MSG_INVALID_KEY
@@ -31,14 +31,29 @@ def _get_db() -> Connection:
3131

3232

3333
def get_real_ip_addr(req): # `req` should be a Flask.request object
34-
if REVERSE_PROXIED:
35-
# NOTE: ONLY trust these headers if reverse proxied!!!
34+
if REVERSE_PROXY_DEPTH:
35+
# we only expect/trust (up to) "REVERSE_PROXY_DEPTH" number of proxies between this server and the outside world.
36+
# a REVERSE_PROXY_DEPTH of 0 means not proxied, i.e. server is globally directly reachable.
37+
# a negative proxy depth is a special case to trust the whole chain -- not generally recommended unless the
38+
# most-external proxy is configured to disregard "X-Forwarded-For" from outside.
39+
# really, ONLY trust the following headers if reverse proxied!!!
3640
if "X-Forwarded-For" in req.headers:
37-
return req.headers["X-Forwarded-For"].split(",")[
38-
0
39-
] # take the first (or only) address from the comma-sep list
41+
full_proxy_chain = req.headers["X-Forwarded-For"].split(",")
42+
# eliminate any extra addresses at the front of this list, as they could be spoofed.
43+
if REVERSE_PROXY_DEPTH > 0:
44+
depth = REVERSE_PROXY_DEPTH
45+
else:
46+
# special case for -1/negative: setting `depth` to 0 will not strip any items from the chain
47+
depth = 0
48+
trusted_proxy_chain = full_proxy_chain[-depth:]
49+
# accept the first (or only) address in the remaining trusted part of the chain as the actual remote address
50+
return trusted_proxy_chain[0].strip()
51+
52+
# fall back to "X-Real-Ip" if "X-Forwarded-For" isnt present
4053
if "X-Real-Ip" in req.headers:
4154
return req.headers["X-Real-Ip"]
55+
56+
# if we are not proxied (or we are proxied but the headers werent present and we fell through to here), just use the remote ip addr as the true client address
4257
return req.remote_addr
4358

4459

src/server/_config.py

+31-8
Original file line numberDiff line numberDiff line change
@@ -26,14 +26,37 @@
2626
SECRET = os.environ.get("FLASK_SECRET", "secret")
2727
URL_PREFIX = os.environ.get("FLASK_PREFIX", "") # if not empty, this value should begin but not end in a slash ('/')
2828

29-
# REVERSE_PROXIED is a boolean value that indicates whether or not this server instance
30-
# is running behind a reverse proxy (like nginx).
31-
# in dev and testing, it is fine (or even preferable) for this variable to be set to 'TRUE'
32-
# even if it is not actually the case. in prod, it is very important that this is set accurately --
33-
# it should _only_ be set to 'TRUE' if it really is behind a reverse proxy, as remote addresses can be "spoofed"
34-
# which can carry security/identity implications. conversely, if this is set to 'FALSE' when in fact
35-
# running behind a reverse proxy, it can hinder logging accuracy. it defaults to 'FALSE' for safety.
36-
REVERSE_PROXIED = os.environ.get("REVERSE_PROXIED", "FALSE").upper() == "TRUE"
29+
30+
"""
31+
REVERSE_PROXY_DEPTH is an integer value that indicates how many "chained" and trusted reverse proxies (like nginx) this
32+
server instance is running behind. "chained" refers to proxies forwarding to other proxies, and then ultimately
33+
forwarding to the app server itself. each of these proxies appends the remote address of the request to the
34+
"X-Forwarded-For" header. in many situations, the most externally facing proxy (the first in the chain, the one that
35+
faces the "open internet") can and should be set to write its own "X-Forwarded-For" header, ignoring and replacing
36+
(or creating anew, if it didnt exist) such a header from the client request -- thus preserving the chain of trusted
37+
proxies under our control.
38+
39+
however, in our typical production environment, the most externally facing "proxy" is the AWS application load balancer,
40+
which seemingly cannot be configured to provide this trust boundary without losing the referring client address
41+
(see: https://docs.aws.amazon.com/elasticloadbalancing/latest/application/x-forwarded-headers.html ). accordingly, in
42+
our current typical production environment, REVERSE_PROXY_DEPTH should be set to "2": one for the AWS application load
43+
balancer, and one for our own nginx/haproxy instance. thus "2" is our default value.
44+
45+
it is important that REVERSE_PROXY_DEPTH is set accurately for two reasons...
46+
47+
setting it too high (or to -1) will respect more of the entries in the "X-Forwarded-For" header than are appropriate.
48+
this can allow remote addresses to be "spoofed" when a client fakes this header, carrying security/identity
49+
implications. in dev and testing, it is not particularly dangerous for this variable to be set to -1 (special case
50+
for an "infinite" depth, where any and all proxy hops will be trusted).
51+
52+
setting it too low can hinder logging accuracy -- that can cause an intermediate proxy IP address to be used as the
53+
"real" client IP address.
54+
55+
setting REVERSE_PROXY_DEPTH to "0" essentially indicates there are no proxies between this server and the outside
56+
world. in this case, the "X-Forwarded-For" header is ignored.
57+
"""
58+
REVERSE_PROXY_DEPTH = int(os.environ.get("PROXY_DEPTH", 2))
59+
3760

3861
REGION_TO_STATE = {
3962
"hhs1": ["VT", "CT", "ME", "MA", "NH", "RI"],

0 commit comments

Comments
 (0)