$now ) {
self::save( $map );
return;
}
$settings = Settings::all();
$window = max( 1, (int) $settings['lockout_window_minutes'] ) * MINUTE_IN_SECONDS;
$max = max( 2, (int) $settings['lockout_max_attempts'] );
$cutoff = $now - $window;
$attempts = isset( $row['attempts'] ) && is_array( $row['attempts'] ) ? $row['attempts'] : array();
$fresh = array();
foreach ( $attempts as $stamp ) {
$stamp = (int) $stamp;
if ( $stamp >= $cutoff ) {
$fresh[] = $stamp;
}
}
$fresh[] = $now;
$row['attempts'] = array_slice( $fresh, -50 );
if ( count( $row['attempts'] ) < $max ) {
$map[ $ip ] = $row;
self::save( $map );
return;
}
$repeat_window = max( 1, (int) $settings['lockout_repeat_window_hours'] ) * HOUR_IN_SECONDS;
$last_block = isset( $row['last_block_at'] ) ? (int) $row['last_block_at'] : 0;
$is_repeat = $last_block > 0 && ( $now - $last_block ) <= $repeat_window;
if ( $is_repeat ) {
$seconds = max( 1, (int) $settings['lockout_repeat_duration_days'] ) * DAY_IN_SECONDS;
$level = 'repeat';
} else {
$seconds = max( 1, (int) $settings['lockout_duration_minutes'] ) * MINUTE_IN_SECONDS;
$level = 'first';
}
$row['attempts'] = array();
$row['blocked_until'] = $now + $seconds;
$row['last_block_at'] = $now;
$row['level'] = $level;
$map[ $ip ] = $row;
self::save( $map );
self::log_lock( $ip, $username, $level, $seconds, $max, $settings );
}
/**
* Notice above the login form when this visitor is locked.
*
* @param string $message Existing message HTML.
* @return string
*/
public static function login_notice( $message ) {
if ( ! self::enabled() ) {
return $message;
}
$until = self::blocked_until( self::client_ip() );
if ( $until <= time() ) {
return $message;
}
$minutes = max( 1, (int) ceil( ( $until - time() ) / MINUTE_IN_SECONDS ) );
$notice = '
' . esc_html(
sprintf(
/* translators: %d: minutes remaining. */
_n(
'Logins from your network are temporarily blocked. Try again in %d minute.',
'Logins from your network are temporarily blocked. Try again in %d minutes.',
$minutes,
'admintrace-activity-logger'
),
$minutes
)
) . '
';
return $notice . $message;
}
/**
* How many IPs are currently blocked.
*
* @return int
*/
public static function active_count() {
return count( self::active_list() );
}
/**
* Active lockouts for the security screen.
*
* @return array
*/
public static function active_list() {
$now = time();
$list = array();
foreach ( self::load() as $ip => $row ) {
if ( ! is_array( $row ) || empty( $row['blocked_until'] ) || (int) $row['blocked_until'] <= $now ) {
continue;
}
$attempts = isset( $row['attempts'] ) && is_array( $row['attempts'] ) ? count( $row['attempts'] ) : 0;
$list[] = array(
'ip' => (string) $ip,
'ip_masked' => Ip::mask( $ip ),
'blocked_until' => (int) $row['blocked_until'],
'last_block_at' => isset( $row['last_block_at'] ) ? (int) $row['last_block_at'] : 0,
'level' => isset( $row['level'] ) ? (string) $row['level'] : '',
'attempts' => $attempts,
);
}
usort(
$list,
static function ( $a, $b ) {
return (int) $b['blocked_until'] <=> (int) $a['blocked_until'];
}
);
return $list;
}
/**
* Remove the lockout for one IP.
*
* @param string $ip Client IP.
* @return bool True when a row was removed.
*/
public static function unblock( $ip ) {
$ip = Ip::valid( $ip );
if ( '' === $ip ) {
return false;
}
$map = self::load();
if ( ! isset( $map[ $ip ] ) ) {
return false;
}
unset( $map[ $ip ] );
if ( $map ) {
update_option( self::OPTION, $map, false );
} else {
delete_option( self::OPTION );
}
return true;
}
/**
* Remove every stored lockout and attempt window.
*/
public static function clear_all() {
delete_option( self::OPTION );
}
/**
* Unix time until which the IP is blocked, or 0.
*
* @param string $ip Client IP.
* @return int
*/
private static function blocked_until( $ip ) {
if ( '' === $ip ) {
return 0;
}
$map = self::load();
if ( empty( $map[ $ip ] ) || ! is_array( $map[ $ip ] ) ) {
return 0;
}
$until = isset( $map[ $ip ]['blocked_until'] ) ? (int) $map[ $ip ]['blocked_until'] : 0;
if ( $until <= time() ) {
return 0;
}
return $until;
}
/**
* Whether the failure is a wrong password or unknown account.
*
* @param mixed $error Auth error.
* @return bool
*/
private static function is_password_or_unknown_failure( $error ) {
if ( ! $error instanceof \WP_Error ) {
return true;
}
$codes = $error->get_error_codes();
if ( in_array( 'srah_recaptcha', $codes, true ) || in_array( 'srah_ip_locked', $codes, true ) ) {
return false;
}
foreach ( array( 'incorrect_password', 'invalid_username', 'invalid_email' ) as $code ) {
if ( in_array( $code, $codes, true ) ) {
return true;
}
}
// Some plugins only pass a generic error; still count toward lockout.
return ! empty( $codes );
}
/**
* Client IP using the trusted-proxy setting.
*
* @return string
*/
private static function client_ip() {
$trust = ! empty( Settings::all()['trust_proxy'] );
return Ip::raw_from_request( $_SERVER, $trust );
}
/**
* Write a journal row for a new lockout.
*
* @param string $ip Client IP.
* @param string $username Attempted username.
* @param string $level first|repeat.
* @param int $seconds Lock duration.
* @param int $max Attempt threshold.
* @param array $settings Plugin settings.
*/
private static function log_lock( $ip, $username, $level, $seconds, $max, array $settings ) {
$masked = Ip::mask( $ip );
$username = Text::plain( $username, 60 );
$window = max( 1, (int) $settings['lockout_window_minutes'] );
if ( 'repeat' === $level ) {
$days = max( 1, (int) round( $seconds / DAY_IN_SECONDS ) );
$summary = sprintf(
/* translators: 1: masked IP, 2: number of days, 3: attempt count, 4: minutes. */
__( 'Blocked network %1$s for %2$d day(s) after another %3$d failed logins within %4$d minutes.', 'admintrace-activity-logger' ),
$masked ? $masked : __( '(unknown)', 'admintrace-activity-logger' ),
$days,
$max,
$window
);
} else {
$minutes = max( 1, (int) round( $seconds / MINUTE_IN_SECONDS ) );
$summary = sprintf(
/* translators: 1: masked IP, 2: minutes locked, 3: attempt count, 4: window minutes. */
__( 'Blocked network %1$s for %2$d minute(s) after %3$d failed logins within %4$d minutes.', 'admintrace-activity-logger' ),
$masked ? $masked : __( '(unknown)', 'admintrace-activity-logger' ),
$minutes,
$max,
$window
);
}
Recorder::log(
array(
'summary' => $summary,
'category' => 'security',
'action' => 'security.ip_locked',
'severity' => 'repeat' === $level ? 'critical' : 'warning',
'user_id' => 0,
'user_login' => $username,
'initiator' => 'system',
'logger' => 'user',
'ip_masked' => $masked,
'context' => array(
'level' => $level,
'duration_secs' => (int) $seconds,
'max_attempts' => (int) $max,
'window_minutes' => $window,
),
)
);
}
/**
* @return array{attempts:array,blocked_until:int,last_block_at:int,level:string}
*/
private static function empty_row() {
return array(
'attempts' => array(),
'blocked_until' => 0,
'last_block_at' => 0,
'level' => '',
);
}
/**
* @return array
*/
private static function load() {
$map = get_option( self::OPTION, array() );
return is_array( $map ) ? $map : array();
}
/**
* Persist and prune the lockout map.
*
* @param array $map Lockout map.
*/
private static function save( array $map ) {
$now = time();
$kept = array();
$stale = $now - ( 30 * DAY_IN_SECONDS );
foreach ( $map as $ip => $row ) {
if ( ! is_array( $row ) ) {
continue;
}
$ip = Ip::valid( $ip );
if ( '' === $ip ) {
continue;
}
$until = isset( $row['blocked_until'] ) ? (int) $row['blocked_until'] : 0;
$last = isset( $row['last_block_at'] ) ? (int) $row['last_block_at'] : 0;
$atts = isset( $row['attempts'] ) && is_array( $row['attempts'] ) ? $row['attempts'] : array();
if ( $until > $now || $atts || $last >= $stale ) {
$kept[ $ip ] = array(
'attempts' => array_values( array_map( 'intval', array_slice( $atts, -50 ) ) ),
'blocked_until' => $until,
'last_block_at' => $last,
'level' => isset( $row['level'] ) ? sanitize_key( (string) $row['level'] ) : '',
);
}
}
if ( count( $kept ) > 500 ) {
uasort(
$kept,
static function ( $a, $b ) {
$la = isset( $a['last_block_at'] ) ? (int) $a['last_block_at'] : 0;
$lb = isset( $b['last_block_at'] ) ? (int) $b['last_block_at'] : 0;
return $lb <=> $la;
}
);
$kept = array_slice( $kept, 0, 500, true );
}
update_option( self::OPTION, $kept, false );
}
}