Implemented: editor uploads are constrained to safe image files inside
the upload tree, and public form submissions are size-bounded and rate-limited
This commit is contained in:
+2
-1
@@ -16,7 +16,8 @@ dist-ssr
|
|||||||
/docs
|
/docs
|
||||||
|
|
||||||
cache
|
cache
|
||||||
uploads
|
uploads/*
|
||||||
|
!uploads/.htaccess
|
||||||
extensions/dev_*
|
extensions/dev_*
|
||||||
.agents
|
.agents
|
||||||
skills-lock.json
|
skills-lock.json
|
||||||
|
|||||||
@@ -27,6 +27,7 @@
|
|||||||
RewriteRule ^themes/([^/]+)/public/(.*)$ themes/$1/public/$2 [L]
|
RewriteRule ^themes/([^/]+)/public/(.*)$ themes/$1/public/$2 [L]
|
||||||
|
|
||||||
# Allow direct access to uploaded files with URL format: /uploads/{filepath;,}
|
# Allow direct access to uploaded files with URL format: /uploads/{filepath;,}
|
||||||
|
RewriteRule ^uploads/.*\.(?:php[0-9]*|phtml|phar)(?:/|$) - [F,NC]
|
||||||
RewriteRule ^uploads/(.*)$ uploads/$1 [L]
|
RewriteRule ^uploads/(.*)$ uploads/$1 [L]
|
||||||
|
|
||||||
# Rewrite all remaining requests to index.php
|
# Rewrite all remaining requests to index.php
|
||||||
|
|||||||
@@ -7,22 +7,44 @@ use Plugi\Extensions\Form\Finishers\FinishersRepository;
|
|||||||
|
|
||||||
class SubmissionHandler
|
class SubmissionHandler
|
||||||
{
|
{
|
||||||
|
public const MAX_REQUEST_BYTES = 65536;
|
||||||
|
public const MAX_FIELD_BYTES = 16384;
|
||||||
|
public const MAX_FIELDS = 100;
|
||||||
|
|
||||||
private $formsRepository;
|
private $formsRepository;
|
||||||
private $finishersRepository;
|
private $finishersRepository;
|
||||||
|
private $rateLimiter;
|
||||||
|
|
||||||
public function __construct($formsRepository = null, $finishersRepository = null)
|
public function __construct($formsRepository = null, $finishersRepository = null, $rateLimiter = null)
|
||||||
{
|
{
|
||||||
$this->formsRepository = $formsRepository ?? new DefinitionsRepository();
|
$this->formsRepository = $formsRepository ?? new DefinitionsRepository();
|
||||||
$this->finishersRepository = $finishersRepository ?? new FinishersRepository();
|
$this->finishersRepository = $finishersRepository ?? new FinishersRepository();
|
||||||
|
$this->rateLimiter = $rateLimiter ?? new SubmissionRateLimiter();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function handle($formId, string $rawData): array
|
public function handle($formId, string $rawData): array
|
||||||
{
|
{
|
||||||
|
if (strlen($rawData) > self::MAX_REQUEST_BYTES) {
|
||||||
|
return $this->failure(413, ['The submission is too large.']);
|
||||||
|
}
|
||||||
|
|
||||||
$formId = filter_var($formId, FILTER_VALIDATE_INT);
|
$formId = filter_var($formId, FILTER_VALIDATE_INT);
|
||||||
if ($formId === false || $formId < 1) {
|
if ($formId === false || $formId < 1) {
|
||||||
return $this->failure(400, ['A valid form id is required.']);
|
return $this->failure(400, ['A valid form id is required.']);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$clientIp = $_SERVER['REMOTE_ADDR'] ?? '';
|
||||||
|
if (!is_string($clientIp) || filter_var($clientIp, FILTER_VALIDATE_IP) === false) {
|
||||||
|
$clientIp = 'unknown';
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
if (!$this->rateLimiter->consume($formId, $clientIp)) {
|
||||||
|
return $this->failure(429, ['Too many submissions. Please try again later.']);
|
||||||
|
}
|
||||||
|
} catch (\Throwable $exception) {
|
||||||
|
return $this->failure(503, ['Submissions are temporarily unavailable.']);
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$form = $this->formsRepository->findWithId($formId);
|
$form = $this->formsRepository->findWithId($formId);
|
||||||
} catch (\Throwable $exception) {
|
} catch (\Throwable $exception) {
|
||||||
@@ -125,6 +147,10 @@ class SubmissionHandler
|
|||||||
$knownFields = [];
|
$knownFields = [];
|
||||||
$supportedTypes = ['text', 'email', 'textarea', 'checkbox', 'radio', 'select'];
|
$supportedTypes = ['text', 'email', 'textarea', 'checkbox', 'radio', 'select'];
|
||||||
|
|
||||||
|
if (count($submittedFields) > self::MAX_FIELDS) {
|
||||||
|
return ['The submission contains too many fields.'];
|
||||||
|
}
|
||||||
|
|
||||||
foreach ($formFields as $field) {
|
foreach ($formFields as $field) {
|
||||||
if (!is_array($field) || !isset($field['name']) || !is_string($field['name']) || trim($field['name']) === '' || !isset($field['label']) || !is_string($field['label']) || !isset($field['type']) || !is_string($field['type']) || !in_array($field['type'], $supportedTypes, true)) {
|
if (!is_array($field) || !isset($field['name']) || !is_string($field['name']) || trim($field['name']) === '' || !isset($field['label']) || !is_string($field['label']) || !isset($field['type']) || !is_string($field['type']) || !in_array($field['type'], $supportedTypes, true)) {
|
||||||
return ['The form contains an invalid field configuration.'];
|
return ['The form contains an invalid field configuration.'];
|
||||||
@@ -160,6 +186,20 @@ class SubmissionHandler
|
|||||||
if (!is_string($name) || !array_key_exists($name, $knownFields)) {
|
if (!is_string($name) || !array_key_exists($name, $knownFields)) {
|
||||||
return ['The submission contains an unknown field.'];
|
return ['The submission contains an unknown field.'];
|
||||||
}
|
}
|
||||||
|
$value = $submittedFields[$name];
|
||||||
|
if (is_string($value) && strlen($value) > self::MAX_FIELD_BYTES) {
|
||||||
|
return ['A submitted field is too large.'];
|
||||||
|
}
|
||||||
|
if (is_array($value)) {
|
||||||
|
if (count($value) > self::MAX_FIELDS) {
|
||||||
|
return ['A submitted field contains too many values.'];
|
||||||
|
}
|
||||||
|
foreach ($value as $item) {
|
||||||
|
if (is_string($item) && strlen($item) > self::MAX_FIELD_BYTES) {
|
||||||
|
return ['A submitted field is too large.'];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach ($knownFields as $name => $field) {
|
foreach ($knownFields as $name => $field) {
|
||||||
|
|||||||
@@ -0,0 +1,79 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Plugi\Extensions\Form;
|
||||||
|
|
||||||
|
use RuntimeException;
|
||||||
|
|
||||||
|
class SubmissionRateLimiter
|
||||||
|
{
|
||||||
|
private const MAX_SUBMISSIONS = 5;
|
||||||
|
private const WINDOW_SECONDS = 600;
|
||||||
|
|
||||||
|
private $db;
|
||||||
|
private string $table;
|
||||||
|
|
||||||
|
public function __construct($db = null)
|
||||||
|
{
|
||||||
|
global $phpb_db;
|
||||||
|
|
||||||
|
$this->db = $db ?? $phpb_db ?? null;
|
||||||
|
$prefix = preg_replace('/[^a-zA-Z0-9_]/', '', $_ENV['DATABASE_PREFIX'] ?? '');
|
||||||
|
$this->table = '`' . $prefix . 'ext__form_submission_limits`';
|
||||||
|
}
|
||||||
|
|
||||||
|
public function consume(int $formId, string $clientIp): bool
|
||||||
|
{
|
||||||
|
if (!is_object($this->db)) {
|
||||||
|
throw new RuntimeException('The submission rate limit store is unavailable.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$now = time();
|
||||||
|
$ipHash = hash('sha256', $clientIp);
|
||||||
|
if (!$this->db->query(
|
||||||
|
"INSERT IGNORE INTO {$this->table} (formId, ipHash, startedAt, submissions) VALUES (?, ?, ?, 0)",
|
||||||
|
[$formId, $ipHash, $now]
|
||||||
|
)) {
|
||||||
|
throw new RuntimeException('The submission rate limit could not be initialized.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$allowed = $this->db->transaction(function () use ($formId, $ipHash, $now): bool {
|
||||||
|
$rows = $this->db->select(
|
||||||
|
"SELECT startedAt, submissions FROM {$this->table} WHERE formId = ? AND ipHash = ? FOR UPDATE",
|
||||||
|
[$formId, $ipHash]
|
||||||
|
);
|
||||||
|
if (empty($rows)) {
|
||||||
|
throw new RuntimeException('The submission rate limit could not be loaded.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$startedAt = (int) $rows[0]['startedAt'];
|
||||||
|
$submissions = (int) $rows[0]['submissions'];
|
||||||
|
if ($now - $startedAt >= self::WINDOW_SECONDS) {
|
||||||
|
$startedAt = $now;
|
||||||
|
$submissions = 0;
|
||||||
|
}
|
||||||
|
if ($submissions >= self::MAX_SUBMISSIONS) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!$this->db->query(
|
||||||
|
"UPDATE {$this->table} SET startedAt = ?, submissions = ? WHERE formId = ? AND ipHash = ?",
|
||||||
|
[$startedAt, $submissions + 1, $formId, $ipHash]
|
||||||
|
)) {
|
||||||
|
throw new RuntimeException('The submission rate limit could not be updated.');
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
|
||||||
|
if ($allowed && random_int(1, 100) === 1) {
|
||||||
|
try {
|
||||||
|
$this->db->query(
|
||||||
|
"DELETE FROM {$this->table} WHERE startedAt < ?",
|
||||||
|
[$now - (self::WINDOW_SECONDS * 2)]
|
||||||
|
);
|
||||||
|
} catch (\Throwable $exception) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $allowed;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -35,6 +35,17 @@ return [
|
|||||||
],
|
],
|
||||||
"uniqueKeys" => [],
|
"uniqueKeys" => [],
|
||||||
],
|
],
|
||||||
|
"submission_limits" => [
|
||||||
|
"columns" => [
|
||||||
|
"formId" => "int NOT NULL",
|
||||||
|
"ipHash" => "char(64) NOT NULL",
|
||||||
|
"startedAt" => "int unsigned NOT NULL",
|
||||||
|
"submissions" => "int unsigned NOT NULL",
|
||||||
|
],
|
||||||
|
"uniqueKeys" => [
|
||||||
|
"form_ip" => ["formId", "ipHash"],
|
||||||
|
],
|
||||||
|
],
|
||||||
"definitions" => [
|
"definitions" => [
|
||||||
"columns" => [
|
"columns" => [
|
||||||
"name" => "varchar(255) NOT NULL",
|
"name" => "varchar(255) NOT NULL",
|
||||||
|
|||||||
@@ -1,7 +1,14 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
$handler = new \Plugi\Extensions\Form\SubmissionHandler();
|
$handler = new \Plugi\Extensions\Form\SubmissionHandler();
|
||||||
$result = $handler->handle($_GET['id'] ?? null, file_get_contents('php://input') ?: '');
|
$rawData = file_get_contents(
|
||||||
|
'php://input',
|
||||||
|
false,
|
||||||
|
null,
|
||||||
|
0,
|
||||||
|
\Plugi\Extensions\Form\SubmissionHandler::MAX_REQUEST_BYTES + 1
|
||||||
|
);
|
||||||
|
$result = $handler->handle($_GET['id'] ?? null, is_string($rawData) ? $rawData : '');
|
||||||
|
|
||||||
http_response_code($result['status']);
|
http_response_code($result['status']);
|
||||||
header('Content-Type: application/json; charset=utf-8');
|
header('Content-Type: application/json; charset=utf-8');
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ namespace FormExtensionTests {
|
|||||||
require_once dirname(__DIR__) . '/admin/Classes/Finishers/SendConfirmationEmailToSubmitter.php';
|
require_once dirname(__DIR__) . '/admin/Classes/Finishers/SendConfirmationEmailToSubmitter.php';
|
||||||
require_once dirname(__DIR__) . '/admin/Classes/Finishers/SendWebhook.php';
|
require_once dirname(__DIR__) . '/admin/Classes/Finishers/SendWebhook.php';
|
||||||
require_once dirname(__DIR__) . '/admin/Classes/Finishers/FinishersRepository.php';
|
require_once dirname(__DIR__) . '/admin/Classes/Finishers/FinishersRepository.php';
|
||||||
|
require_once dirname(__DIR__) . '/admin/Classes/SubmissionRateLimiter.php';
|
||||||
|
|
||||||
class TestMailer
|
class TestMailer
|
||||||
{
|
{
|
||||||
@@ -160,6 +161,40 @@ namespace FormExtensionTests {
|
|||||||
return ['class' => $this->finishers[$key]];
|
return ['class' => $this->finishers[$key]];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class RateLimitDatabase
|
||||||
|
{
|
||||||
|
public array $rows = [];
|
||||||
|
|
||||||
|
public function query(string $query, array $parameters = []): bool
|
||||||
|
{
|
||||||
|
if (str_starts_with($query, 'INSERT IGNORE')) {
|
||||||
|
$key = $parameters[0] . ':' . $parameters[1];
|
||||||
|
$this->rows[$key] ??= ['startedAt' => $parameters[2], 'submissions' => 0];
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (str_starts_with($query, 'UPDATE')) {
|
||||||
|
$key = $parameters[2] . ':' . $parameters[3];
|
||||||
|
$this->rows[$key] = ['startedAt' => $parameters[0], 'submissions' => $parameters[1]];
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (str_starts_with($query, 'DELETE')) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
throw new \RuntimeException('Unexpected rate limiter query.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function select(string $query, array $parameters): array
|
||||||
|
{
|
||||||
|
$key = $parameters[0] . ':' . $parameters[1];
|
||||||
|
return isset($this->rows[$key]) ? [$this->rows[$key]] : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function transaction(callable $callback): mixed
|
||||||
|
{
|
||||||
|
return $callback();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
namespace Plugi {
|
namespace Plugi {
|
||||||
@@ -177,6 +212,7 @@ namespace {
|
|||||||
|
|
||||||
use FormExtensionTests\DefinitionsRepository as TestDefinitionsRepository;
|
use FormExtensionTests\DefinitionsRepository as TestDefinitionsRepository;
|
||||||
use FormExtensionTests\FinishersRepository as TestFinishersRepository;
|
use FormExtensionTests\FinishersRepository as TestFinishersRepository;
|
||||||
|
use FormExtensionTests\RateLimitDatabase as TestRateLimitDatabase;
|
||||||
use Plugi\Extensions\Form\SubmissionHandler;
|
use Plugi\Extensions\Form\SubmissionHandler;
|
||||||
|
|
||||||
if (!function_exists('phpb_instance')) {
|
if (!function_exists('phpb_instance')) {
|
||||||
@@ -193,11 +229,41 @@ namespace {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function makeHandler($form): SubmissionHandler
|
function makeHandler($form, $rateLimiter = null): SubmissionHandler
|
||||||
{
|
{
|
||||||
return new SubmissionHandler(new TestDefinitionsRepository($form), new TestFinishersRepository());
|
return new SubmissionHandler(new TestDefinitionsRepository($form), new TestFinishersRepository(), $rateLimiter ?? new AllowSubmissionRateLimiter());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class AllowSubmissionRateLimiter
|
||||||
|
{
|
||||||
|
public function consume(int $formId, string $clientIp): bool
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class RejectSubmissionRateLimiter
|
||||||
|
{
|
||||||
|
public function consume(int $formId, string $clientIp): bool
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$rateLimitDatabase = new TestRateLimitDatabase();
|
||||||
|
$rateLimiter = new \Plugi\Extensions\Form\SubmissionRateLimiter($rateLimitDatabase);
|
||||||
|
for ($submission = 0; $submission < 5; $submission++) {
|
||||||
|
assertSameValue(true, $rateLimiter->consume(7, '203.0.113.1'), 'Submissions within the limit must be allowed.');
|
||||||
|
}
|
||||||
|
assertSameValue(false, $rateLimiter->consume(7, '203.0.113.1'), 'Submissions over the limit must be rejected.');
|
||||||
|
assertSameValue(true, $rateLimiter->consume(8, '203.0.113.1'), 'Rate limits must be scoped to each form.');
|
||||||
|
assertSameValue(true, $rateLimiter->consume(7, '203.0.113.2'), 'Rate limits must be scoped to each client IP.');
|
||||||
|
$rateLimitKey = '7:' . hash('sha256', '203.0.113.1');
|
||||||
|
$rateLimitDatabase->rows[$rateLimitKey]['startedAt'] = time() - 601;
|
||||||
|
$rateLimitDatabase->rows[$rateLimitKey]['submissions'] = 5;
|
||||||
|
assertSameValue(true, $rateLimiter->consume(7, '203.0.113.1'), 'Expired rate limit windows must reset.');
|
||||||
|
assertSameValue(1, $rateLimitDatabase->rows[$rateLimitKey]['submissions'], 'The reset window must begin at one submission.');
|
||||||
|
|
||||||
function validForm(array $finishers = []): array
|
function validForm(array $finishers = []): array
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
@@ -223,6 +289,31 @@ namespace {
|
|||||||
assertSameValue(true, $result['body']['success'], 'Successful actions must report success');
|
assertSameValue(true, $result['body']['success'], 'Successful actions must report success');
|
||||||
assertSameValue(['first', 'second'], $GLOBALS['formFinisherCalls'], 'Actions must run in configured order');
|
assertSameValue(['first', 'second'], $GLOBALS['formFinisherCalls'], 'Actions must run in configured order');
|
||||||
|
|
||||||
|
$GLOBALS['formFinisherCalls'] = [];
|
||||||
|
$result = makeHandler($form, new RejectSubmissionRateLimiter())->handle(7, $validPayload);
|
||||||
|
assertSameValue(429, $result['status'], 'Rate-limited submissions must be rejected');
|
||||||
|
assertSameValue([], $GLOBALS['formFinisherCalls'], 'Rate-limited submissions must not run actions');
|
||||||
|
|
||||||
|
$GLOBALS['formFinisherCalls'] = [];
|
||||||
|
$result = makeHandler($form)->handle(7, str_repeat('x', 65537));
|
||||||
|
assertSameValue(413, $result['status'], 'Oversized request bodies must be rejected');
|
||||||
|
assertSameValue([], $GLOBALS['formFinisherCalls'], 'Oversized requests must not run actions');
|
||||||
|
|
||||||
|
$GLOBALS['formFinisherCalls'] = [];
|
||||||
|
$oversizedField = json_encode(['fields' => ['name' => str_repeat('A', 16385)]]);
|
||||||
|
$result = makeHandler($form)->handle(7, $oversizedField);
|
||||||
|
assertSameValue(422, $result['status'], 'Oversized field values must be rejected');
|
||||||
|
assertSameValue([], $GLOBALS['formFinisherCalls'], 'Oversized fields must not run actions');
|
||||||
|
|
||||||
|
$tooManyFields = array_fill_keys(array_map('strval', range(1, 101)), 'value');
|
||||||
|
$result = makeHandler($form)->handle(7, json_encode(['fields' => $tooManyFields]));
|
||||||
|
assertSameValue(422, $result['status'], 'Submissions with too many fields must be rejected');
|
||||||
|
|
||||||
|
$submitRoute = file_get_contents(dirname(__DIR__) . '/routes/submit.php');
|
||||||
|
if (strpos($submitRoute, 'MAX_REQUEST_BYTES + 1') === false) {
|
||||||
|
throw new \RuntimeException('The submission route must read no more than the configured body limit plus one byte.');
|
||||||
|
}
|
||||||
|
|
||||||
$GLOBALS['formFinisherCalls'] = [];
|
$GLOBALS['formFinisherCalls'] = [];
|
||||||
$GLOBALS['formFinisherResults'] = ['first' => false, 'second' => true];
|
$GLOBALS['formFinisherResults'] = ['first' => false, 'second' => true];
|
||||||
$result = makeHandler($form)->handle(7, $validPayload);
|
$result = makeHandler($form)->handle(7, $validPayload);
|
||||||
|
|||||||
@@ -135,15 +135,35 @@ class PageBuilder implements PageBuilderContract
|
|||||||
{
|
{
|
||||||
$publicId = sha1(uniqid(rand(), true));
|
$publicId = sha1(uniqid(rand(), true));
|
||||||
$uploader = phpb_instance(Uploader::class, ['files']);
|
$uploader = phpb_instance(Uploader::class, ['files']);
|
||||||
|
$allowedImages = [
|
||||||
|
'image/jpeg' => 'jpg',
|
||||||
|
'image/png' => 'png',
|
||||||
|
'image/gif' => 'gif',
|
||||||
|
'image/webp' => 'webp',
|
||||||
|
'image/bmp' => 'bmp',
|
||||||
|
];
|
||||||
|
if (!is_string($uploader->file_src_name) || !isset($allowedImages[$uploader->file_src_mime])) {
|
||||||
|
http_response_code(415);
|
||||||
|
die('Upload error: Unsupported image type');
|
||||||
|
}
|
||||||
|
|
||||||
|
$sourceName = basename(str_replace('\\', '/', $uploader->file_src_name));
|
||||||
|
$originalFile = preg_replace('/[^A-Za-z0-9._-]/', '-', $sourceName);
|
||||||
|
$originalFile = substr($originalFile, 0, 150);
|
||||||
|
$baseName = preg_replace('/[^A-Za-z0-9_-]+/', '-', pathinfo($sourceName, PATHINFO_FILENAME));
|
||||||
|
$baseName = trim(substr($baseName, 0, 100), '-_');
|
||||||
|
$fileName = ($baseName !== '' ? $baseName : 'image') . '.' . $allowedImages[$uploader->file_src_mime];
|
||||||
|
|
||||||
|
$uploader->MIME_allowed = array_keys($allowedImages);
|
||||||
$uploader
|
$uploader
|
||||||
->file_name($publicId . '/' . str_replace(' ', '-', $uploader->file_src_name))
|
->file_name($publicId . '/' . $fileName)
|
||||||
->upload_to(phpb_config('storage.uploads_folder') . '/')
|
->upload_to(phpb_config('storage.uploads_folder') . '/')
|
||||||
|
->mime_check()
|
||||||
->run();
|
->run();
|
||||||
|
|
||||||
if (! $uploader->was_uploaded) {
|
if (! $uploader->was_uploaded) {
|
||||||
die("Upload error: {$uploader->error}");
|
die("Upload error: {$uploader->error}");
|
||||||
} else {
|
} else {
|
||||||
$originalFile = str_replace(' ', '-', $uploader->file_src_name);
|
|
||||||
$originalMime = $uploader->file_src_mime;
|
$originalMime = $uploader->file_src_mime;
|
||||||
$serverFile = $uploader->final_file_name;
|
$serverFile = $uploader->final_file_name;
|
||||||
|
|
||||||
|
|||||||
@@ -27,7 +27,6 @@ class Uploader {
|
|||||||
$finfo = finfo_open(FILEINFO_MIME_TYPE);
|
$finfo = finfo_open(FILEINFO_MIME_TYPE);
|
||||||
if ($finfo) {
|
if ($finfo) {
|
||||||
$mime = finfo_file($finfo, $filePath);
|
$mime = finfo_file($finfo, $filePath);
|
||||||
finfo_close($finfo);
|
|
||||||
if (!empty($mime)) {
|
if (!empty($mime)) {
|
||||||
return $mime;
|
return $mime;
|
||||||
}
|
}
|
||||||
@@ -256,6 +255,11 @@ class Uploader {
|
|||||||
* @throws Exception
|
* @throws Exception
|
||||||
*/
|
*/
|
||||||
public function run() {
|
public function run() {
|
||||||
|
$uploadRoot = rtrim($this->upload_to, '/\\');
|
||||||
|
if ($uploadRoot === '') {
|
||||||
|
$uploadRoot = DIRECTORY_SEPARATOR;
|
||||||
|
}
|
||||||
|
|
||||||
// check whether the final name is in random mode
|
// check whether the final name is in random mode
|
||||||
if ($this->file_name !== true) {
|
if ($this->file_name !== true) {
|
||||||
// preserve file extension if provided
|
// preserve file extension if provided
|
||||||
@@ -264,13 +268,24 @@ class Uploader {
|
|||||||
} else {
|
} else {
|
||||||
$file = $this->file_name;
|
$file = $this->file_name;
|
||||||
}
|
}
|
||||||
$path = $this->upload_to . $file;
|
|
||||||
$this->upload_to = dirname($path);
|
|
||||||
} else {
|
} else {
|
||||||
$hash = bin2hex(random_bytes(16));
|
$hash = bin2hex(random_bytes(16));
|
||||||
$file = $hash . '.' . $this->file_src_name_ext;
|
$file = $hash . '.' . $this->file_src_name_ext;
|
||||||
$path = $this->upload_to . $file;
|
|
||||||
}
|
}
|
||||||
|
if (!$this->isSafeRelativePath($file)) {
|
||||||
|
$this->was_uploaded = false;
|
||||||
|
$this->error = 'Invalid destination file name.';
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
$relativeFile = str_replace('\\', '/', $file);
|
||||||
|
$destinationDirectory = $this->getSafeDestinationDirectory($uploadRoot, $relativeFile);
|
||||||
|
if ($destinationDirectory === null) {
|
||||||
|
$this->was_uploaded = false;
|
||||||
|
$this->error = 'Destination directory must remain inside the upload folder.';
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
$path = $destinationDirectory . DIRECTORY_SEPARATOR . basename($relativeFile);
|
||||||
|
$this->upload_to = $destinationDirectory;
|
||||||
|
|
||||||
$get_mime = isset($this->mime_check) ? true : false;
|
$get_mime = isset($this->mime_check) ? true : false;
|
||||||
|
|
||||||
@@ -282,6 +297,9 @@ class Uploader {
|
|||||||
$this->was_uploaded = false;
|
$this->was_uploaded = false;
|
||||||
$this->error = "Incorrect type of file";
|
$this->error = "Incorrect type of file";
|
||||||
}
|
}
|
||||||
|
if (!$this->was_uploaded) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
// check file maximum size
|
// check file maximum size
|
||||||
if ($this->file_src_size > $this->get_file_max_size) {
|
if ($this->file_src_size > $this->get_file_max_size) {
|
||||||
@@ -290,18 +308,6 @@ class Uploader {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// check whether destination directory exists or attempt to create it
|
|
||||||
if ($this->get_auto_create_path) {
|
|
||||||
if (! $this->r_mkdir($this->upload_to)) {
|
|
||||||
$this->was_uploaded = false;
|
|
||||||
$this->error = "Destination directory can't be created. Can't carry on a process";
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
} elseif (! is_dir($this->upload_to)) {
|
|
||||||
$this->error = "Destination directory doesn't exist. Can't carry on a process";
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// check whether file already exists or if are replacing it
|
// check whether file already exists or if are replacing it
|
||||||
if (file_exists($path)) {
|
if (file_exists($path)) {
|
||||||
if (! $this->get_auto_replace) {
|
if (! $this->get_auto_replace) {
|
||||||
@@ -364,6 +370,60 @@ class Uploader {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected function isSafeRelativePath(string $file): bool
|
||||||
|
{
|
||||||
|
$file = str_replace('\\', '/', $file);
|
||||||
|
if ($file === '' || str_starts_with($file, '/') || preg_match('/^[A-Za-z]:/', $file) || str_contains($file, "\0")) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (explode('/', $file) as $segment) {
|
||||||
|
if ($segment === '' || $segment === '.' || $segment === '..') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function getSafeDestinationDirectory(string $uploadRoot, string $relativeFile): ?string
|
||||||
|
{
|
||||||
|
if (!is_dir($uploadRoot) && (!$this->get_auto_create_path || !$this->r_mkdir($uploadRoot))) {
|
||||||
|
$this->error = "Destination directory can't be created. Can't carry on a process";
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$realRoot = realpath($uploadRoot);
|
||||||
|
if (!$realRoot) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$relativeDirectory = dirname($relativeFile);
|
||||||
|
if ($relativeDirectory === '.') {
|
||||||
|
return $realRoot;
|
||||||
|
}
|
||||||
|
|
||||||
|
$directory = $realRoot;
|
||||||
|
foreach (explode('/', $relativeDirectory) as $segment) {
|
||||||
|
$nextDirectory = $directory . DIRECTORY_SEPARATOR . $segment;
|
||||||
|
if (is_link($nextDirectory)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (!is_dir($nextDirectory) && (!$this->get_auto_create_path || !$this->_mkdir($nextDirectory))) {
|
||||||
|
$this->error = "Destination directory can't be created. Can't carry on a process";
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$realDirectory = realpath($nextDirectory);
|
||||||
|
if (!$realDirectory || !str_starts_with($realDirectory, $realRoot . DIRECTORY_SEPARATOR)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
$directory = $realDirectory;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $directory;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create directories recursively.
|
* Create directories recursively.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Plugi\Modules\GrapesJS\Upload\Uploader;
|
||||||
|
|
||||||
|
require_once __DIR__ . '/../src/Modules/GrapesJS/Upload/Uploader.php';
|
||||||
|
|
||||||
|
function assertUploadSecurity(bool $condition, string $message): void
|
||||||
|
{
|
||||||
|
if (!$condition) {
|
||||||
|
throw new RuntimeException($message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$uploadRoot = sys_get_temp_dir() . '/plugi-upload-security-' . bin2hex(random_bytes(8));
|
||||||
|
assertUploadSecurity(mkdir($uploadRoot), 'The upload security test folder could not be created.');
|
||||||
|
|
||||||
|
$outsideFile = dirname($uploadRoot) . '/plugi-upload-escape-' . bin2hex(random_bytes(8)) . '.php';
|
||||||
|
$imagePath = __DIR__ . '/../dist/pagebuilder/images/image-placeholder.png';
|
||||||
|
$traversalUpload = new Uploader([
|
||||||
|
'name' => 'image.png',
|
||||||
|
'tmp_name' => $imagePath,
|
||||||
|
'size' => filesize($imagePath),
|
||||||
|
'error' => UPLOAD_ERR_OK,
|
||||||
|
], false);
|
||||||
|
$traversalUpload
|
||||||
|
->file_name('../' . basename($outsideFile))
|
||||||
|
->upload_to($uploadRoot . '/')
|
||||||
|
->run();
|
||||||
|
assertUploadSecurity(!$traversalUpload->was_uploaded, 'Path traversal destinations must be rejected.');
|
||||||
|
assertUploadSecurity(!file_exists($outsideFile), 'Path traversal must not create files outside the upload folder.');
|
||||||
|
|
||||||
|
$linkedDirectory = $uploadRoot . '/linked';
|
||||||
|
assertUploadSecurity(symlink(dirname($uploadRoot), $linkedDirectory), 'The upload symlink test could not be created.');
|
||||||
|
$symlinkFile = dirname($uploadRoot) . '/plugi-upload-symlink-' . bin2hex(random_bytes(8)) . '.png';
|
||||||
|
$symlinkUpload = new Uploader([
|
||||||
|
'name' => 'image.png',
|
||||||
|
'tmp_name' => $imagePath,
|
||||||
|
'size' => filesize($imagePath),
|
||||||
|
'error' => UPLOAD_ERR_OK,
|
||||||
|
], false);
|
||||||
|
$symlinkUpload
|
||||||
|
->file_name('linked/' . basename($symlinkFile))
|
||||||
|
->upload_to($uploadRoot . '/')
|
||||||
|
->run();
|
||||||
|
assertUploadSecurity(!$symlinkUpload->was_uploaded, 'Symlinked destination folders must be rejected.');
|
||||||
|
assertUploadSecurity(!file_exists($symlinkFile), 'Symlinked destinations must not create files outside the upload folder.');
|
||||||
|
assertUploadSecurity(unlink($linkedDirectory), 'The upload symlink test could not be removed.');
|
||||||
|
|
||||||
|
$scriptUpload = new Uploader([
|
||||||
|
'name' => 'payload.php',
|
||||||
|
'tmp_name' => __FILE__,
|
||||||
|
'size' => filesize(__FILE__),
|
||||||
|
'error' => UPLOAD_ERR_OK,
|
||||||
|
], false);
|
||||||
|
$scriptUpload->MIME_allowed = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/bmp'];
|
||||||
|
$scriptUpload
|
||||||
|
->file_name('payload.jpg')
|
||||||
|
->upload_to($uploadRoot . '/')
|
||||||
|
->mime_check()
|
||||||
|
->run();
|
||||||
|
assertUploadSecurity(!$scriptUpload->was_uploaded, 'Non-image uploads must be rejected when image MIME validation is enabled.');
|
||||||
|
|
||||||
|
$uploadRules = file_get_contents(dirname(__DIR__, 2) . '/uploads/.htaccess');
|
||||||
|
assertUploadSecurity(strpos($uploadRules, 'Require all denied') !== false, 'Uploaded PHP scripts must be denied by the Apache upload rules.');
|
||||||
|
assertUploadSecurity(rmdir($uploadRoot), 'The upload security test folder could not be removed.');
|
||||||
|
|
||||||
|
echo "Upload security checks passed.\n";
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
<IfModule mod_rewrite.c>
|
||||||
|
RewriteEngine On
|
||||||
|
RewriteRule \.(?:php[0-9]*|phtml|phar)(?:/|$) - [F,NC]
|
||||||
|
</IfModule>
|
||||||
|
|
||||||
|
<IfModule mod_authz_core.c>
|
||||||
|
<FilesMatch "(?i)\.(php[0-9]*|phtml|phar)$">
|
||||||
|
Require all denied
|
||||||
|
</FilesMatch>
|
||||||
|
</IfModule>
|
||||||
|
|
||||||
|
<IfModule mod_access_compat.c>
|
||||||
|
<FilesMatch "(?i)\.(php[0-9]*|phtml|phar)$">
|
||||||
|
Order allow,deny
|
||||||
|
Deny from all
|
||||||
|
</FilesMatch>
|
||||||
|
</IfModule>
|
||||||
Reference in New Issue
Block a user