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
72 changes: 62 additions & 10 deletions factor/email/email.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,12 @@
*/
// Ignore coding standards for login check, this page does not require login.
// @codingStandardsIgnoreStart
require_once(__DIR__ . '../../../../../../config.php');
require_once(__DIR__ . '/../../../../../config.php');
require_once($CFG->dirroot . '/user/lib.php');
$instanceid = required_param('instance', PARAM_INT);
$pass = optional_param('pass', '0', PARAM_INT);
$secret = optional_param('secret', 0, PARAM_INT);
// @codingStandardsIgnoreEnds
$secret = required_param('secret', PARAM_INT);
// @codingStandardsIgnoreEnd

$context = context_system::instance();
$PAGE->set_context($context);
Expand All @@ -41,18 +42,36 @@
$instance = $DB->get_record('tool_mfa', ['id' => $instanceid]);
$factor = \tool_mfa\plugininfo\factor::get_factor('email');

// Codes are only valid for the configured duration, matching the check made on the sign-in page.
$expired = empty($instance) || ((int)$instance->timecreated + (int)get_config('factor_email', 'duration')) <= time();

// Only a pending, unrevoked email code may be used on this page. The base email record has no secret,
// and records belonging to other factors (e.g. SMS codes) must never be accepted here.
$ispendingcode = !empty($instance) &&
$instance->factor === 'email' &&
empty($instance->revoked) &&
!empty($instance->secret);

// If pass is set, require login to force $SESSION and user, and pass for that session.
if (!empty($instance) && $pass != 0 && $secret != 0) {
require_login();
if ((int)$instance->userid !== (int)$USER->id) {
throw new moodle_exception('error:parameters', 'factor_email');
}
// Load the lock state from the DB, rather than relying on what is already in this session,
// so a fresh session cannot be used to get past the lockout.
$factor->load_locked_state();
if ($factor->get_state() === \tool_mfa\plugininfo\factor::STATE_LOCKED) {
// Redirect through to auth, this will bounce them to the next factor.
redirect(new moodle_url('/admin/tool/mfa/auth.php'));
}
// Only pending email codes may be used, and an expired code can no longer be used to pass;
// a new one must be requested from the sign-in page.
if (!$ispendingcode || $expired) {
throw new moodle_exception('error:parameters', 'factor_email');
}
// Check the code with the same measures on the page entry.
if ($instance->secret != $secret) {
if (!hash_equals((string)$instance->secret, (string)$secret)) {
\tool_mfa\manager::sleep_timer();
$factor->increment_lock_counter();
throw new moodle_exception('error:parameters', 'factor_email');
Expand All @@ -72,26 +91,59 @@
if ($form->is_cancelled()) {
redirect(new moodle_url('/'));
} else if ($fromform = $form->get_data()) {
if (empty($instance)) {
$validcode = false;
// Expired codes are rejected before an attempt is counted, as there is nothing left to guess.
if ($ispendingcode && !$expired) {
// This page is unauthenticated, so the six-digit code must not be open to unlimited guesses.
// Reserve an attempt against the user's email factor lock counter before comparing the code.
// This is the same counter the sign-in path uses, so guesses made here and on the login page
// share a single budget, and exhausting it here also locks the factor for sign-in.
// The increment is done atomically in SQL and checked afterwards, so concurrent requests
// cannot all slip in under the threshold.
$DB->execute(
"UPDATE {tool_mfa} SET lockcounter = lockcounter + 1 WHERE userid = ? AND factor = ? AND revoked = ?",
[$instance->userid, 'email', 0]
);
$attempts = (int)$DB->get_field_sql(
"SELECT MAX(lockcounter) FROM {tool_mfa} WHERE userid = ? AND factor = ?",
[$instance->userid, 'email']
);
$lockthreshold = (int)get_config('tool_mfa', 'lockout');
if ($lockthreshold <= 0) {
$lockthreshold = 10;
}

// Once the threshold is reached, refuse even a correct code; otherwise the brute force could continue.
// The factor is locked at this point, so the code can no longer be used to sign in either.
if ($attempts <= $lockthreshold && hash_equals((string)$instance->secret, (string)$secret)) {
$validcode = true;
}
}

$user = null;
if ($validcode) {
// Make sure the user still exists before changing anything, so the revocation is not left half done.
$user = $DB->get_record('user', ['id' => $instance->userid, 'deleted' => 0]);
}

if (empty($user)) {
$message = get_string('error:badcode', 'factor_email');
} else {
$user = $DB->get_record('user', ['id' => $instance->userid]);

// Stop attacker from using email factor at all, by revoking all email until admin fixes.
$DB->set_field('tool_mfa', 'revoked', 1, ['userid' => $user->id, 'factor' => 'email']);

// Remotely logout all sessions for user.
$manager = \core\session\manager::kill_user_sessions($instance->userid);
\core\session\manager::kill_user_sessions($instance->userid);

// Log event.
$ip = $instance->createdfromip;
$useragent = $instance->label;
$event = \factor_email\event\unauth_email::unauth_email_event($user, $ip, $useragent);
$event->trigger();

// Suspend user account.
// Suspend user account, using the core API so the expected events are triggered.
if (get_config('factor_email', 'suspend')) {
$DB->set_field('user', 'suspended', 1, ['id' => $userid]);
user_suspend_user($user->id);
}

$message = get_string('email:revokesuccess', 'factor_email', fullname($user));
Expand Down
6 changes: 3 additions & 3 deletions factor/email/renderer.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public function generate_email($instanceid) {
$messagestrings = ['secret' => $instance->secret, 'link' => $authurlstring];

$blockurl = new \moodle_url('/admin/tool/mfa/factor/email/email.php',
['instance' => $instanceid]);
['instance' => $instanceid, 'secret' => $instance->secret]);
$blockurlstring = \html_writer::link($blockurl, get_string('email:link', 'factor_email'));

$templateinfo = [
Expand All @@ -69,8 +69,8 @@ public function generate_email($instanceid) {
private function get_ip_location_origin_string(string $ipaddress): string {
try {
$geoinfo = iplookup_find_location($ipaddress);
$city = $geoinfo['city'] ?: '';
$country = $geoinfo['country'] ?: '';
$city = $geoinfo['city'] ?? '';
$country = $geoinfo['country'] ?? '';

// It's possible for errors to be returned, or the geo lookup to simply be empty.
// In these cases, we want to return the 'unknown' string.
Expand Down
28 changes: 28 additions & 0 deletions factor/email/tests/factor_test.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,4 +94,32 @@ public function test_generate_email_ip_address_location(string $ip) {
$containsunknown = strpos($email, get_string('email:geoinfo:unknown', 'factor_email')) != false;
$this->assertTrue($containslocation || $containsunknown);
}

/**
* The revoke link in the email must include the factor secret.
*/
public function test_generate_email_revoke_link_contains_secret() {
global $DB, $PAGE;

$user = $this->getDataGenerator()->create_user();
$secret = 456789;
$record = [
'userid' => $user->id,
'factor' => 'email',
'secret' => $secret,
'label' => 'Test browser',
'createdfromip' => '',
'timecreated' => time(),
'revoked' => 0,
];
$instanceid = $DB->insert_record('tool_mfa', $record, true);

$renderer = $PAGE->get_renderer('factor_email');
$email = $renderer->generate_email($instanceid);
$this->resetDebugging();

// The sign-in link also contains the secret, but has the additional pass parameter.
// This fragment uniquely identifies the revoke link.
$this->assertStringContainsString('instance=' . $instanceid . '&amp;secret=' . $secret, $email);
}
}
2 changes: 1 addition & 1 deletion factor/email/version.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@

defined('MOODLE_INTERNAL') || die();

$plugin->version = 2023082100; // The current plugin version (Date: YYYYMMDDXX).
$plugin->version = 2023082101; // The current plugin version (Date: YYYYMMDDXX).
$plugin->requires = 2017051500.00; // Support back to 3.3 - Totara 12. Patches required.
$plugin->component = 'factor_email';
$plugin->release = 'v0.1';
Expand Down
2 changes: 1 addition & 1 deletion reset_factor.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@

require_once(__DIR__ . '/../../../config.php');
require_once($CFG->libdir . '/adminlib.php');
admin_externalpage_setup('tool_mfa_resetfactor');
\core\setting\page\externalpage::setup($PAGE, 'tool_mfa_resetfactor');

$bulk = !empty($SESSION->bulk_users);

Expand Down
4 changes: 2 additions & 2 deletions version.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@

defined('MOODLE_INTERNAL') || die();

$plugin->version = 2023031601; // The current plugin version (Date: YYYYMMDDXX).
$plugin->release = 2023031601; // Same as version.
$plugin->version = 2023031602; // The current plugin version (Date: YYYYMMDDXX).
$plugin->release = 2023031602; // Same as version.
$plugin->requires = 2023051100.01; // Support from T18. Patches required.
$plugin->component = 'tool_mfa';
$plugin->maturity = MATURITY_STABLE;