From 79594b40c087c19fecc72af042c835b11a519b78 Mon Sep 17 00:00:00 2001 From: Jacob Kaplan-Moss Date: Tue, 13 Aug 2013 11:05:41 -0500 Subject: [PATCH] Fixed is_safe_url() to reject URLs that use a scheme other than HTTP/S. This is a security fix; disclosure to follow shortly. --- django/contrib/auth/tests/test_views.py | 8 ++++++-- django/utils/http.py | 7 ++++--- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/django/contrib/auth/tests/test_views.py b/django/contrib/auth/tests/test_views.py index d5f0c40a57c..42ceea36d38 100644 --- a/django/contrib/auth/tests/test_views.py +++ b/django/contrib/auth/tests/test_views.py @@ -447,7 +447,8 @@ class LoginTest(AuthViewsTestCase): for bad_url in ('http://example.com', 'https://example.com', 'ftp://exampel.com', - '//example.com'): + '//example.com', + 'javascript:alert("XSS")'): nasty_url = '%(url)s?%(next)s=%(bad_url)s' % { 'url': login_url, @@ -468,6 +469,7 @@ class LoginTest(AuthViewsTestCase): '/view?param=ftp://exampel.com', 'view/?param=//example.com', 'https:///', + 'HTTPS:///', '//testserver/', '/url%20with%20spaces/'): # see ticket #12534 safe_url = '%(url)s?%(next)s=%(good_url)s' % { @@ -662,7 +664,8 @@ class LogoutTest(AuthViewsTestCase): for bad_url in ('http://example.com', 'https://example.com', 'ftp://exampel.com', - '//example.com'): + '//example.com', + 'javascript:alert("XSS")'): nasty_url = '%(url)s?%(next)s=%(bad_url)s' % { 'url': logout_url, 'next': REDIRECT_FIELD_NAME, @@ -681,6 +684,7 @@ class LogoutTest(AuthViewsTestCase): '/view?param=ftp://exampel.com', 'view/?param=//example.com', 'https:///', + 'HTTPS:///', '//testserver/', '/url%20with%20spaces/'): # see ticket #12534 safe_url = '%(url)s?%(next)s=%(good_url)s' % { diff --git a/django/utils/http.py b/django/utils/http.py index 4647d898473..ffaf4e96570 100644 --- a/django/utils/http.py +++ b/django/utils/http.py @@ -253,11 +253,12 @@ def same_origin(url1, url2): def is_safe_url(url, host=None): """ Return ``True`` if the url is a safe redirection (i.e. it doesn't point to - a different host). + a different host and uses a safe scheme). Always returns ``False`` on an empty url. """ if not url: return False - netloc = urllib_parse.urlparse(url)[1] - return not netloc or netloc == host + url_info = urllib_parse.urlparse(url) + return (not url_info.netloc or url_info.netloc == host) and \ + (not url_info.scheme or url_info.scheme in ['http', 'https'])