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
- Weeknotes: Llama 3, AI for Data Journalism, llm-evals and datasette-secrets - 23rd April 2024
- Options for accessing Llama 3 from the terminal using LLM - 22nd April 2024
- AI for Data Journalism: demonstrating what we can do with this stuff right now - 17th April 2024
- Three major LLM releases in 24 hours (plus weeknotes) - 10th April 2024
- Building files-to-prompt entirely using Claude 3 Opus - 8th April 2024
- Running OCR against PDFs and images directly in your browser - 30th March 2024
- llm cmd undo last git commit - a new plugin for LLM - 26th March 2024
- Building and testing C extensions for SQLite with ChatGPT Code Interpreter - 23rd March 2024
- Claude and ChatGPT for ad-hoc sidequests - 22nd March 2024
- Weeknotes: the aftermath of NICAR - 16th March 2024