r/netsec • u/speckz • Mar 25 '16
SQL Injection Cheat Sheet by Netsparker
https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/14
u/tolos Mar 25 '16
What about some tips to avoid things like this? I think I've got parameterized input down (entity framework in c# or sqlalchemy in python, and don't use raw sql queries), but I feel like there are a bunch of other ways for things to go wrong. For instance, I have a website where a user can enter arbitrary text to search a field in the database, and I strip out all [^a-zA-Z0-9 ], or check that a non-negative integer input is actually a non-negative integer, but I'm never sure if there are other things I should do.
13
u/ThisIs_MyName Mar 25 '16
user can enter arbitrary text to search a field in the database, and I strip out all
[^a-zA-Z0-9 ]As long as your DB supports Unicode (and it should!), you don't have to do this. Let them search for emojis if they really want to. If your code can truly determine whether the user is entering silly stuff, just show them a warning saying as such.
check that a non-negative integer input is actually a non-negative integer
That's a good place to start defense in depth. I try to ensure that when a function takes
ints as input, it can handle all values in that variable. So if I accidentally call the function without sanitizing negative inputs, the function will throw an exception instead of doing something unexpected.3
Mar 25 '16
Do you take in parameters like orderBy from requests? Those cannot be parameterized in a query. If so I would recommend either a whitelist, or do all that sorting in the view.
3
u/moderatorrater Mar 26 '16
or do all that sorting in the view.
That's terrible. Never do that. Whitelist all the things.
2
u/kageurufu Mar 26 '16
When using sqlalchemy, I use my models with getattr and a whitelist.
Basically
sa.desc(getattr(model, colname))1
Mar 26 '16
Stripping out characters is only really useful if you know you will never have those characters in the database.
There's no harm it not doing it if your other stuff is set up correctly.
0
Mar 25 '16
[deleted]
2
u/flameswor10 Mar 26 '16
Using PDO with parametized queries should help, but its always a good thing to validate most user input if possible.
1
u/tolos Mar 25 '16 edited Mar 26 '16
I haven't used PHP in 10+ years.
edit: this is just a statement saying I'm not qualified to answer, so someone else will need to chime in. I didn't know lacking experience was so unpopular.
26
u/Vakieh Mar 26 '16
Who in [current year] is handling injection protection manually? Even lolphp has PDOs to sort all of this out with a single bullet.
Prepared statements with parameters stop every issue on that list, so long as you aren't a moron and remember to use a single entry point for your database.