我有一个内部有表单的HTML文件。提交此表单后,它将POST请求发送到PHP文件。 PHP文件创建与MySQL DB的连接并在其中更新一行。
问题是任何人都可以获取此POST请求并将其发送到PHP文件同时,因为PHP收到这些请求后,它将在DB中执行更新并破坏DB。
如何阻止用户发送这些请求?如何更改我的代码并使其更安全?
非常感谢!
index.html
<form action="send.php" method="post">
<input type="text" name="product">
<button type="submit">Submit and Send</button>
</form>
和...
send.php
<?php
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'root';
$DATABASE_PASS = '';
$DATABASE_NAME = 'test';
$conn = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
if ( mysqli_connect_errno() ) {
// If there is an error with the connection, stop the script and display the error.
exit('Failed to connect to MySQL: ' . mysqli_connect_error());
}
$prod = $_POST['product'];
$date = date('d.m.Y');
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, "INSERT INTO store (product, date_added) VALUES (?,?)")) {
exit('MySQL Error');
} else {
mysqli_stmt_bind_param($stmt, 'ss', $prod, $date);
mysqli_stmt_execute($stmt);
header('Location: index.html');
exit();
}
?>
我的数据库就像:
id | product | date_added |
--------------------------------
1 | wood | 01.01.2020 |
--------------------------------
[有一个使用fail2ban的解决方案。请给文档fail2ban
您可以在您的代码中引入一行,以在自定义日志文件中添加一行,例如/var/log/mysites/somesite.log
中的一行
以这种方式:
<?php
# ( we will use this function to determine the corect ip of the spammer)
function getRealUserIp(){
switch(true){
case (!empty($_SERVER['HTTP_X_REAL_IP'])) : return $_SERVER['HTTP_X_REAL_IP'];
case (!empty($_SERVER['HTTP_CLIENT_IP'])) : return $_SERVER['HTTP_CLIENT_IP'];
case (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) : return $_SERVER['HTTP_X_FORWARDED_FOR'];
default : return $_SERVER['REMOTE_ADDR'];
}
}
[...]
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, "INSERT INTO store (product, date_added) VALUES (?,?)")) {
exit('MySQL Error');
} else {
mysqli_stmt_bind_param($stmt, 'ss', $prod, $date);
mysqli_stmt_execute($stmt);
$ip = getRealUserIp(); // <<<<<<<<
error_log("Visitor from - $ip !", 3, "/var/log/mysites/somesite.log"); // <<<<<<
header('Location: index.html');
exit();
}
[...]
下一步,您必须安装和配置fail2ban
apt install fail2ban
然后您必须在/ etc / fail2ban / jail.conf中添加一个部分,并在最后添加此部分
[your_app]
port = http,https
logpath = /var/log/mysites/somesite.log
然后您需要在/ etc / fail2ban / filter.d / your_app.conf中插入一个过滤器
# Fail2Ban filter for your_app.conf, looks for failed access attempts [INCLUDES] # Read common prefixes. If any customizations available -- read them from # common.local before = common.conf [Definition] # Regexp to fit your logfile entry ... read the fail2ban documentation # and customize as this is just a example failregex = ^(*.) <HOST> !$ ignoreregex =
然后您返回控制台并打开怪物...
fail2ban-client stop
fail2ban-client add your_app
fail2ban-client start
fail2ban-client status your_app