security: add CSRF protection and harden core handling

Add CSRF token validation and include tokens in authentication, website manager, and GrapesJS forms and requests. Harden login with password hash verification and session ID regeneration, validate database identifiers and charset, and secure upload MIME detection and filename generation.

Update nullable type declarations and PHP syntax across core contracts and modules, switch the Docker image to PHP 8.4, and move the theme script asset to the end of the page. Refresh the PageBuilderBody distribution assets.
This commit is contained in:
2026-11-24 09:48:17 +01:00
parent e86fba0809
commit 606875fdbe
34 changed files with 311 additions and 61 deletions
+2 -2
View File
@@ -1,10 +1,10 @@
FROM php:8.2-apache-bullseye FROM php:8.4-apache-bookworm
WORKDIR "/var/www/html" WORKDIR "/var/www/html"
RUN apt-get update; \ RUN apt-get update; \
docker-php-ext-install pdo pdo_mysql; \ docker-php-ext-install pdo pdo_mysql; \
apt-get -y --no-install-recommends install \ apt-get -y --no-install-recommends install \
git \ git \
php8.2-mysql; \ php8.4-mysql; \
apt-get clean; \ apt-get clean; \
rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /usr/share/doc/* rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /usr/share/doc/*
+1 -1
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -11,7 +11,7 @@ interface PageBuilderContract
* @param $action * @param $action
* @param PageContract|null $page * @param PageContract|null $page
*/ */
public function handleRequest($route, $action, PageContract $page = null); public function handleRequest($route, $action, ?PageContract $page = null);
/** /**
* Render the given page inside the PageBuilder. * Render the given page inside the PageBuilder.
@@ -27,7 +27,7 @@ interface PageBuilderContract
* @param null $language * @param null $language
* @return string * @return string
*/ */
public function renderPage(PageContract $page, $language = null): string; public function renderPage(PageContract $page, ?string $language = null): string;
/** /**
* Update the given page with the given data (an array of html blocks) * Update the given page with the given data (an array of html blocks)
@@ -44,7 +44,7 @@ interface PageBuilderContract
* @param string|null $css * @param string|null $css
* @return string * @return string
*/ */
public function customStyle(string $css = null); public function customStyle(?string $css = null);
/** /**
* Get or set custom scripts for customizing behaviour of the page builder. * Get or set custom scripts for customizing behaviour of the page builder.
@@ -53,7 +53,7 @@ interface PageBuilderContract
* @param string|null $scripts * @param string|null $scripts
* @return string * @return string
*/ */
public function customScripts(string $location, string $scripts = null); public function customScripts(string $location, ?string $scripts = null);
/** /**
* Set a theme for the page builder. * Set a theme for the page builder.
+2 -2
View File
@@ -61,7 +61,7 @@ interface PageContract
* @param string|null $locale * @param string|null $locale
* @return mixed|string|null * @return mixed|string|null
*/ */
public function getTranslation(string $setting, $locale = null); public function getTranslation(string $setting, ?string $locale = null);
/** /**
* Return the translated settings of this page. * Return the translated settings of this page.
@@ -76,7 +76,7 @@ interface PageContract
* @param string|null $locale * @param string|null $locale
* @return mixed * @return mixed
*/ */
public function getRoute($locale = null); public function getRoute(?string $locale = null);
/** /**
* Get the value of the given property of this Page. * Get the value of the given property of this Page.
@@ -22,7 +22,7 @@ interface WebsiteManagerContract
* *
* @param PageContract $page * @param PageContract $page
*/ */
public function renderPageSettings(PageContract $page = null); public function renderPageSettings(?PageContract $page = null);
/** /**
* Render the website manager menu settings (add/edit menu form). * Render the website manager menu settings (add/edit menu form).
+97
View File
@@ -0,0 +1,97 @@
<?php
namespace Plugi\Core;
class Csrf
{
/**
* Session key for storing CSRF tokens.
*/
private const SESSION_KEY = 'phpb_csrf_tokens';
/**
* Generate a new CSRF token and store it in the session.
*
* @return string The generated token
*/
public static function generateToken(): string
{
if (session_status() === PHP_SESSION_NONE) {
throw new \RuntimeException('Session must be started before generating CSRF tokens.');
}
if (!isset($_SESSION[self::SESSION_KEY])) {
$_SESSION[self::SESSION_KEY] = [];
}
$token = bin2hex(random_bytes(32));
$_SESSION[self::SESSION_KEY][$token] = time();
self::cleanupExpiredTokens();
return $token;
}
/**
* Validate a CSRF token against the session-stored tokens.
*
* @param string $token The token to validate
* @return bool True if the token is valid, false otherwise
*/
public static function validateToken(string $token): bool
{
if (empty($token) || !isset($_SESSION[self::SESSION_KEY])) {
return false;
}
// Use hash_equals for timing-safe comparison
foreach ($_SESSION[self::SESSION_KEY] as $storedToken => $timestamp) {
if (hash_equals($storedToken, $token)) {
// Do not remove the token — it is reusable for AJAX requests.
// Tokens expire after 1 hour via cleanupExpiredTokens().
return true;
}
}
return false;
}
/**
* Get the current CSRF token for use in forms.
* Generates a new one if none exists.
*
* @return string The CSRF token
*/
public static function getToken(): string
{
if (session_status() === PHP_SESSION_NONE) {
return '';
}
if (!isset($_SESSION[self::SESSION_KEY]) || empty($_SESSION[self::SESSION_KEY])) {
return self::generateToken();
}
// Return the most recent token
$keys = array_keys($_SESSION[self::SESSION_KEY]);
return end($keys);
}
/**
* Remove expired tokens from the session.
* Tokens expire after 1 hour by default.
*/
private static function cleanupExpiredTokens(): void
{
if (!isset($_SESSION[self::SESSION_KEY])) {
return;
}
$now = time();
$maxAge = 3600; // 1 hour
foreach ($_SESSION[self::SESSION_KEY] as $token => $timestamp) {
if ($now - $timestamp > $maxAge) {
unset($_SESSION[self::SESSION_KEY][$token]);
}
}
}
}
+36 -12
View File
@@ -22,19 +22,28 @@ class DB
*/ */
protected PDO $pdo; protected PDO $pdo;
/**
* @var string $databaseName
*/
protected string $databaseName;
/** /**
* DB constructor. * DB constructor.
* *
*/ */
public function __construct() public function __construct()
{ {
// Validate database charset against a whitelist to prevent SQL injection
$allowedCharsets = ['utf8mb4', 'utf8', 'latin1', 'ascii', 'utf8mb3'];
$charset = in_array($_ENV['DATABASE_CHARSET'], $allowedCharsets, true) ? $_ENV['DATABASE_CHARSET'] : 'utf8mb4';
$this->pdo = new PDO( $this->pdo = new PDO(
$_ENV['DATABASE_DRIVER'] . ':host=' . $_ENV['DATABASE_HOST'] . ';dbname=' . $_ENV['DATABASE_DATABASE'] . ";options='--client_encoding=" . $_ENV['DATABASE_CHARSET'] . "'", $_ENV['DATABASE_DRIVER'] . ':host=' . $_ENV['DATABASE_HOST'] . ';dbname=' . $_ENV['DATABASE_DATABASE'] . ";options='--client_encoding=" . $charset . "'",
$_ENV['DATABASE_USERNAME'], $_ENV['DATABASE_USERNAME'],
$_ENV['DATABASE_PASSWORD'], $_ENV['DATABASE_PASSWORD'],
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION] [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
); );
$this->pdo->exec("set names " . $_ENV['DATABASE_CHARSET']); $this->pdo->exec("set names " . $charset);
$this->databaseName = $_ENV['DATABASE_DATABASE'];
} }
/** /**
@@ -57,14 +66,19 @@ class DB
public function all(string $table, array|string $columns = '*'): array public function all(string $table, array|string $columns = '*'): array
{ {
try { try {
// Sanitize table name to prevent SQL injection
$sanitizedTable = phpb_remove_non_alpha_numeric($table);
if (empty($sanitizedTable)) {
throw new PDOException('Invalid table name.');
}
if (is_array($columns)) { if (is_array($columns)) {
foreach ($columns as &$column) { foreach ($columns as &$column) {
$column = preg_replace('/[^a-zA-Z_]*/', '', $column); $column = preg_replace('/[^a-zA-Z_]*/', '', $column);
} }
$columns = implode(',', $columns); $columns = implode(',', $columns);
$stmt = $this->pdo->prepare("SELECT $columns FROM $table"); $stmt = $this->pdo->prepare("SELECT $columns FROM $sanitizedTable");
} else { } else {
$stmt = $this->pdo->prepare("SELECT * FROM $table"); $stmt = $this->pdo->prepare("SELECT * FROM $sanitizedTable");
} }
$stmt->execute(); $stmt->execute();
return $stmt->fetchAll(); return $stmt->fetchAll();
@@ -86,7 +100,8 @@ class DB
*/ */
public function findWithId(string $table, $id) public function findWithId(string $table, $id)
{ {
$stmt = $this->pdo->prepare("SELECT * FROM {$table} WHERE id = ?"); $sanitizedTable = phpb_remove_non_alpha_numeric($table);
$stmt = $this->pdo->prepare("SELECT * FROM {$sanitizedTable} WHERE id = ?");
$stmt->execute([$id]); $stmt->execute([$id]);
return $stmt->fetchAll(); return $stmt->fetchAll();
} }
@@ -152,13 +167,13 @@ class DB
// check if table with the name $table exists. if not, execute $query.' // check if table with the name $table exists. if not, execute $query.'
try { try {
$keys = $this->select( $keys = $this->select(
"SELECT CONSTRAINT_NAME FROM information_schema.TABLE_CONSTRAINTS WHERE CONSTRAINT_NAME = ? AND TABLE_SCHEMA = 'plugi' AND TABLE_NAME = ? AND CONSTRAINT_TYPE = 'UNIQUE'", "SELECT CONSTRAINT_NAME FROM information_schema.TABLE_CONSTRAINTS WHERE CONSTRAINT_NAME = ? AND TABLE_SCHEMA = ? AND TABLE_NAME = ? AND CONSTRAINT_TYPE = 'UNIQUE'",
[$key, $tableName] [$key, $this->databaseName, $tableName]
); );
if (count($keys) === 1) return true; if (count($keys) === 1) return true;
return false; return false;
} catch (Exception $e) { } catch (Exception $e) {
print_r($e->getMessage()); // Do not expose database error details to the user
return false; return false;
} }
} }
@@ -176,7 +191,7 @@ class DB
} }
public function getDBDefinitionHash() { public function getDBDefinitionHash() {
return sha1(json_encode($this->getDBDefinition())); return hash('sha256', json_encode($this->getDBDefinition()));
} }
public function diffDB() { public function diffDB() {
@@ -207,15 +222,24 @@ class DB
foreach ($diff as $table => $tableDiff) { foreach ($diff as $table => $tableDiff) {
$tableName = $_ENV['DATABASE_PREFIX'] . phpb_remove_non_alpha_numeric($table); $tableName = $_ENV['DATABASE_PREFIX'] . phpb_remove_non_alpha_numeric($table);
if($tableDiff === false){ if($tableDiff === false){
$this->query("CREATE TABLE {$tableName} (`id` int NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3"); $this->query("CREATE TABLE {$tableName} (`id` int NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
$this->query("ALTER TABLE {$tableName} ADD PRIMARY KEY (`id`)"); $this->query("ALTER TABLE {$tableName} ADD PRIMARY KEY (`id`)");
$this->query("ALTER TABLE {$tableName} MODIFY `id` int NOT NULL AUTO_INCREMENT"); $this->query("ALTER TABLE {$tableName} MODIFY `id` int NOT NULL AUTO_INCREMENT");
} elseif (is_array($tableDiff)) { } elseif (is_array($tableDiff)) {
foreach ($tableDiff['columns'] as $column => $columnDefinition) { foreach ($tableDiff['columns'] as $column => $columnDefinition) {
$this->query("ALTER TABLE {$tableName} ADD {$column} {$columnDefinition}"); // Validate column name to prevent SQL injection
$sanitizedColumn = phpb_remove_non_alpha_numeric($column);
if (empty($sanitizedColumn)) continue;
// Validate column definition against a safe pattern
if (!preg_match('/^[A-Z\s(),0-9_`]+$/', $columnDefinition)) continue;
$this->query("ALTER TABLE {$tableName} ADD {$sanitizedColumn} {$columnDefinition}");
} }
foreach ($tableDiff['uniqueKeys'] as $key => $keyDefinition) { foreach ($tableDiff['uniqueKeys'] as $key => $keyDefinition) {
$this->query("ALTER TABLE {$tableName} ADD UNIQUE KEY {$key} ($keyDefinition)"); // Validate key name and definition
$sanitizedKey = phpb_remove_non_alpha_numeric($key);
if (empty($sanitizedKey)) continue;
if (!preg_match('/^[A-Z,`\s_]+$/', $keyDefinition)) continue;
$this->query("ALTER TABLE {$tableName} ADD UNIQUE KEY {$sanitizedKey} ($keyDefinition)");
} }
} }
} }
+1 -1
View File
@@ -33,7 +33,7 @@ class EnvLoader
continue; continue;
} }
list($name, $value) = explode('=', $line, 2); [$name, $value] = explode('=', $line, 2);
$name = trim($name); $name = trim($name);
$value = trim($value); $value = trim($value);
+32 -1
View File
@@ -427,7 +427,7 @@ if (! function_exists('phpb_field_value')) {
/** /**
* Return the posted value or the attribute value of the given instance, or null if no value was found. * Return the posted value or the attribute value of the given instance, or null if no value was found.
*/ */
function phpb_field_value(string $attribute, object $instance = null): ?string function phpb_field_value(string $attribute, ?object $instance = null): ?string
{ {
if (isset($_POST[$attribute])) { if (isset($_POST[$attribute])) {
return phpb_encode_or_null($_POST[$attribute]); return phpb_encode_or_null($_POST[$attribute]);
@@ -588,6 +588,7 @@ if (! function_exists('phpb_render_setting')) {
</label> </label>
</div> </div>
EOL; EOL;
break;
case 'text': case 'text':
echo <<<EOL echo <<<EOL
@@ -660,6 +661,36 @@ if (! function_exists('phpb_registered_assets')) {
} }
} }
if (! function_exists('phpb_csrf_field')) {
/**
* Render a hidden CSRF token input field for forms.
*/
function phpb_csrf_field(): void
{
if (class_exists('\Plugi\Core\Csrf')) {
$token = \Plugi\Core\Csrf::getToken();
echo '<input type="hidden" name="_csrf_token" value="' . phpb_e($token) . '">';
}
}
}
if (! function_exists('phpb_validate_csrf')) {
/**
* Validate the CSRF token from the current POST request.
*
* @return bool True if valid, false otherwise
*/
function phpb_validate_csrf(): bool
{
if (!class_exists('\Plugi\Core\Csrf')) {
return true;
}
$token = $_POST['_csrf_token'] ?? $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
return \Plugi\Core\Csrf::validateToken($token);
}
}
if (! function_exists('phpb_array_merge_deep_array')) { if (! function_exists('phpb_array_merge_deep_array')) {
/** /**
* Deep merging * Deep merging
+1 -1
View File
@@ -171,7 +171,7 @@ class Extensions
/** /**
* Get all settings. * Get all settings.
*/ */
public static function getSettings($ext = null) : array { public static function getSettings(?string $ext = null) : array {
$settingIns = phpb_instance('setting'); $settingIns = phpb_instance('setting');
$hydrSettings = []; $hydrSettings = [];
foreach (self::$settings as $setting) { foreach (self::$settings as $setting) {
+28 -1
View File
@@ -15,7 +15,13 @@ class Auth implements AuthContract
{ {
if (phpb_in_module('auth')) { if (phpb_in_module('auth')) {
if ($action === 'login' && isset($_POST['username']) && isset($_POST['password'])) { if ($action === 'login' && isset($_POST['username']) && isset($_POST['password'])) {
if ($_POST['username'] === $_ENV['USERNAME'] && $_POST['password'] === $_ENV['PASSWORD']) { $usernameValid = hash_equals($_ENV['USERNAME'] ?? '', $_POST['username']);
$passwordValid = $usernameValid && $this->verifyPassword($_POST['password']);
if ($usernameValid && $passwordValid) {
// Regenerate session ID to prevent session fixation
if (session_status() === PHP_SESSION_ACTIVE) {
session_regenerate_id(true);
}
$_SESSION['phpb_logged_in'] = true; $_SESSION['phpb_logged_in'] = true;
phpb_redirect(phpb_url('website_manager')); phpb_redirect(phpb_url('website_manager'));
} else { } else {
@@ -31,6 +37,27 @@ class Auth implements AuthContract
} }
} }
/**
* Verify the submitted password against the stored hash.
*
* Supports both hashed passwords (PASSWORD_HASH env var) and legacy plaintext (PASSWORD env var).
*
* @param string $password The plaintext password to verify
* @return bool
*/
protected function verifyPassword($password)
{
// Prefer hashed password if available
if (isset($_ENV['PASSWORD_HASH']) && !empty($_ENV['PASSWORD_HASH'])) {
return password_verify($password, $_ENV['PASSWORD_HASH']);
}
// Fallback to plaintext for backward compatibility (deprecated)
if (isset($_ENV['PASSWORD']) && !empty($_ENV['PASSWORD'])) {
return hash_equals($_ENV['PASSWORD'], $password);
}
return false;
}
/** /**
* Return whether the current request has an authenticated session. * Return whether the current request has an authenticated session.
* *
@@ -3,6 +3,7 @@
</div> </div>
<form class="login-form mt-3 flex flex-col gap-3 items-center" method="post" action="<?= phpb_url('auth', ['action' => 'login']) ?>"> <form class="login-form mt-3 flex flex-col gap-3 items-center" method="post" action="<?= phpb_url('auth', ['action' => 'login']) ?>">
<?php phpb_csrf_field(); ?>
<?php <?php
if (phpb_flash('message')): if (phpb_flash('message')):
?> ?>
@@ -35,7 +35,7 @@ class BaseModel
* @param PageContract|null $page * @param PageContract|null $page
* @param bool $forPageBuilder * @param bool $forPageBuilder
*/ */
public function __construct(ThemeBlock $block, $data = [], PageContract $page = null, $forPageBuilder = false) public function __construct(ThemeBlock $block, $data = [], ?PageContract $page = null, $forPageBuilder = false)
{ {
$this->block = $block; $this->block = $block;
$this->data = is_array($data) ? $data : []; $this->data = is_array($data) ? $data : [];
@@ -68,7 +68,7 @@ class BlockRenderer
* @param null $id id of the specific block instance * @param null $id id of the specific block instance
* @return string * @return string
*/ */
public function renderWithSlug(string $blockSlug, $blockData = null, $id = null) public function renderWithSlug(string $blockSlug, ?array $blockData = null, ?string $id = null)
{ {
$block = ($path = Extensions::getBlock($blockSlug)) $block = ($path = Extensions::getBlock($blockSlug))
? new ThemeBlock($this->theme, $path, true, $blockSlug) ? new ThemeBlock($this->theme, $path, true, $blockSlug)
@@ -85,7 +85,7 @@ class BlockRenderer
* @param null $id id of the specific block instance * @param null $id id of the specific block instance
* @return string * @return string
*/ */
public function render(ThemeBlock $themeBlock, $blockData = null, $id = null) public function render(ThemeBlock $themeBlock, ?array $blockData = null, ?string $id = null)
{ {
$blockData = $blockData ?? []; $blockData = $blockData ?? [];
@@ -59,7 +59,7 @@ class PageBuilder implements PageBuilderContract
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
public function handleRequest($route, $action, PageContract $page = null) public function handleRequest($route, $action, ?PageContract $page = null)
{ {
phpb_set_in_editmode(); phpb_set_in_editmode();
@@ -377,7 +377,7 @@ class PageBuilder implements PageBuilderContract
* @param string|null $css * @param string|null $css
* @return string * @return string
*/ */
public function customStyle(string $css = null) public function customStyle(?string $css = null)
{ {
if (! is_null($css)) { if (! is_null($css)) {
$this->css = $css; $this->css = $css;
@@ -392,7 +392,7 @@ class PageBuilder implements PageBuilderContract
* @param string|null $scripts * @param string|null $scripts
* @return string * @return string
*/ */
public function customScripts(string $location, string $scripts = null) public function customScripts(string $location, ?string $scripts = null)
{ {
if (! is_null($scripts)) { if (! is_null($scripts)) {
$this->scripts[$location] = $scripts; $this->scripts[$location] = $scripts;
@@ -126,7 +126,7 @@ class PageRenderer
* @param bool $canBeCached * @param bool $canBeCached
* @param string|null $cacheLifetime * @param string|null $cacheLifetime
*/ */
public static function setCanBeCached(bool $canBeCached, $cacheLifetime = null) public static function setCanBeCached(bool $canBeCached, ?int $cacheLifetime = null)
{ {
if (! $canBeCached || ($cacheLifetime && intval($cacheLifetime) <= 0)) { if (! $canBeCached || ($cacheLifetime && intval($cacheLifetime) <= 0)) {
static::$canBeCached = false; static::$canBeCached = false;
@@ -279,7 +279,7 @@ class PageRenderer
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
public function parseShortcodes(string $htmlWithShortcodes, $context = null) public function parseShortcodes(string $htmlWithShortcodes, ?array $context = null)
{ {
$context = $context ?? $this->pageBlocksData; $context = $context ?? $this->pageBlocksData;
return $this->shortcodeParser->doShortcodes($htmlWithShortcodes, $context); return $this->shortcodeParser->doShortcodes($htmlWithShortcodes, $context);
@@ -225,17 +225,17 @@ class ShortcodeParser
// as long as there are attributes in the attributes string, add them to $attributes // as long as there are attributes in the attributes string, add them to $attributes
$attributes = []; $attributes = [];
while (strpos($matchAttributeString, '=') !== false) { while (strpos($matchAttributeString, '=') !== false) {
list($attribute, $remainingString) = explode('=', $matchAttributeString, 2); [$attribute, $remainingString] = explode('=', $matchAttributeString, 2);
$attribute = trim($attribute); $attribute = trim($attribute);
// if first char is " and at least two " exist, get attribute value between "" // if first char is " and at least two " exist, get attribute value between ""
if (strpos($remainingString, '"') === 0 && strpos($remainingString, '"', 1) !== false) { if (strpos($remainingString, '"') === 0 && strpos($remainingString, '"', 1) !== false) {
list($empty, $value, $remainingString) = explode('"', $remainingString, 3); [$empty, $value, $remainingString] = explode('"', $remainingString, 3);
$attributes[$attribute] = $value; $attributes[$attribute] = $value;
} else { } else {
// attribute value was not between "", get value until next whitespace or until end of $remainingString // attribute value was not between "", get value until next whitespace or until end of $remainingString
if (strpos($remainingString, ' ') !== false) { if (strpos($remainingString, ' ') !== false) {
list($value, $remainingString) = explode(' ', $remainingString, 2); [$value, $remainingString] = explode(' ', $remainingString, 2);
$attributes[$attribute] = $value; $attributes[$attribute] = $value;
} else { } else {
$attributes[$attribute] = $remainingString; $attributes[$attribute] = $remainingString;
@@ -10,6 +10,7 @@ html, body {
</style> </style>
<script src="<?= phpb_asset('pagebuilder/html2canvas-v0.4.1.min.js') ?>"></script> <script src="<?= phpb_asset('pagebuilder/html2canvas-v0.4.1.min.js') ?>"></script>
<script> <script>
window.csrfToken = '<?= \Plugi\Core\Csrf::getToken() ?>';
$(document).ready(function() { $(document).ready(function() {
html2canvas($("body"), { html2canvas($("body"), {
allowTaint: false, allowTaint: false,
@@ -21,6 +22,9 @@ $(document).ready(function() {
$.ajax({ $.ajax({
type: "POST", type: "POST",
url: "<?= phpb_url('pagebuilder', ['route' => 'thumb_generator', 'action' => 'upload']) ?>", url: "<?= phpb_url('pagebuilder', ['route' => 'thumb_generator', 'action' => 'upload']) ?>",
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-Token', window.csrfToken);
},
data: { data: {
block: "<?= $blockSlug ?>", block: "<?= $blockSlug ?>",
data: data data: data
@@ -15,6 +15,31 @@ use Exception;
#[\AllowDynamicProperties] #[\AllowDynamicProperties]
class Uploader { class Uploader {
/**
* Detect the MIME type of a file using server-side inspection.
*
* @param string $filePath Path to the file
* @return string The detected MIME type
*/
protected function detectMimeType(string $filePath): string
{
if (function_exists('finfo_file')) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
if ($finfo) {
$mime = finfo_file($finfo, $filePath);
finfo_close($finfo);
if (!empty($mime)) {
return $mime;
}
}
}
// Fallback to mime_content_type if available
if (function_exists('mime_content_type')) {
return mime_content_type($filePath);
}
return '';
}
/** /**
* Indicates if the file has been uploaded properly. * Indicates if the file has been uploaded properly.
* *
@@ -216,7 +241,8 @@ class Uploader {
$this->file_src_temp = $file["tmp_name"]; $this->file_src_temp = $file["tmp_name"];
$this->file_src_size = $file["size"]; $this->file_src_size = $file["size"];
$this->file_src_errors = $file['error']; $this->file_src_errors = $file['error'];
$this->file_src_mime = $file['type']; // Use server-side MIME detection instead of trusting client-supplied $_FILES['type']
$this->file_src_mime = $this->detectMimeType($file['tmp_name']);
$this->file_src_name_ext = pathinfo($file["name"], PATHINFO_EXTENSION); $this->file_src_name_ext = pathinfo($file["name"], PATHINFO_EXTENSION);
$this->was_uploaded = true; $this->was_uploaded = true;
@@ -241,7 +267,7 @@ class Uploader {
$path = $this->upload_to . $file; $path = $this->upload_to . $file;
$this->upload_to = dirname($path); $this->upload_to = dirname($path);
} else { } else {
$hash = md5(uniqid(rand(), true)); $hash = bin2hex(random_bytes(16));
$file = $hash . '.' . $this->file_src_name_ext; $file = $hash . '.' . $this->file_src_name_ext;
$path = $this->upload_to . $file; $path = $this->upload_to . $file;
} }
@@ -317,7 +343,7 @@ class Uploader {
$this->final_file_name = $file; $this->final_file_name = $file;
// extract image dimensions // extract image dimensions
list($w, $h) = getimagesize($path); [$w, $h] = getimagesize($path);
$this->file_width = $w; $this->file_width = $w;
$this->file_height = $h; $this->file_height = $h;
@@ -345,7 +371,7 @@ class Uploader {
* @param integer $mode Optional permissions * @param integer $mode Optional permissions
* @return boolean Success * @return boolean Success
*/ */
protected function r_mkdir($path, $mode = 0777) { protected function r_mkdir($path, $mode = 0755) {
return is_dir($path) || ( $this->r_mkdir(dirname($path), $mode) && $this->_mkdir($path, $mode) ); return is_dir($path) || ( $this->r_mkdir(dirname($path), $mode) && $this->_mkdir($path, $mode) );
} }
@@ -356,7 +382,7 @@ class Uploader {
* @param integer $mode Optional permissions * @param integer $mode Optional permissions
* @return boolean Success * @return boolean Success
*/ */
protected function _mkdir($path, $mode = 0777) { protected function _mkdir($path, $mode = 0755) {
$old = umask(0); $old = umask(0);
$res = @mkdir($path, $mode); $res = @mkdir($path, $mode);
umask($old); umask($old);
@@ -531,7 +531,8 @@
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/x-www-form-urlencoded', 'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest' 'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-Token': window.csrfToken
}, },
body: formData body: formData
}); });
@@ -61,7 +61,8 @@
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/x-www-form-urlencoded', 'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest' 'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-Token': window.csrfToken
}, },
body: formData body: formData
}); });
@@ -273,13 +274,15 @@
const formData = new URLSearchParams(); const formData = new URLSearchParams();
formData.append('data', JSON.stringify(data)); formData.append('data', JSON.stringify(data));
formData.append('_csrf_token', window.csrfToken);
try { try {
const response = await fetch(saveUrl, { const response = await fetch(saveUrl, {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/x-www-form-urlencoded', 'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest' 'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-Token': window.csrfToken
}, },
body: formData body: formData
}); });
@@ -6,7 +6,8 @@ window.editor.on('asset:remove', function(asset) {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/x-www-form-urlencoded", "Content-Type": "application/x-www-form-urlencoded",
"X-Requested-With": "XMLHttpRequest" "X-Requested-With": "XMLHttpRequest",
"X-CSRF-Token": window.csrfToken
}, },
body: new URLSearchParams({ id: assetId }) body: new URLSearchParams({ id: assetId })
}).catch(function() {}); }).catch(function() {});
@@ -36,9 +36,14 @@ window.pages = <?= json_encode($pageBuilder->getPages()) ?>;
window.renderBlockUrl = '<?= phpb_url('pagebuilder', ['action' => 'renderBlock', 'page' => $page->getId()]) ?>'; window.renderBlockUrl = '<?= phpb_url('pagebuilder', ['action' => 'renderBlock', 'page' => $page->getId()]) ?>';
window.injectionScriptUrl = '<?= phpb_asset('pagebuilder/page-injection.js') ?>'; window.injectionScriptUrl = '<?= phpb_asset('pagebuilder/page-injection.js') ?>';
window.renderLanguageVariantUrl = '<?= phpb_url('pagebuilder', ['action' => 'renderLanguageVariant', 'page' => $page->getId()]) ?>'; window.renderLanguageVariantUrl = '<?= phpb_url('pagebuilder', ['action' => 'renderLanguageVariant', 'page' => $page->getId()]) ?>';
window.csrfToken = '<?= phpb_e(\Plugi\Core\Csrf::getToken()) ?>';
<?php <?php
$config = require __DIR__ . '/grapesjs/config.php'; $config = require __DIR__ . '/grapesjs/config.php';
// Add CSRF token header to GrapesJS file uploads
$config['assetManager']['headers'] = [
'X-CSRF-Token' => \Plugi\Core\Csrf::getToken()
];
?> ?>
let config = <?= json_encode($config) ?>; let config = <?= json_encode($config) ?>;
config.selectorManager.escapeName = name => `${name}`.trim().replace(/([^a-z0-9\w-\:\/]+)/gi, '-') config.selectorManager.escapeName = name => `${name}`.trim().replace(/([^a-z0-9\w-\:\/]+)/gi, '-')
@@ -217,7 +217,7 @@ class WebsiteManager implements WebsiteManagerContract
* *
* @param PageContract $page * @param PageContract $page
*/ */
public function renderPageSettings(PageContract $page = null) public function renderPageSettings(?PageContract $page = null)
{ {
$action = isset($page) ? 'edit' : 'create'; $action = isset($page) ? 'edit' : 'create';
$theme = phpb_instance('theme', [ $theme = phpb_instance('theme', [
@@ -10,6 +10,7 @@ $pageTranslations = $page ? $page->getTranslations() : [];
<div class="manager-panel p-8 w-full"> <div class="manager-panel p-8 w-full">
<form method="post" action="<?= phpb_url('website_manager', ['route' => 'page_settings', 'action' => $action]) ?><?= $pageUrlParam ?>"> <form method="post" action="<?= phpb_url('website_manager', ['route' => 'page_settings', 'action' => $action]) ?><?= $pageUrlParam ?>">
<?php phpb_csrf_field(); ?>
<div class="text-center text-3xl font-bold mb-8 mt-2"> <div class="text-center text-3xl font-bold mb-8 mt-2">
<?php <?php
if ($action === 'create'): if ($action === 'create'):
@@ -14,6 +14,7 @@ use Plugi\Setting;
<th>Database</th> <th>Database</th>
<td> <td>
<form method="post" action="<?= phpb_url('website_manager', ['route' => 'database', 'action' => 'update']) ?>"> <form method="post" action="<?= phpb_url('website_manager', ['route' => 'database', 'action' => 'update']) ?>">
<?php phpb_csrf_field(); ?>
<?php <?php
global $phpb_db; global $phpb_db;
$diff = $phpb_db->diffDB(); $diff = $phpb_db->diffDB();
@@ -8,6 +8,7 @@ $pages = $pageRepository->getAll();
?> ?>
<form method="post" action="<?= phpb_url('website_manager', ['route' => 'menus', 'action' => 'update', 'tab' => 'menus']) ?>"> <form method="post" action="<?= phpb_url('website_manager', ['route' => 'menus', 'action' => 'update', 'tab' => 'menus']) ?>">
<?php phpb_csrf_field(); ?>
<div class="main-spacing" x-data="{menus: <?= phpb_e($menusJson) ?>, pages: <?= phpb_e($menuPagesJson) ?>}"> <div class="main-spacing" x-data="{menus: <?= phpb_e($menusJson) ?>, pages: <?= phpb_e($menuPagesJson) ?>}">
@@ -6,6 +6,7 @@ $settingIns = phpb_instance('setting');
?> ?>
<form method="post" action="<?= phpb_url('website_manager', ['route' => 'settings', 'action' => 'update', 'tab' => 'settings']) ?>"> <form method="post" action="<?= phpb_url('website_manager', ['route' => 'settings', 'action' => 'update', 'tab' => 'settings']) ?>">
<?php phpb_csrf_field(); ?>
<div class="" x-data="{activeTab: 0, tabs: ['Website','Language','Theme','Extensions']}"> <div class="" x-data="{activeTab: 0, tabs: ['Website','Language','Theme','Extensions']}">
<div class="tabs mb-6"> <div class="tabs mb-6">
<div class="border-b border-base-300 grow"></div> <div class="border-b border-base-300 grow"></div>
+2 -2
View File
@@ -126,7 +126,7 @@ class Page implements PageContract
* @param string|null $locale * @param string|null $locale
* @return mixed|string|null * @return mixed|string|null
*/ */
public function getTranslation(string $setting, $locale = null) public function getTranslation(string $setting, ?string $locale = null)
{ {
$translations = $this->getTranslations(); $translations = $this->getTranslations();
if (empty($translations)) { if (empty($translations)) {
@@ -145,7 +145,7 @@ class Page implements PageContract
* @param string|null $locale * @param string|null $locale
* @return mixed|string|null * @return mixed|string|null
*/ */
public function getRoute($locale = null) public function getRoute(?string $locale = null)
{ {
$routeTranslation = $this->getTranslation('route', $locale); $routeTranslation = $this->getTranslation('route', $locale);
foreach (phpb_route_parameters() as $routeParameter => $value) { foreach (phpb_route_parameters() as $routeParameter => $value) {
+33 -4
View File
@@ -55,6 +55,12 @@ class Plugi
} }
if (session_status() === PHP_SESSION_NONE) { if (session_status() === PHP_SESSION_NONE) {
// Harden session cookies against hijacking and fixation
$isHttps = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
ini_set('session.cookie_httponly', '1');
ini_set('session.cookie_samesite', 'Strict');
ini_set('session.cookie_secure', $isHttps ? '1' : '0');
ini_set('session.use_strict_mode', '1');
session_start(); session_start();
} }
@@ -360,8 +366,14 @@ class Plugi
* @param string|null $action * @param string|null $action
* @return bool * @return bool
*/ */
public function handleRequest($action = null) public function handleRequest(?string $action = null)
{ {
// Set security headers on every request
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: SAMEORIGIN');
header('X-XSS-Protection: 1; mode=block');
header('Referrer-Policy: strict-origin-when-cross-origin');
$route = $route ?? $_GET['route'] ?? null; $route = $route ?? $_GET['route'] ?? null;
$action = $action ?? $_GET['action'] ?? $_POST['action'] ?? null; $action = $action ?? $_GET['action'] ?? $_POST['action'] ?? null;
if (! phpb_config('auth.use_login') || ! phpb_config('website_manager.use_website_manager')) { if (! phpb_config('auth.use_login') || ! phpb_config('website_manager.use_website_manager')) {
@@ -369,6 +381,16 @@ class Plugi
. 'Implement a piece of code that checks whether the user is logged in. If logged in, call handleAuthenticatedRequest() or else call handlePublicRequest().'); . 'Implement a piece of code that checks whether the user is logged in. If logged in, call handleAuthenticatedRequest() or else call handlePublicRequest().');
} }
// Validate CSRF token on POST requests for authenticated admin routes only
// (login has its own protection, public extension routes don't need CSRF)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action !== 'login') {
$isAdminRoute = phpb_in_module('website_manager') || phpb_in_module('pagebuilder');
if ($isAdminRoute && !phpb_validate_csrf()) {
header('HTTP/1.1 403 Forbidden');
die('Invalid CSRF token. Please refresh the page and try again.');
}
}
// handle login and logout requests // handle login and logout requests
$this->auth->handleRequest($action); $this->auth->handleRequest($action);
@@ -525,7 +547,7 @@ class Plugi
* @param string|null $route * @param string|null $route
* @param string|null $action * @param string|null $action
*/ */
public function handleAuthenticatedRequest($route = null, $action = null) public function handleAuthenticatedRequest(?string $route = null, ?string $action = null)
{ {
$route = $route ?? $_GET['route'] ?? null; $route = $route ?? $_GET['route'] ?? null;
$action = $action ?? $_GET['action'] ?? null; $action = $action ?? $_GET['action'] ?? null;
@@ -568,14 +590,21 @@ class Plugi
} }
$uploadedFile = $uploadedFile[0]; $uploadedFile = $uploadedFile[0];
$serverFile = realpath(phpb_config('storage.uploads_folder') . '/' . $uploadedFile->server_file); $uploadsFolder = realpath(phpb_config('storage.uploads_folder'));
$serverFile = realpath($uploadsFolder . '/' . $uploadedFile->server_file);
// add backwards compatibility for files uploaded with Plugi <= v0.12.0, stored as /uploads/{id}.{extension} // add backwards compatibility for files uploaded with Plugi <= v0.12.0, stored as /uploads/{id}.{extension}
if (! $serverFile) $serverFile = realpath(phpb_config('storage.uploads_folder') . '/' . basename($uploadedFile->server_file)); if (! $serverFile) $serverFile = realpath($uploadsFolder . '/' . basename($uploadedFile->server_file));
if (! $serverFile) { if (! $serverFile) {
header("HTTP/1.1 404 Not Found"); header("HTTP/1.1 404 Not Found");
exit(); exit();
} }
// prevent path traversal by ensuring the resolved path stays within the uploads folder
if (strpos($serverFile, $uploadsFolder) !== 0) {
header("HTTP/1.1 403 Forbidden");
exit();
}
header('Content-Type: ' . $uploadedFile->mime_type); header('Content-Type: ' . $uploadedFile->mime_type);
header('Content-Disposition: inline; filename="' . basename($uploadedFile->original_file) . '"'); header('Content-Disposition: inline; filename="' . basename($uploadedFile->original_file) . '"');
header('Expires: 0'); header('Expires: 0');
+2 -2
View File
@@ -49,7 +49,7 @@ class ThemeBlock
* @param bool $isExtension * @param bool $isExtension
* @param string|null $extensionSlug * @param string|null $extensionSlug
*/ */
public function __construct(ThemeContract $theme, string $blockSlug, bool $isExtension = false, string $extensionSlug = null) public function __construct(ThemeContract $theme, string $blockSlug, bool $isExtension = false, ?string $extensionSlug = null)
{ {
$this->theme = $theme; $this->theme = $theme;
$this->blockSlug = $blockSlug; $this->blockSlug = $blockSlug;
@@ -292,7 +292,7 @@ class ThemeBlock
* @param $key * @param $key
* @return mixed * @return mixed
*/ */
public function get($key = null) public function get(?string $key = null)
{ {
if (empty($key)) { if (empty($key)) {
return $this->config; return $this->config;
+1 -1
View File
@@ -39,7 +39,7 @@ class ThemeLayout
* @param ThemeContract $theme the theme this layout belongs to * @param ThemeContract $theme the theme this layout belongs to
* @param string $layoutSlug * @param string $layoutSlug
*/ */
public function __construct(ThemeContract $theme, string $layoutSlug, bool $isExtension = false, string $extensionSlug = null) public function __construct(ThemeContract $theme, string $layoutSlug, bool $isExtension = false, ?string $extensionSlug = null)
{ {
$this->theme = $theme; $this->theme = $theme;
$this->layoutSlug = $layoutSlug; $this->layoutSlug = $layoutSlug;
+1 -4
View File
@@ -24,8 +24,6 @@ use Plugi\Repositories\MenuRepository;
<?= Extensions::getHeaderAssets() ?> <?= Extensions::getHeaderAssets() ?>
<?php phpb_registered_assets('header'); ?> <?php phpb_registered_assets('header'); ?>
<script src="<?= phpb_theme_asset("dist/script.js") ?>"></script>
</head> </head>
<body> <body>
@@ -145,8 +143,7 @@ use Plugi\Repositories\MenuRepository;
</div> </div>
</footer> </footer>
<script src="<?= phpb_theme_asset("dist/phpb-demo-template.js") ?>"></script> <script src="<?= phpb_theme_asset("dist/script.js") ?>"></script>
<!-- Run Plugi script.js files --> <!-- Run Plugi script.js files -->
<script type="text/javascript"> <script type="text/javascript">
document.querySelectorAll("script").forEach(function(scriptTag) { document.querySelectorAll("script").forEach(function(scriptTag) {