Created
August 6, 2025 00:56
-
-
Save Benunc/659ee74456e9e2a67e69bcbba3d5537e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Immediately bans IPs that attempt to log in with specific forbidden usernames. | |
| * | |
| * This function hooks into the 'authenticate' filter to run before iThemes Security, | |
| * checks against a custom list of usernames, and uses the iThemes Security API | |
| * to execute the lockout. | |
| * | |
| * @param WP_User|WP_Error|null $user User object or error. | |
| * @param string $username The username being attempted. | |
| * @return WP_User|WP_Error|null | |
| */ | |
| function custom_instant_ban_usernames( $user, $username ) { | |
| // Define the list of usernames to ban instantly. | |
| $banned_usernames = array( 'root', 'cpanel', 'test', 'sysadmin' ); | |
| // Clean up the input username just in case. | |
| $trimmed_username = trim( $username ); | |
| // Check if the attempted username is in our forbidden list. | |
| if ( ! empty( $trimmed_username ) && in_array( strtolower( $trimmed_username ), $banned_usernames, true ) ) { | |
| // Get the iThemes Security global lockout object. | |
| global $itsec_lockout; | |
| // Ensure the lockout module is active and its classes are available. | |
| if ( isset( $itsec_lockout ) && class_exists( 'Host_Context' ) ) { | |
| // Create a context for the lockout, identifying the reason. | |
| $context = new Host_Context( 'brute_force_banned_user' ); | |
| $context->set_login_username( $trimmed_username ); | |
| // Trigger the immediate lockout for the host's IP address. | |
| $itsec_lockout->do_lockout( $context ); | |
| // Optional: Log the event for visibility in the plugin's logs. | |
| if ( class_exists( 'ITSEC_Log' ) && class_exists( 'ITSEC_Lib' ) ) { | |
| $details = ITSEC_Lib::get_login_details(); | |
| ITSEC_Log::add_notice( 'brute_force', "auto-ban-custom::username-{$trimmed_username}", compact( 'details' ) ); | |
| } | |
| } | |
| // Return a generic WordPress error to prevent the login from proceeding. | |
| // This simulates a standard failed login to the end-user. | |
| return new WP_Error( 'invalid_username', __( '<strong>Error</strong>: You've been blocked from logging in.' ) . ' <a href="' . wp_lostpassword_url() . '">' . __( 'Lost your password?' ) . '</a>' ); | |
| } | |
| // If it's not a banned username, return the original $user object to continue processing. | |
| return $user; | |
| } | |
| // Add the filter to run with a high priority (9), so it executes before most others. | |
| add_filter( 'authenticate', 'custom_instant_ban_usernames', 9, 2 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment