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?


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)

<?php
$clean = mysql_real_escape_string($q)

MySQLi:

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

PDO:

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

mysql_query("SELECT * FROM users WHERE username = '$username'");

Look what happens when we set the $username variable to something nasty:

$username = "' OR 1";

The query becomes:

SELECT * FROM users WHERE username = '' OR 1

An attacker can use improperly escaped variables to inject SQL into your query, effectively bypassing any (poor) security measure you have in place.

More info here


It's also worth noting that there are tools through which you can test whether your site is susceptible to injection attacks.

Take a look at

http://sqlmap.sourceforge.net/

链接地址: http://www.djcxy.com/p/93816.html

上一篇: SQL注入漏洞添加更多的平衡?

下一篇: SQL注入在概念上如何工作? (简要)