【问题标题】:How to verify uploaded image is an actual image and not a harmful code? [closed]如何验证上传的图片是真实图片而不是有害代码? [关闭]
【发布时间】:2014-10-05 04:04:46
【问题描述】:

对于图片上传网站,我需要基本保证上传的文件是图片,而不是可能影响服务器或网站客户端的有害代码。请不要标记以下任何问题的重复项。我也遇到过类似的问题。

需要指导以开始在 PHP 和 jQuery 前端的实际代码实现中执行此操作。

Image sanitization library

Security issues in accepting image uploads

Is it important to verify that the uploaded file is an actual image file?

【问题讨论】:

  • 请不要让别人为你写代码,自己想办法,然后问怎么做。没有人会为您编写执行此操作的应用程序
  • 不问代码,只求正确的方向。喜欢特定于 PHP 的有效方法
  • > 实用代码实现 webcheatsheet.com/php/file_upload.php
  • 我说的是入门指南...:P
  • 没关系,有效的图像仍然可以包含漏洞利用代码。

标签: php image image-uploading jquery-file-upload


【解决方案1】:

第一步是尝试确定图片类型,可以使用exif_imagetype,例如:

$valid_types = array('jpeg','jpg','gif','png');
if (($type = exif_imagetype($_FILES['image']['tmp_name'])) &&
    in_array(ltrim(image_type_to_extension($type), '.'), $valid_types)) {
    // image appears to be valid

为了进一步安全,您应该将文件上传到无法通过浏览器访问的文件夹,并重命名图像。例如:

$upload_path = '/path/to/uploads'; // folder ABOVE www or public_html
$hash = hash_file('sha1', $_FILES['image']['tmp_name']);
$ext = image_type_to_extension($type);
$fname = $hash . $ext;

// save it
if (move_uploaded_file($_FILES['image']['tmp_name'], "$upload_path/$fname")) {
    // image was saved

或者,您可以尝试使用 GD 库或 Imagick 重绘它,而不是使用 move_uploaded_file,并且只保存重绘的副本。如果图像包含任何错误,那么这些库可能无法绘制它。

这应该足够安全。即使用户确实设法利用了某些漏洞,除非您以可预测的方式将其反馈给他们,否则他们也无法执行它,但这仍然不太可能。

【讨论】:

  • 马丁先生回答得很好!您能否判断没有任何易受攻击内容的图像是否有可能在重绘步骤中面临错误。如果它很频繁,那么我不应该使用这一步。 (我的意思是;常见的图像是否经常出现可能无法重绘的错误?)
  • @XIMRX 不,未损坏的有效图像在重绘时永远不会遇到任何错误。
猜你喜欢
  • 1970-01-01
  • 2017-05-28
  • 1970-01-01
  • 1970-01-01
  • 2017-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多