Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove unsafe inline code for Content Security Policy?

I would like to use Content Security Policy and make my Django web application safe without any unsafe inline code. But while it is easy to move most of the JavaScript code to external files, I also have a segment of inline code which I do not know fix. I am using Django and I have some variables in Django template context which I want to pqww to JavaScript. So currently I simply output that as inline JavaScript. But this does not work because of CSP.

<script type="text/javascript">
    /* <![CDATA[ */
    var documentURL = '{% filter escapejs %}{{ document.get_document_url }}{% endfilter %}';
    /* ]]> */
</script>
like image 953
Mitar Avatar asked Oct 07 '22 04:10

Mitar


1 Answers

To put the comments in answer form and add a little...

The easiest way to do this is generate a tag with an attribute set. I don't know django so I'll just leave it in plain html:

<input type="hidden" id="mything" value="<MY VALUE>">

When I have multiple, related values I might throw them into the same element:

<span class="hidden" data-attribute1="<VALUE1>" data-attribute2="<VALUE2>">
<!-- rename 'attributeN' to something meaningful obviously -->

In either case, just read the values with JS (using jquery for brevity)

$('#mything').data("attribute1")

Or if you need a complex object, throw it in a span as html entity escaped data:

<span class="hidden" id="data-container">
  <your html-escaped JSON>
</span>

And read it in the external file with:

var myObject = JSON.parse($('#data-container').html());

This is also describe at https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet#RULE_.233.1_-_HTML_escape_JSON_values_in_an_HTML_context_and_read_the_data_with_JSON.parse

like image 166
oreoshake Avatar answered Oct 10 '22 04:10

oreoshake