email_code_sender = new Email_Code_Sender(); $this->otp_manager = new OTP_Manager(); $this->recovery_codes = new Recovery_Codes(); $this->user_settings_repository = new User_Settings_Repository(); $this->config = new Two_Factor_Config(); } /** * Handle verification method switches requested on the login stage. * * @return void */ private function process_method_switch(): void { $method = $this->get_requested_method(); $login = $this->get_requested_login(); if ( '' === $login ) { return; } $user = get_user_by( 'login', $login ); if ( ! $user instanceof \WP_User ) { return; } $stage_token = $this->get_requested_stage_token(); if ( '' === $stage_token || ! $this->validate_stage_token( $user, $stage_token ) ) { return; } $available_methods = $this->get_enabled_verification_methods( $user ); if ( ! in_array( $method, $available_methods, true ) ) { return; } $redirect_args = array( self::QUERY_METHOD => $method, self::QUERY_NOTICE => null, self::QUERY_RESEND => null, self::QUERY_SWITCH => null, ); if ( 'email' === $method ) { if ( ! $this->email_code_sender->send_code( $user ) ) { $redirect_args[ self::QUERY_NOTICE ] = 'failed'; } else { $redirect_args[ self::QUERY_NOTICE ] = 'resent'; } } $redirect_url = $this->get_stage_url( $redirect_args ); wp_safe_redirect( $redirect_url ); exit; } /** * Register WordPress hooks. * * @return void */ public function register_hooks(): void { add_action( 'login_init', array( $this, 'maybe_process_stage_requests' ) ); add_action( 'login_form', array( $this, 'render_form_fields' ) ); add_action( 'login_head', array( $this, 'render_stage_styles' ) ); add_action( 'login_footer', array( $this, 'render_stage_scripts' ) ); add_filter( 'login_message', array( $this, 'filter_login_message' ) ); add_filter( 'authenticate', array( $this, 'maybe_complete_verification' ), 5, 3 ); add_filter( 'authenticate', array( $this, 'enforce_verification_challenge' ), 30, 3 ); } /** * Render custom fields on the login form. * * @return void */ public function render_form_fields(): void { if ( ! $this->is_verification_stage() ) { return; } $login = $this->get_requested_login(); $method = $this->get_requested_method(); $code_length = $this->get_method_code_length( $method ); $alternates = array(); if ( '' !== $login ) { $user = get_user_by( 'login', $login ); if ( $user instanceof WP_User ) { $alternates = $this->get_alternate_method_links( $user, $method ); } } if ( '' !== $login ) { printf( '', esc_attr( self::FIELD_LOGIN ), esc_attr( $login ) ); } printf( '', esc_attr( self::FIELD_METHOD ), esc_attr( $method ) ); printf( '', esc_attr( self::FIELD_STAGE ), esc_attr( self::STAGE_VERIFY ) ); $stage_token = $this->get_requested_stage_token(); if ( '' !== $stage_token ) { printf( '', esc_attr( self::FIELD_STAGE_TOKEN ), esc_attr( $stage_token ) ); } wp_nonce_field( self::LOGIN_NONCE_ACTION, self::LOGIN_NONCE_FIELD ); ?>

%s

', esc_html( $instruction ) ); } if ( ! empty( $alternates ) ) { $link_markup = array(); foreach ( $alternates as $alternate ) { $link_markup[] = sprintf( '%2$s', esc_url( $alternate['url'] ), esc_html( $alternate['label'] ) ); } if ( ! empty( $link_markup ) ) { printf( '

%1$s %2$s

', esc_html__( 'Prefer a different verification method?', 'robotstxt-2fa' ), wp_kses_post( implode( ' ', $link_markup ) ) ); } } $back_url = wp_login_url( $this->get_requested_redirect() ); ?> is_verification_stage() ) { return; } ?> is_verification_stage() ) { return $message; } $login = $this->get_requested_login(); $method = $this->get_requested_method(); if ( '' === $login ) { return $message; } $user = get_user_by( 'login', $login ); if ( ! $user instanceof WP_User ) { return $message; } $notice = $this->get_requested_notice(); if ( 'email' === $method ) { $challenge = $this->user_settings_repository->get_email_challenge( $user->ID ); if ( empty( $challenge['sent_at'] ) ) { return $message; } $message .= '

' . esc_html__( 'We sent a verification code to your email. Enter it below to continue.', 'robotstxt-2fa' ) . '

'; if ( 'resent' === $notice ) { $message .= '

' . esc_html__( 'We sent you a fresh verification code. Check your inbox.', 'robotstxt-2fa' ) . '

'; } elseif ( 'failed' === $notice ) { $message .= '

' . esc_html__( 'We could not send a new verification code. Please try again in a moment.', 'robotstxt-2fa' ) . '

'; } } elseif ( 'otp' === $method ) { $message .= '

' . esc_html__( 'Open your authenticator app and enter the code to continue.', 'robotstxt-2fa' ) . '

'; } elseif ( 'recovery' === $method ) { $message .= '

' . esc_html__( 'Enter one of your unused recovery codes to continue.', 'robotstxt-2fa' ) . '

'; } return $message; } /** * Output helper scripts used during the verification stage. * * @return void */ public function render_stage_scripts(): void { if ( ! $this->is_verification_stage() ) { return; } $login = $this->get_requested_login(); ?> is_verification_submission() ) { return $user; } unset( $password ); if ( ! isset( $_POST[ self::LOGIN_NONCE_FIELD ] ) ) { return new \WP_Error( 'robotstxt_2fa_missing_nonce', __( 'The verification form is missing a security token. Please try again.', 'robotstxt-2fa' ) ); } $nonce = sanitize_text_field( wp_unslash( $_POST[ self::LOGIN_NONCE_FIELD ] ) ); if ( ! wp_verify_nonce( $nonce, self::LOGIN_NONCE_ACTION ) ) { return new \WP_Error( 'robotstxt_2fa_invalid_nonce', __( 'The verification request expired. Please sign in again to request a new code.', 'robotstxt-2fa' ) ); } $login = $this->get_requested_login(); if ( '' === $login && '' !== $username ) { $login = sanitize_user( $username, true ); } if ( '' === $login ) { return new \WP_Error( 'robotstxt_2fa_unknown_user', __( 'We could not determine which account you are trying to access.', 'robotstxt-2fa' ) ); } $authenticated_user = get_user_by( 'login', $login ); if ( ! $authenticated_user instanceof \WP_User ) { return new \WP_Error( 'robotstxt_2fa_unknown_user', __( 'We could not load the account requesting verification.', 'robotstxt-2fa' ) ); } $stage_token = $this->get_requested_stage_token(); if ( '' === $stage_token || ! $this->validate_stage_token( $authenticated_user, $stage_token ) ) { return new \WP_Error( 'robotstxt_2fa_invalid_stage', __( 'Your verification session expired. Please sign in again.', 'robotstxt-2fa' ) ); } $method = $this->get_requested_method(); $allowed_methods = $this->get_enabled_verification_methods( $authenticated_user ); if ( ! in_array( $method, $allowed_methods, true ) ) { return new \WP_Error( 'robotstxt_2fa_method_unavailable', __( 'The selected verification method is not available right now.', 'robotstxt-2fa' ) ); } $token = ''; if ( isset( $_POST['robotstxt_2fa_token'] ) ) { $token = sanitize_text_field( wp_unslash( $_POST['robotstxt_2fa_token'] ) ); } if ( '' === $token ) { return new \WP_Error( 'robotstxt_2fa_missing_code', __( 'Enter the verification code to continue.', 'robotstxt-2fa' ) ); } $is_valid = false; switch ( $method ) { case 'email': $is_valid = $this->email_code_sender->verify_code( $authenticated_user, $token ); if ( $is_valid ) { $this->user_settings_repository->delete_email_challenge( $authenticated_user->ID ); } break; case 'recovery': $is_valid = $this->recovery_codes->consume_code( $authenticated_user, $token ); break; case 'otp': $is_valid = $this->otp_manager->verify_code( $authenticated_user, $token ); break; default: return new \WP_Error( 'robotstxt_2fa_method_unavailable', __( 'The selected verification method is not available right now.', 'robotstxt-2fa' ) ); } if ( ! $is_valid ) { return new \WP_Error( 'robotstxt_2fa_invalid_code', __( 'The verification code is incorrect or has expired.', 'robotstxt-2fa' ) ); } $this->user_settings_repository->record_last_verification( $authenticated_user->ID, $method, $this->get_login_context_key(), time() ); return $authenticated_user; } /** * Enforce the verification step for eligible users. * * @param \WP_User|\WP_Error|null $user Previously authenticated user or error. * @param string $username Submitted username. * @param string $password Submitted password. * * @return \WP_User|\WP_Error|null */ public function enforce_verification_challenge( $user, string $username, string $password ) { unset( $username, $password ); if ( $this->is_verification_stage() || $this->is_verification_submission() ) { return $user; } if ( ! $user instanceof \WP_User ) { return $user; } $method = $this->determine_required_verification_method( $user ); if ( '' === $method ) { return $user; } if ( 'email' === $method && ! $this->email_code_sender->send_code( $user ) ) { return new \WP_Error( 'robotstxt_2fa_email_failed', __( 'We could not send a verification code. Please contact the site administrator.', 'robotstxt-2fa' ) ); } $redirect_to = $this->get_requested_redirect(); $stage_token = wp_create_nonce( self::STAGE_TOKEN_ACTION . '|' . $user->ID ); $query_args = array( self::QUERY_STAGE => self::STAGE_VERIFY, self::QUERY_METHOD => $method, self::QUERY_LOGIN => sanitize_user( $user->user_login, true ), self::QUERY_STAGE_TOKEN => $stage_token, ); $login_url = wp_login_url( $redirect_to ); $login_url = add_query_arg( $query_args, $login_url ); wp_safe_redirect( $login_url ); exit; } /** * Process additional verification stage actions triggered from the login screen. * * @return void */ public function maybe_process_stage_requests(): void { if ( ! $this->is_verification_stage() ) { return; } if ( ! empty( $_GET[ self::QUERY_SWITCH ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Stage operations rely on dedicated nonce validation. $this->process_method_switch(); return; } if ( empty( $_GET[ self::QUERY_RESEND ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Action is protected by a dedicated nonce below. return; } $method = $this->get_requested_method(); if ( 'email' !== $method ) { return; } $login = $this->get_requested_login(); if ( '' === $login ) { return; } $user = get_user_by( 'login', $login ); if ( ! $user instanceof \WP_User ) { return; } $stage_token = $this->get_requested_stage_token(); if ( '' === $stage_token || ! $this->validate_stage_token( $user, $stage_token ) ) { return; } $result = $this->email_code_sender->send_code( $user ); $notice_value = $result ? 'resent' : 'failed'; $redirect_url = remove_query_arg( self::QUERY_RESEND, $this->get_stage_url( array( self::QUERY_NOTICE => $notice_value, ) ) ); wp_safe_redirect( $redirect_url ); exit; } /** * Retrieve the verification method requested by the current stage. * * @return string */ private function get_requested_method(): string { $method = ''; if ( isset( $_REQUEST[ self::FIELD_METHOD ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Stage verification relies on dedicated nonce checks. $method = sanitize_key( wp_unslash( $_REQUEST[ self::FIELD_METHOD ] ) ); } if ( '' === $method && isset( $_REQUEST[ self::QUERY_METHOD ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Value used only for display context. $method = sanitize_key( wp_unslash( $_REQUEST[ self::QUERY_METHOD ] ) ); } if ( '' === $method ) { $method = 'email'; } return $method; } /** * Determine the expected code length for a verification method. * * @param string $method Verification method identifier. * * @return int */ private function get_method_code_length( string $method ): int { switch ( $method ) { case 'otp': return max( 1, (int) $this->otp_manager->get_code_length() ); case 'recovery': return max( 1, (int) $this->recovery_codes->get_code_length() ); case 'email': default: return max( 1, (int) $this->email_code_sender->get_code_length() ); } } /** * Retrieve the verification methods that are active for the provided user. * * @param \WP_User $user User attempting to authenticate. * @param array|null $user_settings Optional preloaded settings. * * @return array */ private function get_enabled_verification_methods( \WP_User $user, ?array $user_settings = null ): array { if ( null === $user_settings ) { $user_settings = $this->user_settings_repository->get_user_settings( $user->ID ); } $is_forced = $this->config->is_two_factor_forced_for_user( $user ); $enabled = $is_forced ? true : ! empty( $user_settings['enabled'] ); if ( ! $enabled ) { return array(); } $methods = array(); if ( ! empty( $user_settings['methods'] ) && is_array( $user_settings['methods'] ) ) { $methods = $user_settings['methods']; } if ( $is_forced && empty( $methods ) ) { $methods = array( $this->config->get_default_method() ); } $normalized = array(); foreach ( $methods as $method_key ) { $normalized_method = $this->normalize_method_slug( (string) $method_key ); if ( '' === $normalized_method ) { continue; } $normalized[] = $normalized_method; } $normalized = array_values( array_unique( $normalized ) ); $available = array(); foreach ( $normalized as $method ) { if ( 'email' === $method ) { $email = sanitize_email( $user->user_email ); if ( '' !== $email ) { $available[] = 'email'; } } elseif ( 'otp' === $method ) { if ( '' !== $this->otp_manager->get_secret( $user->ID ) ) { $available[] = 'otp'; } } elseif ( 'recovery' === $method ) { if ( $this->recovery_codes->has_active_codes( $user->ID ) ) { $available[] = 'recovery'; } } } return $available; } /** * Decide which verification method should be enforced for the user. * * @param \WP_User $user User attempting to authenticate. * * @return string */ private function determine_required_verification_method( \WP_User $user ): string { $user_settings = $this->user_settings_repository->get_user_settings( $user->ID ); $methods = $this->get_enabled_verification_methods( $user, $user_settings ); if ( empty( $methods ) ) { return ''; } $frequency = $this->get_effective_frequency( $user, $user_settings ); if ( $this->has_recent_verification( $user, $methods, $frequency ) ) { return ''; } return $this->select_preferred_method( $methods ); } /** * Check whether any verification method was recently validated within the configured interval. * * @param \WP_User $user User attempting to authenticate. * @param array $methods Active verification methods. * @param string $frequency Selected frequency slug. * * @return bool */ private function has_recent_verification( \WP_User $user, array $methods, string $frequency ): bool { if ( empty( $methods ) ) { return false; } if ( Frequency_Options::FREQUENCY_SESSION === $frequency ) { return false; } $interval_seconds = Frequency_Options::get_interval_seconds( $frequency ); if ( $interval_seconds <= 0 ) { return false; } $context_key = $this->get_login_context_key(); foreach ( $methods as $method ) { $last_verified = $this->user_settings_repository->get_last_verification_timestamp( $user->ID, $method, $context_key ); if ( $last_verified > 0 && ( $last_verified + $interval_seconds ) > time() ) { return true; } } return false; } /** * Determine which method should be requested when a challenge is required. * * @param array $methods Active verification methods. * * @return string */ private function select_preferred_method( array $methods ): string { if ( empty( $methods ) ) { return ''; } $preferred = $this->normalize_method_slug( $this->config->get_default_method() ); $priority = array_values( array_filter( array_unique( array_merge( array( 'otp' ), array( $preferred ), array( 'email', 'recovery' ) ) ) ) ); foreach ( $priority as $method ) { if ( 'recovery' === $method && count( $methods ) > 1 ) { continue; } if ( in_array( $method, $methods, true ) ) { return $method; } } return (string) $methods[0]; } /** * Normalize stored method identifiers to the stage slugs used during verification. * * @param string $method Raw method identifier. * * @return string */ private function normalize_method_slug( string $method ): string { $method = sanitize_key( $method ); if ( '' === $method ) { return ''; } if ( 'recovery_codes' === $method || 'recovery' === $method ) { return 'recovery'; } if ( in_array( $method, array( 'email', 'otp' ), true ) ) { return $method; } return ''; } /** * Build the list of alternate verification method links for the login stage. * * @param \WP_User $user User attempting to authenticate. * @param string $current_method Active verification method slug. * * @return array> */ private function get_alternate_method_links( \WP_User $user, string $current_method ): array { $available_methods = $this->get_enabled_verification_methods( $user ); $available_methods = array_values( array_diff( $available_methods, array( $current_method ) ) ); if ( empty( $available_methods ) ) { return array(); } $labels = array( 'email' => __( 'Use an email code instead', 'robotstxt-2fa' ), 'otp' => __( 'Use your authenticator app instead', 'robotstxt-2fa' ), 'recovery' => __( 'Use a recovery code instead', 'robotstxt-2fa' ), ); $links = array(); foreach ( $available_methods as $method ) { if ( ! isset( $labels[ $method ] ) ) { continue; } $links[] = array( 'url' => $this->get_stage_url( array( self::QUERY_METHOD => $method, self::QUERY_NOTICE => null, self::QUERY_RESEND => null, self::QUERY_SWITCH => '1', ) ), 'label' => $labels[ $method ], ); } return $links; } /** * Determine whether the login request is currently displaying the verification stage. * * @return bool */ private function is_verification_stage(): bool { if ( isset( $_REQUEST[ self::FIELD_STAGE ] ) ) { $stage = sanitize_key( wp_unslash( $_REQUEST[ self::FIELD_STAGE ] ) ); if ( self::STAGE_VERIFY === $stage ) { return true; } } if ( isset( $_REQUEST[ self::QUERY_STAGE ] ) ) { $stage = sanitize_key( wp_unslash( $_REQUEST[ self::QUERY_STAGE ] ) ); if ( self::STAGE_VERIFY === $stage ) { return true; } } return false; } /** * Check whether the login POST submission belongs to the verification stage. * * @return bool */ private function is_verification_submission(): bool { if ( ! isset( $_POST[ self::FIELD_STAGE ] ) ) { return false; } $stage = sanitize_key( wp_unslash( $_POST[ self::FIELD_STAGE ] ) ); return self::STAGE_VERIFY === $stage; } /** * Retrieve the login identifier carried across requests. * * @return string */ private function get_requested_login(): string { $login = ''; if ( isset( $_REQUEST[ self::FIELD_LOGIN ] ) ) { $login = sanitize_user( wp_unslash( $_REQUEST[ self::FIELD_LOGIN ] ), true ); } if ( '' === $login && isset( $_REQUEST[ self::QUERY_LOGIN ] ) ) { $login = sanitize_user( wp_unslash( $_REQUEST[ self::QUERY_LOGIN ] ), true ); } return $login; } /** * Retrieve the stage nonce carried in the current request. * * @return string */ private function get_requested_stage_token(): string { $token = ''; if ( isset( $_REQUEST[ self::FIELD_STAGE_TOKEN ] ) ) { $token = sanitize_text_field( wp_unslash( $_REQUEST[ self::FIELD_STAGE_TOKEN ] ) ); } if ( '' === $token && isset( $_REQUEST[ self::QUERY_STAGE_TOKEN ] ) ) { $token = sanitize_text_field( wp_unslash( $_REQUEST[ self::QUERY_STAGE_TOKEN ] ) ); } return $token; } /** * Retrieve the notice slug carried in the current request. * * @return string */ private function get_requested_notice(): string { if ( ! isset( $_REQUEST[ self::QUERY_NOTICE ] ) ) { return ''; } return sanitize_key( wp_unslash( $_REQUEST[ self::QUERY_NOTICE ] ) ); } /** * Validate whether the provided stage token is valid for the given user. * * @param \WP_User $user Authenticated user. * @param string $stage_token Submitted stage token. * * @return bool */ private function validate_stage_token( \WP_User $user, string $stage_token ): bool { return (bool) wp_verify_nonce( $stage_token, self::STAGE_TOKEN_ACTION . '|' . $user->ID ); } /** * Retrieve the sanitized redirect_to parameter from the current request. * * @return string */ private function get_requested_redirect(): string { if ( ! isset( $_REQUEST['redirect_to'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Value is only echoed back. return ''; } return esc_url_raw( wp_unslash( $_REQUEST['redirect_to'] ) ); } /** * Build a URL pointing to the active verification stage. * * @param array $extra_args Optional additional query parameters to merge. * * @return string */ private function get_stage_url( array $extra_args = array() ): string { $redirect_to = $this->get_requested_redirect(); $login_url = wp_login_url( $redirect_to ); $args = array( self::QUERY_STAGE => self::STAGE_VERIFY, self::QUERY_METHOD => $this->get_requested_method(), ); $login = $this->get_requested_login(); if ( '' !== $login ) { $args[ self::QUERY_LOGIN ] = $login; } $stage_token = $this->get_requested_stage_token(); if ( '' !== $stage_token ) { $args[ self::QUERY_STAGE_TOKEN ] = $stage_token; } foreach ( $extra_args as $key => $value ) { if ( null === $value || '' === $key ) { $login_url = remove_query_arg( $key, $login_url ); continue; } $args[ $key ] = $value; } $args = array_filter( $args, static function ( $value ) { return null !== $value && '' !== $value; } ); return add_query_arg( $args, $login_url ); } /** * Determine the effective verification frequency for the current user. * * @param \WP_User $user Authenticated user object. * @param array $user_settings Stored per-user preferences. * * @return string */ private function get_effective_frequency( \WP_User $user, array $user_settings ): string { unset( $user ); if ( $this->config->is_frequency_forced() ) { return $this->config->get_frequency(); } if ( ! empty( $user_settings['frequency'] ) ) { return Frequency_Options::sanitize( (string) $user_settings['frequency'] ); } return $this->config->get_frequency(); } /** * Build a hashed context key representing the current login environment. * * @return string */ private function get_login_context_key(): string { $ip = ''; if ( isset( $_SERVER['REMOTE_ADDR'] ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized below. $ip = sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ); $ip = wp_privacy_anonymize_ip( $ip ); $ip = is_string( $ip ) ? $ip : ''; } $user_agent = ''; if ( isset( $_SERVER['HTTP_USER_AGENT'] ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized below. $user_agent = sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ); } $user_agent = strtolower( substr( $user_agent, 0, 255 ) ); if ( '' === $ip && '' === $user_agent ) { return sha1( 'unknown' ); } return sha1( $ip . '|' . $user_agent ); } }