web攻击方式和防御方法

来源:互联网 发布:台达plc编程视频教程 编辑:程序博客网 时间:2024/04/29 08:20
在http请求报文中加载攻击代码,就能发起对web应用的攻击。通过url查询字段或者表单、http首部、cookie等途径吧攻击代码传入,若这时web应用存在安全漏洞,那内部信息就会遭到窃取!

对web的攻击模式有两种:
  1. 主动攻击(主动攻击服务器)
  2. 被动攻击(上传木马程序,用户访问时触发http陷阱)


实施的安全策略主要分为两步:
  1. 客户端验证
  2. 服务端验证(输入值验证,输出值转义)

两种主要的攻击方式
1.SQL注入攻击(php防止方法是使用mysqli_real_escape_string或者addslashes进行输入数据的转义)
2.XSS攻击(执行js代码获取用户的cookie等信息,进行验证。使用strip_tagshtmlspecialchars或者htmlentities


sql攻击破解

<?php
 $clean = array();
$mysql = array();

$clean['last_name'] = "O'Reilly";
$mysql['last_name'] = mysql_real_escape_string($clean['last_name']);

$sql = "INSERT
      INTO   user (last_name)
      VALUES ('{$mysql['last_name']}')";
 ?>

mysqli_real_escape_string

(PHP 5)

mysqli::real_escape_string -- mysqli_real_escape_string — Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection


尽量使用为你的数据库设计的转义函数。如果没有,使用函数addslashes()是最终的比较好的方法。
string addslashes string $str )

返回字符串,该字符串为了数据库查询语句等的需要在某些字符前加上了反斜线。这些字符是单引号(')、双引号(")、反斜线(\)与    NUL( NULL 字符)。




htmlspecialchars只是将下列的特殊字符转换成实体,htmlentities是将所有的有实体的html标签转换成对应的实体
  • '&' (ampersand) becomes '&amp;'
  • '"' (double quote) becomes '&quot;' when ENT_NOQUOTES is not set.
  • "'" (single quote) becomes '&#039;' (or &apos;) only when ENT_QUOTES is set.
  • '<' (less than) becomes '&lt;'
  • '>' (greater than) becomes '&gt;' 

防止xss攻击

//这是一个有xss攻击的php代码xss.php
<?php
if (isset($_POST['name'])){
//     $str = trim($_POST['name']);  //清理空格
//     $str = strip_tags($str);   //去除html标签
//     $str = htmlspecialchars($str);   //将字符串内容转化成html实体
//     $str = addslashes($str);
//     echo $str;
echo $_POST['name'];
}
setcookie("aaa",'bbb');
?>
<form method="post" action="">
<input name="name" type="text" width="200">
<input type="submit" value="提交" >
</form>


当我访问该页面,并且输入框中输入<script>alert(document.cookie);</script>,下面是原始的页面

点击提交之后

点击确定按钮

注意head内部已经有我们提交的js代码。

如果我们取消代码中的红色的注释部分,再次执行

0 0
原创粉丝点击