Home > php教程 > php手册 > php 防sql注入方法详解(1/4)

php 防sql注入方法详解(1/4)

WBOY
Release: 2016-06-13 10:11:53
Original
973 people have browsed it

. magic_quotes_gpc = off 时的注入攻击
  magic_quotes_gpc = off 是 php教程 中一种非常不安全的选项。新版本的 php 已经将默认的值改为了 on。但仍有相当多的服务器的选项为 off。毕竟,再古董的服务器也是有人用的。
  当magic_quotes_gpc = on 时,它会将提交的变量中所有的 '(单引号)、"(双号号)、(反斜线)、空白字符,都为在前面自动加上 。下面是 php 的官方说明:


 代码如下:

magic_quotes_gpc boolean
sets the magic_quotes state for gpc (get/post/cookie) operations. when magic_quotes are on, all ' (single-quote), " (double quote), (backslash) and nul's are escaped with a backslash automatically

如果没有转义,即 off 情况下,就会让攻击者有机可乘。以下列测试脚本为例:
 代码如下:


if ( isset($_post["f_login"] ) )
{
// 连接数据库教程...
// ...代码略...

// 检查用户是否存在
$t_struname = $_post["f_uname"];
$t_strpwd = $_post["f_pwd"];
$t_strsql = "select * from tbl_users where username='$t_struname' and password = '$t_strpwd' limit 0,1";

if ( $t_hres = mysql教程_query($t_strsql) )
{
// 成功查询之后的处理. 略...
}
}
?>

sample test


username:

password:



在这个脚本中,当用户输入正常的用户名和密码,假设值分别为 zhang3、abc123,则提交的 sql 语句如下:
 代码如下:

select * from tbl_users
where username='zhang3' and password = 'abc123' limit 0,1

如果攻击者在 username 字段中输入:zhang3' or 1=1 #,在 password 输入 abc123,则提交的 sql 语句变成如下:
 代码如下:

select * from tbl_users
where username='zhang3' or 1=1 #' and password = 'abc123' limit 0,1

由于 # 是 mysql中的注释符, #之后的语句不被执行,实现上这行语句就成了:
 代码如下:

select * from tbl_users
where username='zhang3' or 1=1

这样攻击者就可以绕过认证了。如果攻击者知道数据库结构,那么它构建一个 union select,那就更危险了:
  假设在 username 中输入:zhang3 ' or 1 =1 union select cola, colb,cold from tbl_b #
  在password 输入: abc123,
  则提交的 sql 语句变成:
 代码如下:

select * from tbl_users
where username='zhang3 '
or 1 =1 union select cola, colb,cold from tbl_b #' and password = 'abc123' limit 0,1

1 2 3 4

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template