如何在PHP中阻止无效文件上传

软文推广2个月前发布 刘老三
5 0

老练的威胁行为者经常制作恶意文件来利用我们的文件渲染和处理应用程序(甚至包括我们的 Web 浏览器)中的零日漏洞。这些攻击可能会让我们完全措手不及,并导致各种灾难性后果。

如何在PHP中阻止无效文件上传

大多数时候,特制的恶意文件会绕过传统的防病毒扫描(按设计)。但是,它们不会绕过彻底的确定性扫描,根据预期格式验证文件内容。

使用免费的威胁检测 API,我们可以严格验证 PHP 表单中的文件上传,以确保它们符合文件格式标准。它支持数十种常见文件格式 – 包括所有主要 Office 格式、PDF 和 100 多种图像格式 – 因此我们可以在典型的文件上传过程中真正涵盖我们的基础(例如,简历上传、个人资料图片上传、保险索赔上传等) .)

我们也不必担心病毒和恶意软件感染的文件。该 API 将根据定期更新的近 2000 万个病毒和恶意软件签名列表来引用文件内容,因此我们将了解已建立的恶意软件系列是否也隐藏在文件上传中。

为了构造我们的 API 调用,我们需要首先安装 PHP 客户端。我们可以通过从命令行执行以下命令来安装 Composer:

composer require cloudmersive/cloudmersive_virusscan_api_client

接下来,我们应该迅速将注意力转移到授权 API 调用上。我们需要一个免费的 Cloudmersive API 密钥;这将使我们每月能够进行多达 800 次 API 调用,且额外承诺为零。

现在,我们可以使用以下可立即运行的 PHP 代码示例来调用该函数。如果我们想专门指出并阻止任何类型的无效文件上传,我们可以将$allow_invalid_files威胁规则设置为:false

<?php
require_once(__DIR__ . ‘/vendor/autoload.php’);

// Configure API key authorization: Apikey
$config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey(‘Apikey’, ‘YOUR_API_KEY’);

$apiInstance = new Swagger\Client\Api\ScanApi(

new GuzzleHttp\Client(),
$config
);
$input_file = “/path/to/inputfile”; // \SplFileObject | Input file to perform the operation on.
$allow_executables = true; // bool | Set to false to block executable files (program code) from being allowed in the input file. Default is false (recommended).
$allow_invalid_files = true; // bool | Set to false to block invalid files, such as a PDF file that is not really a valid PDF file, or a Word Document that is not a valid Word Document. Default is false (recommended).
$allow_scripts = true; // bool | Set to false to block script files, such as a PHP files, Python scripts, and other malicious content or security threats that can be embedded in the file. Set to true to allow these …) [for API keys created prior to the release of this feature default is true for backward compatability].
$restrict_file_types = “restrict_file_types_example”; // string | Specify a restricted set of file formats to allow as clean as a comma-separated list of file formats, such as .pdf,.docx,.png would allow only PDF, PNG and Word document files. All files must pass content verification against this list of file formats, if they do not, then the result will be returned as CleanResult=false. Set restrictFileTypes parameter to null or empty string to disable; default is disabled.

try {
$result = $apiInstance->scanFileAdvanced($input_file, $allow_executables, $allow_invalid_files, $allow_scripts, $allow_password_protected_files, $allow_macros, $allow_xml_external_entities, $allow_insecure_deserialization, $allow_html, $restrict_file_types);
print_r($result);
} catch (Exception $e) {
echo ‘Exception when calling ScanApi->scanFileAdvanced: ‘, $e->getMessage(), PHP_EOL;
}
?>

这就是全部 – 现在我们可以使用确定性威胁扫描解决方案来阻止无效文件上传。

© 版权声明

相关文章