15

I have some code in Python that sets a char(80) value in an sqlite DB.

The string is obtained directly from the user through a text input field and sent back to the server with a POST method in a JSON structure.

On the server side I currently pass the string to a method calling the SQL UPDATE operation.

It works, but I'm aware it is not safe at all.

I expect that the client side is unsafe anyway, so any protection is to be put on the server side. What can I do to secure the UPDATE operation agains SQL injection ?

A function that would "quote" the text so that it can't confuse the SQL parser is what I'm looking for. I expect such function exist but couldn't find it.

Edit: Here is my current code setting the char field name label:

def setLabel( self, userId, refId, label ):
    self._db.cursor().execute( """
        UPDATE items SET label = ? WHERE userId IS ? AND refId IS ?""", ( label, userId, refId) )
    self._db.commit()
chmike
  • 20,922
  • 21
  • 83
  • 106

3 Answers3

12

From the documentation:

con.execute("insert into person(firstname) values (?)", ("Joe",))

This escapes "Joe", so what you want is

con.execute("insert into person(firstname) values (?)", (firstname_from_client,))
sergzach
  • 6,578
  • 7
  • 46
  • 84
Martijn
  • 11,964
  • 12
  • 50
  • 96
  • I updated my question with the code I currently use. I did it as you suggest. Does it mean my code is safe against SQL injection ? – chmike Jun 08 '12 at 14:13
  • I forgot that "escaping" means securing against sql injection. I gave you the answer because of the example. Thank you very much for sharing your knowledge and helping me. – chmike Jun 08 '12 at 14:25
  • if the bad actor gives input such as `joe")` what effect would that have? – OakenDuck Mar 04 '21 at 21:27
  • In this answer, it would insert the name `joe")` into the column firstname – Martijn Mar 07 '21 at 16:15
4

The DB-API's .execute() supports parameter substitution which will take care of escaping for you, its mentioned near the top of the docs; http://docs.python.org/library/sqlite3.html above Never do this -- insecure.

Alex K.
  • 171,639
  • 30
  • 264
  • 288
  • Thank you for the reference. I remember now reading this a long time ago and applying since. I wasn't aware it was protecting me against SQL injection. That's great. I did it the right way. Sorry for not giving you the answer. Martijn has less points than you and he gave an example which would be handy for people like me searching for an answer to this question. – chmike Jun 08 '12 at 14:22
1

Noooo... USE BIND VARIABLES! That's what they're there for. See this

Another name for the technique is parameterized sql (I think "bind variables" may be the name used with Oracle specifically).

Gerrat
  • 28,863
  • 9
  • 73
  • 101