Merge pull request 'security: add CSRF protection and harden core handling' (#3) from security into main
Reviewed-on: #3
This commit was merged in pull request #3.
This commit is contained in:
+2
-2
@@ -1,10 +1,10 @@
|
||||
FROM php:8.2-apache-bullseye
|
||||
FROM php:8.4-apache-bookworm
|
||||
WORKDIR "/var/www/html"
|
||||
|
||||
RUN apt-get update; \
|
||||
docker-php-ext-install pdo pdo_mysql; \
|
||||
apt-get -y --no-install-recommends install \
|
||||
git \
|
||||
php8.2-mysql; \
|
||||
php8.4-mysql; \
|
||||
apt-get clean; \
|
||||
rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /usr/share/doc/*
|
||||
|
||||
Vendored
+1
-1
File diff suppressed because one or more lines are too long
+1
-1
File diff suppressed because one or more lines are too long
@@ -11,7 +11,7 @@ interface PageBuilderContract
|
||||
* @param $action
|
||||
* @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.
|
||||
@@ -27,7 +27,7 @@ interface PageBuilderContract
|
||||
* @param null $language
|
||||
* @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)
|
||||
@@ -44,7 +44,7 @@ interface PageBuilderContract
|
||||
* @param string|null $css
|
||||
* @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.
|
||||
@@ -53,7 +53,7 @@ interface PageBuilderContract
|
||||
* @param string|null $scripts
|
||||
* @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.
|
||||
|
||||
@@ -61,7 +61,7 @@ interface PageContract
|
||||
* @param string|null $locale
|
||||
* @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.
|
||||
@@ -76,7 +76,7 @@ interface PageContract
|
||||
* @param string|null $locale
|
||||
* @return mixed
|
||||
*/
|
||||
public function getRoute($locale = null);
|
||||
public function getRoute(?string $locale = null);
|
||||
|
||||
/**
|
||||
* Get the value of the given property of this Page.
|
||||
|
||||
@@ -22,7 +22,7 @@ interface WebsiteManagerContract
|
||||
*
|
||||
* @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).
|
||||
|
||||
@@ -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
@@ -22,19 +22,28 @@ class DB
|
||||
*/
|
||||
protected PDO $pdo;
|
||||
|
||||
/**
|
||||
* @var string $databaseName
|
||||
*/
|
||||
protected string $databaseName;
|
||||
|
||||
/**
|
||||
* DB constructor.
|
||||
*
|
||||
*/
|
||||
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(
|
||||
$_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_PASSWORD'],
|
||||
[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
|
||||
{
|
||||
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)) {
|
||||
foreach ($columns as &$column) {
|
||||
$column = preg_replace('/[^a-zA-Z_]*/', '', $column);
|
||||
}
|
||||
$columns = implode(',', $columns);
|
||||
$stmt = $this->pdo->prepare("SELECT $columns FROM $table");
|
||||
$stmt = $this->pdo->prepare("SELECT $columns FROM $sanitizedTable");
|
||||
} else {
|
||||
$stmt = $this->pdo->prepare("SELECT * FROM $table");
|
||||
$stmt = $this->pdo->prepare("SELECT * FROM $sanitizedTable");
|
||||
}
|
||||
$stmt->execute();
|
||||
return $stmt->fetchAll();
|
||||
@@ -86,7 +100,8 @@ class DB
|
||||
*/
|
||||
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]);
|
||||
return $stmt->fetchAll();
|
||||
}
|
||||
@@ -152,13 +167,13 @@ class DB
|
||||
// check if table with the name $table exists. if not, execute $query.'
|
||||
try {
|
||||
$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'",
|
||||
[$key, $tableName]
|
||||
"SELECT CONSTRAINT_NAME FROM information_schema.TABLE_CONSTRAINTS WHERE CONSTRAINT_NAME = ? AND TABLE_SCHEMA = ? AND TABLE_NAME = ? AND CONSTRAINT_TYPE = 'UNIQUE'",
|
||||
[$key, $this->databaseName, $tableName]
|
||||
);
|
||||
if (count($keys) === 1) return true;
|
||||
return false;
|
||||
} catch (Exception $e) {
|
||||
print_r($e->getMessage());
|
||||
// Do not expose database error details to the user
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -176,7 +191,7 @@ class DB
|
||||
}
|
||||
|
||||
public function getDBDefinitionHash() {
|
||||
return sha1(json_encode($this->getDBDefinition()));
|
||||
return hash('sha256', json_encode($this->getDBDefinition()));
|
||||
}
|
||||
|
||||
public function diffDB() {
|
||||
@@ -207,15 +222,24 @@ class DB
|
||||
foreach ($diff as $table => $tableDiff) {
|
||||
$tableName = $_ENV['DATABASE_PREFIX'] . phpb_remove_non_alpha_numeric($table);
|
||||
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} MODIFY `id` int NOT NULL AUTO_INCREMENT");
|
||||
} elseif (is_array($tableDiff)) {
|
||||
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) {
|
||||
$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)");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ class EnvLoader
|
||||
continue;
|
||||
}
|
||||
|
||||
list($name, $value) = explode('=', $line, 2);
|
||||
[$name, $value] = explode('=', $line, 2);
|
||||
$name = trim($name);
|
||||
$value = trim($value);
|
||||
|
||||
|
||||
@@ -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.
|
||||
*/
|
||||
function phpb_field_value(string $attribute, object $instance = null): ?string
|
||||
function phpb_field_value(string $attribute, ?object $instance = null): ?string
|
||||
{
|
||||
if (isset($_POST[$attribute])) {
|
||||
return phpb_encode_or_null($_POST[$attribute]);
|
||||
@@ -588,6 +588,7 @@ if (! function_exists('phpb_render_setting')) {
|
||||
</label>
|
||||
</div>
|
||||
EOL;
|
||||
break;
|
||||
|
||||
case 'text':
|
||||
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')) {
|
||||
/**
|
||||
* Deep merging
|
||||
|
||||
@@ -171,7 +171,7 @@ class Extensions
|
||||
/**
|
||||
* Get all settings.
|
||||
*/
|
||||
public static function getSettings($ext = null) : array {
|
||||
public static function getSettings(?string $ext = null) : array {
|
||||
$settingIns = phpb_instance('setting');
|
||||
$hydrSettings = [];
|
||||
foreach (self::$settings as $setting) {
|
||||
|
||||
@@ -15,7 +15,13 @@ class Auth implements AuthContract
|
||||
{
|
||||
if (phpb_in_module('auth')) {
|
||||
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;
|
||||
phpb_redirect(phpb_url('website_manager'));
|
||||
} 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.
|
||||
*
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
</div>
|
||||
|
||||
<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
|
||||
if (phpb_flash('message')):
|
||||
?>
|
||||
|
||||
@@ -35,7 +35,7 @@ class BaseModel
|
||||
* @param PageContract|null $page
|
||||
* @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->data = is_array($data) ? $data : [];
|
||||
|
||||
@@ -68,7 +68,7 @@ class BlockRenderer
|
||||
* @param null $id id of the specific block instance
|
||||
* @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))
|
||||
? new ThemeBlock($this->theme, $path, true, $blockSlug)
|
||||
@@ -85,7 +85,7 @@ class BlockRenderer
|
||||
* @param null $id id of the specific block instance
|
||||
* @return string
|
||||
*/
|
||||
public function render(ThemeBlock $themeBlock, $blockData = null, $id = null)
|
||||
public function render(ThemeBlock $themeBlock, ?array $blockData = null, ?string $id = null)
|
||||
{
|
||||
$blockData = $blockData ?? [];
|
||||
|
||||
|
||||
@@ -59,7 +59,7 @@ class PageBuilder implements PageBuilderContract
|
||||
* @return bool
|
||||
* @throws Exception
|
||||
*/
|
||||
public function handleRequest($route, $action, PageContract $page = null)
|
||||
public function handleRequest($route, $action, ?PageContract $page = null)
|
||||
{
|
||||
phpb_set_in_editmode();
|
||||
|
||||
@@ -377,7 +377,7 @@ class PageBuilder implements PageBuilderContract
|
||||
* @param string|null $css
|
||||
* @return string
|
||||
*/
|
||||
public function customStyle(string $css = null)
|
||||
public function customStyle(?string $css = null)
|
||||
{
|
||||
if (! is_null($css)) {
|
||||
$this->css = $css;
|
||||
@@ -392,7 +392,7 @@ class PageBuilder implements PageBuilderContract
|
||||
* @param string|null $scripts
|
||||
* @return string
|
||||
*/
|
||||
public function customScripts(string $location, string $scripts = null)
|
||||
public function customScripts(string $location, ?string $scripts = null)
|
||||
{
|
||||
if (! is_null($scripts)) {
|
||||
$this->scripts[$location] = $scripts;
|
||||
|
||||
@@ -126,7 +126,7 @@ class PageRenderer
|
||||
* @param bool $canBeCached
|
||||
* @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)) {
|
||||
static::$canBeCached = false;
|
||||
@@ -279,7 +279,7 @@ class PageRenderer
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
public function parseShortcodes(string $htmlWithShortcodes, $context = null)
|
||||
public function parseShortcodes(string $htmlWithShortcodes, ?array $context = null)
|
||||
{
|
||||
$context = $context ?? $this->pageBlocksData;
|
||||
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
|
||||
$attributes = [];
|
||||
while (strpos($matchAttributeString, '=') !== false) {
|
||||
list($attribute, $remainingString) = explode('=', $matchAttributeString, 2);
|
||||
[$attribute, $remainingString] = explode('=', $matchAttributeString, 2);
|
||||
$attribute = trim($attribute);
|
||||
|
||||
// if first char is " and at least two " exist, get attribute value between ""
|
||||
if (strpos($remainingString, '"') === 0 && strpos($remainingString, '"', 1) !== false) {
|
||||
list($empty, $value, $remainingString) = explode('"', $remainingString, 3);
|
||||
[$empty, $value, $remainingString] = explode('"', $remainingString, 3);
|
||||
$attributes[$attribute] = $value;
|
||||
} else {
|
||||
// attribute value was not between "", get value until next whitespace or until end of $remainingString
|
||||
if (strpos($remainingString, ' ') !== false) {
|
||||
list($value, $remainingString) = explode(' ', $remainingString, 2);
|
||||
[$value, $remainingString] = explode(' ', $remainingString, 2);
|
||||
$attributes[$attribute] = $value;
|
||||
} else {
|
||||
$attributes[$attribute] = $remainingString;
|
||||
|
||||
@@ -10,6 +10,7 @@ html, body {
|
||||
</style>
|
||||
<script src="<?= phpb_asset('pagebuilder/html2canvas-v0.4.1.min.js') ?>"></script>
|
||||
<script>
|
||||
window.csrfToken = '<?= \Plugi\Core\Csrf::getToken() ?>';
|
||||
$(document).ready(function() {
|
||||
html2canvas($("body"), {
|
||||
allowTaint: false,
|
||||
@@ -21,6 +22,9 @@ $(document).ready(function() {
|
||||
$.ajax({
|
||||
type: "POST",
|
||||
url: "<?= phpb_url('pagebuilder', ['route' => 'thumb_generator', 'action' => 'upload']) ?>",
|
||||
beforeSend: function(xhr) {
|
||||
xhr.setRequestHeader('X-CSRF-Token', window.csrfToken);
|
||||
},
|
||||
data: {
|
||||
block: "<?= $blockSlug ?>",
|
||||
data: data
|
||||
|
||||
@@ -15,6 +15,31 @@ use Exception;
|
||||
#[\AllowDynamicProperties]
|
||||
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.
|
||||
*
|
||||
@@ -216,7 +241,8 @@ class Uploader {
|
||||
$this->file_src_temp = $file["tmp_name"];
|
||||
$this->file_src_size = $file["size"];
|
||||
$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->was_uploaded = true;
|
||||
@@ -241,7 +267,7 @@ class Uploader {
|
||||
$path = $this->upload_to . $file;
|
||||
$this->upload_to = dirname($path);
|
||||
} else {
|
||||
$hash = md5(uniqid(rand(), true));
|
||||
$hash = bin2hex(random_bytes(16));
|
||||
$file = $hash . '.' . $this->file_src_name_ext;
|
||||
$path = $this->upload_to . $file;
|
||||
}
|
||||
@@ -317,7 +343,7 @@ class Uploader {
|
||||
$this->final_file_name = $file;
|
||||
|
||||
// extract image dimensions
|
||||
list($w, $h) = getimagesize($path);
|
||||
[$w, $h] = getimagesize($path);
|
||||
$this->file_width = $w;
|
||||
$this->file_height = $h;
|
||||
|
||||
@@ -345,7 +371,7 @@ class Uploader {
|
||||
* @param integer $mode Optional permissions
|
||||
* @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) );
|
||||
}
|
||||
|
||||
@@ -356,7 +382,7 @@ class Uploader {
|
||||
* @param integer $mode Optional permissions
|
||||
* @return boolean Success
|
||||
*/
|
||||
protected function _mkdir($path, $mode = 0777) {
|
||||
protected function _mkdir($path, $mode = 0755) {
|
||||
$old = umask(0);
|
||||
$res = @mkdir($path, $mode);
|
||||
umask($old);
|
||||
|
||||
@@ -531,7 +531,8 @@
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'X-Requested-With': 'XMLHttpRequest'
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
'X-CSRF-Token': window.csrfToken
|
||||
},
|
||||
body: formData
|
||||
});
|
||||
|
||||
@@ -61,7 +61,8 @@
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'X-Requested-With': 'XMLHttpRequest'
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
'X-CSRF-Token': window.csrfToken
|
||||
},
|
||||
body: formData
|
||||
});
|
||||
@@ -273,13 +274,15 @@
|
||||
|
||||
const formData = new URLSearchParams();
|
||||
formData.append('data', JSON.stringify(data));
|
||||
formData.append('_csrf_token', window.csrfToken);
|
||||
|
||||
try {
|
||||
const response = await fetch(saveUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'X-Requested-With': 'XMLHttpRequest'
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
'X-CSRF-Token': window.csrfToken
|
||||
},
|
||||
body: formData
|
||||
});
|
||||
|
||||
@@ -6,7 +6,8 @@ window.editor.on('asset:remove', function(asset) {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"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 })
|
||||
}).catch(function() {});
|
||||
|
||||
@@ -36,9 +36,14 @@ window.pages = <?= json_encode($pageBuilder->getPages()) ?>;
|
||||
window.renderBlockUrl = '<?= phpb_url('pagebuilder', ['action' => 'renderBlock', 'page' => $page->getId()]) ?>';
|
||||
window.injectionScriptUrl = '<?= phpb_asset('pagebuilder/page-injection.js') ?>';
|
||||
window.renderLanguageVariantUrl = '<?= phpb_url('pagebuilder', ['action' => 'renderLanguageVariant', 'page' => $page->getId()]) ?>';
|
||||
window.csrfToken = '<?= phpb_e(\Plugi\Core\Csrf::getToken()) ?>';
|
||||
|
||||
<?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) ?>;
|
||||
config.selectorManager.escapeName = name => `${name}`.trim().replace(/([^a-z0-9\w-\:\/]+)/gi, '-')
|
||||
|
||||
@@ -217,7 +217,7 @@ class WebsiteManager implements WebsiteManagerContract
|
||||
*
|
||||
* @param PageContract $page
|
||||
*/
|
||||
public function renderPageSettings(PageContract $page = null)
|
||||
public function renderPageSettings(?PageContract $page = null)
|
||||
{
|
||||
$action = isset($page) ? 'edit' : 'create';
|
||||
$theme = phpb_instance('theme', [
|
||||
|
||||
@@ -10,6 +10,7 @@ $pageTranslations = $page ? $page->getTranslations() : [];
|
||||
|
||||
<div class="manager-panel p-8 w-full">
|
||||
<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">
|
||||
<?php
|
||||
if ($action === 'create'):
|
||||
|
||||
@@ -14,6 +14,7 @@ use Plugi\Setting;
|
||||
<th>Database</th>
|
||||
<td>
|
||||
<form method="post" action="<?= phpb_url('website_manager', ['route' => 'database', 'action' => 'update']) ?>">
|
||||
<?php phpb_csrf_field(); ?>
|
||||
<?php
|
||||
global $phpb_db;
|
||||
$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']) ?>">
|
||||
<?php phpb_csrf_field(); ?>
|
||||
|
||||
<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']) ?>">
|
||||
<?php phpb_csrf_field(); ?>
|
||||
<div class="" x-data="{activeTab: 0, tabs: ['Website','Language','Theme','Extensions']}">
|
||||
<div class="tabs mb-6">
|
||||
<div class="border-b border-base-300 grow"></div>
|
||||
|
||||
@@ -126,7 +126,7 @@ class Page implements PageContract
|
||||
* @param string|null $locale
|
||||
* @return mixed|string|null
|
||||
*/
|
||||
public function getTranslation(string $setting, $locale = null)
|
||||
public function getTranslation(string $setting, ?string $locale = null)
|
||||
{
|
||||
$translations = $this->getTranslations();
|
||||
if (empty($translations)) {
|
||||
@@ -145,7 +145,7 @@ class Page implements PageContract
|
||||
* @param string|null $locale
|
||||
* @return mixed|string|null
|
||||
*/
|
||||
public function getRoute($locale = null)
|
||||
public function getRoute(?string $locale = null)
|
||||
{
|
||||
$routeTranslation = $this->getTranslation('route', $locale);
|
||||
foreach (phpb_route_parameters() as $routeParameter => $value) {
|
||||
|
||||
@@ -55,6 +55,12 @@ class Plugi
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
@@ -360,8 +366,14 @@ class Plugi
|
||||
* @param string|null $action
|
||||
* @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;
|
||||
$action = $action ?? $_GET['action'] ?? $_POST['action'] ?? null;
|
||||
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().');
|
||||
}
|
||||
|
||||
// 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
|
||||
$this->auth->handleRequest($action);
|
||||
|
||||
@@ -525,7 +547,7 @@ class Plugi
|
||||
* @param string|null $route
|
||||
* @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;
|
||||
$action = $action ?? $_GET['action'] ?? null;
|
||||
@@ -568,14 +590,21 @@ class Plugi
|
||||
}
|
||||
|
||||
$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}
|
||||
if (! $serverFile) $serverFile = realpath(phpb_config('storage.uploads_folder') . '/' . basename($uploadedFile->server_file));
|
||||
if (! $serverFile) $serverFile = realpath($uploadsFolder . '/' . basename($uploadedFile->server_file));
|
||||
if (! $serverFile) {
|
||||
header("HTTP/1.1 404 Not Found");
|
||||
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-Disposition: inline; filename="' . basename($uploadedFile->original_file) . '"');
|
||||
header('Expires: 0');
|
||||
|
||||
@@ -49,7 +49,7 @@ class ThemeBlock
|
||||
* @param bool $isExtension
|
||||
* @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->blockSlug = $blockSlug;
|
||||
@@ -292,7 +292,7 @@ class ThemeBlock
|
||||
* @param $key
|
||||
* @return mixed
|
||||
*/
|
||||
public function get($key = null)
|
||||
public function get(?string $key = null)
|
||||
{
|
||||
if (empty($key)) {
|
||||
return $this->config;
|
||||
|
||||
@@ -39,7 +39,7 @@ class ThemeLayout
|
||||
* @param ThemeContract $theme the theme this layout belongs to
|
||||
* @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->layoutSlug = $layoutSlug;
|
||||
|
||||
@@ -24,8 +24,6 @@ use Plugi\Repositories\MenuRepository;
|
||||
<?= Extensions::getHeaderAssets() ?>
|
||||
<?php phpb_registered_assets('header'); ?>
|
||||
|
||||
<script src="<?= phpb_theme_asset("dist/script.js") ?>"></script>
|
||||
|
||||
</head>
|
||||
|
||||
<body>
|
||||
@@ -145,8 +143,7 @@ use Plugi\Repositories\MenuRepository;
|
||||
</div>
|
||||
</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 -->
|
||||
<script type="text/javascript">
|
||||
document.querySelectorAll("script").forEach(function(scriptTag) {
|
||||
|
||||
Reference in New Issue
Block a user