fix(security): Add security hardening and CSRF protection.

Added .htaccess rules to deny access to hidden files. Escaped JSON output in views to prevent XSS attacks. Converted delete links and forms to use POST with CSRF tokens. Enforced POST method on sensitive routes. Added tests to verify these security controls.
This commit is contained in:
2026-12-02 11:07:41 +01:00
parent 6f02b0bc8d
commit b44b1bfc72
11 changed files with 318 additions and 18 deletions
+5
View File
@@ -1,5 +1,10 @@
<FilesMatch "^\.">
Require all denied
</FilesMatch>
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule (^|/)\.(?!well-known/) - [F,L]
# Redirect non-www. to www. (except when on a subdomain)
# RewriteCond %{HTTP_HOST} !^www\.
@@ -17,6 +17,10 @@ if(isset($_GET['id']))
$form = $formsRepository->findWithId($_GET['id']);
$isEditing = isset($form['id']) && $form['id'] > 0;
$fieldsJson = json_encode(json_decode($form['fields']) ?? [], JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
$finishersJson = json_encode(json_decode($form['finishers']) ?? [], JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
$fieldsJson = $fieldsJson === false ? '[]' : $fieldsJson;
$finishersJson = $finishersJson === false ? '[]' : $finishersJson;
?>
<header class="mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
@@ -34,8 +38,8 @@ $isEditing = isset($form['id']) && $form['id'] > 0;
</header>
<script>
const fields = <?= $form["fields"] ?>;
const finishers = <?= $form["finishers"] ?>;
const fields = <?= $fieldsJson ?>;
const finishers = <?= $finishersJson ?>;
const finisherDefinitions = <?= json_encode($finisherDefinitions, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) ?>;
</script>
@@ -102,6 +106,7 @@ $isEditing = isset($form['id']) && $form['id'] > 0;
this.fields.splice(toIndex, 0, field);
}
}">
<?php phpb_csrf_field(); ?>
<?php
if(isset($form['id'])) echo '<input type="hidden" name="id" value="'.$form['id'].'">';
?>
@@ -75,9 +75,14 @@ $entries = $entriesRepository->findWhere('formId', $id);
<?php endforeach; ?>
<td>
<div class="flex justify-end">
<a href="/ext--form/delete-entry?id=<?= $entry['id'] ?>&formId=<?= $id ?>" class="btn btn-ghost btn-square btn-sm text-error" title="<?= phpb_trans('website-manager.remove') ?>" aria-label="<?= phpb_trans('website-manager.remove') ?> submission <?= phpb_e($entry['id']) ?>">
<form action="/ext--form/delete-entry" method="post">
<?php phpb_csrf_field(); ?>
<input type="hidden" name="id" value="<?= phpb_e((string) $entry['id']) ?>">
<input type="hidden" name="formId" value="<?= phpb_e((string) $id) ?>">
<button type="submit" class="btn btn-ghost btn-square btn-sm text-error" title="<?= phpb_trans('website-manager.remove') ?>" aria-label="<?= phpb_trans('website-manager.remove') ?> submission <?= phpb_e($entry['id']) ?>">
<i class="ph-duotone ph-trash text-lg" aria-hidden="true"></i>
</a>
</button>
</form>
</div>
</td>
</tr>
@@ -58,9 +58,13 @@ $forms = $formsRepository->getAll();
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--form', 'action' => 'editForm', 'id' => $form['id']]) ?>" class="btn btn-ghost btn-square btn-sm" title="<?= phpb_trans('website-manager.edit') ?>" aria-label="<?= phpb_trans('website-manager.edit') ?> <?= phpb_e($form['name']) ?>">
<i class="ph-duotone ph-pencil-line text-lg" aria-hidden="true"></i>
</a>
<a href="/ext--form/delete-form?id=<?= $form['id'] ?>" class="btn btn-ghost btn-square btn-sm text-error" title="<?= phpb_trans('website-manager.remove') ?>" aria-label="<?= phpb_trans('website-manager.remove') ?> <?= phpb_e($form['name']) ?>">
<form action="/ext--form/delete-form" method="post">
<?php phpb_csrf_field(); ?>
<input type="hidden" name="id" value="<?= phpb_e((string) $form['id']) ?>">
<button type="submit" class="btn btn-ghost btn-square btn-sm text-error" title="<?= phpb_trans('website-manager.remove') ?>" aria-label="<?= phpb_trans('website-manager.remove') ?> <?= phpb_e($form['name']) ?>">
<i class="ph-duotone ph-trash text-lg" aria-hidden="true"></i>
</a>
</button>
</form>
</div>
</td>
</tr>
@@ -1,11 +1,20 @@
<?php
phpb_requires_authenticated();
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
http_response_code(405);
return;
}
if (!function_exists('phpb_validate_csrf') || !phpb_validate_csrf()) {
http_response_code(403);
return;
}
$entriesRepository = new \Plugi\Extensions\Form\EntriesRepository();
if(
isset($_GET['id'])
isset($_POST['id'])
) {
$entriesRepository->destroy($_GET['id']);
$entriesRepository->destroy($_POST['id']);
}
phpb_redirect(phpb_url('website_manager', ['tab' => 'ext--form', 'action' => 'listEntries', 'id' => $_GET['formId']]));
phpb_redirect(phpb_url('website_manager', ['tab' => 'ext--form', 'action' => 'listEntries', 'id' => $_POST['formId'] ?? '']));
@@ -1,13 +1,22 @@
<?php
phpb_requires_authenticated();
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
http_response_code(405);
return;
}
if (!function_exists('phpb_validate_csrf') || !phpb_validate_csrf()) {
http_response_code(403);
return;
}
$formsRepository = new \Plugi\Extensions\Form\DefinitionsRepository();
$entriesRepository = new \Plugi\Extensions\Form\EntriesRepository();
if(
isset($_GET['id'])
isset($_POST['id'])
) {
$formsRepository->destroy($_GET['id']);
$entriesRepository->destroyWhere('formId', $_GET['id']);
$formsRepository->destroy($_POST['id']);
$entriesRepository->destroyWhere('formId', $_POST['id']);
}
phpb_redirect(phpb_url('website_manager', ['tab' => 'ext--form', 'action' => 'listForms']));
@@ -1,6 +1,15 @@
<?php
phpb_requires_authenticated();
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
http_response_code(405);
return;
}
if (!function_exists('phpb_validate_csrf') || !phpb_validate_csrf()) {
http_response_code(403);
return;
}
$formsRepository = new \Plugi\Extensions\Form\DefinitionsRepository();
if(
@@ -0,0 +1,209 @@
<?php
namespace Plugi\Extensions\Form {
class DefinitionsRepository
{
public static array $form = [];
public static array $created = [];
public static array $destroyed = [];
public function findWithId($id)
{
return self::$form;
}
public function create(array $data): null|object|array
{
self::$created[] = $data;
return null;
}
public function update($instance, array $data): void
{
}
public function destroy($id): void
{
self::$destroyed[] = $id;
}
}
class EntriesRepository
{
public static array $destroyed = [];
public static array $deleted = [];
public function destroy($id): void
{
self::$deleted[] = $id;
}
public function destroyWhere($column, $value): void
{
self::$destroyed[] = [$column, $value];
}
}
}
namespace Plugi\Extensions\Form\Finishers {
class FinishersRepository
{
public function getEditorConfig(): array
{
return [];
}
}
}
namespace {
use Plugi\Extensions\Form\DefinitionsRepository;
use Plugi\Extensions\Form\EntriesRepository;
class FormAdminSecurityRedirect extends RuntimeException
{
}
function assertFormAdminSecurity(bool $condition, string $message): void
{
if (!$condition) {
throw new RuntimeException($message);
}
}
function phpb_requires_authenticated(): void
{
if (!($GLOBALS['formAdminSecurityAuthenticated'] ?? false)) {
throw new RuntimeException('The form admin route did not require authentication.');
}
}
function phpb_validate_csrf(): bool
{
return $GLOBALS['formAdminSecurityCsrfValid'] ?? false;
}
function phpb_csrf_field(): void
{
echo '<input type="hidden" name="_csrf_token" value="test-token">';
}
function phpb_e(string $value): string
{
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
function phpb_url(string $module, array $parameters = []): string
{
return $module . '?' . http_build_query($parameters);
}
function phpb_redirect(string $url, array $flashData = [], int $statusCode = 302): void
{
throw new FormAdminSecurityRedirect();
}
function includeFormSecurityRoute(string $route): void
{
try {
require $route;
} catch (FormAdminSecurityRedirect) {
}
}
$projectRoot = dirname(__DIR__, 3);
$apacheRules = file_get_contents($projectRoot . '/.htaccess');
assertFormAdminSecurity(
is_string($apacheRules) && str_contains($apacheRules, 'Require all denied'),
'Apache must deny requests for hidden files such as the root .env file.'
);
$attack = '</script><script>window.pwned=1</script>';
DefinitionsRepository::$form = [
'id' => 7,
'name' => 'Test form',
'fields' => json_encode([['name' => $attack]]),
'finishers' => '[]',
];
$_GET = ['id' => '7'];
ob_start();
require dirname(__DIR__) . '/admin/Views/EditForm.php';
$editor = ob_get_clean();
assertFormAdminSecurity(
!str_contains($editor, $attack) && str_contains($editor, '\\u003C'),
'Stored form JSON must be escaped before it is emitted inside a script element.'
);
assertFormAdminSecurity(
str_contains($editor, 'name="_csrf_token"'),
'Form saves must submit a CSRF token.'
);
$GLOBALS['formAdminSecurityAuthenticated'] = true;
$GLOBALS['formAdminSecurityCsrfValid'] = false;
$saveRoute = dirname(__DIR__) . '/routes/saveForm.php';
$_SERVER['REQUEST_METHOD'] = 'GET';
$_POST = [];
http_response_code(200);
includeFormSecurityRoute($saveRoute);
assertFormAdminSecurity(http_response_code() === 405, 'Form saves must reject non-POST requests.');
assertFormAdminSecurity(DefinitionsRepository::$created === [], 'A GET request must not save a form.');
$_SERVER['REQUEST_METHOD'] = 'POST';
$_POST = ['name' => 'Rejected form', 'fields' => '[]', 'finishers' => '[]'];
http_response_code(200);
includeFormSecurityRoute($saveRoute);
assertFormAdminSecurity(http_response_code() === 403, 'Form saves must reject invalid CSRF tokens.');
assertFormAdminSecurity(DefinitionsRepository::$created === [], 'An invalid CSRF token must not save a form.');
$GLOBALS['formAdminSecurityCsrfValid'] = true;
$_POST['_csrf_token'] = 'test-token';
includeFormSecurityRoute($saveRoute);
assertFormAdminSecurity(count(DefinitionsRepository::$created) === 1, 'A valid POST should save a form.');
$deleteRoute = dirname(__DIR__) . '/routes/deleteForm.php';
$_SERVER['REQUEST_METHOD'] = 'GET';
$_GET = ['id' => '7'];
$_POST = [];
http_response_code(200);
includeFormSecurityRoute($deleteRoute);
assertFormAdminSecurity(http_response_code() === 405, 'Form deletion must reject non-POST requests.');
assertFormAdminSecurity(DefinitionsRepository::$destroyed === [], 'A GET request must not delete a form.');
$_SERVER['REQUEST_METHOD'] = 'POST';
$_POST = ['id' => '7'];
$GLOBALS['formAdminSecurityCsrfValid'] = false;
http_response_code(200);
includeFormSecurityRoute($deleteRoute);
assertFormAdminSecurity(http_response_code() === 403, 'Form deletion must reject invalid CSRF tokens.');
assertFormAdminSecurity(DefinitionsRepository::$destroyed === [], 'An invalid CSRF token must not delete a form.');
$_POST = ['id' => '7', '_csrf_token' => 'test-token'];
$GLOBALS['formAdminSecurityCsrfValid'] = true;
includeFormSecurityRoute($deleteRoute);
assertFormAdminSecurity(DefinitionsRepository::$destroyed === ['7'], 'A valid POST should delete the form.');
assertFormAdminSecurity(EntriesRepository::$destroyed === [['formId', '7']], 'Deleting a form should still delete its entries.');
$deleteEntryRoute = dirname(__DIR__) . '/routes/deleteEntry.php';
$_SERVER['REQUEST_METHOD'] = 'GET';
$_GET = ['id' => '12', 'formId' => '7'];
$_POST = [];
http_response_code(200);
includeFormSecurityRoute($deleteEntryRoute);
assertFormAdminSecurity(http_response_code() === 405, 'Entry deletion must reject non-POST requests.');
assertFormAdminSecurity(EntriesRepository::$deleted === [], 'A GET request must not delete an entry.');
$_SERVER['REQUEST_METHOD'] = 'POST';
$_POST = ['id' => '12', 'formId' => '7'];
$GLOBALS['formAdminSecurityCsrfValid'] = false;
http_response_code(200);
includeFormSecurityRoute($deleteEntryRoute);
assertFormAdminSecurity(http_response_code() === 403, 'Entry deletion must reject invalid CSRF tokens.');
assertFormAdminSecurity(EntriesRepository::$deleted === [], 'An invalid CSRF token must not delete an entry.');
$_POST['_csrf_token'] = 'test-token';
$GLOBALS['formAdminSecurityCsrfValid'] = true;
includeFormSecurityRoute($deleteEntryRoute);
assertFormAdminSecurity(EntriesRepository::$deleted === ['12'], 'A valid POST should delete an entry.');
fwrite(STDOUT, "PASS: form admin actions require POST and CSRF, and stored JSON is script-safe.\n");
}
@@ -151,6 +151,7 @@ class WebsiteManager implements WebsiteManagerContract
exit();
} elseif ($action === "destroy") {
$this->handleDestroy($page);
exit();
}
}
}
@@ -297,6 +298,15 @@ class WebsiteManager implements WebsiteManagerContract
*/
public function handleDestroy(PageContract $page)
{
if (($_SERVER["REQUEST_METHOD"] ?? "") !== "POST") {
http_response_code(405);
return false;
}
if (!function_exists("phpb_validate_csrf") || !phpb_validate_csrf()) {
http_response_code(403);
return false;
}
$pageRepository = new PageRepository();
if (!$pageRepository->destroy($page->getId())) {
phpb_redirect(phpb_url("website_manager"), [
@@ -161,17 +161,20 @@
) ?>" class="btn btn-ghost btn-square btn-sm">
<i class="text-xl ph-duotone ph-gear" aria-hidden="true"></i>
</a>
<a href="<?= phpb_url("website_manager", [
<form method="post" action="<?= phpb_url("website_manager", [
"route" => "page_settings",
"action" => "destroy",
"page" => $page->getId(),
]) ?>" title="<?= phpb_trans(
]) ?>">
<?php phpb_csrf_field(); ?>
<button type="submit" title="<?= phpb_trans(
"website-manager.remove",
) ?>" aria-label="<?= phpb_e(
phpb_trans("website-manager.remove"),
) ?>" class="btn btn-error btn-square btn-sm">
<i class="text-xl ph-duotone ph-trash" aria-hidden="true"></i>
</a>
</button>
</form>
</div>
</td>
</tr>
@@ -1058,6 +1058,38 @@ $cases = [
'Successful deletion did not invalidate every stored localized route: ' . json_encode(PageCreationTestCache::$invalidatedRoutes)
);
},
'website manager page deletion requires POST and a valid CSRF token' => function (): void {
resetPageCreationDatabase();
$repository = new PageRepository();
$repository->create(pageCreationPayload());
global $phpb_db;
$page = $repository->findWithId($phpb_db->rows('pages')[0]['id']);
$websiteManager = new WebsiteManager();
$_SERVER['REQUEST_METHOD'] = 'GET';
$_POST = [];
http_response_code(200);
$websiteManager->handleDestroy($page);
assertPageCreation(http_response_code() === 405, 'Page deletion must reject GET requests.');
assertPageCreation(count($phpb_db->rows('pages')) === 1, 'A GET request deleted a page.');
$_SERVER['REQUEST_METHOD'] = 'POST';
$_POST = ['_csrf_token' => 'invalid-token'];
http_response_code(200);
$websiteManager->handleDestroy($page);
assertPageCreation(http_response_code() === 403, 'Page deletion must reject invalid CSRF tokens.');
assertPageCreation(count($phpb_db->rows('pages')) === 1, 'An invalid CSRF token deleted a page.');
$_SESSION['phpb_csrf_tokens'] = ['valid-token' => time()];
$_POST = ['_csrf_token' => 'valid-token'];
try {
$websiteManager->handleDestroy($page);
} catch (PageCreationRedirectException $exception) {
assertPageCreation($exception->redirectUrl === '/website_manager', 'Successful deletion redirected to an unexpected page.');
}
assertPageCreation(count($phpb_db->rows('pages')) === 0, 'A valid token did not delete the page.');
},
'failed page deletion rolls back translation cleanup without invalidating caches' => function (): void {
resetPageCreationDatabase();
$repository = new PageRepository();