Sanitize All Input!May 13, 2021
Make sure that input validation relies on allow-listing and not blocklisting. The blocklist approach sets up a collection of rules that define vulnerable input. If the input meets these rules, then the request gets blocked. However, if the ruling is too weak, then a malicious entry will still be effective. If it is too strong, it will block a valid entry. Instead, try to create a rule that describes all allowed patterns with, for instance, a regular expression, or use a well-maintained library for this.
<dependency> <groupId>org.owasp.encoder</groupId> <artifactId>encoder</artifactId> <version>1.2.3</version> </dependency>
String untrusted = "<script> alert(1); </script>"; System.out.println(Encode.forHtml(untrusted)); // output: <script> alert(1); </script>
Sanitizing user text input is an obvious one. But what about the data you retrieve from a database, even when it’s your own database? What if your database was breached and someone planted some malicious text in a database field or document?
Also, keep an eye on incoming files. The Zip-slip vulnerability in many libraries exists because the path of the zipped files was not sanitized. Zip-files containing files with paths
../../../../foo.xy could be extracted and potentially override arbitrary files. Although this is not an XSS attack, it is a good example of why you have to sanitize all input.
Every input is potentially malicious and should be sanitized accordingly.