base64编码映像的安全性问题

Bri*_*ler 5 php security gd image

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

我担心如果在尝试创建缩略图之前未正确验证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);
Run Code Online (Sandbox Code Playgroud)

Bri*_*ler 2

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

经过进一步研究后,我发现我最关心的问题之一是使用内联 PHP、Ruby 等编码的有效图像文件。 EG:末尾带有以下内容的图像:

<?php phpinfo();
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

就总体思路而言,我还发现另一篇 SO 帖子很有用: 验证 base64 编码图像

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