Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
7ce98ca
copilot 1st draft
simonLeary42 Dec 12, 2025
db933b0
remove form helpers
simonLeary42 Dec 12, 2025
f6ec3c3
remove constants
simonLeary42 Dec 12, 2025
40bb069
remove magic
simonLeary42 Dec 12, 2025
93b44f6
array_key_exists
simonLeary42 Dec 12, 2025
0ce0313
WIP single use tokens
simonLeary42 Dec 12, 2025
983eba4
remove normal token in favor of single use tokens
simonLeary42 Dec 12, 2025
3717068
rename function
simonLeary42 Dec 12, 2025
7b1a6db
better logging
simonLeary42 Dec 12, 2025
0b43ca5
fixup
simonLeary42 Dec 12, 2025
242a934
require
simonLeary42 Dec 12, 2025
436a564
refactor
simonLeary42 Dec 12, 2025
13e402b
add inputs to all forms
simonLeary42 Dec 12, 2025
05a1d51
validate in all pages
simonLeary42 Dec 12, 2025
06db60b
remove file
simonLeary42 Dec 12, 2025
5c37312
remove from init
simonLeary42 Dec 12, 2025
e2a8049
remove from ajax
simonLeary42 Dec 12, 2025
68c3baa
fixup tests
simonLeary42 Dec 12, 2025
7049556
init csrf_tokens array
simonLeary42 Dec 12, 2025
eb5409d
unique sessions for test cases
simonLeary42 Dec 12, 2025
16e819e
automatically generate csrf tokens for http_post in testing
simonLeary42 Dec 12, 2025
990ef60
add missing imports
simonLeary42 Dec 12, 2025
5514b56
don't overwrite tokens
simonLeary42 Dec 12, 2025
50b8568
validate in POST in header.php
simonLeary42 Dec 12, 2025
9e9954c
remove bad test
simonLeary42 Dec 12, 2025
7800a74
set csrf_tokens array even if unauthenticated
simonLeary42 Dec 12, 2025
02d652a
add session cleanup
simonLeary42 Dec 12, 2025
ab8aed0
write session data to filesystem immediately on cleanup
simonLeary42 Dec 12, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions defaults/config.ini.default
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ enable_verbose_error_log = true ; internal use only
enable_redirect_message = true ; internal use only
enable_exception_handler = true ; internal use only
enable_error_handler = true ; internal use only
session_cleanup_age_seconds = 1800 ; how old a session must be before messages and CSRF tokens are cleared

[ldap]
uri = "ldap://identity" ; URI of remote LDAP server
Expand Down
1 change: 1 addition & 0 deletions resources/autoload.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
require_once __DIR__ . "/lib/UnityWebhook.php";
require_once __DIR__ . "/lib/UnityGithub.php";
require_once __DIR__ . "/lib/utils.php";
require_once __DIR__ . "/lib/CSRFToken.php";
require_once __DIR__ . "/lib/exceptions/NoDieException.php";
require_once __DIR__ . "/lib/exceptions/SSOException.php";
require_once __DIR__ . "/lib/exceptions/ArrayKeyException.php";
Expand Down
16 changes: 14 additions & 2 deletions resources/init.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,6 @@
set_error_handler(["UnityWebPortal\lib\UnityHTTPD", "errorHandler"]);
}

session_start();

if (isset($GLOBALS["ldapconn"])) {
$LDAP = $GLOBALS["ldapconn"];
} else {
Expand All @@ -38,6 +36,20 @@
$_SESSION["messages"] = [];
}

if (!array_key_exists("csrf_tokens", $_SESSION)) {
$_SESSION["csrf_tokens"] = [];
}

session_start();
// https://stackoverflow.com/a/1270960/18696276
if (time() - ($_SESSION["LAST_ACTIVITY"] ?? 0) > CONFIG["site"]["session_cleanup_age_seconds"]) {
$_SESSION["csrf_tokens"] = [];
$_SESSION["messages"] = [];
session_write_close();
session_start();
}
$_SESSION["LAST_ACTIVITY"] = time();

