三十三、MySQL基础系列笔记之MySQL安全问题与SQL注入攻击
SQL注入攻击大多数与程序有关系,程序不严谨是导致SQL注入攻击成功的一个原因。安全问题不容忽视,平常的开发中应关注安全问题。下面简单记录PHP中的SQL攻击问题。
什么是SQL注入攻击
SQL注入(SQL Injection)是利用某些数据库的外部接口将用户数据插入到实际的数据库操作语言(SQL)当中,从而达到入侵数据库甚至是操作系统的目的。SQL注入攻击产生的原因是由于程序对用户输入的数据没有严格过滤,导致非法数据库查询语句的执行。
PHP案例演示SQL注入攻击
正常演示
下面将使用PHP进行简单的SQL注入攻击演示,因此没有多大的代码严谨度,只为演示SQL注入。
<!-- index.html -->
<form action="./my.php" method="POST">
<input type="text" name="name" placeholder="用户名">
<input type="text" name="password" placeholder="密码">
<input type="submit" name="submit" value="提交">
</form>
<?php
// test.php
$conn = mysqli_connect('localhost','root','123456','demo');
if (!$conn) {
exit('数据库连接失败 '. mysqli_connect_error());
}
$name = $_GET['name'];
$password = $_GET['password'];
# 重点在于sql语句
$sql = "select * from user where name='$name' and password='$password'";
$result = mysqli_query($conn, $sql);
$userinfo = mysqli_fetch_array($result);
if (empty($userinfo)) {
echo '登录失败';
} else {
echo '登录成功';
}
echo "<p>SQL语句: $sql </p>";
第一:进行一次正确和错误的用户名与密码进行登录测试。
# 表单中分别输入正确与错误的用户名与密码
# 可以看到用户名与密码正确时正常登录
登录成功
SQL语句: select * from user where name='lisi' and password='123456'
# 可以看到结果,登录失败了
登录失败
SQL语句: select * from user where name='lisi1' and password='1234561'
注意:需要在地址栏输入访问
SQL注入攻击演示
重头戏来了,SQL注入攻击。
注入一:用户名表单中填入 lisi' or '1=1
,密码可填可不填写
注入二:用户名表单中填入lii'#
,密码可填可不填
登录成功
SQL语句: select * from user where name='lisi' or '1=1' and password=''
登录成功
SQL语句: select * from user where name='lisi' #' and password=''
很明显的可以看到,竟然登录成功了,我的天,登录没有密码竟然登录成功了!有些慌呀,有木有。
既然有攻击,那就有防范,下面就利用PHP内置函数对SQL注入进行防范。
预防SQL注入攻击
针对字符串注入攻击,可以在SQL语句中限制特殊符号:单引号,双引号,注释等,已知非法符号有:'、"、;、=、(、)、/*、*/、%、+、>、<、--、[、]
。
方式一:使用正则表达式
$res = "/^[a-zA-Z0-9]{6}$/";
if (empty($name) || empty($password) || !preg_match($res, $name)) {
die('非法登录');
}
方式二:使用PHP内置函数过滤和转义字符串
$name = $_POST['name'];
$name=addslashes($name);
$name=str_replace("%","\%",$name);
$name=str_replace("_","\_",$name);
结果
登录失败
SQL语句: select * from user where name='lisi\' or \'1=1\'' and password=''
2020-11-26
请登录后再评论