My programming teacher was full of useful acronyms when it came to teaching us things. KISS (Keep it Simple Stupid), DRY (Donâ€™t Repeat Yourself), IPO (Input-Process-Output), and probably one of the most useful, if understated:
GIGO = Garbage In, Garbage Out
Those four letters are probably some of the most ignored four (OK, three) letters in programming. Most programmers assume wrongly that their users are not out to get them and destroy precious data, but they are. Fortunately most users donâ€™t know that they are trying to destroy the precious balance that most web apps have, and unfortunately most web apps donâ€™t care. Programmers then have to worry about the rest of the users that are trying to abuse the system, and then the users who are maliciously attacking the system. By ignoring GIGO, you end up with a sad list like the OWASP Top 10.
OWASP Top 10 â€“ We Shouldnâ€™t Need It
Despite what that heading says, Iâ€™m not saying that the Top 10 is a bad thing. Itâ€™s just sad that most of the vulnerabilities can easily be done away with if programmers just take a little extra time and remember to treat everything that a user submits as garbage. Letâ€™s take a look two that should have never made the list, let alone made it to the top two:
What do both of these problems have in common? Both are caused by applications blindly accepting user input. The problem is made even more sad by the fact that PHP, especially, has many tools available to help mitigate these two types of attacks.
Filtering Out Cross Site Scripting
Cross Site Scripting, or XSS, is actually a form of injection, but instead of being executed by the server it is executed by the userâ€™s browser. The classic example, one that happens so frequently it makes an appearance in the satirical Forum Warz, is of the guestbook or forum that just displays whatever a user types in back to everyone. Since the Forum (in this case) doesnâ€™t actually do any filtering on the userâ€™s input when they make a post, they can enter things like this:
While the author of the forum may have never intended for users to type in HTML tags, in this case a user did. Now anytime someone visits that post, a pop-up will show the cookie data to the user. An actual attack would probably post that back to a URL and be completely silent. So, how do we get rid of this attack?
PHPâ€™s Filtering Functions
Whitelist HTML Tags with strip_tags()
strip_tags() can either be used in two ways â€“ remove all the HTML tags in a string or to only remove tags that are not in a white list. This is convenient if you want to allow a subset of HTML to be used in an input form.
// Grab the user's input from POST $message = $_POST['message']; // Just remove all the HTML tags $message = strip_tags($message) // Only allow basic text formatting such as Bold, Italics, Underline $whitelist = '<b><i><u>'; $message = strip_tags($message, $whitelist);
This will filter out that nasty