ID : 0; } public static function on_failed( $login ) { self::$action = 'login_failed'; self::$detail = (string) $login; } public static function on_logout( $user_id ) { self::$action = 'logout'; self::$user = (int) $user_id; } /** * Called by the firewall right before a blocked request stops. */ public static function blocked( $rule, $code ) { if ( 'off' === self::mode() ) { return; } self::$action = 'blocked'; self::$detail = (string) $rule; self::write( (int) $code ); self::count_surge(); } public static function on_shutdown() { if ( self::$logged || ( defined( 'DOING_CRON' ) && DOING_CRON ) || ( defined( 'WP_CLI' ) && WP_CLI ) ) { return; } $status = (int) http_response_code(); $status = $status > 0 ? $status : 200; if ( '' === self::$action && 404 === $status ) { self::$action = '404'; } if ( '' === self::$action && 'all' !== self::mode() ) { return; } $uid = self::$user ? self::$user : get_current_user_id(); if ( '' === self::$action ) { // Page views: skip what only adds noise. if ( wp_doing_ajax() || preg_match( '#/(?:wp-json/softvoltai-ai-bodyguard/|wp-admin/admin-ajax\.php)#', Softvolt_Ai_Bodyguard_Helpers::request_path() ) ) { return; } if ( $uid && Softvolt_Ai_Bodyguard_Settings::get( 'traffic_ignore_logged_in', 1 ) && user_can( $uid, 'edit_posts' ) ) { return; } } self::$user = $uid; self::write( $status ); } private static function write( $status ) { global $wpdb; if ( self::$logged || ! isset( $wpdb ) ) { return; } self::$logged = true; $ip = Softvolt_Ai_Bodyguard_Helpers::client_ip(); if ( Softvolt_Ai_Bodyguard_Helpers::ip_in_list( $ip, Softvolt_Ai_Bodyguard_Settings::get( 'traffic_ignore_ips', '' ) ) ) { return; } $ua = Softvolt_Ai_Bodyguard_Helpers::user_agent(); if ( false !== strpos( $ua, '(self-check)' ) ) { return; } $ignore = Softvolt_Ai_Bodyguard_Settings::list_to_array( Softvolt_Ai_Bodyguard_Settings::get( 'traffic_ignore_uas', '' ) ); if ( $ignore && class_exists( 'Softvolt_Ai_Bodyguard_Blocking' ) && Softvolt_Ai_Bodyguard_Blocking::text_matches( $ua, $ignore ) ) { return; } $country = class_exists( 'Softvolt_Ai_Bodyguard_Geoip' ) ? Softvolt_Ai_Bodyguard_Geoip::country( $ip ) : ''; $uri = Softvolt_Ai_Bodyguard_Helpers::loggable_url( Softvolt_Ai_Bodyguard_Helpers::request_uri() ); $ref = Softvolt_Ai_Bodyguard_Helpers::loggable_url( Softvolt_Ai_Bodyguard_Helpers::referer() ); $visitor = class_exists( 'Softvolt_Ai_Bodyguard_Blocking' ) && Softvolt_Ai_Bodyguard_Blocking::is_crawler( $ua ) ? 'crawler' : 'human'; $table = Softvolt_Ai_Bodyguard_Db::table( 'traffic' ); $wpdb->suppress_errors( true ); $wpdb->insert( $table, array( 'created_at' => gmdate( 'Y-m-d H:i:s' ), 'ip' => $ip, 'country' => $country, 'method' => substr( Softvolt_Ai_Bodyguard_Helpers::request_method(), 0, 10 ), 'uri' => mb_substr( $uri, 0, 1000 ), 'status' => (int) $status, 'visitor' => $visitor, 'action' => self::$action, 'detail' => mb_substr( self::$detail, 0, 255 ), 'user_id' => (int) self::$user, 'ua' => mb_substr( $ua, 0, 255 ), 'referer' => mb_substr( $ref, 0, 500 ), ) ); $wpdb->suppress_errors( false ); } /** * Many blocks in a short time: queue an "attack in progress" alert (sent by cron, where mail works). */ private static function count_surge() { if ( ! Softvolt_Ai_Bodyguard_Settings::get( 'alert_on_attack_surge', 1 ) ) { return; } $minutes = max( 1, (int) Softvolt_Ai_Bodyguard_Settings::get( 'alert_surge_minutes', 10 ) ); $limit = max( 5, (int) Softvolt_Ai_Bodyguard_Settings::get( 'alert_surge_count', 100 ) ); $n = Softvolt_Ai_Bodyguard_Firewall::count( 'svabg_surge', $minutes * MINUTE_IN_SECONDS ); if ( $n === $limit && ! get_transient( 'svabg_surge_sent' ) ) { set_transient( 'svabg_surge_sent', 1, $minutes * MINUTE_IN_SECONDS ); update_option( 'svabg_surge_pending', array( 'count' => $n, 'minutes' => $minutes, 'time' => time() ), false ); if ( ! wp_next_scheduled( 'svabg_surge_alert' ) ) { wp_schedule_single_event( time() + 30, 'svabg_surge_alert' ); } } } /* ------------------------------- reading ------------------------------ */ /** * Rows for the live traffic screen. * * @param array $args filter (all|human|crawler|blocked|logins|404), ip, since_id, page. */ public static function rows( array $args ) { global $wpdb; $table = Softvolt_Ai_Bodyguard_Db::table( 'traffic' ); $where = array( '1=1' ); $params = array(); switch ( isset( $args['filter'] ) ? $args['filter'] : 'all' ) { case 'human': case 'crawler': $where[] = 'visitor = %s'; $params[] = $args['filter']; break; case 'blocked': $where[] = "action = 'blocked'"; break; case 'logins': $where[] = "action IN ('login_ok','login_failed','logout')"; break; case '404': $where[] = 'status = 404'; break; } if ( ! empty( $args['ip'] ) ) { $where[] = 'ip = %s'; $params[] = (string) $args['ip']; } if ( ! empty( $args['since_id'] ) ) { $where[] = 'id > %d'; $params[] = (int) $args['since_id']; } $per = 50; $page = max( 1, (int) ( $args['page'] ?? 1 ) ); $where_sql = implode( ' AND ', $where ); $rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM %i WHERE {$where_sql} ORDER BY id DESC LIMIT %d OFFSET %d", array_merge( array( $table ), $params, array( $per, ( $page - 1 ) * $per ) ) ), ARRAY_A ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- The interpolated part holds fixed column names and placeholders only; every value goes through prepare(). $out = array(); foreach ( (array) $rows as $r ) { $user = $r['user_id'] ? get_userdata( (int) $r['user_id'] ) : null; $out[] = array( 'id' => (int) $r['id'], 'time' => strtotime( $r['created_at'] . ' UTC' ), 'ago' => human_time_diff( strtotime( $r['created_at'] . ' UTC' ) ), 'ip' => $r['ip'], 'country' => $r['country'], 'method' => $r['method'], 'uri' => $r['uri'], 'status' => (int) $r['status'], 'visitor' => $r['visitor'], 'action' => $r['action'], 'detail' => $r['detail'], 'user' => $user ? $user->user_login : '', 'ua' => $r['ua'], 'referer' => $r['referer'], ); } return array( 'rows' => $out, 'page' => $page, 'more' => count( $out ) === $per ); } /** * Counts for the last 24 hours and the busiest addresses. */ /** * Pages not found: a count per day, the most requested missing addresses and the addresses that asked. * * @since 1.4.0 * @param int $days Days back. * @return array */ public static function stats_404( $days = 7 ) { global $wpdb; $table = Softvolt_Ai_Bodyguard_Db::table( 'traffic' ); $days = max( 1, min( 90, (int) $days ) ); $since = gmdate( 'Y-m-d 00:00:00', time() - ( $days - 1 ) * DAY_IN_SECONDS ); $per = array(); foreach ( (array) $wpdb->get_results( $wpdb->prepare( "SELECT DATE(created_at) AS d, COUNT(*) AS n FROM %i WHERE status = 404 AND created_at >= %s GROUP BY DATE(created_at)", $table, $since ), ARRAY_A ) as $r ) { $per[ $r['d'] ] = (int) $r['n']; } $out = array(); $max = 0; for ( $i = $days - 1; $i >= 0; $i-- ) { $ts = time() - $i * DAY_IN_SECONDS; $key = gmdate( 'Y-m-d', $ts ); $n = isset( $per[ $key ] ) ? $per[ $key ] : 0; $max = max( $max, $n ); $out[] = array( 'date' => $key, 'label' => wp_date( 'D j', $ts ), 'n' => $n ); } $paths = (array) $wpdb->get_results( $wpdb->prepare( "SELECT uri, COUNT(*) AS n FROM %i WHERE status = 404 AND created_at >= %s GROUP BY uri ORDER BY n DESC LIMIT 10", $table, $since ), ARRAY_A ); $ips = (array) $wpdb->get_results( $wpdb->prepare( "SELECT ip, COUNT(*) AS n FROM %i WHERE status = 404 AND created_at >= %s GROUP BY ip ORDER BY n DESC LIMIT 10", $table, $since ), ARRAY_A ); foreach ( $paths as &$p ) { $p['n'] = (int) $p['n']; } unset( $p ); foreach ( $ips as &$r ) { $r['n'] = (int) $r['n']; $r['locked'] = (bool) Softvolt_Ai_Bodyguard_Lockouts::is_blocked( $r['ip'] ); } unset( $r ); return array( 'days' => $out, 'max' => $max, 'total' => array_sum( wp_list_pluck( $out, 'n' ) ), 'paths' => $paths, 'ips' => $ips, ); } public static function summary() { global $wpdb; $table = Softvolt_Ai_Bodyguard_Db::table( 'traffic' ); $since = gmdate( 'Y-m-d H:i:s', time() - DAY_IN_SECONDS ); $c = $wpdb->get_row( $wpdb->prepare( "SELECT COUNT(*) AS total, SUM(visitor='human') AS human, SUM(visitor='crawler') AS crawler, SUM(action='blocked') AS blocked, SUM(action='login_failed') AS failed, SUM(action='login_ok') AS logins, SUM(status=404) AS notfound FROM %i WHERE created_at >= %s", $table, $since ), ARRAY_A ); $top = $wpdb->get_results( $wpdb->prepare( "SELECT ip, MAX(country) AS country, COUNT(*) AS n, SUM(action='blocked') AS blocked FROM %i WHERE created_at >= %s GROUP BY ip ORDER BY n DESC LIMIT 8", $table, $since ), ARRAY_A ); foreach ( (array) $top as &$t ) { $t['n'] = (int) $t['n']; $t['blocked'] = (int) $t['blocked']; $t['locked'] = (bool) Softvolt_Ai_Bodyguard_Lockouts::is_blocked( $t['ip'] ); } return array( 'counts' => array_map( 'intval', (array) $c ), 'top' => (array) $top, 'mode' => self::mode(), ); } /** * Daily: keep the configured days and rows. */ public static function trim() { global $wpdb; $table = Softvolt_Ai_Bodyguard_Db::table( 'traffic' ); if ( ! $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) ) { return; } $wpdb->query( $wpdb->prepare( "DELETE FROM %i WHERE created_at < %s", $table, gmdate( 'Y-m-d H:i:s', time() - (int) Softvolt_Ai_Bodyguard_Settings::get( 'traffic_max_days', 14 ) * DAY_IN_SECONDS ) ) ); $max = (int) Softvolt_Ai_Bodyguard_Settings::get( 'traffic_max_rows', 50000 ); $cut = (int) $wpdb->get_var( $wpdb->prepare( "SELECT id FROM %i ORDER BY id DESC LIMIT 1 OFFSET %d", $table, $max ) ); if ( $cut > 0 ) { $wpdb->query( $wpdb->prepare( "DELETE FROM %i WHERE id <= %d", $table, $cut ) ); } } public static function clear() { global $wpdb; $wpdb->query( $wpdb->prepare( 'TRUNCATE TABLE %i', Softvolt_Ai_Bodyguard_Db::table( 'traffic' ) ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Maintenance query on demand. } }