Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

No filter for HTML attributes? #350

Closed
mehaase opened this issue Jul 10, 2014 · 3 comments
Closed

No filter for HTML attributes? #350

mehaase opened this issue Jul 10, 2014 · 3 comments

Comments

@mehaase
Copy link

mehaase commented Jul 10, 2014

HTML attributes have unique issues when it comes to escaping user-controlled content. I don't see an existing filter in Jinja2 that covers this common use case. (Correct me if I'm wrong.) More worryling, I'm sure too many people are relying on Jinja2's auto escaping to sanitize HTML attributes, which is actually really dangerous!

Here's an example of a custom HTML attribute filter I wrote:

@app.template_filter("html_attribute")
def html_attribute(html_attribute_string):
    """
    Formats a string to be placed inside an HTML element's attribute.

    Attribute sanitization is so tricky (and so prone to browser-specific flaws) that we take an extreme approach:
    escape EVERYTHING that's not an alphanumeric into &#NN; syntax.

    See: http://wonko.com/post/html-escaping
    """

    sanitized_string = ''

    for char in html_attribute_string:
        if char.isalnum():
            sanitized_string += char
        else:
            sanitized_string += "&#%s;" % ord(char)

    return jinja2.Markup(sanitized_string)

If this is something you're interested in, I can submit a pull request.

@mitsuhiko
Copy link
Contributor

I do not see the value of this pull request. What is the problem with the escaping that markupsafe provides?

@mitsuhiko
Copy link
Contributor

I'm going to close this issue. Using the escape filter without quotation marks is not supported for a good reason. There is nothing wrong with the escaping provided if you enclose your attributes in standard conformant quotes. If you do not do this, there is no escaping in the world that's going to help you.

@mehaase
Copy link
Author

mehaase commented Jul 12, 2014

Sorry, my mistake. The Chrome inspector tricked me – I thought I was seeing injection. You're definitely right. I need to go delete my filter now. :)

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Nov 13, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants