base64编码图像的安全性问题

时间:2015-12-14 04:39:25

标签: php image security gd

我有一个接受base64编码图像数据的API,需要解码数据,保存图像文件,然后从该图像创建缩略图。

我担心如果在尝试创建缩略图之前我没有正确验证POST有效内容的内容,恶意代码就会被执行。

我到目前为止的基本工作流程如下。是否有足够的验证,我不需要担心安全性?我想我担心某人编码不好的东西,然后当调用下面的图像函数之一时,互联网会爆炸。

<?php

$decodedImage = base64_decode($_POST["canvas"]);
if ($decodedImage === false) {
    // Error out
}

$imageSizeValidation = getimagesizefromstring($decodedImage);
if ($imageSizeValidation[0] < 1 || $imageSizeValidation[1] < 1 || !$imageSizeValidation['mime']) {
    // Error out
}

$tempFilePath = "/tmp/" . microtime(true) . "-canvas-web.jpg";
file_put_contents($tempFilePath, $decodedImage);

$originalWidth = $imageSizeValidation[0];
$originalHeight = $imageSizeValidation[1];
$newWidth = 49;
$newHeight = 49;

$scaleWidth = $newWidth / $originalWidth;
$scaleHeight = $newHeight / $originalHeight;
$scale = min($scaleWidth, $scaleHeight);

$width = (int)($originalWidth * $scale);
$height = (int)($originalHeight * $scale);

$xpos = (int)(($newWidth - $width) / 2);
$ypos = (int)(($newHeight - $height) / 2);

$oldImage = imagecreatefromjpeg($tempFilePath);
$newImage = imagecreatetruecolor($width, $height);
$background = imagecolorallocate($oldImage, 255, 255, 255);

imagefilledrectangle($newImage, 0, 0, $width, $height, $background);

imagecopyresampled($newImage, $oldImage, $xpos, $ypos, 0, 0, $width, $height, $originalWidth, $originalHeight);
imagedestroy($oldImage);

imagejpeg($newImage, "/path/to/new.jpg", 90);

imagedestroy($newImage);

1 个答案:

答案 0 :(得分:0)

没有得到任何答案,所以对那些对我最终做的事感兴趣的人:

在对此进行了更多研究之后,我发现我最担心的一个问题是使用内联PHP,Ruby等编码的有效图像文件.EG:最后一张图片包含以下内容:

<?php phpinfo();

我最终获取了解码后的图像数据,并将其提供给imagecreatefromstring(),然后通过imagejpeg()将图像保存到临时目录。

这似乎从原始图像数据中删除了任何编码的PHP。此时,我使用getimagesize()验证了保存图像的图像大小数据。假设此时一切都有效,我将图像移动到永久位置。

我改变的另一件事是,我没有使用基于静态字符串和microtime()的文件名,而是使用了哈希。

关于注入代码的图像的关注,我发现这个链接很有帮助: https://www.owasp.org/index.php/Unrestricted_File_Upload

我还发现其他SO帖子很有用,就整体想法而言: Validating base64 encoded images

最后,下面的书首先引起了我对关注图像的关注: http://www.apress.com/9781430233183

相关问题