动态站点安全风险


dynamic site security risk

我听说我的网站或整个服务器很容易被黑客攻击,因为我的index.php

<?php
include_once 'config.php';
include_once 'includes/mysqlconnect.php';
$url_slash=$_SERVER['REQUEST_URI'];
$url= rtrim($url_slash, '/');
?>
<head>
    <meta charset="UTF-8">
    <title>Site Title</title>
    <link rel="stylesheet" type="text/css" href="<?php echo $domain;?>themes/reset.css">
    <link rel="stylesheet" type="text/css" href="<?php echo $domain;?>themes/<?php echo $theme;?>.css">
</head>
<body class="body">
    <div class="container-all">
        <?php include_once 'includes/header.php';?>
        <div class="container">
            <?php include_once 'includes/navigationbar.php';?>
            <?php include_once 'includes/rightsidebar.php';?>
            <div class="content"><?php
            if ($url==''){
                include_once "sites/home.php";
            }
            elseif (file_exists("sites/$url.php") && is_readable("sites/$url.php")){
                include_once "sites/$url.php";
            }
            else {
                include_once 'sites/404.php';
            }

            ?></div>
            <?php include_once 'includes/footer.php';?>
        </div>
    </div>
</body>

和。htaccess

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index'.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

如何防止人们输入example.com/../../../somefilepeoplemaynotsee.txt

我真的想保持我的url干净,所以没有关于example.com?page=example我想通过在/var/www/html/sites/dir创建一个文件来添加一个站点,然后我添加了一个页面。这不是它的工作原理,但正如我所说的。这是一个很大的安全风险我真的想让我的网站保持动态

任何想法

使用basename,参见:http://php.net/basename

的例子:

$url = rtrim($url_slash, '/');
$url = basename($url);

(注意:这是在最简单的动态级别上。使用MVC之类的已知路由可能更安全)

为了防止本地文件包含漏洞,您必须在尝试将用户输入用作包含的文件名之前验证用户输入。

if (!preg_match("/[^A-Za-z0-9]/", $url)){
    // user input is valided to A-Za-z0-9
    if(file_exists("sites/$url.php")){
        include_once "sites/$url.php";
    }
}

这假设您将只放置用于包含在sites目录中的脚本。显然,如果你有其他代码不包括,那么你需要使用白名单来代替。