这段代码如何引入SQL注入漏洞?
问题描述:
此代码是从另一篇文章在Notice: Undefined offset: 0 in采取它被指出存在SQL注入漏洞。这个代码是脆弱的,它如何被利用,以及如何安全呢?这段代码如何引入SQL注入漏洞?
<?php
include("config.php");
function getAllVotes($id)
{
$votes = array();
$q = "SELECT * FROM entries WHERE id = $id";
$r = mysql_query($q);
if(mysql_num_rows($r)==1)//id found in the table
{
$row = mysql_fetch_assoc($r);
$votes[0] = $row['votes_up'];
$votes[1] = $row['votes_down'];
}
return $votes;
}
function getEffectiveVotes($id)
{
$votes = getAllVotes($id);
$effectiveVote = $votes[0] - $votes[1]; //ERROR THROWN HERE
return $effectiveVote;
}
$id = $_POST['id'];
$action = $_POST['action'];
//get the current votes
$cur_votes = getAllVotes($id);
//ok, now update the votes
if($action=='vote_up') //voting up
{
$votes_up = $cur_votes[0]+1; //AND ERROR THROWN HERE
$q = "UPDATE threads SET votes_up = $votes_up WHERE id = $id";
}
elseif($action=='vote_down')
{
$votes_down = $cur_votes[1]+1;
$q = "UPDATE threads SET votes_down = $votes_down WHERE id = $id";
}
$r = mysql_query($q);
if($r)
{
$effectiveVote = getEffectiveVotes($id);
echo $effectiveVote." votes";
}
elseif(!$r) //voting failed
{
echo "Failed!";
}
?>
这样的:'WHERE ID = $ id'。如果我要传递“$ id = 17; DROP TABLE条目”会怎么样?你可以阅读更多关于sql注入[这里](http://bobby-tables.com/)。你可以通过使用[prepared statements。](https://dev.mysql.com/doc/refman/5.0/en/sql-syntax-prepared-statements.html)来避免它。还有其他技术,比如铸造$ id如果你知道它应该总是一个整数,则为整数。 –
请参阅[母亲的利用](http://imgs.xkcd.com/comics/exploits_of_a_mom.png) – user3791372
做得好@devlincarnate。我在答案中忘记了“准备好的陈述”的名字。此外,提供替代解决方案(铸造)。 – andrewgu