PHP上传文件增强了安全性

man*_*ril 15 php security upload file

嘿..我的问题是如何防止有人上传病毒或某些恶意代码与您假装的扩展程序,例如我有一个pdf文件上传器,任何人都可以上传带有pdf伪装的二进制文件,有很多程序可以做到这一点.

roo*_*ook 13

上传文件时会出现一些安全问题.第一个问题是文件可能不是您想要的文件,在本例中是pdf.该变量$_FILES['file_name']['type']由攻击者控制,永远不可信任.通常使用漏洞利用代码或使用篡改数据修改此值.

1)您的secuirty系统的第一步是确保该文件具有.pdf扩展名:

if("pdf"!=substr($fileName, strrpos($fileName, '.') + 1)){
   die("Invalid File Type");
}
Run Code Online (Sandbox Code Playgroud)

2)接下来你应该使用php filetype()函数检查它是什么文件类型.

3)一个严重的问题是这些PDF文件可以利用Adobe制作的软件中常见的缓冲区溢出等漏洞.这些PDF用于在Drive By Download攻击中传播病毒.

最佳解决方案是安装Web应用程序防火墙Mod_Security.这将阻止sql注入和xss等攻击攻击您的Web应用程序.可以将Mod_Secuirty配置为使用modsec-clamscan扫描所有上载文件中的病毒.

  • filetype()如何帮助?在我看来,它所做的就是告诉你文件是否是文件与目录.也许你的意思是[finfo-file()](http://www.php.net/manual/en/function.finfo-file.php)? (2认同)

Gab*_*osa 7

我们使用fileinfo+文件扩展名检查的组合.虽然浏览器通常发送mime类型,但你永远不应该相信它,因为它可能被劫持.

在我们的例子中,我们不在服务器中运行任何文件.所以我们所做的就是拥有一个extension while list像(例如):pdf jpg pngetc ..和一个列表blacklisted mime extensions.这样我们就可以避免出现扩展名与mime类型不匹配的文件的风险.

一旦文件保存在服务器中,我们总是强制使用mime类型,application/octet-stream因此总是下载文件.

这样的事情:

<?php

$allowed_types = array(
/* images extensions */
'jpeg', 'bmp', 'png', 'gif', 'tiff', 'jpg',
/* audio extensions */
'mp3', 'wav', 'midi', 'aac', 'ogg', 'wma', 'm4a', 'mid', 'orb', 'aif',
/* movie extensions */                              
'mov', 'flv', 'mpeg', 'mpg', 'mp4', 'avi', 'wmv', 'qt',
/* document extensions */                               
'txt', 'pdf', 'ppt', 'pps', 'xls', 'doc', 'xlsx', 'pptx', 'ppsx', 'docx'
                        );


$mime_type_black_list= array(
# HTML may contain cookie-stealing JavaScript and web bugs
'text/html', 'text/javascript', 'text/x-javascript',  'application/x-shellscript',
# PHP scripts may execute arbitrary code on the server
'application/x-php', 'text/x-php', 'text/x-php',
# Other types that may be interpreted by some servers
'text/x-python', 'text/x-perl', 'text/x-bash', 'text/x-sh', 'text/x-csh',
'text/x-c++', 'text/x-c',
# Windows metafile, client-side vulnerability on some systems
# 'application/x-msmetafile',
# A ZIP file may be a valid Java archive containing an applet which exploits the
# same-origin policy to steal cookies      
# 'application/zip',
                        );


$tmp_file_extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

if(!strlen($tmp_file_extension) || (!$allow_all_types &&
  !in_array($tmp_file_extension,$allowed_types))) {
    return false;
}

$finfo = new finfo(FILEINFO_MIME, MIME_MAGIC_PATH);

if ($finfo) {
    $mime = $finfo->file($file_name_tmp);
}
else {
    $mime = $file_type;
}

$mime = explode(" ", $mime);
$mime = $mime[0];

if (substr($mime, -1, 1) == ";") {
    $mime = trim(substr($mime, 0, -1));
}

return (in_array($mime, $mime_type_black_list) == false);
Run Code Online (Sandbox Code Playgroud)

除此之外你可以添加virus scan使用clamav+ 扩展名


Vol*_*erK 1

看一下 php 的FileInfo扩展。实际内容类型的识别与unix命令
类似。 但这仅对恶意用户简单地将virus.exe 重命名为virus.pdf 有用。它不会阻止有害 pdf 的上传(使用一个或多个更广泛使用的 pdf 阅读器中的某些错误)。file