Bear in mind that CSP is not to be used as a first line of defense. You should properly encode per context to prevent XSS in your application. OWSAP has good information on this.
That being said, CSP can be a good fallback to make XSS much less serious, should an XSS vulnerability (i.e. wrong or no encoding somewhere on your page) be found in your application and exploited.
I know that it is possible to overwrite existing functions, but it's not clear to me how exactly this would work.
It is very easy to do. For example,
XMLHttpRequest = myFunction, or
XMLHttpRequest = null would prevent scripts from using
The problem is that if an attacker may not be using that particular function, and if the attacker knows you are doing this, he could easily use an alternative method.
While it might be possible to overwrite all functions, it is not recommended as a reliable solution.
Is there a trivial solution that 100% prevents any further script execution?
If you have a syntax error in your
<script>, then nothing in that
<script>...</script> will run. Unfortunately, with XSS, the attacker could easily start a new
<script> that would work just fine.
<script>, for example
<img onload> or
To my knowledge you cannot reliably stop all following HTML from containing XSS execution.
If not, are there solutions that work in most contexts or for most browsers (and ways to bypass them for other contexts/browsers)?
CSP version 1 browser support is starting to get good, and since CSP was designed as a backup anyway (not a first line of defense) you may be able to stop your search there knowing that browser support will be a shrinking problem.
That being said, I think the idea of overwriting functions could go a long way towards success. It seems like that could work reliably in theory. While this is not recommended, I think it would be an interesting study. I wonder how complex it would be to implement.