Talk is cheap,show me the code.
問(wèn)題代碼:
<?php
$servername="127.0.0.1";
$dbuser="muke_user";
$dbpassword="9Gcag71Gaa";
$dbname="muke";
$mysqli = new mysqli($servername,$dbuser,$dbpassword,$dbname); //配置MySQL連接
if($mysqli->connect_error){
die('connect error:'.$mysqli->connect_errno);
}
$mysqli->set_charset('UTF-8'); // 設(shè)置數(shù)據(jù)庫(kù)字符集
$username = isset($_GET['username']) ? $_GET['username'] : '';
$password = isset($_GET['password']) ? $_GET['password'] : '';
$sql = "select * from t24 where username='$username' and password= '$password'";
echo "$sql<br/>";
$result = $mysqli->query("$sql");
$data = $result->fetch_all(); // 從結(jié)果集中獲取所有數(shù)據(jù)
if (empty($data))
{
echo "登錄失敗";
} else {
echo "登錄成功";
}
echo "<br/>";
print_r($data);
?>
sql注入攻擊:
http://localhost/index.php?username=tmd' or '1=1
sql語(yǔ)句變?yōu)椋?br>
select * from d_table where username = 'tmd' or '1=1' and password=''
登錄成功!
解決方案:
1.參數(shù)的過(guò)濾
<?php
$servername="127.0.0.1";
$dbuser="muke_user";
$dbpassword="9Gcag71Gaa";
$dbname="muke";
$mysqli = new mysqli($servername,$dbuser,$dbpassword,$dbname); //配置MySQL連接
if($mysqli->connect_error){
die('connect error:'.$mysqli->connect_errno);
}
$mysqli->set_charset('UTF-8'); // 設(shè)置數(shù)據(jù)庫(kù)字符集
$username = isset($_GET['username']) ? $_GET['username'] : '';
$password = isset($_GET['password']) ? $_GET['password'] : '';
//增加對(duì)輸入用戶名密碼的判斷,如果不是字母或者數(shù)字,就直接提示格式錯(cuò)誤而退出。
if( !preg_match("/^[a-zA-Z0-9]{1,}$/",$username) || !preg_match("/^[a-zA-Z0-9]{1,}$/",$password) ) {
die("You input username and password format error ");
}
$sql = "select * from t24 where username='$username' and password= '$password'";
echo "$sql<br/>";
$result = $mysqli->query("$sql");
$data = $result->fetch_all(); // 從結(jié)果集中獲取所有數(shù)據(jù)
if (empty($data))
{
echo "登錄失敗";
} else {
echo "登錄成功";
}
echo "<br/>";
print_r($data);
?>
對(duì)用戶輸入的用戶名和密碼,進(jìn)行了正則的匹配,不符合規(guī)則的終止程序執(zhí)行,參數(shù)校驗(yàn)不要忘記!
- addslashes()函數(shù)轉(zhuǎn)義特殊字符
$sql = "select * from t24 where username='" . addslashes($username) . "' and password= '" . addslashes($password) . "'";
再次攻擊:
http://localhost/index.php?username=tmd' or '1=1
sql語(yǔ)句變?yōu)椋?br>
select * from d_table where username = 'tmd\'or\'1=1' and password=''
登錄失敗!