if (isset($_SERVER["REMOTE_USER"])) {
// Check if SSO is enabled on this page
$SSO = UnitySSO::getSSO();
Expand Down
66 changes: 66 additions & 0 deletions resources/lib/CSRFToken.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php
namespace UnityWebPortal\lib;

class CSRFToken
{
private static function ensureSessionCSRFTokensSanity(): void
{
if (!isset($_SESSION)) {
throw new \RuntimeException("Session is not started. Call session_start() first.");
}
if (!array_key_exists("csrf_tokens", $_SESSION)) {
UnityHTTPD::errorLog(
"invalid session",
'$_SESSION has no array key "csrf_tokens"',
data: ['$_SESSION' => $_SESSION],
);
$_SESSION["csrf_tokens"] = [];
}
if (!is_array($_SESSION["csrf_tokens"])) {
UnityHTTPD::errorLog(
"invalid session",
'$_SESSION["csrf_tokens"] is not an array',
data: ['$_SESSION' => $_SESSION],
);
$_SESSION["csrf_tokens"] = [];
}
}

public static function generate(): string
{
self::ensureSessionCSRFTokensSanity();
$token = bin2hex(random_bytes(32));
$_SESSION["csrf_tokens"][$token] = false;
return $token;
}

public static function validate(string $token): bool
{
self::ensureSessionCSRFTokensSanity();
if ($token === "") {
UnityHTTPD::errorLog("empty CSRF token", "");
return false;
}
if (!array_key_exists($token, $_SESSION["csrf_tokens"])) {
UnityHTTPD::errorLog("unknown CSRF token", $token);
return false;
}
$entry = $_SESSION["csrf_tokens"][$token];
if ($entry === true) {
UnityHTTPD::errorLog("reused CSRF token", $token);
return false;
}
$_SESSION["csrf_tokens"][$token] = true;
return true;
}

public static function clear(): void
{
if (!isset($_SESSION)) {
return;
}
if (array_key_exists("csrf_tokens", $_SESSION)) {
unset($_SESSION["csrf_tokens"]);
}
}
}
14 changes: 14 additions & 0 deletions resources/lib/UnityHTTPD.php
Original file line number Diff line number Diff line change
Expand Up @@ -327,4 +327,18 @@ public static function clearMessages()
{
$_SESSION["messages"] = [];
}

public static function validatePostCSRFToken(): void
{
$token = self::getPostData("csrf_token");
if (!CSRFToken::validate($token)) {
self::badRequest("CSRF token validation failed", data: ["token" => $token]);
}
}

public static function getCSRFTokenHiddenFormInput(): string
{
$token = htmlspecialchars(CSRFToken::generate());
return "<input type='hidden' name='csrf_token' value='$token'>";
}
}
3 changes: 3 additions & 0 deletions resources/templates/header.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
use UnityWebPortal\lib\UnityHTTPD;

