1
0
Fork 0
mirror of https://github.com/sbrl/Pepperminty-Wiki.git synced 2024-11-10 00:23:01 +00:00
Pepperminty-Wiki/modules/page-login.php

330 lines
14 KiB
PHP
Raw Normal View History

<?php
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
2015-09-19 09:19:56 +00:00
register_module([
"name" => "Login",
"version" => "0.9.7",
2015-09-19 09:19:56 +00:00
"author" => "Starbeamrainbowlabs",
"description" => "Adds a pair of actions (login and checklogin) that allow users to login. You need this one if you want your users to be able to login.",
"id" => "page-login",
"code" => function() {
global $settings;
2020-04-18 11:37:07 +00:00
2016-06-15 18:20:03 +00:00
/**
* @api {get} ?action=login[&failed=yes][&returnto={someUrl}] Get the login page
* @apiName Login
* @apiGroup Authorisation
* @apiPermission Anonymous
*
2016-06-15 18:20:03 +00:00
* @apiParam {string} failed Setting to yes causes a login failure message to be displayed above the login form.
* @apiParam {string} returnto Set to the url to redirect to upon a successful login.
*/
2020-04-18 11:37:07 +00:00
2015-09-19 09:19:56 +00:00
/*
2016-06-04 19:27:14 +00:00
* ██ ██████ ██████ ██ ███ ██
* ██ ██ ██ ██ ██ ████ ██
* ██ ██ ██ ██ ███ ██ ██ ██ ██
* ██ ██ ██ ██ ██ ██ ██ ██ ██
* ███████ ██████ ██████ ██ ██ ████
2015-09-19 09:19:56 +00:00
*/
add_action("login", function() {
global $settings, $env;
2020-04-18 11:37:07 +00:00
// Build the action url that will actually perform the login
$login_form_action_url = "index.php?action=checklogin";
if(isset($_GET["returnto"]))
$login_form_action_url .= "&amp;returnto=" . rawurlencode($_GET["returnto"]);
2020-04-18 11:37:07 +00:00
if($env->is_logged_in && !empty($_GET["returnto"]))
{
http_response_code(307);
header("location: " . $_GET["returnto"]);
}
2020-04-18 11:37:07 +00:00
header("x-robots-tag: noindex, nofollow");
page_renderer::add_header_html('<meta name="robots" content="noindex, nofollow" />');
2015-09-19 09:19:56 +00:00
$title = "Login to $settings->sitename";
$content = "<h1>Login to $settings->sitename</h1>\n";
if(isset($_GET["failed"]))
$content .= "\t\t<p><em>Login failed.</em></p>\n";
if(isset($_GET["required"]))
$content .= "\t\t<p><em>$settings->sitename requires that you login before continuing.</em></p>\n";
if(isset($_GET["returnto"]))
$content .= "\t\t<p>Login to be redirected to <code>".htmlentities($_GET["returnto"])."</code>.</p>";
$content .= "\t\t<form method='post' action='$login_form_action_url'>
2015-09-19 09:19:56 +00:00
<label for='user'>Username:</label>
2016-04-09 10:02:25 +00:00
<input type='text' name='user' id='user' autofocus />
2015-09-19 09:19:56 +00:00
<br />
<label for='pass'>Password:</label>
<input type='password' name='pass' id='pass' />
<br />
<input type='submit' value='Login' />
</form>\n";
2015-09-19 09:19:56 +00:00
exit(page_renderer::render_main($title, $content));
});
2020-04-18 11:37:07 +00:00
2016-06-15 18:20:03 +00:00
/**
* @api {post} ?action=checklogin Perform a login
* @apiName CheckLogin
* @apiGroup Authorisation
* @apiPermission Anonymous
*
2016-06-15 18:20:03 +00:00
* @apiParam {string} user The user name to login with.
2018-03-30 15:40:29 +00:00
* @apiParam {string} pass The password to login with.
2016-06-15 18:20:03 +00:00
* @apiParam {string} returnto The URL to redirect to upon a successful login.
*
* @apiError InvalidCredentialsError The supplied credentials were invalid. Note that this error is actually a redirect to ?action=login&failed=yes (with the returnto parameter appended if you supplied one)
*/
2020-04-18 11:37:07 +00:00
2015-09-19 09:19:56 +00:00
/*
2016-06-04 19:27:14 +00:00
* ██████ ██ ██ ███████ ██████ ██ ██
* ██ ██ ██ ██ ██ ██ ██
* ██ ███████ █████ ██ █████
* ██ ██ ██ ██ ██ ██ ██
2016-06-04 19:27:14 +00:00
* ██████ ██ ██ ███████ ██████ ██ ██
*
2016-06-04 19:27:14 +00:00
* ██ ██████ ██████ ██ ███ ██
* ██ ██ ██ ██ ██ ████ ██
* ██ ██ ██ ██ ███ ██ ██ ██ ██
* ██ ██ ██ ██ ██ ██ ██ ██ ██
* ███████ ██████ ██████ ██ ██ ████
2015-09-19 09:19:56 +00:00
*/
add_action("checklogin", function() {
global $settings, $env;
2020-04-18 11:37:07 +00:00
if(!isset($_POST["user"]) or !isset($_POST["pass"])) {
2015-09-19 09:19:56 +00:00
http_response_code(302);
2016-06-04 19:27:14 +00:00
$nextUrl = "index.php?action=login&failed=yes&badrequest=yes";
if(!empty($_GET["returnto"]))
$nextUrl .= "&returnto=" . rawurlencode($_GET["returnto"]);
header("location: $nextUrl");
exit();
}
2020-04-18 11:37:07 +00:00
// Actually do the login
2020-04-18 11:37:07 +00:00
// The user wants to log in
$user = $_POST["user"];
$pass = $_POST["pass"];
2020-04-18 11:37:07 +00:00
// Verify their password
if(empty($settings->users->$user) || !verify_password($pass, $settings->users->$user->password)) {
// Login failed :-(
http_response_code(302);
header("x-login-success: no");
$nextUrl = "index.php?action=login&failed=yes";
2016-06-04 19:27:14 +00:00
if(!empty($_GET["returnto"]))
$nextUrl .= "&returnto=" . rawurlencode($_GET["returnto"]);
header("location: $nextUrl");
2015-09-19 09:19:56 +00:00
exit();
}
2020-04-18 11:37:07 +00:00
// Success! :D
2020-04-18 11:37:07 +00:00
// Avoid a session fixation attack
// Ref https://guides.codepath.com/websecurity/Session-Fixation
session_regenerate_id(true);
send_cookie(session_name(), session_id(), time() + $settings->sessionlifetime);
// Update the environment
$env->is_logged_in = true;
$env->user = $user;
$env->user_data = $settings->users->{$env->user};
2020-04-18 11:37:07 +00:00
$new_password_hash = hash_password_update($pass, $settings->users->$user->password);
2020-04-18 11:37:07 +00:00
// Update the password hash
if($new_password_hash !== null) {
$env->user_data->password = $new_password_hash;
if(!save_userdata()) {
http_response_code(503);
exit(page_renderer::render_main("Login Error - $settings->sitename", "<p>Your credentials were correct, but $settings->sitename was unable to log you in as an updated hash of your password couldn't be saved. Updating your password hash to the latest and strongest hashing algorithm is an important part of keeping your account secure.</p>
<p>Please contact ".htmlentities($settings->admindetails_name).", $settings->sitename's adminstrator, for assistance (their email address can be found at the bottom of every page, including this one).</p>"));
}
error_log("[PeppermintyWiki/$settings->sitename/login] Updated password hash for $user.");
}
2020-04-18 11:37:07 +00:00
// If the email address is still in the old field, migrate it
if(!empty($settings->users->{$user}->email)) {
$settings->users->{$user}->emailAddress = $settings->users->{$user}->email;
unset($settings->users->{$user}->email);
save_settings();
}
2020-04-18 11:37:07 +00:00
$_SESSION["$settings->sessionprefix-user"] = $user;
$_SESSION["$settings->sessionprefix-pass"] = $new_password_hash ?? hash_password($pass);
$_SESSION["$settings->sessionprefix-expiretime"] = time() + 60*60*24*30; // 30 days from now
2020-04-18 11:37:07 +00:00
// Redirect to wherever the user was going
http_response_code(302);
header("x-login-success: yes");
2021-09-30 20:06:07 +00:00
if(isset($_GET["returnto"])) {
$returnto_redirect = $_GET["returnto"];
if(strpos($returnto_redirect, "?") === false) {
http_response_code(307);
header("location: ?action=view");
exit(page_renderer::render_main("Login error - $settings->sitename", "<p>Your credentials were correct, but the 'returnto' URL specified (in the <code>returnto</code> GET parameter) did not contain a question mark. To protect you from being redirected to another site, $settings->sitename only allows redirects that do not leave $settings->sitename.</p>"));
}
// Ensure that this redirect takes to only somewhere else in this site
$returnto_redirect = substr($returnto_redirect, strpos($returnto_redirect, "?"));
header("location: $returnto_redirect");
}
else
header("location: index.php");
exit();
2015-09-19 09:19:56 +00:00
});
2020-04-18 11:37:07 +00:00
add_action("hash-cost-test", function() {
global $env;
2020-04-18 11:37:07 +00:00
header("content-type: text/plain");
2020-04-18 11:37:07 +00:00
if(!$env->is_logged_in || !$env->is_admin) {
http_response_code(401);
header("content-type: text/plain");
exit("Error: Only moderators are allowed to use this action.");
}
2020-04-18 11:37:07 +00:00
$time_compute = microtime(true);
$cost = hash_password_compute_cost(true);
$time_compute = (microtime(true) - $time_compute)*1000;
2020-04-18 11:37:07 +00:00
$time_cost = microtime(true);
password_hash("testing", PASSWORD_DEFAULT, [ "cost" => $cost ]);
$time_cost = (microtime(true) - $time_cost)*1000;
2020-04-18 11:37:07 +00:00
echo("Calculated cost: $cost ({$time_cost}ms)\n");
echo("Time taken: {$time_compute}ms\n");
exit(date("r"));
});
2020-04-18 11:37:07 +00:00
// Register a section on logging in on the help page.
add_help_section("30-login", "Logging in", "<p>In order to edit $settings->sitename and have your edit attributed to you, you need to be logged in. Depending on the settings, logging in may be a required step if you want to edit at all. Thankfully, loggging in is not hard. Simply click the &quot;Login&quot; link in the top left, type your username and password, and then click login.</p>
<p>If you do not have an account yet and would like one, try contacting " . hide_email($settings->admindetails_email, $settings->admindetails_name) . ", $settings->sitename's administrator and ask them nicely to see if they can create you an account.</p>");
2020-04-18 11:37:07 +00:00
2018-05-10 22:28:08 +00:00
// Re-check the password hashing cost, if necessary
do_password_hash_code_update();
2015-09-19 09:19:56 +00:00
}
]);
2018-05-25 11:07:51 +00:00
/**
* Recalculates and updates the password hashing cost.
*/
function do_password_hash_code_update() {
2018-05-10 22:28:08 +00:00
global $settings, $paths;
2020-04-18 11:37:07 +00:00
// There's no point if we're using Argon2i, as it doesn't take a cost
if(defined("PASSWORD_ARGON2I") && hash_password_properties()["algorithm"] == PASSWORD_ARGON2I)
return;
2020-04-18 11:37:07 +00:00
// Skip rechecking if the automatic check has been disabled
if($settings->password_cost_time_interval == -1)
return;
// Skip the recheck if we've done one recently
if(isset($settings->password_cost_time_lastcheck) &&
time() - $settings->password_cost_time_lastcheck < $settings->password_cost_time_interval)
return;
2020-04-18 11:37:07 +00:00
$new_cost = hash_password_compute_cost();
2020-04-18 11:37:07 +00:00
// Save the new cost, but only if it's higher than the old one
2018-05-10 22:28:08 +00:00
if($new_cost > $settings->password_cost)
$settings->password_cost = $new_cost;
// Save the current time in the settings
$settings->password_cost_time_lastcheck = time();
file_put_contents($paths->settings_file, json_encode($settings, JSON_PRETTY_PRINT));
}
/**
* Figures out the appropriate algorithm & options for hashing passwords based
* on the current settings.
* @return array The appropriate password hashing algorithm and options.
*/
function hash_password_properties() {
global $settings;
2020-04-18 11:37:07 +00:00
$result = [
"algorithm" => constant($settings->password_algorithm),
2018-05-10 22:28:08 +00:00
"options" => [ "cost" => $settings->password_cost ]
];
2018-05-10 22:28:08 +00:00
if(defined("PASSWORD_ARGON2I") && $result["algorithm"] == PASSWORD_ARGON2I)
$result["options"] = [];
return $result;
}
/**
* Hashes the given password according to the current settings defined
* in $settings.
* @package page-login
* @param string $pass The password to hash.
*
2019-05-11 11:13:06 +00:00
* @return string The hashed password. Uses password_hash() under-the-hood, but with some additional extras to avoid known issues.
*/
function hash_password($pass) {
$props = hash_password_properties();
return password_hash(
base64_encode(hash("sha384", $pass)),
$props["algorithm"],
$props["options"]
);
}
2018-05-11 10:36:29 +00:00
/**
* Verifies a user's password against a pre-generated hash.
* @param string $pass The user's password.
* @param string $hash The hash to compare against.
* @return bool Whether the password matches the has or not.
*/
function verify_password($pass, $hash) {
$pass_transformed = base64_encode(hash("sha384", $pass));
return password_verify($pass_transformed, $hash);
}
/**
* Determines if the provided password needs re-hashing or not.
* @param string $pass The password to check.
* @param string $hash The hash of the provided password to check.
* @return string|null Returns null if an updaste is not required - otherwise returns the new updated hash.
*/
function hash_password_update($pass, $hash) {
$props = hash_password_properties();
if(password_needs_rehash($hash, $props["algorithm"], $props["options"])) {
return hash_password($pass);
}
return null;
}
/**
* Computes the appropriate cost value for password_hash based on the settings
* automatically.
* Starts at 10 and works upwards in increments of 1. Goes on until a value is
* found that's greater than the target - or 10x the target time elapses.
2019-05-11 11:13:06 +00:00
* @param bool $verbose Whether to output verbose progress information to the client or not.
* @return int The automatically calculated password hashing cost.
*/
function hash_password_compute_cost($verbose = false) {
global $settings;
$props = hash_password_properties();
if($props["algorithm"] == PASSWORD_ARGON2I)
return null;
$props["options"]["cost"] = 10;
2020-04-18 11:37:07 +00:00
2018-05-10 22:28:08 +00:00
$target_cost_time = $settings->password_cost_time / 1000; // The setting is in ms
2020-04-18 11:37:07 +00:00
do {
$props["options"]["cost"]++;
$start_i = microtime(true);
password_hash("testing", $props["algorithm"], $props["options"]);
$end_i = microtime(true);
if($verbose) echo("Attempt | cost = {$props["options"]["cost"]}, time = " . ($end_i - $start_i)*1000 . "ms\n");
// Iterate until we find a cost high enough
// ....but don't keep going forever - try for at most 10x the target
// time in total (in case the specified algorithm doesn't take a
// cost parameter)
} while($end_i - $start_i < $target_cost_time);
2020-04-18 11:37:07 +00:00
return $props["options"]["cost"];
}