ID ) ) {
return true;
}
$roles = (array) Softvolt_Ai_Bodyguard_Settings::get( 'twofa_roles', array( 'administrator' ) );
if ( ! array_intersect( $roles, (array) $user->roles ) ) {
return false;
}
$grace = (int) Softvolt_Ai_Bodyguard_Settings::get( 'twofa_grace_days', 7 );
$since = (int) Softvolt_Ai_Bodyguard_Settings::get( 'activated_at', 0 );
if ( $grace > 0 && $since && time() < $since + $grace * DAY_IN_SECONDS ) {
return false; // Still in the grace period: log in normally, nag on the dashboard.
}
return true;
}
/* ---------------------------- login flow ---------------------------- */
public static function intercept( $user_login, $user ) {
if ( self::$completing || ! self::required_for( $user ) ) {
return;
}
if ( self::trusted_device( $user ) ) {
return;
}
$methods = (array) Softvolt_Ai_Bodyguard_Settings::get( 'twofa_methods', array( 'totp', 'email' ) );
$method = self::method_for_user( $user->ID );
$setup = false;
if ( 'email' === $method && ! in_array( 'email', $methods, true ) ) {
$setup = true; // No app configured and email is not allowed: set the app up now.
}
$remember = ! empty( $_POST['rememberme'] ); // phpcs:ignore WordPress.Security.NonceVerification.Missing
$redirect = isset( $_REQUEST['redirect_to'] ) ? esc_url_raw( wp_unslash( $_REQUEST['redirect_to'] ) ) : admin_url(); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$token = wp_generate_password( 32, false, false );
$pending = '';
if ( $setup ) {
$pending = self::new_secret();
update_user_meta( $user->ID, self::META_PENDING, $pending );
} elseif ( 'email' === $method ) {
self::send_email_code( $user );
}
set_transient(
'svabg_2fa_' . $token,
array(
'user' => $user->ID,
'remember' => $remember,
'redirect' => $redirect,
'method' => $setup ? 'setup' : $method,
'tries' => 0,
),
10 * MINUTE_IN_SECONDS
);
wp_clear_auth_cookie();
wp_destroy_current_session();
Softvolt_Ai_Bodyguard_Logger::log( 'info', 'login_2fa', sprintf( /* translators: %s: user login */ __( 'Second factor requested for "%s".', 'ai-guardwall' ), $user_login ), array(), $user->ID );
self::render_form( $user, $token, $setup ? 'setup' : $method, '', $pending );
exit;
}
public static function handle_form() {
$token = isset( $_POST['svabg_2fa_token'] ) ? sanitize_key( wp_unslash( $_POST['svabg_2fa_token'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing
$code = isset( $_POST['svabg_2fa_code'] ) ? preg_replace( '/[^A-Za-z0-9]/', '', sanitize_text_field( wp_unslash( $_POST['svabg_2fa_code'] ) ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing
$data = '' !== $token ? get_transient( 'svabg_2fa_' . $token ) : false;
if ( ! is_array( $data ) || empty( $data['user'] ) ) {
wp_safe_redirect( add_query_arg( 'svabg_2fa', 'expired', wp_login_url() ) );
exit;
}
$user = get_userdata( (int) $data['user'] );
if ( ! $user ) {
delete_transient( 'svabg_2fa_' . $token );
wp_safe_redirect( wp_login_url() );
exit;
}
if ( isset( $_POST['svabg_2fa_resend'] ) && 'email' === $data['method'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
self::send_email_code( $user );
self::render_form( $user, $token, 'email', __( 'A new code was sent.', 'ai-guardwall' ) );
exit;
}
$ok = false;
if ( 'setup' === $data['method'] ) {
$pending = (string) get_user_meta( $user->ID, self::META_PENDING, true );
if ( '' !== $pending && self::verify_totp( $pending, $code, $user->ID ) ) {
update_user_meta( $user->ID, self::META_SECRET, $pending );
update_user_meta( $user->ID, self::META_ENABLED, 1 );
delete_user_meta( $user->ID, self::META_PENDING );
self::regenerate_backup_codes( $user->ID );
$ok = true;
}
} elseif ( 'totp' === $data['method'] ) {
$ok = self::verify_totp( (string) get_user_meta( $user->ID, self::META_SECRET, true ), $code, $user->ID ) || self::use_backup_code( $user->ID, $code );
} else {
$ok = self::verify_email_code( $user->ID, $code ) || self::use_backup_code( $user->ID, $code );
}
if ( ! $ok ) {
$data['tries']++;
if ( $data['tries'] >= 5 ) {
delete_transient( 'svabg_2fa_' . $token );
Softvolt_Ai_Bodyguard_Lockouts::block( Softvolt_Ai_Bodyguard_Helpers::client_ip(), 'login', __( 'Five wrong two-factor codes', 'ai-guardwall' ), (int) Softvolt_Ai_Bodyguard_Settings::get( 'login_lockout_minutes', 20 ) );
wp_safe_redirect( add_query_arg( 'svabg_2fa', 'locked', wp_login_url() ) );
exit;
}
set_transient( 'svabg_2fa_' . $token, $data, 10 * MINUTE_IN_SECONDS );
Softvolt_Ai_Bodyguard_Logger::log( 'notice', 'login_2fa', sprintf( /* translators: %s: user login */ __( 'Wrong second-factor code for "%s".', 'ai-guardwall' ), $user->user_login ), array(), $user->ID );
self::render_form( $user, $token, $data['method'], __( 'That code is not right. Try again.', 'ai-guardwall' ), 'setup' === $data['method'] ? (string) get_user_meta( $user->ID, self::META_PENDING, true ) : '' );
exit;
}
delete_transient( 'svabg_2fa_' . $token );
self::$completing = true;
wp_set_auth_cookie( $user->ID, ! empty( $data['remember'] ), is_ssl() );
if ( ! empty( $_POST['svabg_2fa_trust'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
self::trust_device( $user );
}
do_action( 'wp_login', $user->user_login, $user );
Softvolt_Ai_Bodyguard_Logger::log( 'info', 'login_2fa', sprintf( /* translators: %s: user login */ __( 'Second factor passed for "%s".', 'ai-guardwall' ), $user->user_login ), array(), $user->ID );
$redirect = ! empty( $data['redirect'] ) ? $data['redirect'] : admin_url();
$redirect = apply_filters( 'login_redirect', $redirect, $redirect, $user );
wp_safe_redirect( $redirect );
exit;
}
private static function render_form( $user, $token, $method, $error = '', $pending = '' ) {
$action = site_url( 'wp-login.php?action=svabg_2fa', 'login_post' );
$title = 'setup' === $method ? __( 'Set up two-factor authentication', 'ai-guardwall' ) : __( 'Two-factor authentication', 'ai-guardwall' );
nocache_headers();
status_header( 200 );
header( 'Content-Type: text/html; charset=utf-8' );
?>
>
ยท
body{margin:0;background:#f0f0f1;font:14px/1.6 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;color:#1d2327}
.svabg-2fa{max-width:360px;margin:8vh auto;padding:28px;background:#fff;border:1px solid #c3c4c7;box-shadow:0 1px 3px rgba(0,0,0,.04)}
.svabg-2fa h1{margin:0 0 6px;font-size:20px}.svabg-2fa p{margin:0 0 14px}
.svabg-2fa label{display:block;margin-bottom:6px;font-weight:600}
.svabg-2fa input[type=text]{width:100%;box-sizing:border-box;padding:10px;font-size:22px;letter-spacing:.2em;text-align:center;border:1px solid #8c8f94;border-radius:4px}
.svabg-2fa button{width:100%;padding:10px;border:0;border-radius:4px;background:#2271b1;color:#fff;font-size:15px;cursor:pointer}
.svabg-2fa button.secondary{margin-top:8px;background:#f6f7f7;color:#2271b1;border:1px solid #2271b1}
.svabg-2fa .error{padding:10px 12px;margin-bottom:14px;border-left:4px solid #d63638;background:#fcf0f1}
.svabg-2fa .notice{padding:10px 12px;margin-bottom:14px;border-left:4px solid #72aee6;background:#f0f6fc}
.svabg-2fa code{display:block;padding:10px;margin:8px 0;background:#f6f7f7;font-size:15px;letter-spacing:.08em;word-break:break-all;text-align:center}
.svabg-2fa .small{color:#646970;font-size:12px}.svabg-2fa .trust{display:flex;gap:8px;align-items:center;margin:12px 0;font-weight:400}
.svabg-brand{display:block;margin:0 0 18px;color:#646970;font-size:11px;font-weight:700;letter-spacing:.1em;text-transform:uppercase}
AI GuardWall
; ?>)
user_email ) ) ); ?>
ID . '|' . $expires . '|' . self::device_hash( $user, $expires );
setcookie( self::COOKIE, $value, $expires, COOKIEPATH ? COOKIEPATH : '/', COOKIE_DOMAIN, is_ssl(), true );
}
private static function trusted_device( $user ) {
if ( empty( $_COOKIE[ self::COOKIE ] ) ) {
return false;
}
$parts = explode( '|', sanitize_text_field( wp_unslash( $_COOKIE[ self::COOKIE ] ) ) );
if ( 3 !== count( $parts ) || (int) $parts[0] !== (int) $user->ID || (int) $parts[1] < time() ) {
return false;
}
return hash_equals( self::device_hash( $user, (int) $parts[1] ), $parts[2] );
}
private static function device_hash( $user, $expires ) {
return hash_hmac( 'sha256', $user->ID . '|' . $expires . '|' . substr( $user->user_pass, 8, 8 ), wp_salt( 'auth' ) );
}
/* ---------------------------- TOTP ---------------------------- */
public static function new_secret() {
return self::base32_encode( random_bytes( 20 ) );
}
public static function otpauth_uri( $user, $secret ) {
$issuer = rawurlencode( wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ) );
return 'otpauth://totp/' . $issuer . ':' . rawurlencode( $user->user_login ) . '?secret=' . $secret . '&issuer=' . $issuer . '&algorithm=SHA1&digits=6&period=30';
}
public static function totp( $secret, $slice ) {
$key = self::base32_decode( $secret );
$hash = hash_hmac( 'sha1', pack( 'N*', 0 ) . pack( 'N*', $slice ), $key, true );
$off = ord( $hash[19] ) & 0xF;
$code = ( ( ord( $hash[ $off ] ) & 0x7F ) << 24 ) | ( ( ord( $hash[ $off + 1 ] ) & 0xFF ) << 16 ) | ( ( ord( $hash[ $off + 2 ] ) & 0xFF ) << 8 ) | ( ord( $hash[ $off + 3 ] ) & 0xFF );
return str_pad( (string) ( $code % 1000000 ), 6, '0', STR_PAD_LEFT );
}
public static function verify_totp( $secret, $code, $user_id = 0 ) {
if ( '' === $secret || ! preg_match( '/^\d{6}$/', $code ) ) {
return false;
}
$slice = (int) floor( time() / 30 );
$last = $user_id ? (int) get_user_meta( $user_id, self::META_LAST, true ) : 0;
for ( $i = -1; $i <= 1; $i++ ) {
if ( $slice + $i <= $last ) {
continue; // A code may only be used once.
}
if ( hash_equals( self::totp( $secret, $slice + $i ), $code ) ) {
if ( $user_id ) {
update_user_meta( $user_id, self::META_LAST, $slice + $i );
}
return true;
}
}
return false;
}
public static function base32_encode( $bin ) {
$alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
$bits = '';
foreach ( str_split( $bin ) as $c ) {
$bits .= str_pad( decbin( ord( $c ) ), 8, '0', STR_PAD_LEFT );
}
$out = '';
foreach ( str_split( $bits, 5 ) as $chunk ) {
$out .= $alphabet[ bindec( str_pad( $chunk, 5, '0', STR_PAD_RIGHT ) ) ];
}
return $out;
}
public static function base32_decode( $b32 ) {
$alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
$b32 = strtoupper( preg_replace( '/[^A-Z2-7]/i', '', $b32 ) );
$bits = '';
for ( $i = 0, $n = strlen( $b32 ); $i < $n; $i++ ) {
$pos = strpos( $alphabet, $b32[ $i ] );
if ( false === $pos ) {
continue;
}
$bits .= str_pad( decbin( $pos ), 5, '0', STR_PAD_LEFT );
}
$out = '';
foreach ( str_split( $bits, 8 ) as $chunk ) {
if ( 8 === strlen( $chunk ) ) {
$out .= chr( bindec( $chunk ) );
}
}
return $out;
}
/* ---------------------------- email codes ---------------------------- */
public static function send_email_code( $user ) {
$code = str_pad( (string) wp_rand( 0, 999999 ), 6, '0', STR_PAD_LEFT );
update_user_meta( $user->ID, self::META_EMAIL, array( 'hash' => hash_hmac( 'sha256', $code, wp_salt( 'auth' ) ), 'expires' => time() + 10 * MINUTE_IN_SECONDS ) );
$site = wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES );
wp_mail(
$user->user_email,
sprintf( /* translators: %s: site */ __( '[%s] Your login code', 'ai-guardwall' ), $site ),
sprintf( __( "Your login code for %1\$s is:\n\n%2\$s\n\nIt is valid for 10 minutes. If you did not try to log in, change your password now.", 'ai-guardwall' ), $site, $code )
);
}
private static function verify_email_code( $user_id, $code ) {
$data = get_user_meta( $user_id, self::META_EMAIL, true );
if ( ! is_array( $data ) || empty( $data['hash'] ) || (int) $data['expires'] < time() || ! preg_match( '/^\d{6}$/', $code ) ) {
return false;
}
if ( hash_equals( $data['hash'], hash_hmac( 'sha256', $code, wp_salt( 'auth' ) ) ) ) {
delete_user_meta( $user_id, self::META_EMAIL );
return true;
}
return false;
}
/* ---------------------------- backup codes ---------------------------- */
public static function regenerate_backup_codes( $user_id ) {
$plain = array();
$hashed = array();
for ( $i = 0; $i < 8; $i++ ) {
$code = strtolower( wp_generate_password( 10, false, false ) );
$plain[] = $code;
$hashed[] = wp_hash_password( $code );
}
update_user_meta( $user_id, self::META_BACKUP, $hashed );
set_transient( 'svabg_backup_show_' . $user_id, $plain, 10 * MINUTE_IN_SECONDS );
return $plain;
}
private static function use_backup_code( $user_id, $code ) {
$code = strtolower( $code );
$hashed = get_user_meta( $user_id, self::META_BACKUP, true );
if ( ! is_array( $hashed ) || strlen( $code ) < 8 ) {
return false;
}
foreach ( $hashed as $i => $hash ) {
if ( wp_check_password( $code, $hash ) ) {
unset( $hashed[ $i ] );
update_user_meta( $user_id, self::META_BACKUP, array_values( $hashed ) );
Softvolt_Ai_Bodyguard_Logger::log( 'notice', 'login_2fa', __( 'A backup code was used.', 'ai-guardwall' ), array(), $user_id );
return true;
}
}
return false;
}
private static function mask_email( $email ) {
$parts = explode( '@', (string) $email );
if ( 2 !== count( $parts ) ) {
return $email;
}
return substr( $parts[0], 0, 2 ) . str_repeat( '*', max( 1, strlen( $parts[0] ) - 2 ) ) . '@' . $parts[1];
}
/* ---------------------------- profile ---------------------------- */
public static function profile_fields( $user ) {
if ( ! Softvolt_Ai_Bodyguard_Settings::hardening_enabled( 'two_factor' ) && ! self::enabled_for_user( $user->ID ) ) {
return;
}
$own = get_current_user_id() === (int) $user->ID;
$enabled = self::enabled_for_user( $user->ID );
$pending = (string) get_user_meta( $user->ID, self::META_PENDING, true );
if ( $own && ! $enabled && '' === $pending ) {
$pending = self::new_secret();
update_user_meta( $user->ID, self::META_PENDING, $pending );
}
$show = get_transient( 'svabg_backup_show_' . $user->ID );
wp_nonce_field( 'svabg_2fa_profile', 'svabg_2fa_nonce' );
?>
add( 'svabg_2fa', __( 'The two-factor code was wrong; the authenticator app was not enabled. Check the time on your phone and try again.', 'ai-guardwall' ) );
} );
}
}
}
}
}