[mod_python] addSlashes() in python, sql cgi question

Michael C. Neel neel at mediapulse.com
Thu Jun 5 18:59:06 EST 2003


I'm surprised no one has mentioned this yet, but you really need to be
using placeholders with the cursor; otherwise you are writing
exploitable code.

Consider this:

C.execute("SELECT name FROM users WHERE user_id='" +
cgi_submitted_userid + "'")

Now I send my userid as "hackyou'; DELETE FROM users --"

You get:

SELECT name FROM users WHERE user_id='hackyou'; DELETE FROM users --'

Not good (MySQL seperates stmts with ;'s, other DBs do it differently
but we'll leave that as an exersice for the reader.  The -- comments out
the rest of the line).  So you do a addSlash to userid and get:

SELECT name FROM users WHERE user_id='hackyou\'; DELETE FROM users --'

Okay if you're MySQL, MSSQL escapes a ' as ''.  
But we have a good hacker, so he tries userid as "hackyou\'; DELETE FROM
users --"

SELECT name FROM users WHERE user_id='hackyou\\'; DELETE FROM users --'

Doh!

But, if we do this:

C.execute("SELECT name FROM users WHERE
user_id=%s",(cgi_submitted_userid,) )

The query is sent seperatly from the data, so the server can handle
anything it's own way correctly (i.e. MySQL will use a \', MS SQL will
use a '').  And you don't have to think about it.  Simpler and safer.

Mike



More information about the Mod_python mailing list