diff --git a/.gitignore b/.gitignore index 7495b29..c868951 100644 --- a/.gitignore +++ b/.gitignore @@ -16,7 +16,8 @@ dist-ssr /docs cache -uploads +uploads/* +!uploads/.htaccess extensions/dev_* .agents skills-lock.json diff --git a/.htaccess b/.htaccess index 9d077ef..eded6ae 100644 --- a/.htaccess +++ b/.htaccess @@ -27,6 +27,7 @@ RewriteRule ^themes/([^/]+)/public/(.*)$ themes/$1/public/$2 [L] # 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] # Rewrite all remaining requests to index.php diff --git a/extensions/plugi-ext-form/admin/Classes/SubmissionHandler.php b/extensions/plugi-ext-form/admin/Classes/SubmissionHandler.php index a66e5dd..01af273 100644 --- a/extensions/plugi-ext-form/admin/Classes/SubmissionHandler.php +++ b/extensions/plugi-ext-form/admin/Classes/SubmissionHandler.php @@ -7,22 +7,44 @@ use Plugi\Extensions\Form\Finishers\FinishersRepository; class SubmissionHandler { + public const MAX_REQUEST_BYTES = 65536; + public const MAX_FIELD_BYTES = 16384; + public const MAX_FIELDS = 100; + private $formsRepository; 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->finishersRepository = $finishersRepository ?? new FinishersRepository(); + $this->rateLimiter = $rateLimiter ?? new SubmissionRateLimiter(); } 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); if ($formId === false || $formId < 1) { 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 { $form = $this->formsRepository->findWithId($formId); } catch (\Throwable $exception) { @@ -125,6 +147,10 @@ class SubmissionHandler $knownFields = []; $supportedTypes = ['text', 'email', 'textarea', 'checkbox', 'radio', 'select']; + if (count($submittedFields) > self::MAX_FIELDS) { + return ['The submission contains too many fields.']; + } + 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)) { return ['The form contains an invalid field configuration.']; @@ -160,6 +186,20 @@ class SubmissionHandler if (!is_string($name) || !array_key_exists($name, $knownFields)) { 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) { diff --git a/extensions/plugi-ext-form/admin/Classes/SubmissionRateLimiter.php b/extensions/plugi-ext-form/admin/Classes/SubmissionRateLimiter.php new file mode 100644 index 0000000..1eba319 --- /dev/null +++ b/extensions/plugi-ext-form/admin/Classes/SubmissionRateLimiter.php @@ -0,0 +1,79 @@ +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; + } +} \ No newline at end of file diff --git a/extensions/plugi-ext-form/config.php b/extensions/plugi-ext-form/config.php index cb9a0e9..d6ed03e 100644 --- a/extensions/plugi-ext-form/config.php +++ b/extensions/plugi-ext-form/config.php @@ -35,6 +35,17 @@ return [ ], "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" => [ "columns" => [ "name" => "varchar(255) NOT NULL", diff --git a/extensions/plugi-ext-form/routes/submit.php b/extensions/plugi-ext-form/routes/submit.php index c1662eb..ba96b4b 100644 --- a/extensions/plugi-ext-form/routes/submit.php +++ b/extensions/plugi-ext-form/routes/submit.php @@ -1,7 +1,14 @@ 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']); header('Content-Type: application/json; charset=utf-8'); diff --git a/extensions/plugi-ext-form/tests/SubmissionHandlerTest.php b/extensions/plugi-ext-form/tests/SubmissionHandlerTest.php index 3d87f1a..299eeaa 100644 --- a/extensions/plugi-ext-form/tests/SubmissionHandlerTest.php +++ b/extensions/plugi-ext-form/tests/SubmissionHandlerTest.php @@ -6,6 +6,7 @@ namespace FormExtensionTests { 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/FinishersRepository.php'; + require_once dirname(__DIR__) . '/admin/Classes/SubmissionRateLimiter.php'; class TestMailer { @@ -160,6 +161,40 @@ namespace FormExtensionTests { 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 { @@ -177,6 +212,7 @@ namespace { use FormExtensionTests\DefinitionsRepository as TestDefinitionsRepository; use FormExtensionTests\FinishersRepository as TestFinishersRepository; + use FormExtensionTests\RateLimitDatabase as TestRateLimitDatabase; use Plugi\Extensions\Form\SubmissionHandler; 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 { return [ @@ -223,6 +289,31 @@ namespace { assertSameValue(true, $result['body']['success'], 'Successful actions must report success'); 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['formFinisherResults'] = ['first' => false, 'second' => true]; $result = makeHandler($form)->handle(7, $validPayload); diff --git a/plugi-core/src/Modules/GrapesJS/PageBuilder.php b/plugi-core/src/Modules/GrapesJS/PageBuilder.php index 766be3c..65d2476 100644 --- a/plugi-core/src/Modules/GrapesJS/PageBuilder.php +++ b/plugi-core/src/Modules/GrapesJS/PageBuilder.php @@ -135,15 +135,35 @@ class PageBuilder implements PageBuilderContract { $publicId = sha1(uniqid(rand(), true)); $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 - ->file_name($publicId . '/' . str_replace(' ', '-', $uploader->file_src_name)) + ->file_name($publicId . '/' . $fileName) ->upload_to(phpb_config('storage.uploads_folder') . '/') + ->mime_check() ->run(); if (! $uploader->was_uploaded) { die("Upload error: {$uploader->error}"); } else { - $originalFile = str_replace(' ', '-', $uploader->file_src_name); $originalMime = $uploader->file_src_mime; $serverFile = $uploader->final_file_name; diff --git a/plugi-core/src/Modules/GrapesJS/Upload/Uploader.php b/plugi-core/src/Modules/GrapesJS/Upload/Uploader.php index 4aec432..be27a17 100644 --- a/plugi-core/src/Modules/GrapesJS/Upload/Uploader.php +++ b/plugi-core/src/Modules/GrapesJS/Upload/Uploader.php @@ -27,7 +27,6 @@ class Uploader { $finfo = finfo_open(FILEINFO_MIME_TYPE); if ($finfo) { $mime = finfo_file($finfo, $filePath); - finfo_close($finfo); if (!empty($mime)) { return $mime; } @@ -256,6 +255,11 @@ class Uploader { * @throws Exception */ public function run() { + $uploadRoot = rtrim($this->upload_to, '/\\'); + if ($uploadRoot === '') { + $uploadRoot = DIRECTORY_SEPARATOR; + } + // check whether the final name is in random mode if ($this->file_name !== true) { // preserve file extension if provided @@ -264,13 +268,24 @@ class Uploader { } else { $file = $this->file_name; } - $path = $this->upload_to . $file; - $this->upload_to = dirname($path); } else { $hash = bin2hex(random_bytes(16)); $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; @@ -282,6 +297,9 @@ class Uploader { $this->was_uploaded = false; $this->error = "Incorrect type of file"; } + if (!$this->was_uploaded) { + return false; + } // check file maximum size if ($this->file_src_size > $this->get_file_max_size) { @@ -290,18 +308,6 @@ class Uploader { 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 if (file_exists($path)) { if (! $this->get_auto_replace) { @@ -364,6 +370,60 @@ class Uploader { 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. * diff --git a/plugi-core/tests/upload-security.php b/plugi-core/tests/upload-security.php new file mode 100644 index 0000000..8d55753 --- /dev/null +++ b/plugi-core/tests/upload-security.php @@ -0,0 +1,67 @@ + '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"; \ No newline at end of file diff --git a/uploads/.htaccess b/uploads/.htaccess new file mode 100644 index 0000000..ea25be0 --- /dev/null +++ b/uploads/.htaccess @@ -0,0 +1,17 @@ + + RewriteEngine On + RewriteRule \.(?:php[0-9]*|phtml|phar)(?:/|$) - [F,NC] + + + + + Require all denied + + + + + + Order allow,deny + Deny from all + + \ No newline at end of file