What are the best practices to avoid XSS and SQL Injections attacks (platform agnostic)?
4th February 2012
My answer to What are the best practices to avoid XSS and SQL Injections attacks (platform agnostic)? on Quora
Input validation is, in my opinion, a red herring. Sure—if you ask the user for an integer or date you should make sure they entered one before attempting to save it anywhere or use it for processing, but injection attacks often involve text fields (e.g. names, or comments posted on Quora) and validating those on input is a recipe for banning “Tim O’Reilly” from ever creating a proper profile on your site!
The most important thing you can do to avoid XSS/SQLi is this: never concatenate strings. Any time you find yourself concatenating strings together, especially if those strings are executable code in another language (like SQL, or HTML, or JavaScript, or something being passed to a command line), you’re risking a potential injection attack. Sure you can escape stuff during the concatenation with addslashes / htmlentities / PHP’s hilariously named mysql_real_escape_string / whatever escaping function you have to hand, but one tiny mistake will destroy the security of your application.
Instead, you should use abstractions that handle escaping for you. Both Django and Rails have escape-by-default templating languages, which go a LONG way towards protecting against accidental XSS. Good ORM or database abstraction layers will handle SQL escaping for you—if you don’t have one, you can write something yourself pretty quickly (here’s the most basic thing that would work: "$results = $mydb->execute("SELECT * FROM TABLE WHERE user = %user", {"user": "simon"});)
SQL injections are so easy to protect against it’s embarrassing to us as an industry that they still show up in any applications. XSS protection requires a bit more work, but template languages that escape by default really do cover 95% of the cases without any extra development effort.
And as Mike Fratto said, the OWASP guides are invaluable.
More recent articles
- Gemini 2.0 Flash: An outstanding multi-modal LLM with a sci-fi streaming mode - 11th December 2024
- ChatGPT Canvas can make API requests now, but it's complicated - 10th December 2024
- I can now run a GPT-4 class model on my laptop - 9th December 2024