0

when i am reading :http://docs.python.org/2/library/sqlite3.html

# Never do this -- insecure!  
symbol = 'RHAT'  
c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)  

why it is insecure? No reason in detail in the web to explain.

showkey
  • 482
  • 42
  • 140
  • 295

2 Answers2

3

Think about what happens if symbol contains, say, ' OR '' = ' -- an attacker could insert completely arbitrary criteria for the query. This is of particular concern if you have information about other customers' accounts in the same table, or are doing an update.

Also, http://xkcd.com/327/

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
0

This creates an SQL injection vulnerability if symbol contains user-supplied or untrusted data.

To be safe, always do it like this (as mentionned in the same page you're reading) :

symbol = ('RHAT',)
c.execute('SELECT * FROM stocks WHERE symbol=?', symbol)

So now even if symbol contains malicious data, it'll be properly escaped and won't do any harm, the worse that can happen is the query returning no results.

  • "Escaped" if you're using a database with a poorly-designed wire protocol. If you're using a database with a well-designed wire protocol (and a library taking advantage of same), bind parameters' values aren't just escaped, but are passed completely out-of-band from the query proper. SQLite doesn't have a wire protocol as such, but its C API uses the `sqlite_3_bind_*` family of calls to pass data completely out-of-band from the query -- no escaping, as such, needed. – Charles Duffy Mar 23 '14 at 03:02