Monday, February 4, 2019

php - How do SQL injections conceptually work? (brief)





Possible Duplicates:
What is SQL injection?
XKCD SQL injection - please explain







I own a company and am wishing to know the runabouts of PHP while I am hiring for people to maintain and extend code for its websites, I was looing up on security on SQL injections and do not quite understand how these codes can affect the SQL database as they are in contained strings to the query.



How may one show the security flaw, so that I can see for myself what is happening?


Answer



Although much of this can be explained online, I have a feeling to explain this in a bit more detail.



If you can visualise what the string will become, you will understand the underlying risks of the script you are writing, in that it will become something else before it is actually ran.




A trivial malicious example:



$fromtheuser = "foo'; DROP TABLE affiliates; --";
$q = "SELECT id FROM affiliates WHERE website = '$fromtheuser'";


Can you explain what this will become? The developer couldn't.



"SELECT id FROM affiliates WHERE website = 'foo'; DROP TABLE affiliates; --'"



The key portions of this vector being '; to end the SQL string primitive, and --' to comment out the pushed quote.



What you would be looking for in the code written, is proper sanitization and filtering of the data before it is even placed in to the query. One important tool to help secure this front is some form of prepared query, in such you can bind the parameters to the query so that there is nothing to manipulate.



We can achieve this with prepared statements in either MySQLi (improved) or my personal favourite PDO. A quick rundown of what they look like.



mysql_real_escape_string (can handle encoding and quotes)




$clean = mysql_real_escape_string($q)


MySQLi:



$clean = $mysqli->prepare("SELECT id FROM affiliates WHERE website = ?");
$clean->bind_param('s', $website); //'s' for 'string'



PDO:



$clean = $pdo->prepare("SELECT id FROM affiliates WHERE website = ?");
$clean->bindParam(1, $website); //you can use :site rather than ? and 1

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...