In my Django template, I have a link like this:

<a href='{{ my_model.some_url }}'>

The some_url bit is a Django URLField that a user can influence.

Can this be exploited in any way? (What comes to mind is including a quote in the URL and then arbitrary HTML.)

What can I do to protect this code?

  • The field is automatically validated, it's a Django URLField. I'm concerned that there could be vulnerabilities despite the URL being a valid one. – Ram Rachum Mar 4 '14 at 11:47

In general there are valid URL schemes that are dangerous. Most obviously javascript:, which as a pseudo-URL refers not to a new location, but to a command to execute on the current page. Allowing a javascript: URL to be added to your page means you have a cross-site scripting problem.

There are also other scripting aliases (vbscript:, mocha: et al), as well as data: and any number of arbitrary protocol handlers that third-party software might have installed at the client. So typically you need to whitelist URL schemes.

Django's default URLValidator for URLField does this, allowing only http, https, ftp and ftps links, so as long as you haven't replaced the validators it should be OK. (You may wish to do so, if that's not the set of schemes you want.) If you have any other means to populate the some_url field that doesn't go through the normal field/validator then you'll need to make sure that is validated too.

(What comes to mind is including a quote in the URL and then arbitrary HTML.)

As long as you haven't disabled autoescape, the default HTML-escaping provided by {{...}} templating prevents that (it correctly encodes single quotes to &#39;).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.