Skip to content

Instantly share code, notes, and snippets.

@lanmaster53
Last active April 23, 2016 17:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lanmaster53/e9c4d4a396810066eed68a2366c48eac to your computer and use it in GitHub Desktop.
Save lanmaster53/e9c4d4a396810066eed68a2366c48eac to your computer and use it in GitHub Desktop.
def is_safe_url(url, origin):
# url: "next" parameter value
# origin: full request URL
host = urlparse(origin).netloc
proto = urlparse(origin).scheme
# reject blank urls
if not url:
return False
url = url.strip()
url = url.replace('\\', '/')
# simplify down to proto://, //, and /
if url.startswith('///'):
return False
url_info = urlparse(url)
# prevent browser manipulation via proto:///...
if url_info.scheme and not url_info.netloc:
return False
# no proto for relative paths, or a matching proto for absolute paths
if not url_info.scheme or url_info.scheme == proto:
# no host for relative paths, or a matching host for absolute paths
if not url_info.netloc or url_info.netloc == host:
return True
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment