Search code examples
javascripthtmlsecuritygoogle-caja

Google caja - Block malicious code


I need safe html on my website.

I read though the caja guide and I am not sure if I understand the conecpt.

https://developers.google.com/caja/docs/gettingstarted/

I think it goes like this:

  • User submits malicious content to my db
  • I want to render it. Caja recognizes the malicious code and blocks it.

But how do I render it though caja? They don't explain this on their page, they only show how to replace the code.

<script type="text/javascript">
      document.getElementById('dynamicContent').innerHTML = 'Dynamic hello world';
</script>

Let's say our document would look like this

<body>
    <div class="input">
        <h3>User Input </h3>
        <script> alert("I am really bad!"); </script>
    </div>

    <div class="input">
        <h3>User Input </h3>
        <p> I am safe HTML!</p>
    </div>
</body>

How would I tell caja to block the script tag?


Solution

  • If you want to have just sanitized html (ie. no script execution at all), you don't need all of Caja, just the html-sanitizer.

    To use:

    <script src="http://caja.appspot.com/html-css-sanitizer-minified.js"></script>
    <script>
      var sanitized = html_sanitize(untrustedCode,
        /* optional */ function(url) { return url /* rewrite urls if needed */ },
        /* optional */ function(id) { return id; /* rewrite ids, names and classes if needed */ })
    </script>
    

    If you don't want to allow sanitized css styles, use http://caja.appspot.com/html-sanitizer-minified.js instead.