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

闲话不说,直接来!

理论补充:1.http://blog.csdn.net/wusuopubupt/article/details/8752348

                         2.http://www.cnblogs.com/hkncd/archive/2012/03/31/2426274.html

1.什么是SQL注入,猛戳wikipedia查看

2.本地测试代码:

如果表单提交正确,就打印hello,“username”

否则,打印“404 not found!”

[php] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. <?php   
  2.     require 'config.php';  
  3.     $DBConnection = mysql_connect ( "$dbhost", "$dbuser", "$dbpwd" );  
  4.     mysql_select_db ( "$dbdatabase" );  
  5.       
  6.     if(isset($_GET['submit']) && $_GET['submit']){      
  7.     $sql="select * from test where name='".$_GET['username']."'and password='".$_GET['password']."'";  
  8.     //echo $sql;exit;  
  9.     $result=mysql_query($sql,$DBConnection);      
  10.     $num=mysql_num_rows($result);         
  11.     if($num>=1)  
  12.     {  
  13.         echo "hello,".$_GET['username'];  
  14.     }  
  15.     else {  
  16.         echo"404 not found";  
  17.     }  
  18. }  
  19. ?>  
  20. <form action="login.php" method="GET">  
  21. <table>  
  22.     <tr>  
  23.         <td>username</td>  
  24.         <td><input type="textbox" name="username"/></td>  
  25.         <td>password</td>  
  26.         <td><input type="textbox" name="password"></td>  
  27.         <td>submit</td>  
  28.         <td><input type="submit" name="submit"></td>  
  29.     </tr>  
  30. </table>  
  31. </form>  

3.浏览器界面显示:

4.重头戏,sql注入:

5.原理--为什么用户名不正确,却可以显示hello?

我可以echo一下:

[php] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. <span style="font-size:18px;">$sql="select * from test where name='".$_GET['username']."'and password='".$_GET['password']."'";  
  2. 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后面的内容就都被注释掉了。哈哈~

参考:http://newaurora.pixnet.net/blog/post/166231341-sql-injection-%E7%AF%84%E4%BE%8B(%E7%99%BB%E5%85%A5%E7%AF%84%E4%BE%8B)

by wusuopuBUPT

原文地址:https://www.cnblogs.com/fyy-888/p/5085048.html