简体   繁体   中英

HTML: disable dynamically added <script> tags?

I never thought to ask this, but I work on a security product and so we implement pretty strict protection against XSS:

  • We disallow < and > in user input both server- and client-side
  • If the user does manage to make a request containing either of those characters, the server will disable their account and leave a warning for an admin
  • Angular also sanitizes interpolated content before injecting it into the DOM

This is all great and dandy, except, it hurts UX and it's bad for performance. Surely, SURELY, there is a way to just tell the browser NOT to execute <script> tags added after initial document parsing, right? We use a modern bundled workflow and any lazy-loading of JavaScript will be done via import("/some/js/module") calls which get rebased by the bundler but will never be fed a dynamic value at runtime.

Even if there isn't a way to straight up tell the browser not to run dynamically added (by JS after page load) <script> tags, is there a tried and true workflow for rendering, say, markdown + HTML subset user-produced content in iframes? I am familiar with iframes at a high-level, but I mean can the parent document/page manipulate the DOM content of the iframe or something so even if it does add a <script> tag inside the iframe, the script code will not have access to the parent document's JS environment?

Actually that would be cool as a sandboxed way to display user content because they could intentionally include a script and make a little interactive widget for other users to mess with, in theory (maybe an antifeature in practice).

You can do it with CSP (Content Security Policy)

https://developers.google.com/web/fundamentals/security/csp#inline-code-considered-harmful

Example: Allow only :

<script nonce="EDNnf03nceIOfn39fn3e9h3sdfa">
  // Some inline code I can't remove yet, but need to asap.
</script>

with

Content-Security-Policy: script-src 'nonce-EDNnf03nceIOfn39fn3e9h3sdfa'

Start by blocking all with:

default-src 'none'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM