最简单的sql注入

       这里写的是最简单的sql注入,刚入门其他之后再写。首先,先理解一下sql注入,百度百科:所谓sql注入,就是通过把sql命令插入到Web表单提交或输入域名或页面请求的查询字符串,最终达到欺骗服务器执行恶意的sql命令。具体来说,它是利用现有应用程序,将(恶意的)sql命令注入到后台数据库引擎执行的能力,它可以通过在Web表单中输入(恶意)sql语句得到一个存在安全漏洞的网站上的数据库,而不是按照设计者意图去执行sql语句。当应用程序使用输入内容来构造动态sql语句以访问数据库时,就会发生sql注入攻击。

       比如做一个表单提交的页面就要连接数据库,连接数据库代码使用的就是许多sql语句,而sql注入攻击就是构造一个特殊的sql语句在不知道用户名密码的情况下直接登录。然后实验一下:

       先创建建一张数据表再添加几条记录(这里就不写了)用于测验,之后就是做一个有sql注入漏洞的web提交表单。代码:登录界面login.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>登录页面</title>
<style type="text/css">
form {
text-align: center;
}
</style>
</head>
<body>
<form method="post" action="login.php">
用户名:<input type="text" name='username' maxlength="20"/><br />
密 码:<input type="password" name='password' maxlength="18"/><br /><br />
<input type="submit" value='登录' name="submit" />
</form>
</body>
</html>

表单数据提交到login.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php
header('content-type:text/html;charset=utf-8');
error_reporting(E_ALL ^ E_NOTICE);
if ( ( $_POST['username'] != null ) && ( $_POST['password'] != null ) ) {
$userName = $_POST['username'];
$password = $_POST['password'];
$con = mysqli_connect('localhost','root','root');
if (!$con) {
die('数据库连接失败'.$mysql_error());
}
mysqli_select_db($con,"ymh");

$sql = "select * from user where username = '$userName' and password='$password'";
$res = mysqli_query($con,$sql);
$arr = mysqli_fetch_assoc($res);
if($arr)
{
header('Location: welcome.html');
}
else
{
echo"<script>alert('用户名或密码错误!');location.href = 'login.html';</script>";
}
}else{
echo"<script>alert('用户名和密码不能为空!');location.href = 'login.html';</script>";
}
?>

       这一步是web表单最重要的一步连接数据库,但也是sql漏洞所在。看上面代码是直接将提交过来的数据执行,没有进行任何防范措施,也就是这一句

1
$sql = "select * from user where username = '$userName' and password='$password'";

判断用户名密码是否正确,可以进行sql注入。

登陆成功welcome.html

1
2
3
4
5
6
7
8
9
<html>
<head>
<meta charset="UTF-8">
<title>欢迎登陆</title>
</head>
<body>
<p>Hello World</p>
</body>
</html>

先进PHPstudy中的MySQL-Front试一下,首先看正确的执行语句1

然后就是用’ or 1=1#构造sql语句:

1
select * from user where username = '' or 1=1#' and password='123456'

执行一下:2

       可以看到执行成功并且表中所有值都显示出来了,这是因为#是注释的意思后面都被注释掉了,这时sql语句就等价与

1
select * from user where username = '' or 1=1

那这条语句是成立的,因为1=1是恒成立的,where语句为真。所以这条sql语句又等价于

1
select * from user

这条语句就是检索user表中所有字段。

这样在web表单提交页面用户名一栏输入’ or 1=1#,密码随意输就能登陆成功了。试一下3


4

       登陆成功,sql注入完成。可以看出来sql注入就是通过构造特殊的sql语句来进行的,所以学习sql注入首先就要熟练各种sql语句、数据库的增删改查等。