logo       
Google Custom Search
    AddThis Social Bookmark Button
-->

Re: Sanitizing SQL?: msg#00079

Subject: Re: Sanitizing SQL?
Michael Hipp wrote:

Please forgive if this is a dumb question...


On the contrary, it's a very important question.

Is there any need to "sanitize" SQL against injection by a user?

For example, I allow the user to enter a search string and then pass psycopg a statement something like this:

"SELECT * FROM people WHERE last_name ILIKE '%s';" % srchText

Do I need to attempt to parse srchText for bad stuff like escape characters, quotes and such (or does psycopg do that for me)?


If you do exactly what you show above, then YES you have huge injection problem. Consider the wag who submits as his search criteria:
    xyz' ; DROP TABLE people; --

However, what you have shown above is not the recommended way to do subsitution. Instead of using the % operator, you should allow psycopg to do it: cur.execute( "SELECT * FROM people WHERE last_name ILIKE %s;" , srchText )

In that case, psycopg will do the right thing. (Note also the removal of the single quite marks.)

If so, anyone have a well-written sanitize function they could share?


You can probably find several on the web; single quote marks are the biggest problem. However, the right answer is to let psycopg do the substitution.

--
Tim Roberts, timr-EQQNi8F+HVEAvxtiuMwx3w@xxxxxxxxxxxxxxxx
Providenza & Boekelheide, Inc.


<Prev in Thread] Current Thread [Next in Thread>