qileilove

blog已经转移至github,大家请访问 http://qaseven.github.io/

手把手叫你SQL注入攻防(PHP语法)

1.什么是SQL注入,猛戳wikipedia查看
  2.本地测试代码:
  如果表单提交正确,就打印hello,“username”
  否则,打印“404 not found!”
<?php
require 'config.php';
$DBConnection = mysql_connect ( "$dbhost", "$dbuser", "$dbpwd" );
mysql_select_db ( "$dbdatabase" );
if(isset($_GET['submit']) && $_GET['submit']){
$sql="select * from test where name='".$_GET['username']."'and password='".$_GET['password']."'";
//echo $sql;exit;
$result=mysql_query($sql,$DBConnection);
$num=mysql_num_rows($result);
if($num>=1)
{
echo "hello,".$_GET['username'];
}
else {
echo"404 not found";
}
}
?>
<form action="login.php" method="GET">
<table>
<tr>
<td>username</td>
<td><input type="textbox" name="username"/></td>
<td>password</td>
<td><input type="textbox" name="password"></td>
<td>submit</td>
<td><input type="submit" name="submit"></td>
</tr>
</table>
</form>
  3.浏览器界面显示:
  4.重头戏,sql注入:
5.原理--为什么用户名不正确,却可以显示hello?
  我可以echo一下:
<span style="font-size:18px;">$sql="select * from test where name='".$_GET['username']."'and password='".$_GET['password']."'";
echo $sql;exit;</span>
  显示:
  拿到我的mysql数据库中查询:
  可以看到,居然能查到信息,因为sql语句中,前一半单引号被闭合,后一半单引号被 “--”给注释掉,中间多了一个永远成立的条件“1=1”,这就造成任何字符都能成功登录的结果。
  6.小结:
  1)其实这个sql注入过程上很简单,困难的地方在于提交SQL注入语句的灵活性上面,单引号的使用很关键,另外,多用echo打印调试也很值得一试~~
  2)GET方式提交表单很危险,所以还是用POST方式吧!
  参考:http://blog.csdn.net/gideal_wang/article/details/4316691
  3)防止SQL注入:可以看出,sql注入就是用户提交一些非法的字符(如本文的单引号’和sql语句的注释号--,还有反斜杠\等),所以要用转义:  htmlspecialchars函数,mysql_read_escape_string函数都可以实现。
  4)JS段验证表单了,JSP/PHP等后台还要验证码?
  ---需要,因为friebug可以禁用JS...
  --------------------------------------------------------------------------
  update:
  上面的方法,当password通过md5加密的话,就无法实现注入了,那么就在username上做手脚:
  username后面的内容就都被注释掉了。哈哈~

posted on 2014-01-29 10:49 顺其自然EVO 阅读(315) 评论(0)  编辑  收藏 所属分类: 数据库


只有注册用户登录后才能发表评论。


网站导航:
 
<2014年1月>
2930311234
567891011
12131415161718
19202122232425
2627282930311
2345678

导航

统计

常用链接

留言簿(55)

随笔分类

随笔档案

文章分类

文章档案

搜索

最新评论

阅读排行榜

评论排行榜