Page 1 of 1
found this security code, tell me what it prevents?
Posted: Sat Nov 26, 2011 4:01 pm
by Markto
Can someone elaborate what this code prevents?
it is suggested to do this on any input that is used in a mysql query.
Code: Select all
function safe($string) {
return "'" . mysqli_real_escape_string($string) . "'"
}
My trouble is that I do not understand why the ' (single quote) is being concatenated before and after the mysqli-escaped-string. (The "'" is a " ' " in case you cannot see it.) Is anything added by these single quotes that is not covered by mysqli_real_escape_string?
Re: found this security code, tell me what it prevents?
Posted: Sat Nov 26, 2011 6:44 pm
by Celauran
No idea why the single quotes are being added, but the function will fail anyways since
mysqli_real_escape_string requires two arguments.
Re: found this security code, tell me what it prevents?
Posted: Sat Nov 26, 2011 8:42 pm
by califdon
Generally the risk is that if you allow unescaped strings received from an unknown user to be processed by the MySQL engine, a hacker can insert characters in their input string that can be interpreted by MySQL to do destructive things like deleting your entire database and such. This is known as "SQL injection" and you can read about it at
http://msdn.microsoft.com/en-us/library/ms161953.aspx and many other places.
Re: found this security code, tell me what it prevents?
Posted: Sat Nov 26, 2011 9:12 pm
by Markto
Thanks. I am aware of SQL injections (reading about them brought me to this code), but I do not know what specific injection attempts are being address by putting single quotes around a string that has *already* been escaped by mysqli_real_escape_string.
Sorry I didn't put the database connection argument in mysqli_real_escape_string. My fault.
Code: Select all
function safe($string) {
return "'" . mysqli_real_escape_string($link, $string) . "'"
}
Re: found this security code, tell me what it prevents?
Posted: Sat Nov 26, 2011 9:17 pm
by califdon
I can only guess that that function was intended to be used by some code that expected a string that began and ended with single quotes. That doesn't sound like a good coding practice to me, so I'd consider it likely just a mistake.
Re: found this security code, tell me what it prevents?
Posted: Mon Nov 28, 2011 6:05 am
by Mordred
The reasoning the author of this snippet put in it is sound - if you don't have quotes around values in your SQL queries, mysql_real_escape_string will not be sufficient to prevent SQL injections. You can read about this in the article from my sig (read the plain txt version though, the html one is broken).
I don't like his solution to the problem though: I like to put the quotes in the query. If you're careful on how you use this function is should be equivalent, but in writing secure code clarity is very valuable, so having two equivalent solutions one should choose the more readable one.