if ($_SERVER["REQUEST_METHOD"] == "POST") {
UnityHTTPD::validatePostCSRFToken();
if (
($_SESSION["is_admin"] ?? false) == true
&& ($_POST["form_type"] ?? null) == "clearView"
Expand Down Expand Up @@ -162,10 +163,12 @@
&& isset($_SESSION["viewUser"])
) {
$viewUser = $_SESSION["viewUser"];
$CSRFTokenHiddenFormInput = UnityHTTPD::getCSRFTokenHiddenFormInput();
echo "
<div id='viewAsBar'>
<span>You are accessing the web portal as the user <strong>$viewUser</strong></span>
<form method='POST' action=''>
$CSRFTokenHiddenFormInput
<input type='hidden' name='form_type' value='clearView'>
<input type='hidden' name='uid' value='$viewUser'>
<input type='submit' value='Return to My User'>
Expand Down
7 changes: 6 additions & 1 deletion test/phpunit-bootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
require_once __DIR__ . "/../resources/lib/UnityWebhook.php";
require_once __DIR__ . "/../resources/lib/UnityGithub.php";
require_once __DIR__ . "/../resources/lib/utils.php";
require_once __DIR__ . "/../resources/lib/CSRFToken.php";
require_once __DIR__ . "/../resources/lib/exceptions/NoDieException.php";
require_once __DIR__ . "/../resources/lib/exceptions/SSOException.php";
require_once __DIR__ . "/../resources/lib/exceptions/ArrayKeyException.php";
Expand All @@ -24,6 +25,7 @@
require_once __DIR__ . "/../resources/lib/exceptions/EncodingUnknownException.php";
require_once __DIR__ . "/../resources/lib/exceptions/EncodingConversionException.php";

use UnityWebPortal\lib\CSRFToken;
use UnityWebPortal\lib\UnityGroup;
use UnityWebPortal\lib\UnityHTTPD;
use UnityWebPortal\lib\UnitySQL;
Expand Down Expand Up @@ -96,7 +98,7 @@ function switchUser(
ensure(!is_null($USER));
}

function http_post(string $phpfile, array $post_data): void
function http_post(string $phpfile, array $post_data, bool $do_generate_csrf_token = true): void
{
global $LDAP,
$SQL,
Expand All @@ -114,6 +116,9 @@ function http_post(string $phpfile, array $post_data): void
$_SERVER["REQUEST_METHOD"] = "POST";
$_SERVER["PHP_SELF"] = preg_replace("/.*webroot\//", "/", $phpfile);
$_SERVER["REQUEST_URI"] = preg_replace("/.*webroot\//", "/", $phpfile); // Slightly imprecise because it doesn't include get parameters
if (!array_key_exists("csrf_token", $post_data) && $do_generate_csrf_token) {
$post_data["csrf_token"] = CSRFToken::generate();
}
$_POST = $post_data;
ob_start();
$post_did_redirect_or_die = false;
Expand Down
83 changes: 83 additions & 0 deletions test/unit/CSRFTokenTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
<?php
use PHPUnit\Framework\TestCase;
use UnityWebPortal\lib\CSRFToken;

class CSRFTokenTest extends TestCase
{
protected function setUp(): void
{
session_id(uniqid());
session_start();
$_SESSION["csrf_tokens"] = [];
}

protected function tearDown(): void
{
CSRFToken::clear();
session_write_close();
session_id(uniqid());
}

public function testGenerateCreatesToken(): void
{
$token = CSRFToken::generate();
$this->assertIsString($token);
$this->assertEquals(64, strlen($token));
$this->assertMatchesRegularExpression('/^[0-9a-f]{64}$/', $token);
}

public function testGenerateStoresTokenInSession(): void
{
$token = CSRFToken::generate();
$this->assertArrayHasKey("csrf_tokens", $_SESSION);
$this->assertArrayHasKey($token, $_SESSION["csrf_tokens"]);
$this->assertFalse($_SESSION["csrf_tokens"][$token]);
}

public function testValidateWithValidToken(): void
{
$token = CSRFToken::generate();
$this->assertTrue(CSRFToken::validate($token));
$this->assertTrue($_SESSION["csrf_tokens"][$token]);
}

public function testValidateWithInvalidToken(): void
{
CSRFToken::generate();
$this->assertFalse(CSRFToken::validate("invalid_token"));
}

public function testValidateWithEmptyToken(): void
{
CSRFToken::generate();
$this->assertFalse(CSRFToken::validate(""));
}

public function testValidateWithoutSessionToken(): void
{
$this->assertFalse(CSRFToken::validate("any_token"));
}

public function testClearRemovesToken(): void
{
CSRFToken::generate();
$this->assertArrayHasKey("csrf_tokens", $_SESSION);
CSRFToken::clear();
$this->assertArrayNotHasKey("csrf_tokens", $_SESSION);
}

public function testMultipleTokenGenerations(): void
{
$token1 = CSRFToken::generate();
$token2 = CSRFToken::generate();
$this->assertNotEquals($token1, $token2);
}

public function testTokenIsSingleUse(): void
{
$token = CSRFToken::generate();
$this->assertTrue(CSRFToken::validate($token));
$this->assertFalse(CSRFToken::validate($token));
$this->assertTrue($_SESSION["csrf_tokens"][$token]);
}
}
4 changes: 4 additions & 0 deletions webroot/admin/ajax/get_group_members.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
echo "<td>$uid</td>";
echo "<td><a href='mailto:$mail'>$mail</a></td>";
echo "<td>";
$CSRFTokenHiddenFormInput = UnityHTTPD::getCSRFTokenHiddenFormInput();
echo "
<form
action=''
Expand All @@ -42,6 +43,7 @@
return confirm(\"Are you sure you want to remove $uid from this group?\");
'
>
$CSRFTokenHiddenFormInput
<input type='hidden' name='form_type' value='remUserChild'>
<input type='hidden' name='uid' value='$uid'>
<input type='hidden' name='pi' value='$group->gid'>
Expand All @@ -65,9 +67,11 @@
echo "<td>$user->uid</td>";
echo "<td><a href='mailto:$email'>$email</a></td>";
echo "<td>";
$CSRFTokenHiddenFormInput = UnityHTTPD::getCSRFTokenHiddenFormInput();
echo
"<form action='' method='POST'
onsubmit='return confirm(\"Are you sure you want to approve $user->uid ?\");'>
$CSRFTokenHiddenFormInput
<input type='hidden' name='form_type' value='reqChild'>
<input type='hidden' name='uid' value='$user->uid'>
<input type='hidden' name='pi' value='$group->gid'>
Expand Down
2 changes: 2 additions & 0 deletions webroot/admin/content.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
UnityHTTPD::validatePostCSRFToken();
if (!empty($_POST["pageSel"])) {
$SQL->editPage($_POST["pageSel"], $_POST["content"], $USER);
}
Expand All @@ -21,6 +22,7 @@
<hr>

<form id="pageForm" method="POST" action="">
<?php echo UnityHTTPD::getCSRFTokenHiddenFormInput(); ?>
<select name="pageSel" required>
<option value="" selected disabled hidden>Select page...</option>
<?php
Expand Down
8 changes: 6 additions & 2 deletions webroot/admin/notices.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
UnityHTTPD::validatePostCSRFToken();
switch ($_POST["form_type"]) {
case "newNotice":
$SQL->addNotice($_POST["title"], $_POST["date"], $_POST["content"], $USER);
Expand Down Expand Up @@ -36,6 +37,7 @@
<button style='display: none;' class='btnClear'>Create New Notice Instead</button>

<form action="" method="POST" id="noticeForm">
<?php echo UnityHTTPD::getCSRFTokenHiddenFormInput(); ?>
<input type="hidden" name=id>
<input type="hidden" name="form_type" value="newNotice">
<input type="text" name="title" placeholder="Notice Title">
Expand All @@ -62,8 +64,10 @@
echo "<span class='noticeDate'>" . date('Y-m-d', strtotime($notice["date"])) . "</span>";
echo "<div class='noticeText'>" . $notice["message"] . "</div>";
echo "<button class='btnEdit'>Edit</button>";
echo
"<form style='display: inline-block; margin-left: 10px;' method='POST' action=''>
$CSRFTokenHiddenFormInput = UnityHTTPD::getCSRFTokenHiddenFormInput();
echo "
<form style='display: inline-block; margin-left: 10px;' method='POST' action=''>
$CSRFTokenHiddenFormInput
<input type='hidden' name='form_type' value='delNotice'>
<input type='hidden' name='id' value='" . $notice["id"] . "'>
<input type='submit' value='Delete'>
Expand Down
3 changes: 3 additions & 0 deletions webroot/admin/pi-mgmt.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
UnityHTTPD::validatePostCSRFToken();
if (isset($_POST["uid"])) {
$form_user = new UnityUser($_POST["uid"], $LDAP, $SQL, $MAILER, $WEBHOOK);
}
Expand Down Expand Up @@ -76,8 +77,10 @@
echo "<td><a href='mailto:$email'>$email</a></td>";
echo "<td>" . date("jS F, Y", strtotime($request['timestamp'])) . "</td>";
echo "<td>";
$CSRFTokenHiddenFormInput = UnityHTTPD::getCSRFTokenHiddenFormInput();
echo
"<form action='' method='POST'>
$CSRFTokenHiddenFormInput
<input type='hidden' name='form_type' value='req'>
<input type='hidden' name='uid' value='$uid'>
<input type='submit' name='action' value='Approve'
Expand Down
3 changes: 3 additions & 0 deletions webroot/admin/user-mgmt.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
UnityHTTPD::validatePostCSRFToken();
switch ($_POST["form_type"]) {
case "viewAsUser":
$_SESSION["viewUser"] = $_POST["uid"];
Expand Down Expand Up @@ -74,8 +75,10 @@ class="filterSearch"
}
echo "</td>";
echo "<td>";
$CSRFTokenHiddenFormInput = UnityHTTPD::getCSRFTokenHiddenFormInput();
echo "<form class='viewAsUserForm' action='' method='POST'
onsubmit='return confirm(\"Are you sure you want to switch to the user $uid?\");'>
$CSRFTokenHiddenFormInput
<input type='hidden' name='form_type' value='viewAsUser'>
<input type='hidden' name='uid' value='$uid'>
<input type='submit' name='action' value='Access'>
Expand Down
Loading