diff --git a/flask_seasurf.py b/flask_seasurf.py index b3d5cf6..32cc59f 100755 --- a/flask_seasurf.py +++ b/flask_seasurf.py @@ -63,10 +63,13 @@ def _same_origin(url1, url2): :param url1: The first URL to compare. :param url2: The second URL to compare. ''' - p1, p2 = urlparse.urlparse(url1), urlparse.urlparse(url2) - origin1 = p1.scheme, p1.hostname, p1.port - origin2 = p2.scheme, p2.hostname, p2.port - return origin1 == origin2 + try: + p1, p2 = urlparse.urlparse(url1), urlparse.urlparse(url2) + origin1 = p1.scheme, p1.hostname, p1.port + origin2 = p2.scheme, p2.hostname, p2.port + return origin1 == origin2 + except ValueError: + return False class SeaSurf(object): diff --git a/test_seasurf.py b/test_seasurf.py index b5e3f6f..3dcca76 100644 --- a/test_seasurf.py +++ b/test_seasurf.py @@ -175,6 +175,21 @@ def test_https_good_referer(self): self.assertEqual(rv.status_code, 200) + def test_malformed_referer(self): + with self.app.test_client() as client: + with client.session_transaction() as sess: + token = self.csrf._generate_token() + + client.set_cookie('www.example.com', self.csrf._csrf_name, token) + sess[self.csrf._csrf_name] = token + + rv = client.post('/bar', + data={self.csrf._csrf_name: token}, + base_url='https://www.example.com', + headers={'Referer': u'https://foobar:abc'}) + + self.assertEqual(403, rv.status_code) + def test_token_in_header(self): with self.app.test_client() as client: with client.session_transaction() as sess: