View Full Version : Security risk with innerHTML?

03-09-2012, 02:37 PM
I have written a little bit of javascript which displays a popup div.

The essence of the idea is simple, and works like this:

In the javascript:

function popup(markup)
var div = document.createElement("div");
div.innerHTML = markup;

And in the PHP:

$markup = "<h3>Help</h3><p>You clicked on help, so here it is.</p>";

echo '<a href="javascript:popup('.htmlentities($markup, ENT_QUOTES).');">help</a>';

Of course, there's a whole load more code (e.g. I have a mechanism for displaying the pop-up near the mouse and for allowing the user to close the pop-up, etc, etc, etc), but that is irrelevant to my question.

Note also that $markup can contain anything I want - e.g. it could contain a form.

Note also that the server populates $markup with predictable content - it is NOT populated by the user.

Are there any security risks inherent in the code as I have posted it? (i.e. barring the fact that $markup could be used for code injection, but I have accounted for that and mitigated against it).

03-09-2012, 03:02 PM
Looks like even in case of injection this would be executed on client-side. So it is (I think) far less dangerous (than SQL or PHP injection)... Though some very subtle possibility of some tricky activity against your user may be found here, I think it is necessary to check more thoroughly than you do only in case you are creating some payment system etc. It looks similar to adding something to your page or javascript on client side with greasemonkey (which you could not prevent, but which leads to no awful consequences for you)... ;-)

03-09-2012, 04:39 PM
The only concerns you should have are verifying data sent back to the server. As I understand it (and I'm not familiar with the process) a user can execute their own javascript against your pages (via mozilla add-ons or via the url?). So no matter what you code in your javascript it can be overridden anyway. That is why browser javascript by itself was originally supposed to be run in the browser only, and be completely safe. (I don't know anymore with all this talk of Node.js and such)

The code your server sends to the browser and the code executed in the browser bear no risk. Just make sure you sanitize any input posted back to the server. Even if it doesn't look like the user would have access to it, cuz they can find it anyway...

03-09-2012, 08:10 PM
<a href="javascript: should never be used - it is invalid syntax for both HTML and JavaScript and the script may not run correctly even when JavaScript is enabled - the page will be broken for anyone with JavaScript disabled. JavaScript should be attached using onclick= when you want it to run when someone clicks on something (or better yet use an event listener to listen for the click event).