From 8ea7e503c6ec89a5548aeb3aec49d0de31832541 Mon Sep 17 00:00:00 2001 From: Lars Holm Nielsen Date: Wed, 17 Aug 2016 09:36:43 +0200 Subject: [PATCH] Use ProxyFix instead of inspecting X-Forwarded-For header Changes trackable feature to always rely on having a correctly set IP address in request.remote_addr via e.g. Werkzeug's ProxyFix instead of inspecting X-Forwarded-For headers (in which the current implementation doesn't take multiple trusted proxies into account). --- flask_security/utils.py | 6 +----- tests/test_trackable.py | 6 +++++- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/flask_security/utils.py b/flask_security/utils.py index ad8039aa..af896f5b 100644 --- a/flask_security/utils.py +++ b/flask_security/utils.py @@ -62,11 +62,7 @@ def login_user(user, remember=None): return False if _security.trackable: - if 'X-Forwarded-For' in request.headers: - remote_addr = request.headers.getlist( - "X-Forwarded-For")[0].rpartition(' ')[-1] - else: - remote_addr = request.remote_addr or 'untrackable' + remote_addr = request.remote_addr or 'untrackable' old_current_login, new_current_login = user.current_login_at, datetime.utcnow() old_current_ip, new_current_ip = user.current_login_ip, remote_addr diff --git a/tests/test_trackable.py b/tests/test_trackable.py index 70177542..78749a1a 100644 --- a/tests/test_trackable.py +++ b/tests/test_trackable.py @@ -9,11 +9,13 @@ import pytest from utils import authenticate, logout +from werkzeug.contrib.fixers import ProxyFix pytestmark = pytest.mark.trackable() def test_trackable_flag(app, client): + app.wsgi_app = ProxyFix(app.wsgi_app, num_proxies=1) e = 'matt@lp.com' authenticate(client, email=e) logout(client) @@ -29,11 +31,13 @@ def test_trackable_flag(app, client): def test_trackable_with_multiple_ips_in_headers(app, client): + app.wsgi_app = ProxyFix(app.wsgi_app, num_proxies=2) + e = 'matt@lp.com' authenticate(client, email=e) logout(client) authenticate(client, email=e, headers={ - 'X-Forwarded-For': '99.99.99.99, 88.88.88.88'}) + 'X-Forwarded-For': '99.99.99.99, 88.88.88.88, 77.77.77.77'}) with app.app_context(): user = app.security.datastore.find_user(email=e)