如何防止服务器上的每个恶意文件上传? (检查文件类型)? [英] How to prevent every malicious file upload on my server? (check file type)?

查看:976
本文介绍了如何防止服务器上的每个恶意文件上传? (检查文件类型)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是避免用户在我的Web服务器上上传一些恶意文件. 我正在linux环境(debian)上工作.

my proble is to avoid that users upload some malicious file on my web-server. Im working on linux environment (debian).

实际上,上传是通过以下代码通过php处理的:

Actually the uploads are handled via php by this code:

function checkFile($nomeFile, $myExt = false){
if($myExt != false){ $goodExt = "_$myExt"."_"; }else{ $goodExt = "_.jpg_.bmp_.zip_.pdf_.gif_.doc_.xls_.csv_.docx_.rar_"; }
$punto = strrpos($nomeFile, '.');
$ext = "_".substr($nomeFile, $punto, 8)."_";
if(stristr($goodExt, $ext)){ return 1; }else{ return 0; }
}

在这里我可以指定允许上传的扩展名,如果文件不符合要求,我将在上传完成后立即删除. 但是通过这种方式,用户可以通过简单的重命名来自由更改文件扩展名.即使在file.jpg中重命名了file.exe(例如)永远不会执行(是吗?),我也不希望服务器上有潜在的危险文件.

here i can specify the extensions allowed to be uploaded, and if the file dont meet them i delete as soon as the upload is completed. But this way let the user free to change the file extension with a simple rename.. and thats bad for me; even if a file.exe (for example) wont never be executed if is renamed in file.jpg (am i right?), i dont want to have potential danger files on my server.

有没有一种方法可以在php,python或其他方式下轻松地运行unix系统来检查文件的真实类型?

There is a way, in php, python, or whatelse can a unix system run easly, to check the truly type of a file?

我已经尝试了python mimetypes模块,但是它基于扩展名-.-

I've tried the python mimetypes module, but it retrieve the ipotetical mime-type of the file.. based on the extension -.-

推荐答案

您需要验证上传的文件实际上是扩展名指示的类型.您可以通过多种方法来执行此操作,最简单的方法可能是通过file命令.我不知道它是否有API.您可以在shell中自己尝试一下.对于在上载之前已重命名为file.jpg的file.exe示例,请运行file file.jpg,它将打印出一些内容,告诉您它是可执行文件.但是,它可以被愚弄.

You're going to need to validate that the uploaded file is actually the type that the extension indicates it is. You can do that through various methods, probably the easiest is via the file command. I don't know if it has an API. You can try it out yourself in the shell. For your example of file.exe that was renamed to file.jpg before being uploaded, run file file.jpg and it will print out something telling you it's an executable. It can be fooled, however.

我想如果您认为.exe意味着它将被执行,则您对Linux文件权限的了解不多.在Linux上,只有文件许可权中的execute位才能确定-如果该位打开,则可以执行任何文件,而无需考虑扩展名.不要在任何上传的文件上设置它,应该安全地执行它们.您可能仍在将他们提供给您网站的访问者,因此它仍可能是XSS攻击的媒介,因此请当心.

I'm guessing you don't know much about Linux file permissions if you think .exe means it will be executed. On linux, only the execute bit in the file permissions determine that -- you can execute any file, regardless of extension, if that bit is turned on. Don't set it on any uploaded files and you should be safe from executing them. You may still be serving them back up to your site's visitors, so it could still be a vector for XSS attacks, so watch out for that.

这篇关于如何防止服务器上的每个恶意文件上传? (检查文件类型)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