就是通过把SQL命令插入到Web表单提交或输入域名或页面请求的查询字符串,最终达到欺骗服务器执行恶意的SQL命令.在用户名输入框中输入:' or 1=1#,密码随便输入,这时候的合成后的SQL查询语句为“#”在mysql中是注释符,这样井号后面的内容将被mysql视为注释内容,这样就不会去执行了,等价于
- select * from users where username='' or 1=1
防止SQL注入
- <?php
- $field = explode(',', $data);
- array_walk($field, array($this, 'add_special_char'));
- $data = implode(',', $field);
- /**
- * 对字段两边加反引号,以保证数据库安全
- * @param $value 数组值
- */
- function add_special_char(&$value)
- {
- if ('*' == $value || false !== strpos($value, '(') || false !== strpos($value, '.') || false !== strpos($value, '`')) {
- //不处理包含* 或者 使用了sql方法。
- } else {
- $value = '`' . trim($value) . '`';
- }
- return $value;
- }
- /*
- 函数名称:inject_check()
- 函数作用:检测提交的值是不是含有SQL注入的字符,保护服务器安全
- 参 数:$sql_str: 提交的变量inject_check($id) { exit('提交的参数非法!');
- 返 回 值:返回检测结果,true or false
- */
- function inject_check($sql_str)
- {
- return preg_match('/^select|insert|and|or|create|update|delete|alter|count|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile/i', $sql_str); // 进行过滤
- }
- //递归ddslashes
- function daddslashes($string, $force = 0, $strip = FALSE)
- {
- if (!get_magic_quotes_gpc() || $force) {
- if (is_array($string)) {
- foreach ($string as $key => $val) {
- $string [$key] = daddslashes($val, $force);
- }
- } else {
- $string = addslashes($strip ? stripslashes($string) : $string);
- }
- }
- return $string;
- }
- //递归stripslashes
- function dstripslashes($string)
- {
- if (is_array($string)) {
- foreach ($string as $key => $val) {
- $string [$key] = $this->dstripslashes($val);
- }
- } else {
- $string = stripslashes($string);
- }
- return $string;
- }
CSRF攻击(跨站请求伪造)原理比较简单,如图1所示。
其中Web A为存在CSRF漏洞的网站,Web B为攻击者构建的恶意网站,User C为Web A网站的合法用户。
1. 用户C打开浏览器,访问受信任网站A,输入用户名和密码请求登录网站A;
2.在用户信息通过验证后,网站A产生Cookie信息并返回给浏览器,此时用户登录网站A成功,可以正常发送请求到网站A;
3. 用户未退出网站A之前,在同一浏览器中,打开一个TAB页访问网站B;
4. 网站B接收到用户请求后,返回一些攻击性代码,并发出一个请求要求访问第三方站点A;
5. 浏览器在接收到这些攻击性代码后,根据网站B的请求,在用户不知情的情况下携带Cookie信息,向网站A发出请求。网站A并不知道该请求其实是由B发起的,所以会根据用户C的Cookie信息以C的权限处理该请求,导致来自网站B的恶意代码被执行。
网站A
- <?php
- session_start();
- if (isset($_POST['toBankId']) && isset($_POST['money'])) {
- buy_stocks($_POST['toBankId'], $_POST['money']);
- }
- ?>
危险网站B
- <html>
- <head>
- <script type="text/javascript">
- function steal() {
- iframe = document.frames["steal"];
- iframe.document.Submit("transfer");
- }
- </script>
- </head>
- <body onload="steal()">
- <iframe name="steal" display="none">
- <form method="POST" name="transfer" action="http://www.myBank.com/Transfer.php">
- <input type="hidden" name="toBankId" value="11">
- <input type="hidden" name="money" value="1000">
- </form>
- </iframe>
- </body>
- </html>
修复方式:1验证码 2检测refer 3目前主流的做法是使用Token抵御CSRF攻击
XSS(跨站脚本)它允许恶意web用户将代码植入到提供给其它用户使用的页面中。比如这些代码包括HTML代码和客户端脚本.
当用户点击以上攻击者提供的URL时,index.php页面被植入脚本,页面源码如下:
- <?php
- $name = $_GET['name'];
- echo "Welcome $name<br>";
- echo '<a href="http://www.cnblogs.com/bangerlee/">Click to Download</a>';
- ?>
这时,当攻击者给出以下URL链接:
- index.php?name=guest<script>alert('attacked')</script>
当用户点击该链接时,将产生以下html代码,带'attacked'的告警提示框弹出:
- Welcome guest
- <script>alert('attacked')</script>
- <br>
- <a href='http://www.cnblogs.com/bangerlee/'>Click to Download</a>
跨站脚本的过滤RemoveXss函数
- function RemoveXSS($val) {
- // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
- // this prevents some character re-spacing such as <java\0script>
- // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
- $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);
- // straight replacements, the user should never need these since they're normal characters
- // this prevents like <IMG SRC=@avascript:alert('XSS')>
- $search = 'abcdefghijklmnopqrstuvwxyz';
- $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
- $search .= '1234567890!@#$%^&*()';
- $search .= '~`";:?+/={}[]-_|\'\\';
- for ($i = 0; $i < strlen($search); $i++) {
- // ;? matches the ;, which is optional
- // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
- // @ @ search for the hex values
- $val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ;
- // @ @ 0{0,7} matches '0' zero to seven times
- $val = preg_replace('/(�{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
- }
- // now the only remaining whitespace attacks are \t, \n, and \r
- $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
- $ra2 = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
- $ra = array_merge($ra1, $ra2);
- $found = true; // keep replacing as long as the previous round replaced something
- while ($found == true) {
- $val_before = $val;
- for ($i = 0; $i < sizeof($ra); $i++) {
- $pattern = '/';
- for ($j = 0; $j < strlen($ra[$i]); $j++) {
- if ($j > 0) {
- $pattern .= '(';
- $pattern .= '(&#[xX]0{0,8}([9ab]);)';
- $pattern .= '|';
- $pattern .= '|(�{0,8}([9|10|13]);)';
- $pattern .= ')*';
- }
- $pattern .= $ra[$i][$j];
- }
- $pattern .= '/i';
- $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag
- $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
- if ($val_before == $val) {
- // no replacements were made, so exit the loop
- $found = false;
- }
- }
- }
- return $val;
- }