如何防止脚本直接从URL执行?

时间:2017-12-26 15:50:37

标签: php security nginx

我们最近发现某些脚本(如果您知道路径)可以直接从网站外部执行。 (理想情况下,执行脚本的唯一方法应该是ssh - 进入服务器或设置cron(或应用程序功能)

exmple.com/scripts_directory/script_sub_dir_1/script_1_name.php

同样地,我们发现可以直接从媒体文件的路径直接从网站外部访问大量图像和视频。

exmple.com/media_directory/media_sub_directory/media_file.mp4

理想情况下,该网站的用户应该登录以查看任何内容,因为它受版权保护并且需要付费。

我们可以做些什么:

  1. 保护我们的网站免受从网址
  2. 执行的脚本的影响
  3. 保护媒体文件不被访问(如果用户未登录/未在应用程序之外)。
  4. 这些是我正在关注的一些链接: https://webmasters.stackexchange.com/questions/84615/protecting-video-being-from-downloaded Prevent direct access to a php include file

    我们有一个使用php 5.6的nginx服务器。

    更新

    无法访问以下位置。

    exmple.com/scripts_directory/script_sub_dir_1/

    exmple.com/media_directory/media_sub_directory/

    exmple.com/scripts_directory/

    exmple.com/media_directory/

1 个答案:

答案 0 :(得分:2)

防止未经授权的人员下载文件。

要阻止对文件的访问,您可以进行以下配置而不是Nginx:

在我的情况下,文件是:/ etc / nginx / sites-available / default

location ~ \.mp4$ {
        rewrite (.*) /download.php?$args last;
}

此代码将导致对视频的所有访问权限,重定向到文件 download.php

在此文件中,我们可以检查用户是否已登录。

<强>的download.php

<?php

/* Current Folder */
define("PATH", __DIR__);

/* Removes arguments from URL. (You can also do this check in nginx.) */
$request_uri = preg_replace("/\?.*/", "", $_SERVER['REQUEST_URI']);

/* File path */
$file = sprintf("%s%s",
        PATH,
        $request_uri);


/**
 * Checks whether the file exists (You can also do this check in nginx.)
 * Add your rule to see if the user has permission.
 */
if( file_exists($file) && Auth::isLogged()) {

        /* The Content-Type you can add "application/octet-stream" */
        header('Content-Type: video/mp4');
        header("Content-Transfer-Encoding: Binary");
        header("Content-disposition: attachment; filename=\"" . basename($file) . "\"");
        readfile($file);
}
elseif (!file_exists($file)) {
        header("HTTP/1.1 404 Not Found");
} else {
        header("HTTP/1.1 401 Unauthorized");
}

阻止人们访问PHP文件。

要阻止对给定脚本的访问,有两种方法。

  1. index.php中添加常量并检查其他文件(如果已创建)。如果它不是由index.php创建的,则会显示错误消息。
  2. <强>的index.php

    <?php
    
    define("APP_VERSION", "1.0.0");
    

    <强> my_script.php

    <?php
    
    if (!defined("APP_VERSION")) {
        die("Error");
    }
    
    1. 另一种方法是设置评论中提到的deny all
    2. 在我的情况下,文件是:/ etc / nginx / sites-available / default

      location ~ \.php$ {
          include snippets/fastcgi-php.conf;
          fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
      }
      
      # Change path
      location ~ /scripts_directory/script_sub_dir_1/.*\.php$ {
          deny  all;
      }
      

      您也可以只允许几个ip访问。要执行此操作,只需添加:allow YOUR-IP

相关问题