I'm not able to make sense of this. Sanitize it for what context? SQL? JSON? HTML? Inclusion as a command-line argument? All of these, and hope that sanitizing it for one context doesn't un-sanitize it for others?
I'm not able to make sense of this. Sanitize it for what context? SQL? JSON? HTML? Inclusion as a command-line argument? All of these, and hope that sanitizing it for one context doesn't un-sanitize it for others?
Usually this means the HTML context. Different sanitization is needed depending on _where_ in the HTML document the input is used.
For instance, if the input is used in between HTML tags (let's say $foo is user input in this PHP example):
... <body><?php echo $foo ?></body>
Here, the input that you need to transition to JavaScript execution is a < character (among other things): <script>alert(1)</script>.Therefore, to correctly sanitize this, you would call the PHP `htmlentities` function:
... <body><?php echo htmlentities($foo) ?></body>
Now, this XSS vulnerability is fixed.What if foo is used in a different context?
... <body><a href='<?php echo htmlentities($foo) ?>'>...
Here, what we need to transition the HTML parser to executing JavaScript is a ' character, and this can be exploited by the following input (in between the double quotes): "' onclick='alert(1)"The key problem is that `htmlentities` is not valid sanitization in the context of an HTML attribute value. In this example, you need to use `urlencode`
... <body><a href='<?php echo urlencode($foo) ?>'>...
The general idea also applies to CSS, JSON, and JavaScript. SQL is a different vulnerability class (SQL injection).I highly recommend the following research paper from 2011 that discusses the context-sensitivity of JavaScript in depth: http://www.comp.nus.edu.sg/~prateeks/papers/scriptgard-ccs11...
In my mind, the context-sensitivity of XSS is one of the key reasons why it is so prevalent.
I'm a big fan of not necessarily sanitizing, but treating it appropriate in context. This may mean removing characters, or mapping them, or just delimiting the entire thing.
To that end, I argue that you should not necessarily sanitize on the way to the storage mechanism. You should only sanitize at the boundaries. So, a web view should make sure any strings are treated as strings. A database layer should make sure query parameters are not able to alter the query. Etc.
(All of this is trying to simply reinforce your point.)