I posted a question about sql injection yesterday and I’ve been reading up on it like a madman. Combined with the comments I got from my previous question, I’d like to make sure that I truly understand the issues before adding security to my site. So, before I clean up my site,
True or False
Sql Injection occurs when $_POSTs and $_GETs are not properly cleaned up. To minimize the risk, all html input should be validated (for example, no “tricky” characters in usernames/passwords) and all queries that use dynamic input from the user need to be properly taken care of (using, for example, a parameter binding method).
However, if a query is done internally that’s either static in nature, OR doesn’t require input from the user (for example, "Select * from tablex where user_id=$_SESSION[‘user_id’] ----- no $_POST or $_GET here!) then for these queries, there’s no threat of SQL injection.
However, if a query is done internally that’s either static in nature, OR doesn’t require input from the user (for example, "Select * from tablex where user_id=$_SESSION[‘user_id’] ----- no $_POST or $_GET here!) then for these queries, there’s no threat of SQL injection.
maybe it’s belt and braces (suspenders [I think], to you US guys ) but, I sanitise data even if it is obtained from the session. I don’t know how easy it is to crack a session (even if only the session ID is on the user’s computer), but I prefer to be safe as possible.
Direct user input comes from these sources:
$_GET, $_POST (that together form $_REQUEST), $_COOKIE and HTTP headers (that are assigned to various elements of $_SERVER array). Obviously you need to validate and sanititise everything that comes from here.
Sessions ($_SESSION) are usually considered as being not directly changeable by user. With one exception - $_SESSION[‘id’] - in default configuration this value is being set by $_COOKIE[‘PHPSESSIONID’] or $_GET[‘PHPSESSIONID’] (if browser refuses to use cookies). So, if, for instance, one has query:
'SELECT somefields FROM sometable WHERE session_id = ' . $_SESSION['id']
then by manipulating cookie PHPSESSIONID one can do SQL injection.
So as IBazz already said - it is very good practice to validate and sanitise all session values as well.
Going even further - design your application so that each component trusts as little as necessary/possible to other components. For example - PHP script should assume that attacker can manipulate data in database directly and hence validate all data that it gets from DB (and all headers - e.g. referrer that come from web-server). DB has to assume that PHP will try to feed it malicious data and validate by means available to it. Even web-server should do some validation on input/output.