I recently learned that the browser will fire the toggle
event of the details
element simply by setting the contents on an element, even when it's not in the DOM. The following executes an alert:
document.createElement('p').innerHTML = "<details open ontoggle=\"alert('BAD')\">"
Same works for images and their onload
event.
Compare this with using a script
tag. The following does nothing:
document.createElement('p').innerHTML = "<script>alert('FINE')</script>"
Tested in Chrome and Firefox.
Is there a way to suppress execution of inline event handlers like this? Ideally something that can be set on the parent element
I considered adding an event handler on the parent, but the toggle event doesn't bubble!
An obvious solution is to sanitise the html source, but I am looking for something more graceful and bulletproof than string manipulation.
CodePudding user response:
The answer is Content-Security-Policy. Simply don't allow unsafe-inline
.