r/xkcdcomic • u/shannondoah I'll miss your bee,orchid. • Mar 29 '14
SQL injection banner from xkcd.com
0
Mar 29 '14
[deleted]
22
u/gschizas Mar 29 '14
In general, you aren't supposed to write this:
c = conn.cursor() student_name = input("Enter the student's name:") sql = "SELECT * FROM Students WHERE Name = '" + student_name + "'" c.execute(sql)this is commonly called SQL concatenation, and it's the devil
because some clever mom may name her son
'; drop table Students --and so the above becomessql = "SELECT * FROM Students WHERE Name = ''; drop table Students --'"therefore dropping the whole Students table. Or you may do other evil stuff.
What you are supposed to do is this:
c = conn.cursor() student_name = input("Enter the student's name:") sql = "SELECT * FROM Students WHERE Name = ?" c.execute(sql, (student_name,))(That's almost Python, BTW)
2
u/drakeAndrews Mar 30 '14
That is actual python, as long as
conncontains a sqlite object (or really any DBAPI2 object, although the parameterisation sigil might be different for different drivers (MySQL uses %s I think, some drivers support named paramters)). Although in python 2.x you should useraw_input()asinput()is the same as runningeval(raw_input()).2
u/gschizas Mar 30 '14
Well, that's the beauty of Python: executable pseudocode :)
I'm a professional developer, and I've written in Python professionally as well. This would be "exactly" Python if I included the conn object, opening the database, etc.
0
Mar 29 '14
[deleted]
10
u/Jonno_FTW Mar 30 '14
You still have to sanitize the input. Your users might not be be dropping tables, but they could accidentally type in erroneous
=<>\(),;'-characters and get a nasty DB error message, or worse the query executes with unwanted side effects.I'm sure there was a discussion in /r/php not too long ago about why it's necessary to sanitize input regardless of who the users are.
0
Apr 11 '14
[deleted]
1
u/Jonno_FTW Apr 11 '14
I never mentioned stripping characters, only that you just have to sanitize by escaping, either by using mysql_real_escape_string or parametrized queries. You're getting angry over nothing.
0
13
3
u/michaelfarker Mar 29 '14
ELI5 - If certain inputs would be bad, don't let them ever come in. Implement a filter that disallows them. It is one of those things we all learned in school and then sometimes don't bother with in real life.
1
Mar 30 '14
Sanitising the input is not always enough, because every filter can be circumvented. Sure, filtering all "DROP TABLE \w;" and "DELETE FROM \w WHERE..." from inputs is good. Parameterizing your database calls in addition is even better.
0
u/[deleted] Mar 29 '14
Wow, does this subreddit have me flummoxed. I have no clue what it's about. All the best though.