Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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_idle_seconds = 1800 ; how long a session must be idle 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 @@ -34,10 +32,24 @@
$WEBHOOK = new UnityWebhook();
$GITHUB = new UnityGithub();

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

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

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

if (isset($_SERVER["REMOTE_USER"])) {
// Check if SSO is enabled on this page
$SSO = UnitySSO::getSSO();
Expand Down
67 changes: 67 additions & 0 deletions resources/lib/CSRFToken.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?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"]);
}
$_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 @@ -390,4 +390,18 @@ public static function deleteMessage(UnityHTTPDMessageLevel $level, string $titl
unset($_SESSION["messages"][$index]);
$_SESSION["messages"] = array_values($_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'>";
}
}
4 changes: 4 additions & 0 deletions resources/templates/header.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
use UnityWebPortal\lib\UnityHTTPD;

if ($_SERVER["REQUEST_METHOD"] == "POST") {
// another page should have already validated and we can't validate the same token twice
// UnityHTTPD::validatePostCSRFToken();
if (
($_SESSION["is_admin"] ?? false) == true
&& ($_POST["form_type"] ?? null) == "clearView"
Expand Down Expand Up @@ -179,10 +181,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
2 changes: 1 addition & 1 deletion test/functional/ViewAsUserTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public function _testViewAsUser(array $beforeUser, array $afterUser)
// now we should be new user
$this->assertEquals($afterUid, $USER->uid);
// $this->assertTrue($_SESSION["user_exists"]);
http_post(__DIR__ . "/../../resources/templates/header.php", [
http_post(__DIR__ . "/../../webroot/panel/account.php", [
"form_type" => "clearView",
]);
$this->assertArrayNotHasKey("viewUser", $_SESSION);
Expand Down
13 changes: 11 additions & 2 deletions 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 @@ -25,6 +26,7 @@
require_once __DIR__ . "/../resources/lib/exceptions/EncodingConversionException.php";
require_once __DIR__ . "/../resources/lib/exceptions/UnityHTTPDMessageNotFoundException.php";

use UnityWebPortal\lib\CSRFToken;
use UnityWebPortal\lib\UnityGroup;
use UnityWebPortal\lib\UnityHTTPD;
use UnityWebPortal\lib\UnitySQL;
Expand Down Expand Up @@ -97,8 +99,12 @@ function switchUser(
ensure(!is_null($USER));
}

function http_post(string $phpfile, array $post_data, bool $enforce_PRG = true): void
{
function http_post(
string $phpfile,
array $post_data,
bool $enforce_PRG = true,
bool $do_generate_csrf_token = true,
): void {
global $LDAP,
$SQL,
$MAILER,
Expand All @@ -115,6 +121,9 @@ function http_post(string $phpfile, array $post_data, bool $enforce_PRG = true):
$_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->assertNotEmpty($_SESSION["csrf_tokens"]);
CSRFToken::clear();
$this->assertEmpty($_SESSION["csrf_tokens"]);
}

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 @@ -31,6 +31,7 @@
echo "<td>$uid</td>";
echo "<td><a href='mailto:$mail'>$mail</a></td>";
echo "<td>";
$CSRFTokenHiddenFormInput = UnityHTTPD::getCSRFTokenHiddenFormInput();
echo "
<form
action=''
Expand All @@ -39,6 +40,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 @@ -62,9 +64,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
Loading