From 0a116f556a4d8c2eabe3a07bc9b560538d2d530d Mon Sep 17 00:00:00 2001 From: Cédric Bonhomme Date: Tue, 4 Aug 2015 19:00:58 +0200 Subject: Secure back redirects with WTForms. --- pyaggr3g470r/utils.py | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) (limited to 'pyaggr3g470r/utils.py') diff --git a/pyaggr3g470r/utils.py b/pyaggr3g470r/utils.py index 3d8bb483..bcea5109 100755 --- a/pyaggr3g470r/utils.py +++ b/pyaggr3g470r/utils.py @@ -49,11 +49,12 @@ import sqlalchemy try: from urlparse import urlparse, parse_qs, urlunparse except: - from urllib.parse import urlparse, parse_qs, urlunparse + from urllib.parse import urlparse, parse_qs, urlunparse, urljoin from bs4 import BeautifulSoup from datetime import timedelta from collections import Counter from contextlib import contextmanager +from flask import request import conf from flask import g @@ -65,6 +66,25 @@ logger = logging.getLogger(__name__) ALLOWED_EXTENSIONS = set(['xml', 'opml', 'json']) +def is_safe_url(target): + """ + Ensures that a redirect target will lead to the same server. + """ + ref_url = urlparse(request.host_url) + test_url = urlparse(urljoin(request.host_url, target)) + return test_url.scheme in ('http', 'https') and \ + ref_url.netloc == test_url.netloc + +def get_redirect_target(): + """ + Looks at various hints to find the redirect target. + """ + for target in request.args.get('next'), request.referrer: + if not target: + continue + if is_safe_url(target): + return target + def allowed_file(filename): """ Check if the uploaded file is allowed. -- cgit