v1.4.0
This commit is contained in:
parent
8e9c6bc472
commit
467560d420
8 changed files with 1478 additions and 74 deletions
213
includes/admin/class-dashboard-page.php
Normal file
213
includes/admin/class-dashboard-page.php
Normal file
|
|
@ -0,0 +1,213 @@
|
|||
<?php
|
||||
/**
|
||||
* Admin dashboard for 2FA audit overview.
|
||||
*
|
||||
* @package Robotstxt_2FA
|
||||
*/
|
||||
|
||||
namespace Robotstxt\TwoFA\Admin;
|
||||
|
||||
use Robotstxt\TwoFA\Attempts_Log;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the top-level 2FA admin menu and audit dashboard page.
|
||||
*/
|
||||
class Dashboard_Page {
|
||||
/**
|
||||
* Slug for the dashboard admin page.
|
||||
*/
|
||||
public const PAGE_SLUG = 'robotstxt-2fa-dashboard';
|
||||
|
||||
/**
|
||||
* Failed attempts log.
|
||||
*
|
||||
* @var Attempts_Log
|
||||
*/
|
||||
private Attempts_Log $attempts_log;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param Attempts_Log $attempts_log Failed attempts log instance.
|
||||
*/
|
||||
public function __construct( Attempts_Log $attempts_log ) {
|
||||
$this->attempts_log = $attempts_log;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register WordPress hooks.
|
||||
*
|
||||
* @since 1.3.0
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register_hooks(): void {
|
||||
add_action( 'admin_menu', array( $this, 'register_menu' ) );
|
||||
add_filter( 'manage_users_columns', array( $this, 'add_users_column' ) );
|
||||
add_filter( 'manage_users_custom_column', array( $this, 'render_users_column' ), 10, 3 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the top-level and dashboard submenu pages.
|
||||
*
|
||||
* @since 1.3.0
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register_menu(): void {
|
||||
add_menu_page(
|
||||
__( '2FA (by ROBOTSTXT)', 'robotstxt-2fa' ),
|
||||
__( '2FA', 'robotstxt-2fa' ),
|
||||
'manage_options',
|
||||
self::PAGE_SLUG,
|
||||
array( $this, 'render_page' ),
|
||||
'dashicons-shield'
|
||||
);
|
||||
|
||||
add_submenu_page(
|
||||
self::PAGE_SLUG,
|
||||
__( 'Dashboard — 2FA', 'robotstxt-2fa' ),
|
||||
__( 'Dashboard', 'robotstxt-2fa' ),
|
||||
'manage_options',
|
||||
self::PAGE_SLUG,
|
||||
array( $this, 'render_page' )
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the audit dashboard page.
|
||||
*
|
||||
* @since 1.3.0
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function render_page(): void {
|
||||
if ( ! current_user_can( 'manage_options' ) ) {
|
||||
wp_die( esc_html__( 'Sorry, you are not allowed to access this page.', 'robotstxt-2fa' ) );
|
||||
}
|
||||
|
||||
$count_result = count_users();
|
||||
$total_users = $count_result['total_users'];
|
||||
$query_2fa = new \WP_User_Query(
|
||||
array(
|
||||
'meta_key' => 'robotstxt_2fa_user_settings',
|
||||
'meta_compare' => 'EXISTS',
|
||||
'fields' => 'ID',
|
||||
'number' => -1,
|
||||
)
|
||||
);
|
||||
$users_with_2fa = $query_2fa->get_total();
|
||||
|
||||
$log = get_option( 'robotstxt_2fa_failed_log', array() );
|
||||
$log = is_array( $log ) ? $log : array();
|
||||
$week_ago = time() - WEEK_IN_SECONDS;
|
||||
|
||||
$failed_7d = 0;
|
||||
|
||||
foreach ( $log as $entry ) {
|
||||
if ( is_array( $entry ) && isset( $entry['timestamp'] ) && is_numeric( $entry['timestamp'] ) && (int) $entry['timestamp'] >= $week_ago ) {
|
||||
++$failed_7d;
|
||||
}
|
||||
}
|
||||
|
||||
$recent_attempts = $this->attempts_log->get_recent( 20 );
|
||||
|
||||
$card_style = 'background:#fff;border:1px solid #dcdcde;padding:16px 20px;min-width:160px;text-align:center;';
|
||||
?>
|
||||
<div class="wrap">
|
||||
<h1><?php esc_html_e( 'Two-Factor Authentication Dashboard', 'robotstxt-2fa' ); ?></h1>
|
||||
|
||||
<div style="display:flex;gap:16px;flex-wrap:wrap;margin:1.5em 0;">
|
||||
<div style="<?php echo esc_attr( $card_style ); ?>">
|
||||
<div style="font-size:2em;font-weight:700;"><?php echo absint( $total_users ); ?></div>
|
||||
<div style="font-size:0.875em;color:#646970;"><?php esc_html_e( 'Total users', 'robotstxt-2fa' ); ?></div>
|
||||
</div>
|
||||
<div style="<?php echo esc_attr( $card_style ); ?>">
|
||||
<div style="font-size:2em;font-weight:700;"><?php echo absint( $users_with_2fa ); ?></div>
|
||||
<div style="font-size:0.875em;color:#646970;"><?php esc_html_e( '2FA enabled', 'robotstxt-2fa' ); ?></div>
|
||||
</div>
|
||||
<div style="<?php echo esc_attr( $card_style ); ?>">
|
||||
<div style="font-size:2em;font-weight:700;"><?php echo absint( $failed_7d ); ?></div>
|
||||
<div style="font-size:0.875em;color:#646970;"><?php esc_html_e( 'Failed attempts (7 days)', 'robotstxt-2fa' ); ?></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2><?php esc_html_e( 'Recent failed attempts', 'robotstxt-2fa' ); ?></h2>
|
||||
|
||||
<?php if ( empty( $recent_attempts ) ) : ?>
|
||||
<p><?php esc_html_e( 'No failed attempts recorded.', 'robotstxt-2fa' ); ?></p>
|
||||
<?php else : ?>
|
||||
<table class="widefat striped">
|
||||
<thead>
|
||||
<tr>
|
||||
<th><?php esc_html_e( 'Date/Time', 'robotstxt-2fa' ); ?></th>
|
||||
<th><?php esc_html_e( 'User', 'robotstxt-2fa' ); ?></th>
|
||||
<th><?php esc_html_e( 'Method', 'robotstxt-2fa' ); ?></th>
|
||||
<th><?php esc_html_e( 'IP', 'robotstxt-2fa' ); ?></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php foreach ( $recent_attempts as $attempt ) : ?>
|
||||
<tr>
|
||||
<td><?php echo esc_html( gmdate( 'Y-m-d H:i:s', $attempt['timestamp'] ) ); ?></td>
|
||||
<td><?php echo esc_html( $attempt['user_login'] ); ?></td>
|
||||
<td><?php echo esc_html( $attempt['method'] ); ?></td>
|
||||
<td><?php echo esc_html( $attempt['ip'] ); ?></td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
<?php endif; ?>
|
||||
|
||||
<p style="margin-top:1.5em;">
|
||||
<a href="<?php echo esc_url( admin_url( 'users.php' ) ); ?>"><?php esc_html_e( 'View all users →', 'robotstxt-2fa' ); ?></a>
|
||||
</p>
|
||||
</div>
|
||||
<?php
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a 2FA status column to the users list table.
|
||||
*
|
||||
* @since 1.3.0
|
||||
*
|
||||
* @param array<string, string> $columns Existing columns.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function add_users_column( array $columns ): array {
|
||||
$columns['robotstxt_2fa'] = __( '2FA', 'robotstxt-2fa' );
|
||||
|
||||
return $columns;
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the 2FA status cell in the users list table.
|
||||
*
|
||||
* @since 1.3.0
|
||||
*
|
||||
* @param mixed $output Cell output (typically empty string or existing content).
|
||||
* @param string $column_name Current column identifier.
|
||||
* @param int $user_id User ID for the current row.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function render_users_column( mixed $output, string $column_name, int $user_id ): string {
|
||||
if ( 'robotstxt_2fa' !== $column_name ) {
|
||||
return is_string( $output ) ? $output : '';
|
||||
}
|
||||
|
||||
$raw_settings = get_user_meta( $user_id, 'robotstxt_2fa_user_settings', true );
|
||||
$enabled = is_array( $raw_settings ) && ! empty( $raw_settings['enabled'] );
|
||||
|
||||
if ( $enabled ) {
|
||||
return '<span style="color:#00a32a;">●</span> ' . esc_html__( 'Active', 'robotstxt-2fa' );
|
||||
}
|
||||
|
||||
return '<span style="color:#999;">○</span> ' . esc_html__( 'Off', 'robotstxt-2fa' );
|
||||
}
|
||||
}
|
||||
|
|
@ -37,6 +37,11 @@ class Settings_Page {
|
|||
*/
|
||||
private const DOCS_PAGE_SLUG = 'robotstxt-2fa-docs';
|
||||
|
||||
/**
|
||||
* Dashboard page slug (single-site parent menu, owned by Dashboard_Page).
|
||||
*/
|
||||
private const DASHBOARD_PAGE_SLUG = 'robotstxt-2fa-dashboard';
|
||||
|
||||
/**
|
||||
* Verification methods available for per-role configuration.
|
||||
*
|
||||
|
|
@ -226,6 +231,76 @@ class Settings_Page {
|
|||
self::PAGE_SLUG,
|
||||
'robotstxt_2fa_data'
|
||||
);
|
||||
|
||||
add_settings_section(
|
||||
'robotstxt_2fa_access',
|
||||
__( 'Access control', 'robotstxt-2fa' ),
|
||||
array( $this, 'render_access_section' ),
|
||||
self::PAGE_SLUG
|
||||
);
|
||||
|
||||
add_settings_field(
|
||||
'robotstxt_2fa_app_passwords_exempt',
|
||||
__( 'Application Passwords', 'robotstxt-2fa' ),
|
||||
array( $this, 'render_app_passwords_exempt_field' ),
|
||||
self::PAGE_SLUG,
|
||||
'robotstxt_2fa_access'
|
||||
);
|
||||
|
||||
add_settings_field(
|
||||
'robotstxt_2fa_ip_allow',
|
||||
__( 'IP allow list', 'robotstxt-2fa' ),
|
||||
array( $this, 'render_ip_allow_field' ),
|
||||
self::PAGE_SLUG,
|
||||
'robotstxt_2fa_access'
|
||||
);
|
||||
|
||||
add_settings_field(
|
||||
'robotstxt_2fa_ip_deny',
|
||||
__( 'IP deny list', 'robotstxt-2fa' ),
|
||||
array( $this, 'render_ip_deny_field' ),
|
||||
self::PAGE_SLUG,
|
||||
'robotstxt_2fa_access'
|
||||
);
|
||||
|
||||
add_settings_section(
|
||||
'robotstxt_2fa_notifications',
|
||||
__( 'Email notifications', 'robotstxt-2fa' ),
|
||||
array( $this, 'render_notifications_section' ),
|
||||
self::PAGE_SLUG
|
||||
);
|
||||
|
||||
add_settings_field(
|
||||
'robotstxt_2fa_notif_on_enable',
|
||||
__( 'On method activation', 'robotstxt-2fa' ),
|
||||
array( $this, 'render_notif_on_enable_field' ),
|
||||
self::PAGE_SLUG,
|
||||
'robotstxt_2fa_notifications'
|
||||
);
|
||||
|
||||
add_settings_field(
|
||||
'robotstxt_2fa_notif_on_new_ip',
|
||||
__( 'New location', 'robotstxt-2fa' ),
|
||||
array( $this, 'render_notif_on_new_ip_field' ),
|
||||
self::PAGE_SLUG,
|
||||
'robotstxt_2fa_notifications'
|
||||
);
|
||||
|
||||
add_settings_field(
|
||||
'robotstxt_2fa_notif_on_recovery',
|
||||
__( 'Recovery code used', 'robotstxt-2fa' ),
|
||||
array( $this, 'render_notif_on_recovery_field' ),
|
||||
self::PAGE_SLUG,
|
||||
'robotstxt_2fa_notifications'
|
||||
);
|
||||
|
||||
add_settings_field(
|
||||
'robotstxt_2fa_notif_digest',
|
||||
__( 'Activity digest', 'robotstxt-2fa' ),
|
||||
array( $this, 'render_notif_digest_field' ),
|
||||
self::PAGE_SLUG,
|
||||
'robotstxt_2fa_notifications'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -429,7 +504,7 @@ class Settings_Page {
|
|||
*
|
||||
* @param mixed $raw_settings Raw settings submitted by the user.
|
||||
*
|
||||
* @return array{role_methods: array<string, array<int, string>>, frequency: string, force_frequency: bool, delete_on_uninstall: bool, max_attempts: int, lockout_duration: int, trust_device_days: int, grace_period_days: int, grace_period_action: string}
|
||||
* @return array{role_methods: array<string, array<int, string>>, frequency: string, force_frequency: bool, delete_on_uninstall: bool, max_attempts: int, lockout_duration: int, trust_device_days: int, grace_period_days: int, grace_period_action: string, app_passwords_exempt: bool, ip_allow: string, ip_deny: string, notifications: array{on_enable: bool, on_new_ip: bool, on_recovery_used: bool, on_recovery_used_admin: bool, digest_enabled: bool, digest_frequency: string}}
|
||||
*/
|
||||
public function sanitize_settings( $raw_settings ): array {
|
||||
$capability = $this->get_required_capability();
|
||||
|
|
@ -518,13 +593,36 @@ class Settings_Page {
|
|||
$sanitized['grace_period_action'] = $raw_settings['grace_period_action'];
|
||||
}
|
||||
|
||||
if ( array_key_exists( 'app_passwords_exempt', $raw_settings ) ) {
|
||||
$sanitized['app_passwords_exempt'] = '1' === ( is_scalar( $raw_settings['app_passwords_exempt'] ) ? (string) $raw_settings['app_passwords_exempt'] : '' );
|
||||
}
|
||||
|
||||
if ( isset( $raw_settings['ip_allow'] ) && is_string( $raw_settings['ip_allow'] ) ) {
|
||||
$sanitized['ip_allow'] = sanitize_textarea_field( $raw_settings['ip_allow'] );
|
||||
}
|
||||
|
||||
if ( isset( $raw_settings['ip_deny'] ) && is_string( $raw_settings['ip_deny'] ) ) {
|
||||
$sanitized['ip_deny'] = sanitize_textarea_field( $raw_settings['ip_deny'] );
|
||||
}
|
||||
|
||||
$raw_notif = isset( $raw_settings['notifications'] ) && is_array( $raw_settings['notifications'] ) ? $raw_settings['notifications'] : array();
|
||||
|
||||
$sanitized['notifications'] = array(
|
||||
'on_enable' => ! empty( $raw_notif['on_enable'] ),
|
||||
'on_new_ip' => ! empty( $raw_notif['on_new_ip'] ),
|
||||
'on_recovery_used' => ! empty( $raw_notif['on_recovery_used'] ),
|
||||
'on_recovery_used_admin' => ! empty( $raw_notif['on_recovery_used_admin'] ),
|
||||
'digest_enabled' => ! empty( $raw_notif['digest_enabled'] ),
|
||||
'digest_frequency' => isset( $raw_notif['digest_frequency'] ) && 'monthly' === $raw_notif['digest_frequency'] ? 'monthly' : 'weekly',
|
||||
);
|
||||
|
||||
return $sanitized;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve plugin settings, migrating from legacy format when necessary.
|
||||
*
|
||||
* @return array{role_methods: array<string, array<int, string>>, frequency: string, force_frequency: bool, delete_on_uninstall: bool, max_attempts: int, lockout_duration: int, trust_device_days: int, grace_period_days: int, grace_period_action: string}
|
||||
* @return array{role_methods: array<string, array<int, string>>, frequency: string, force_frequency: bool, delete_on_uninstall: bool, max_attempts: int, lockout_duration: int, trust_device_days: int, grace_period_days: int, grace_period_action: string, app_passwords_exempt: bool, ip_allow: string, ip_deny: string, notifications: array{on_enable: bool, on_new_ip: bool, on_recovery_used: bool, on_recovery_used_admin: bool, digest_enabled: bool, digest_frequency: string}}
|
||||
*/
|
||||
public function get_settings(): array {
|
||||
$options = array();
|
||||
|
|
@ -544,37 +642,61 @@ class Settings_Page {
|
|||
}
|
||||
}
|
||||
|
||||
$defaults = $this->get_default_settings();
|
||||
$defaults = $this->get_default_settings();
|
||||
$raw_notif = isset( $options['notifications'] ) && is_array( $options['notifications'] ) ? $options['notifications'] : array();
|
||||
$def_notif = $defaults['notifications'];
|
||||
|
||||
return array(
|
||||
'role_methods' => $this->resolve_role_methods( $options ),
|
||||
'frequency' => Frequency_Options::sanitize( isset( $options['frequency'] ) && is_string( $options['frequency'] ) ? $options['frequency'] : '' ),
|
||||
'force_frequency' => ! empty( $options['force_frequency'] ),
|
||||
'delete_on_uninstall' => ! empty( $options['delete_on_uninstall'] ),
|
||||
'max_attempts' => isset( $options['max_attempts'] ) && is_numeric( $options['max_attempts'] ) ? max( 0, absint( $options['max_attempts'] ) ) : $defaults['max_attempts'],
|
||||
'lockout_duration' => isset( $options['lockout_duration'] ) && is_numeric( $options['lockout_duration'] ) ? max( 1, absint( $options['lockout_duration'] ) ) : $defaults['lockout_duration'],
|
||||
'trust_device_days' => isset( $options['trust_device_days'] ) && is_numeric( $options['trust_device_days'] ) ? max( 0, absint( $options['trust_device_days'] ) ) : $defaults['trust_device_days'],
|
||||
'grace_period_days' => isset( $options['grace_period_days'] ) && is_numeric( $options['grace_period_days'] ) ? max( 0, absint( $options['grace_period_days'] ) ) : $defaults['grace_period_days'],
|
||||
'grace_period_action' => isset( $options['grace_period_action'] ) && in_array( $options['grace_period_action'], array( 'block', 'wizard' ), true ) ? $options['grace_period_action'] : $defaults['grace_period_action'],
|
||||
'role_methods' => $this->resolve_role_methods( $options ),
|
||||
'frequency' => Frequency_Options::sanitize( isset( $options['frequency'] ) && is_string( $options['frequency'] ) ? $options['frequency'] : '' ),
|
||||
'force_frequency' => ! empty( $options['force_frequency'] ),
|
||||
'delete_on_uninstall' => ! empty( $options['delete_on_uninstall'] ),
|
||||
'max_attempts' => isset( $options['max_attempts'] ) && is_numeric( $options['max_attempts'] ) ? max( 0, absint( $options['max_attempts'] ) ) : $defaults['max_attempts'],
|
||||
'lockout_duration' => isset( $options['lockout_duration'] ) && is_numeric( $options['lockout_duration'] ) ? max( 1, absint( $options['lockout_duration'] ) ) : $defaults['lockout_duration'],
|
||||
'trust_device_days' => isset( $options['trust_device_days'] ) && is_numeric( $options['trust_device_days'] ) ? max( 0, absint( $options['trust_device_days'] ) ) : $defaults['trust_device_days'],
|
||||
'grace_period_days' => isset( $options['grace_period_days'] ) && is_numeric( $options['grace_period_days'] ) ? max( 0, absint( $options['grace_period_days'] ) ) : $defaults['grace_period_days'],
|
||||
'grace_period_action' => isset( $options['grace_period_action'] ) && in_array( $options['grace_period_action'], array( 'block', 'wizard' ), true ) ? $options['grace_period_action'] : $defaults['grace_period_action'],
|
||||
'app_passwords_exempt' => isset( $options['app_passwords_exempt'] ) ? (bool) $options['app_passwords_exempt'] : $defaults['app_passwords_exempt'],
|
||||
'ip_allow' => isset( $options['ip_allow'] ) && is_string( $options['ip_allow'] ) ? $options['ip_allow'] : $defaults['ip_allow'],
|
||||
'ip_deny' => isset( $options['ip_deny'] ) && is_string( $options['ip_deny'] ) ? $options['ip_deny'] : $defaults['ip_deny'],
|
||||
'notifications' => array(
|
||||
'on_enable' => isset( $raw_notif['on_enable'] ) ? (bool) $raw_notif['on_enable'] : $def_notif['on_enable'],
|
||||
'on_new_ip' => isset( $raw_notif['on_new_ip'] ) ? (bool) $raw_notif['on_new_ip'] : $def_notif['on_new_ip'],
|
||||
'on_recovery_used' => isset( $raw_notif['on_recovery_used'] ) ? (bool) $raw_notif['on_recovery_used'] : $def_notif['on_recovery_used'],
|
||||
'on_recovery_used_admin' => isset( $raw_notif['on_recovery_used_admin'] ) ? (bool) $raw_notif['on_recovery_used_admin'] : $def_notif['on_recovery_used_admin'],
|
||||
'digest_enabled' => isset( $raw_notif['digest_enabled'] ) ? (bool) $raw_notif['digest_enabled'] : $def_notif['digest_enabled'],
|
||||
'digest_frequency' => isset( $raw_notif['digest_frequency'] ) && 'monthly' === $raw_notif['digest_frequency'] ? 'monthly' : $def_notif['digest_frequency'],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve default settings.
|
||||
*
|
||||
* @return array{role_methods: array<string, array<int, string>>, frequency: string, force_frequency: bool, delete_on_uninstall: bool, max_attempts: int, lockout_duration: int, trust_device_days: int, grace_period_days: int, grace_period_action: string}
|
||||
* @return array{role_methods: array<string, array<int, string>>, frequency: string, force_frequency: bool, delete_on_uninstall: bool, max_attempts: int, lockout_duration: int, trust_device_days: int, grace_period_days: int, grace_period_action: string, app_passwords_exempt: bool, ip_allow: string, ip_deny: string, notifications: array{on_enable: bool, on_new_ip: bool, on_recovery_used: bool, on_recovery_used_admin: bool, digest_enabled: bool, digest_frequency: string}}
|
||||
*/
|
||||
private function get_default_settings(): array {
|
||||
return array(
|
||||
'role_methods' => array(),
|
||||
'frequency' => Frequency_Options::FREQUENCY_SESSION,
|
||||
'force_frequency' => false,
|
||||
'delete_on_uninstall' => false,
|
||||
'max_attempts' => 3,
|
||||
'lockout_duration' => 15,
|
||||
'trust_device_days' => 30,
|
||||
'grace_period_days' => 7,
|
||||
'grace_period_action' => 'wizard',
|
||||
'role_methods' => array(),
|
||||
'frequency' => Frequency_Options::FREQUENCY_SESSION,
|
||||
'force_frequency' => false,
|
||||
'delete_on_uninstall' => false,
|
||||
'max_attempts' => 3,
|
||||
'lockout_duration' => 15,
|
||||
'trust_device_days' => 30,
|
||||
'grace_period_days' => 7,
|
||||
'grace_period_action' => 'wizard',
|
||||
'app_passwords_exempt' => true,
|
||||
'ip_allow' => '',
|
||||
'ip_deny' => '',
|
||||
'notifications' => array(
|
||||
'on_enable' => false,
|
||||
'on_new_ip' => false,
|
||||
'on_recovery_used' => false,
|
||||
'on_recovery_used_admin' => false,
|
||||
'digest_enabled' => false,
|
||||
'digest_frequency' => 'weekly',
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -906,42 +1028,233 @@ class Settings_Page {
|
|||
/**
|
||||
* Register the plugin admin page in the desired context.
|
||||
*
|
||||
* On the network dashboard the Settings_Page creates its own top-level menu.
|
||||
* On single-site installs the top-level menu is owned by Dashboard_Page; this
|
||||
* method only registers the Settings and Documentation submenus under it.
|
||||
*
|
||||
* @param bool $network Whether the menu is registered for the network dashboard.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function register_admin_page( bool $network ): void {
|
||||
unset( $network );
|
||||
|
||||
$capability = $this->get_required_capability();
|
||||
|
||||
add_menu_page(
|
||||
__( '2FA (by ROBOTSTXT)', 'robotstxt-2fa' ),
|
||||
__( '2FA', 'robotstxt-2fa' ),
|
||||
$capability,
|
||||
self::PAGE_SLUG,
|
||||
array( $this, 'render_page' ),
|
||||
'dashicons-shield'
|
||||
if ( $network ) {
|
||||
add_menu_page(
|
||||
__( '2FA (by ROBOTSTXT)', 'robotstxt-2fa' ),
|
||||
__( '2FA', 'robotstxt-2fa' ),
|
||||
$capability,
|
||||
self::PAGE_SLUG,
|
||||
array( $this, 'render_page' ),
|
||||
'dashicons-shield'
|
||||
);
|
||||
|
||||
// Rename the first auto-created submenu entry to "Settings".
|
||||
add_submenu_page(
|
||||
self::PAGE_SLUG,
|
||||
__( 'Settings — 2FA', 'robotstxt-2fa' ),
|
||||
__( 'Settings', 'robotstxt-2fa' ),
|
||||
$capability,
|
||||
self::PAGE_SLUG,
|
||||
array( $this, 'render_page' )
|
||||
);
|
||||
|
||||
add_submenu_page(
|
||||
self::PAGE_SLUG,
|
||||
__( 'Documentation — 2FA', 'robotstxt-2fa' ),
|
||||
__( 'Documentation', 'robotstxt-2fa' ),
|
||||
$capability,
|
||||
self::DOCS_PAGE_SLUG,
|
||||
array( $this, 'render_docs_page' )
|
||||
);
|
||||
} else {
|
||||
// Single-site: Dashboard_Page owns the top-level menu. Register submenus only.
|
||||
add_submenu_page(
|
||||
self::DASHBOARD_PAGE_SLUG,
|
||||
__( 'Settings — 2FA', 'robotstxt-2fa' ),
|
||||
__( 'Settings', 'robotstxt-2fa' ),
|
||||
$capability,
|
||||
self::PAGE_SLUG,
|
||||
array( $this, 'render_page' )
|
||||
);
|
||||
|
||||
add_submenu_page(
|
||||
self::DASHBOARD_PAGE_SLUG,
|
||||
__( 'Documentation — 2FA', 'robotstxt-2fa' ),
|
||||
__( 'Documentation', 'robotstxt-2fa' ),
|
||||
$capability,
|
||||
self::DOCS_PAGE_SLUG,
|
||||
array( $this, 'render_docs_page' )
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the Access control section description.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function render_access_section(): void {
|
||||
echo '<p>' . esc_html__( 'Application Passwords, IP allow lists and deny lists.', 'robotstxt-2fa' ) . '</p>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the Application Passwords exemption checkbox.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function render_app_passwords_exempt_field(): void {
|
||||
$settings = $this->get_settings();
|
||||
$is_checked = $settings['app_passwords_exempt'];
|
||||
|
||||
printf(
|
||||
'<input type="hidden" name="%1$s[app_passwords_exempt]" value="0" />',
|
||||
esc_attr( self::OPTION_NAME )
|
||||
);
|
||||
|
||||
// Rename the first auto-created submenu entry to "Settings".
|
||||
add_submenu_page(
|
||||
self::PAGE_SLUG,
|
||||
__( 'Settings — 2FA', 'robotstxt-2fa' ),
|
||||
__( 'Settings', 'robotstxt-2fa' ),
|
||||
$capability,
|
||||
self::PAGE_SLUG,
|
||||
array( $this, 'render_page' )
|
||||
printf(
|
||||
'<label><input type="checkbox" name="%1$s[app_passwords_exempt]" value="1" %2$s /> %3$s</label>',
|
||||
esc_attr( self::OPTION_NAME ),
|
||||
checked( $is_checked, true, false ),
|
||||
esc_html__( 'Exempt Application Password requests from the 2FA challenge', 'robotstxt-2fa' )
|
||||
);
|
||||
|
||||
add_submenu_page(
|
||||
self::PAGE_SLUG,
|
||||
__( 'Documentation — 2FA', 'robotstxt-2fa' ),
|
||||
__( 'Documentation', 'robotstxt-2fa' ),
|
||||
$capability,
|
||||
self::DOCS_PAGE_SLUG,
|
||||
array( $this, 'render_docs_page' )
|
||||
echo '<p class="description">' . esc_html__( 'Application Password requests cannot complete browser-based 2FA challenges. Enable to let REST API and WP-CLI clients using Application Passwords skip the verification step.', 'robotstxt-2fa' ) . '</p>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the IP allow list textarea field.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function render_ip_allow_field(): void {
|
||||
$settings = $this->get_settings();
|
||||
|
||||
printf(
|
||||
'<textarea name="%1$s[ip_allow]" rows="5" cols="40">%2$s</textarea>',
|
||||
esc_attr( self::OPTION_NAME ),
|
||||
esc_textarea( $settings['ip_allow'] )
|
||||
);
|
||||
|
||||
echo '<p class="description">' . esc_html__( 'One IP address or CIDR range per line (e.g. 192.168.1.0/24). Requests from these IPs skip the 2FA challenge.', 'robotstxt-2fa' ) . '</p>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the IP deny list textarea field.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function render_ip_deny_field(): void {
|
||||
$settings = $this->get_settings();
|
||||
|
||||
printf(
|
||||
'<textarea name="%1$s[ip_deny]" rows="5" cols="40">%2$s</textarea>',
|
||||
esc_attr( self::OPTION_NAME ),
|
||||
esc_textarea( $settings['ip_deny'] )
|
||||
);
|
||||
|
||||
echo '<p class="description">' . esc_html__( 'One IP address or CIDR range per line. Login is blocked outright for these IPs.', 'robotstxt-2fa' ) . '</p>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the Email notifications section description.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function render_notifications_section(): void {
|
||||
echo '<p>' . esc_html__( 'Automatic email alerts for security-relevant events.', 'robotstxt-2fa' ) . '</p>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the on-method-enable notification checkbox.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function render_notif_on_enable_field(): void {
|
||||
$settings = $this->get_settings();
|
||||
|
||||
printf(
|
||||
'<label><input type="checkbox" name="%1$s[notifications][on_enable]" value="1" %2$s /> %3$s</label>',
|
||||
esc_attr( self::OPTION_NAME ),
|
||||
checked( $settings['notifications']['on_enable'], true, false ),
|
||||
esc_html__( 'Notify the user when an administrator enables 2FA for their account.', 'robotstxt-2fa' )
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the new-IP notification checkbox.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function render_notif_on_new_ip_field(): void {
|
||||
$settings = $this->get_settings();
|
||||
|
||||
printf(
|
||||
'<label><input type="checkbox" name="%1$s[notifications][on_new_ip]" value="1" %2$s /> %3$s</label>',
|
||||
esc_attr( self::OPTION_NAME ),
|
||||
checked( $settings['notifications']['on_new_ip'], true, false ),
|
||||
esc_html__( 'Notify the user on login from an unrecognised browser or IP.', 'robotstxt-2fa' )
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the recovery-code-used notification checkboxes.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function render_notif_on_recovery_field(): void {
|
||||
$settings = $this->get_settings();
|
||||
|
||||
printf(
|
||||
'<label><input type="checkbox" name="%1$s[notifications][on_recovery_used]" value="1" %2$s /> %3$s</label>',
|
||||
esc_attr( self::OPTION_NAME ),
|
||||
checked( $settings['notifications']['on_recovery_used'], true, false ),
|
||||
esc_html__( 'Notify user when a recovery code is used.', 'robotstxt-2fa' )
|
||||
);
|
||||
|
||||
echo '<br />';
|
||||
|
||||
printf(
|
||||
'<label style="margin-top:6px;display:inline-block;"><input type="checkbox" name="%1$s[notifications][on_recovery_used_admin]" value="1" %2$s /> %3$s</label>',
|
||||
esc_attr( self::OPTION_NAME ),
|
||||
checked( $settings['notifications']['on_recovery_used_admin'], true, false ),
|
||||
esc_html__( 'Also notify site administrator.', 'robotstxt-2fa' )
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the activity digest checkbox and frequency radio buttons.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function render_notif_digest_field(): void {
|
||||
$settings = $this->get_settings();
|
||||
$frequency = $settings['notifications']['digest_frequency'];
|
||||
|
||||
printf(
|
||||
'<label><input type="checkbox" name="%1$s[notifications][digest_enabled]" value="1" %2$s /> %3$s</label>',
|
||||
esc_attr( self::OPTION_NAME ),
|
||||
checked( $settings['notifications']['digest_enabled'], true, false ),
|
||||
esc_html__( 'Send a periodic activity digest to site administrators.', 'robotstxt-2fa' )
|
||||
);
|
||||
|
||||
echo '<fieldset style="margin-top:8px;">';
|
||||
|
||||
printf(
|
||||
'<label><input type="radio" name="%1$s[notifications][digest_frequency]" value="weekly" %2$s /> %3$s</label><br />',
|
||||
esc_attr( self::OPTION_NAME ),
|
||||
checked( 'weekly', $frequency, false ),
|
||||
esc_html__( 'Weekly', 'robotstxt-2fa' )
|
||||
);
|
||||
|
||||
printf(
|
||||
'<label><input type="radio" name="%1$s[notifications][digest_frequency]" value="monthly" %2$s /> %3$s</label>',
|
||||
esc_attr( self::OPTION_NAME ),
|
||||
checked( 'monthly', $frequency, false ),
|
||||
esc_html__( 'Monthly (every 30 days)', 'robotstxt-2fa' )
|
||||
);
|
||||
|
||||
echo '</fieldset>';
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
127
includes/class-attempts-log.php
Normal file
127
includes/class-attempts-log.php
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
<?php
|
||||
/**
|
||||
* Failed 2FA attempts log.
|
||||
*
|
||||
* @package Robotstxt_2FA
|
||||
*/
|
||||
|
||||
namespace Robotstxt\TwoFA;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Maintains a ring-buffer of recent failed 2FA verification attempts.
|
||||
*/
|
||||
class Attempts_Log {
|
||||
/**
|
||||
* Option name for storing the failed attempts log.
|
||||
*/
|
||||
private const OPTION_NAME = 'robotstxt_2fa_failed_log';
|
||||
|
||||
/**
|
||||
* Maximum number of entries to retain in the log.
|
||||
*/
|
||||
private const MAX_ENTRIES = 100;
|
||||
|
||||
/**
|
||||
* Register WordPress hooks.
|
||||
*
|
||||
* @since 1.3.0
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register_hooks(): void {
|
||||
add_action( 'robotstxt_2fa_verification_failed', array( $this, 'append' ), 10, 2 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Append a failed attempt entry to the log.
|
||||
*
|
||||
* Called by the robotstxt_2fa_verification_failed action hook.
|
||||
*
|
||||
* @since 1.3.0
|
||||
*
|
||||
* @param \WP_User $user User who failed the challenge.
|
||||
* @param string $method Verification method that was attempted.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function append( \WP_User $user, string $method ): void {
|
||||
$raw_ip = '';
|
||||
|
||||
if ( isset( $_SERVER['REMOTE_ADDR'] ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized below.
|
||||
$raw_ip = is_string( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
|
||||
$raw_ip = sanitize_text_field( wp_unslash( $raw_ip ) );
|
||||
}
|
||||
|
||||
$entry = array(
|
||||
'user_id' => $user->ID,
|
||||
'user_login' => $user->user_login,
|
||||
'method' => sanitize_key( $method ),
|
||||
'ip' => wp_privacy_anonymize_ip( $raw_ip ),
|
||||
'timestamp' => time(),
|
||||
);
|
||||
|
||||
$log = get_option( self::OPTION_NAME, array() );
|
||||
|
||||
if ( ! is_array( $log ) ) {
|
||||
$log = array();
|
||||
}
|
||||
|
||||
array_unshift( $log, $entry );
|
||||
|
||||
if ( count( $log ) > self::MAX_ENTRIES ) {
|
||||
$log = array_slice( $log, 0, self::MAX_ENTRIES );
|
||||
}
|
||||
|
||||
update_option( self::OPTION_NAME, $log, false );
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the most recent failed attempt entries.
|
||||
*
|
||||
* @since 1.3.0
|
||||
*
|
||||
* @param int $limit Maximum number of entries to return.
|
||||
*
|
||||
* @return array<int, array{user_id: int, user_login: string, method: string, ip: string, timestamp: int}>
|
||||
*/
|
||||
public function get_recent( int $limit = 20 ): array {
|
||||
$log = get_option( self::OPTION_NAME, array() );
|
||||
|
||||
if ( ! is_array( $log ) ) {
|
||||
return array();
|
||||
}
|
||||
|
||||
$result = array();
|
||||
|
||||
foreach ( array_slice( $log, 0, max( 1, $limit ) ) as $entry ) {
|
||||
if ( ! is_array( $entry ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$result[] = array(
|
||||
'user_id' => isset( $entry['user_id'] ) && is_numeric( $entry['user_id'] ) ? (int) $entry['user_id'] : 0,
|
||||
'user_login' => isset( $entry['user_login'] ) && is_string( $entry['user_login'] ) ? $entry['user_login'] : '',
|
||||
'method' => isset( $entry['method'] ) && is_string( $entry['method'] ) ? $entry['method'] : '',
|
||||
'ip' => isset( $entry['ip'] ) && is_string( $entry['ip'] ) ? $entry['ip'] : '',
|
||||
'timestamp' => isset( $entry['timestamp'] ) && is_numeric( $entry['timestamp'] ) ? (int) $entry['timestamp'] : 0,
|
||||
);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the failed attempts log option.
|
||||
*
|
||||
* @since 1.3.0
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function delete(): void {
|
||||
delete_option( self::OPTION_NAME );
|
||||
}
|
||||
}
|
||||
416
includes/class-email-notifications.php
Normal file
416
includes/class-email-notifications.php
Normal file
|
|
@ -0,0 +1,416 @@
|
|||
<?php
|
||||
/**
|
||||
* Email notifications for security-relevant 2FA events.
|
||||
*
|
||||
* @package Robotstxt_2FA
|
||||
*/
|
||||
|
||||
namespace Robotstxt\TwoFA;
|
||||
|
||||
use Robotstxt\TwoFA\User\Two_Factor_Config;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends automatic email alerts for 2FA events and activity digests.
|
||||
*/
|
||||
class Email_Notifications {
|
||||
/**
|
||||
* Maximum number of known login contexts to retain per user.
|
||||
*/
|
||||
private const KNOWN_CONTEXTS_LIMIT = 50;
|
||||
|
||||
/**
|
||||
* User meta key storing known login contexts.
|
||||
*/
|
||||
private const KNOWN_CONTEXTS_META = 'robotstxt_2fa_known_contexts';
|
||||
|
||||
/**
|
||||
* Cron hook name for digest emails.
|
||||
*/
|
||||
private const DIGEST_CRON_HOOK = 'robotstxt_2fa_digest_cron';
|
||||
|
||||
/**
|
||||
* Global two-factor configuration.
|
||||
*
|
||||
* @var Two_Factor_Config
|
||||
*/
|
||||
private Two_Factor_Config $config;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param Two_Factor_Config $config Global two-factor configuration.
|
||||
*/
|
||||
public function __construct( Two_Factor_Config $config ) {
|
||||
$this->config = $config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register WordPress hooks.
|
||||
*
|
||||
* @since 1.3.0
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register_hooks(): void {
|
||||
add_action( 'robotstxt_2fa_method_enabled', array( $this, 'on_method_enabled' ), 10, 2 );
|
||||
add_action( 'robotstxt_2fa_verification_success', array( $this, 'on_verification_success' ), 10, 2 );
|
||||
add_action( self::DIGEST_CRON_HOOK, array( $this, 'send_digest' ) );
|
||||
add_filter( 'cron_schedules', array( $this, 'add_cron_schedules' ) );
|
||||
add_action( 'init', array( $this, 'maybe_schedule_digest' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a custom monthly cron schedule.
|
||||
*
|
||||
* @since 1.3.0
|
||||
*
|
||||
* @param array<string, array{interval: int, display: string}> $schedules Existing cron schedules.
|
||||
*
|
||||
* @return array<string, array{interval: int, display: string}>
|
||||
*/
|
||||
public function add_cron_schedules( array $schedules ): array {
|
||||
$schedules['robotstxt_2fa_monthly'] = array(
|
||||
'interval' => 2592000,
|
||||
'display' => __( 'Every 30 days', 'robotstxt-2fa' ),
|
||||
);
|
||||
|
||||
return $schedules;
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedule or unschedule the digest cron event based on settings.
|
||||
*
|
||||
* @since 1.3.0
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function maybe_schedule_digest(): void {
|
||||
$notifications = $this->config->get_notifications();
|
||||
$digest_enabled = $notifications['digest_enabled'];
|
||||
$digest_frequency = $notifications['digest_frequency'];
|
||||
$next_scheduled = wp_next_scheduled( self::DIGEST_CRON_HOOK );
|
||||
|
||||
if ( $digest_enabled ) {
|
||||
if ( false === $next_scheduled ) {
|
||||
$interval = 'monthly' === $digest_frequency ? 'robotstxt_2fa_monthly' : 'weekly';
|
||||
wp_schedule_event( time() + DAY_IN_SECONDS, $interval, self::DIGEST_CRON_HOOK );
|
||||
}
|
||||
} elseif ( false !== $next_scheduled ) {
|
||||
wp_clear_scheduled_hook( self::DIGEST_CRON_HOOK );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a notification when an administrator enables 2FA for a user.
|
||||
*
|
||||
* @since 1.3.0
|
||||
*
|
||||
* @param \WP_User $user User for whom 2FA was enabled.
|
||||
* @param string $method Verification method that was enabled.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function on_method_enabled( \WP_User $user, string $method ): void {
|
||||
unset( $method );
|
||||
|
||||
$notifications = $this->config->get_notifications();
|
||||
|
||||
if ( ! $notifications['on_enable'] ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Only notify when an admin enables it for someone else.
|
||||
if ( get_current_user_id() === $user->ID ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$site_name = get_bloginfo( 'name' );
|
||||
$profile_url = wp_login_url();
|
||||
|
||||
$subject = sprintf(
|
||||
/* translators: %s: site name. */
|
||||
__( '[%s] Two-factor authentication has been activated on your account', 'robotstxt-2fa' ),
|
||||
$site_name
|
||||
);
|
||||
|
||||
$message = sprintf(
|
||||
/* translators: 1: display name, 2: site name, 3: login URL. */
|
||||
__(
|
||||
'Hi %1$s,
|
||||
|
||||
An administrator has enabled two-factor authentication on your account at %2$s.
|
||||
|
||||
You can review and configure your two-factor preferences from your profile page:
|
||||
%3$s
|
||||
|
||||
If you did not expect this change, please contact the site administrator.
|
||||
|
||||
-- %2$s',
|
||||
'robotstxt-2fa'
|
||||
),
|
||||
$user->display_name,
|
||||
$site_name,
|
||||
$profile_url
|
||||
);
|
||||
|
||||
$this->send_mail( $user->user_email, $subject, $message );
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle post-verification notifications (new location or recovery code used).
|
||||
*
|
||||
* @since 1.3.0
|
||||
*
|
||||
* @param \WP_User $user Authenticated user.
|
||||
* @param string $method Verification method that succeeded.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function on_verification_success( \WP_User $user, string $method ): void {
|
||||
$notifications = $this->config->get_notifications();
|
||||
$context_key = $this->get_login_context_key();
|
||||
|
||||
// New location / IP check.
|
||||
if ( $notifications['on_new_ip'] ) {
|
||||
$known_raw = get_user_meta( $user->ID, self::KNOWN_CONTEXTS_META, true );
|
||||
$known = is_array( $known_raw ) ? $known_raw : array();
|
||||
|
||||
if ( ! in_array( $context_key, $known, true ) ) {
|
||||
$site_name = get_bloginfo( 'name' );
|
||||
|
||||
$raw_ip = '';
|
||||
|
||||
if ( isset( $_SERVER['REMOTE_ADDR'] ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized below.
|
||||
$raw_ip = is_string( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
|
||||
$raw_ip = sanitize_text_field( wp_unslash( $raw_ip ) );
|
||||
}
|
||||
|
||||
$anon_ip = wp_privacy_anonymize_ip( $raw_ip );
|
||||
|
||||
$subject = sprintf(
|
||||
/* translators: %s: site name. */
|
||||
__( '[%s] New login to your account', 'robotstxt-2fa' ),
|
||||
$site_name
|
||||
);
|
||||
|
||||
$message = sprintf(
|
||||
/* translators: 1: display name, 2: site name, 3: date/time, 4: anonymized IP. */
|
||||
__(
|
||||
'Hi %1$s,
|
||||
|
||||
A new login to your account at %2$s was detected from an unrecognised browser or location.
|
||||
|
||||
Date/time: %3$s
|
||||
IP address: %4$s
|
||||
|
||||
If this was you, no action is needed.
|
||||
If you do not recognise this login, please change your password and contact the site administrator immediately.
|
||||
|
||||
-- %2$s',
|
||||
'robotstxt-2fa'
|
||||
),
|
||||
$user->display_name,
|
||||
$site_name,
|
||||
gmdate( 'Y-m-d H:i:s T' ),
|
||||
$anon_ip
|
||||
);
|
||||
|
||||
$this->send_mail( $user->user_email, $subject, $message );
|
||||
|
||||
// Store new context.
|
||||
$known[] = $context_key;
|
||||
|
||||
if ( count( $known ) > self::KNOWN_CONTEXTS_LIMIT ) {
|
||||
$known = array_slice( $known, - self::KNOWN_CONTEXTS_LIMIT );
|
||||
}
|
||||
|
||||
update_user_meta( $user->ID, self::KNOWN_CONTEXTS_META, $known );
|
||||
}
|
||||
}
|
||||
|
||||
// Recovery code used.
|
||||
if ( 'recovery' === $method ) {
|
||||
$site_name = get_bloginfo( 'name' );
|
||||
|
||||
if ( $notifications['on_recovery_used'] ) {
|
||||
$subject = sprintf(
|
||||
/* translators: %s: site name. */
|
||||
__( '[%s] A recovery code was used to access your account', 'robotstxt-2fa' ),
|
||||
$site_name
|
||||
);
|
||||
|
||||
$message = sprintf(
|
||||
/* translators: 1: display name, 2: site name, 3: date/time. */
|
||||
__(
|
||||
'Hi %1$s,
|
||||
|
||||
One of your two-factor recovery codes was used to log in to %2$s.
|
||||
|
||||
Date/time: %3$s
|
||||
|
||||
If this was you, no action is needed. Recovery codes are single-use; the code has now been consumed.
|
||||
If you do not recognise this activity, please contact your site administrator immediately.
|
||||
|
||||
-- %2$s',
|
||||
'robotstxt-2fa'
|
||||
),
|
||||
$user->display_name,
|
||||
$site_name,
|
||||
gmdate( 'Y-m-d H:i:s T' )
|
||||
);
|
||||
|
||||
$this->send_mail( $user->user_email, $subject, $message );
|
||||
}
|
||||
|
||||
if ( $notifications['on_recovery_used_admin'] ) {
|
||||
$admin_email = get_option( 'admin_email' );
|
||||
|
||||
if ( is_string( $admin_email ) && '' !== $admin_email ) {
|
||||
$subject = sprintf(
|
||||
/* translators: %s: site name. */
|
||||
__( '[%s] A recovery code was used — administrator notice', 'robotstxt-2fa' ),
|
||||
$site_name
|
||||
);
|
||||
|
||||
$message = sprintf(
|
||||
/* translators: 1: user display name, 2: user login, 3: site name, 4: date/time. */
|
||||
__(
|
||||
'Administrator notice from %3$s:
|
||||
|
||||
User "%1$s" (%2$s) used a recovery code to log in.
|
||||
|
||||
Date/time: %4$s
|
||||
|
||||
Please verify this was an expected action.
|
||||
|
||||
-- %3$s',
|
||||
'robotstxt-2fa'
|
||||
),
|
||||
$user->display_name,
|
||||
$user->user_login,
|
||||
$site_name,
|
||||
gmdate( 'Y-m-d H:i:s T' )
|
||||
);
|
||||
|
||||
$this->send_mail( $admin_email, $subject, $message );
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send the periodic activity digest email to all administrators.
|
||||
*
|
||||
* @since 1.3.0
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function send_digest(): void {
|
||||
$site_name = get_bloginfo( 'name' );
|
||||
$count_result = count_users();
|
||||
$total_users = $count_result['total_users'];
|
||||
|
||||
$query_2fa = new \WP_User_Query(
|
||||
array(
|
||||
'meta_key' => 'robotstxt_2fa_user_settings',
|
||||
'meta_compare' => 'EXISTS',
|
||||
'fields' => 'ID',
|
||||
'number' => -1,
|
||||
)
|
||||
);
|
||||
$users_with_2fa = $query_2fa->get_total();
|
||||
|
||||
// Count failed attempts in the last 7 days.
|
||||
$log = get_option( 'robotstxt_2fa_failed_log', array() );
|
||||
$log = is_array( $log ) ? $log : array();
|
||||
$week_ago = time() - WEEK_IN_SECONDS;
|
||||
$recent_fails = 0;
|
||||
|
||||
foreach ( $log as $entry ) {
|
||||
if ( is_array( $entry ) && isset( $entry['timestamp'] ) && is_numeric( $entry['timestamp'] ) && (int) $entry['timestamp'] >= $week_ago ) {
|
||||
++$recent_fails;
|
||||
}
|
||||
}
|
||||
|
||||
$subject = sprintf(
|
||||
/* translators: %s: site name. */
|
||||
__( '2FA activity digest — %s', 'robotstxt-2fa' ),
|
||||
$site_name
|
||||
);
|
||||
|
||||
$message = sprintf(
|
||||
/* translators: 1: site name, 2: total users, 3: users with 2FA, 4: failed attempts last 7 days. */
|
||||
__(
|
||||
'Two-factor authentication activity digest for %1$s
|
||||
|
||||
Total registered users: %2$d
|
||||
Users with 2FA configured: %3$d
|
||||
Failed 2FA attempts (last 7 days): %4$d
|
||||
|
||||
-- %1$s',
|
||||
'robotstxt-2fa'
|
||||
),
|
||||
$site_name,
|
||||
$total_users,
|
||||
$users_with_2fa,
|
||||
$recent_fails
|
||||
);
|
||||
|
||||
$admins = get_users( array( 'capability' => 'manage_options' ) );
|
||||
|
||||
foreach ( $admins as $admin ) {
|
||||
$this->send_mail( $admin->user_email, $subject, $message );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a hashed context key representing the current login environment.
|
||||
*
|
||||
* @since 1.3.0
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function get_login_context_key(): string {
|
||||
$ip = '';
|
||||
|
||||
if ( isset( $_SERVER['REMOTE_ADDR'] ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized below.
|
||||
$raw_addr = is_string( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
|
||||
$ip = sanitize_text_field( wp_unslash( $raw_addr ) );
|
||||
$ip = wp_privacy_anonymize_ip( $ip );
|
||||
}
|
||||
|
||||
$user_agent = '';
|
||||
|
||||
if ( isset( $_SERVER['HTTP_USER_AGENT'] ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized below.
|
||||
$raw_ua = is_string( $_SERVER['HTTP_USER_AGENT'] ) ? $_SERVER['HTTP_USER_AGENT'] : '';
|
||||
$user_agent = sanitize_text_field( wp_unslash( $raw_ua ) );
|
||||
}
|
||||
|
||||
$user_agent = strtolower( substr( $user_agent, 0, 255 ) );
|
||||
|
||||
if ( '' === $ip && '' === $user_agent ) {
|
||||
return sha1( 'unknown' );
|
||||
}
|
||||
|
||||
return sha1( $ip . '|' . $user_agent );
|
||||
}
|
||||
|
||||
/**
|
||||
* Send an email with a plain-text content type.
|
||||
*
|
||||
* @since 1.3.0
|
||||
*
|
||||
* @param string $to Recipient email address.
|
||||
* @param string $subject Email subject.
|
||||
* @param string $message Email body.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function send_mail( string $to, string $subject, string $message ): void {
|
||||
wp_mail( $to, $subject, $message, array( 'Content-Type: text/plain; charset=UTF-8' ) );
|
||||
}
|
||||
}
|
||||
211
includes/class-ip-restrictions.php
Normal file
211
includes/class-ip-restrictions.php
Normal file
|
|
@ -0,0 +1,211 @@
|
|||
<?php
|
||||
/**
|
||||
* IP-based access restrictions.
|
||||
*
|
||||
* @package Robotstxt_2FA
|
||||
*/
|
||||
|
||||
namespace Robotstxt\TwoFA;
|
||||
|
||||
use Robotstxt\TwoFA\User\Two_Factor_Config;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles IP allow listing (skip challenge) and deny-listing (block login).
|
||||
*/
|
||||
class IP_Restrictions {
|
||||
/**
|
||||
* Global two-factor configuration.
|
||||
*
|
||||
* @var Two_Factor_Config
|
||||
*/
|
||||
private Two_Factor_Config $config;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param Two_Factor_Config $config Global two-factor configuration.
|
||||
*/
|
||||
public function __construct( Two_Factor_Config $config ) {
|
||||
$this->config = $config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register WordPress hooks.
|
||||
*
|
||||
* @since 1.3.0
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register_hooks(): void {
|
||||
add_filter( 'robotstxt_2fa_skip_challenge', array( $this, 'maybe_skip_for_allowed_ip' ), 5, 2 );
|
||||
add_filter( 'authenticate', array( $this, 'maybe_block_denied_ip' ), 1, 3 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true when the request IP is on the allow list.
|
||||
*
|
||||
* @since 1.3.0
|
||||
*
|
||||
* @param bool $skip Whether to skip the challenge.
|
||||
* @param \WP_User $user Authenticated user about to be challenged.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function maybe_skip_for_allowed_ip( bool $skip, \WP_User $user ): bool {
|
||||
unset( $user );
|
||||
|
||||
if ( $skip ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$allow_list = $this->config->get_ip_allow();
|
||||
|
||||
if ( '' === $allow_list ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$ip = $this->get_current_ip();
|
||||
|
||||
if ( '' === $ip ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->ip_in_list( $ip, $allow_list );
|
||||
}
|
||||
|
||||
/**
|
||||
* Block login when the request IP is on the deny list.
|
||||
*
|
||||
* @since 1.3.0
|
||||
*
|
||||
* @param mixed $user Previously authenticated user or error.
|
||||
* @param string $username Submitted username.
|
||||
* @param string $password Submitted password.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function maybe_block_denied_ip( mixed $user, string $username, string $password ): mixed {
|
||||
unset( $username, $password );
|
||||
|
||||
$deny_list = $this->config->get_ip_deny();
|
||||
|
||||
if ( '' === $deny_list ) {
|
||||
return $user;
|
||||
}
|
||||
|
||||
$ip = $this->get_current_ip();
|
||||
|
||||
if ( '' === $ip ) {
|
||||
return $user;
|
||||
}
|
||||
|
||||
if ( $this->ip_in_list( $ip, $deny_list ) ) {
|
||||
return new \WP_Error(
|
||||
'robotstxt_2fa_ip_blocked',
|
||||
__( 'Access denied. Your IP address is not allowed to log in.', 'robotstxt-2fa' )
|
||||
);
|
||||
}
|
||||
|
||||
return $user;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the client IP address from the server environment.
|
||||
*
|
||||
* @since 1.3.0
|
||||
*
|
||||
* @return string Empty string when not available.
|
||||
*/
|
||||
private function get_current_ip(): string {
|
||||
if ( ! isset( $_SERVER['REMOTE_ADDR'] ) ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$raw = is_string( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized below.
|
||||
|
||||
return sanitize_text_field( wp_unslash( $raw ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether an IP address matches any entry in a newline-separated list.
|
||||
*
|
||||
* @since 1.3.0
|
||||
*
|
||||
* @param string $ip IP address to check.
|
||||
* @param string $entries Newline-separated list of IPs or CIDR ranges.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function ip_in_list( string $ip, string $entries ): bool {
|
||||
$parts = preg_split( '/\r\n|\r|\n/', $entries );
|
||||
|
||||
if ( ! is_array( $parts ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ( $parts as $entry ) {
|
||||
$entry = trim( $entry );
|
||||
|
||||
if ( '' === $entry ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ( $this->ip_matches_cidr( $ip, $entry ) ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether an IP address matches a CIDR range or exact IP.
|
||||
*
|
||||
* Supports both IPv4 and IPv6 via inet_pton().
|
||||
*
|
||||
* @since 1.3.0
|
||||
*
|
||||
* @param string $ip IP address to test.
|
||||
* @param string $cidr CIDR range or exact IP to test against.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function ip_matches_cidr( string $ip, string $cidr ): bool {
|
||||
$cidr = trim( $cidr );
|
||||
|
||||
if ( ! str_contains( $cidr, '/' ) ) {
|
||||
return $ip === $cidr;
|
||||
}
|
||||
|
||||
$parts = explode( '/', $cidr, 2 );
|
||||
$subnet = trim( $parts[0] );
|
||||
$bits_str = trim( $parts[1] );
|
||||
$ip_bin = inet_pton( $ip );
|
||||
$subnet_bin = inet_pton( $subnet );
|
||||
|
||||
if ( false === $ip_bin || false === $subnet_bin || strlen( $ip_bin ) !== strlen( $subnet_bin ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$total_bits = strlen( $ip_bin ) * 8;
|
||||
$bits_int = max( 0, min( (int) $bits_str, $total_bits ) );
|
||||
$bytes = (int) floor( $bits_int / 8 );
|
||||
$rem = $bits_int % 8;
|
||||
|
||||
if ( $bytes > 0 && substr( $ip_bin, 0, $bytes ) !== substr( $subnet_bin, 0, $bytes ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( $rem > 0 ) {
|
||||
$mask = 0xFF & ( 0xFF << ( 8 - $rem ) );
|
||||
|
||||
return ( ord( substr( $ip_bin, $bytes, 1 ) ) & $mask ) === ( ord( substr( $subnet_bin, $bytes, 1 ) ) & $mask );
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
@ -7,6 +7,7 @@
|
|||
|
||||
namespace Robotstxt\TwoFA;
|
||||
|
||||
use Robotstxt\TwoFA\Admin\Dashboard_Page;
|
||||
use Robotstxt\TwoFA\Admin\Settings_Page;
|
||||
use Robotstxt\TwoFA\Cli\Cli_Command;
|
||||
use Robotstxt\TwoFA\Login\Login_Form_Manager;
|
||||
|
|
@ -15,6 +16,7 @@ use Robotstxt\TwoFA\User\Grace_Period;
|
|||
use Robotstxt\TwoFA\User\Profile_Settings;
|
||||
use Robotstxt\TwoFA\User\Recovery_Codes;
|
||||
use Robotstxt\TwoFA\User\Trusted_Devices;
|
||||
use Robotstxt\TwoFA\User\Two_Factor_Config;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
|
|
@ -80,6 +82,34 @@ class Plugin {
|
|||
*/
|
||||
private Grace_Period $grace_period;
|
||||
|
||||
/**
|
||||
* Failed attempts log.
|
||||
*
|
||||
* @var Attempts_Log
|
||||
*/
|
||||
private Attempts_Log $attempts_log;
|
||||
|
||||
/**
|
||||
* Email notifications handler.
|
||||
*
|
||||
* @var Email_Notifications
|
||||
*/
|
||||
private Email_Notifications $email_notifications;
|
||||
|
||||
/**
|
||||
* IP restrictions handler.
|
||||
*
|
||||
* @var IP_Restrictions
|
||||
*/
|
||||
private IP_Restrictions $ip_restrictions;
|
||||
|
||||
/**
|
||||
* Audit dashboard page.
|
||||
*
|
||||
* @var Dashboard_Page
|
||||
*/
|
||||
private Dashboard_Page $dashboard_page;
|
||||
|
||||
/**
|
||||
* Get singleton instance.
|
||||
*
|
||||
|
|
@ -97,13 +127,18 @@ class Plugin {
|
|||
* Constructor.
|
||||
*/
|
||||
public function __construct() {
|
||||
$this->login_manager = new Login_Form_Manager();
|
||||
$this->profile_settings = new Profile_Settings();
|
||||
$this->recovery_codes = new Recovery_Codes();
|
||||
$this->settings_page = new Settings_Page();
|
||||
$this->frontend_profile = new Frontend_Profile();
|
||||
$this->trusted_devices = new Trusted_Devices();
|
||||
$this->grace_period = new Grace_Period();
|
||||
$config = new Two_Factor_Config();
|
||||
$this->attempts_log = new Attempts_Log();
|
||||
$this->login_manager = new Login_Form_Manager();
|
||||
$this->profile_settings = new Profile_Settings();
|
||||
$this->recovery_codes = new Recovery_Codes();
|
||||
$this->settings_page = new Settings_Page();
|
||||
$this->frontend_profile = new Frontend_Profile();
|
||||
$this->trusted_devices = new Trusted_Devices();
|
||||
$this->grace_period = new Grace_Period();
|
||||
$this->email_notifications = new Email_Notifications( $config );
|
||||
$this->ip_restrictions = new IP_Restrictions( $config );
|
||||
$this->dashboard_page = new Dashboard_Page( $this->attempts_log );
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -113,6 +148,10 @@ class Plugin {
|
|||
*/
|
||||
public function init(): void {
|
||||
$this->maybe_load_textdomain();
|
||||
$this->attempts_log->register_hooks();
|
||||
$this->email_notifications->register_hooks();
|
||||
$this->ip_restrictions->register_hooks();
|
||||
$this->dashboard_page->register_hooks();
|
||||
$this->login_manager->register_hooks();
|
||||
$this->profile_settings->register_hooks();
|
||||
$this->recovery_codes->register_hooks();
|
||||
|
|
|
|||
|
|
@ -745,6 +745,11 @@ class Login_Form_Manager {
|
|||
return $user;
|
||||
}
|
||||
|
||||
// Application Passwords: skip challenge for requests authenticated via Application Passwords.
|
||||
if ( $this->config->is_app_passwords_exempt() && (bool) did_action( 'application_password_did_authenticate' ) ) {
|
||||
return $user;
|
||||
}
|
||||
|
||||
// Trusted devices: skip challenge when the browser carries a valid trust cookie.
|
||||
if ( $this->config->get_trust_device_days() > 0 && $this->trusted_devices->is_trusted( $user ) ) {
|
||||
return $user;
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ class Two_Factor_Config {
|
|||
/**
|
||||
* Retrieve global two-factor settings with multisite support.
|
||||
*
|
||||
* @return array{role_methods: array<string, array<int, string>>, frequency: string, force_frequency: bool, delete_on_uninstall: bool, max_attempts: int, lockout_duration: int, trust_device_days: int, grace_period_days: int, grace_period_action: string}
|
||||
* @return array{role_methods: array<string, array<int, string>>, frequency: string, force_frequency: bool, delete_on_uninstall: bool, max_attempts: int, lockout_duration: int, trust_device_days: int, grace_period_days: int, grace_period_action: string, app_passwords_exempt: bool, ip_allow: string, ip_deny: string, notifications: array{on_enable: bool, on_new_ip: bool, on_recovery_used: bool, on_recovery_used_admin: bool, digest_enabled: bool, digest_frequency: string}}
|
||||
*/
|
||||
public function get_settings(): array {
|
||||
$settings_page = new Settings_Page();
|
||||
|
|
@ -181,4 +181,48 @@ class Two_Factor_Config {
|
|||
public function get_grace_period_action(): string {
|
||||
return $this->get_settings()['grace_period_action'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether Application Password requests are exempt from the 2FA challenge.
|
||||
*
|
||||
* @since 1.3.0
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function is_app_passwords_exempt(): bool {
|
||||
return $this->get_settings()['app_passwords_exempt'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the IP allow list string (newline-separated IPs/CIDRs).
|
||||
*
|
||||
* @since 1.3.0
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function get_ip_allow(): string {
|
||||
return $this->get_settings()['ip_allow'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the IP deny list string (newline-separated IPs/CIDRs).
|
||||
*
|
||||
* @since 1.3.0
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function get_ip_deny(): string {
|
||||
return $this->get_settings()['ip_deny'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the email notifications configuration.
|
||||
*
|
||||
* @since 1.3.0
|
||||
*
|
||||
* @return array{on_enable: bool, on_new_ip: bool, on_recovery_used: bool, on_recovery_used_admin: bool, digest_enabled: bool, digest_frequency: string}
|
||||
*/
|
||||
public function get_notifications(): array {
|
||||
return $this->get_settings()['notifications'];
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue