Как безопасно очистить файлы Word и Excel в обработчике загрузки файлов PHP? [закрыто]Php

Кемеровские программисты php общаются здесь
Ответить
Anonymous
 Как безопасно очистить файлы Word и Excel в обработчике загрузки файлов PHP? [закрыто]

Сообщение Anonymous »

Я создаю функцию PHP для очистки файлов, загруженных через форму. Форма позволяет пользователям загружать изображения (JPEG, PNG), документы PDF, Excel и Word. Меня беспокоят потенциальные риски, связанные с макросами в файлах Word и Excel.

Код: Выделить всё

function process_file_upload() {
$uploaded_files = [];

foreach ($_FILES as $file_input_name => $file_info) {
if (is_array($file_info['name'])) {
foreach ($file_info['name'] as $key => $value) {
$file = [
'name' => $file_info['name'][$key],
'type' => $file_info['type'][$key],
'tmp_name' => $file_info['tmp_name'][$key],
'error' => $file_info['error'][$key],
'size' => $file_info['size'][$key],
];

$file_result = process_single_file_upload($file);
if ($file_result['success']) {
$uploaded_files[] = $file_result['file_path'];
} else {
return $file_result;
}
}
} else {
$file_result = process_single_file_upload($file_info);
if ($file_result['success']) {
$uploaded_files[] = $file_result['file_path'];
} else {
return $file_result;
}
}
}

return ['success' => true, 'message' => 'Files processed successfully.', 'file_paths' => $uploaded_files];
}

function process_single_file_upload($file) {
if ($file['size'] == 0) {
return ['success' => true, 'file_path' => ''];
}

if ($file['error'] !== UPLOAD_ERR_OK) {
return ['success' => false, 'message' => 'File upload error.'];
}

$max_upload_size_bytes = get_option('max_upload_size', 3) * 1024 * 1024; // Convert MB to Bytes

if ($file['size'] > $max_upload_size_bytes) {
return ['success' => false, 'message' => 'File is too large.'];
}

$allowedTypes = ['image/jpeg', 'image/png', 'application/pdf','application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document','application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$fileType = finfo_file($finfo, $file['tmp_name']);
finfo_close($finfo);

if (!in_array($fileType, $allowedTypes)) {
return ['success' => false, 'message' => 'Invalid file type.'];
}

$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
$randomFileName = bin2hex(random_bytes(16)) . '.' . $extension;
$new_location = get_option('upload_directory', '/home/ibteka5/tmp/') . $randomFileName;

if (!move_uploaded_file($file['tmp_name'], $new_location)) {
return ['success' => false, 'message' => 'Failed to move uploaded file.'];
}

// Sanitize the file based on its type
if ($fileType === 'application/pdf') {
if (!sanitize_pdf_with_imagick_in_place($new_location)) {
return ['success' => false, 'message' => 'Failed to sanitize PDF.'];
}
} elseif (in_array($fileType, ['image/jpeg', 'image/png'])) {
if (!sanitize_image_with_imagick($new_location)) {
return ['success' => false, 'message' => 'Failed to sanitize image.'];
}
}

return ['success' => true, 'message' => 'File processed successfully.', 'file_path' => $new_location];
}

function sanitize_pdf_with_imagick_in_place($pdf_path) {
try {
$imagick = new Imagick();
$pdf_res = get_option('pdf_resolution', 300); // Increase resolution to 300 DPI
$pdf_comp = get_option('pdf_compression', 95); // Increase compression quality to 95

$imagick->setResolution($pdf_res, $pdf_res);
$imagick->readImage($pdf_path);
$imagick->setImageCompression(Imagick::COMPRESSION_JPEG);
$imagick->setImageCompressionQuality($pdf_comp);
$imagick->setImageFormat('pdf');

// Write each page to a new file and combine them into a single PDF
$imagick->writeImages($pdf_path, true);

$imagick->clear();
$imagick->destroy();

if (file_exists($pdf_path)) {
return true;
} else {
error_log("Sanitized PDF not created. Path: " .  $pdf_path);
return false;
}
} catch (Exception $e) {
error_log("Imagick Error: " . $e->getMessage());
return false;
}
}

function sanitize_image_with_imagick($image_path) {
try {
$imagick = new Imagick($image_path);

// Resize the image to a maximum width and height (optional)
$max_width = 1920;
$max_height = 1080;

if ($imagick->getImageWidth() > $max_width || $imagick->getImageHeight() > $max_height) {
$imagick->resizeImage($max_width, $max_height, Imagick::FILTER_LANCZOS, 1, true);
}

// Set compression and format
$imagick->setImageCompression(Imagick::COMPRESSION_JPEG);
$imagick->setImageCompressionQuality(90);
$imagick->stripImage(); // Remove metadata
$imagick->writeImage($image_path);

$imagick->clear();
$imagick->destroy();

if (file_exists($image_path)) {
return true;
} else {
error_log("Sanitized image not created. Path: " . $image_path);
return false;
}
} catch (Exception $e) {
error_log("Imagick Error: " . $e->getMessage());
return false;
}
}
Хотя мне удалось обработать и очистить изображения и PDF-файлы, я не знаю, как подойти к очистке файлов Word и Excel из-за риска вредоносного ПО на основе макросов.
  • Каковы наилучшие методы очистки файлов Word и Excel?
  • Существуют ли в PHP какие-либо библиотеки или инструменты, которые могут помочь в обнаружении и удалить макросы в этих документах?
Будем очень признательны за любые рекомендации или примеры.

Подробнее здесь: https://stackoverflow.com/questions/787 ... ad-handler
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Php»