default category, for filters and labels */ public static function types() { return array( 'login_failed' => array('login', __('Failed login', 'all-in-one-wp-content-security')), 'login_lockout' => array('protection', __('Login lockout', 'all-in-one-wp-content-security')), 'admin_login' => array('login', __('Administrator login', 'all-in-one-wp-content-security')), 'request_blocked' => array('protection', __('Request blocked', 'all-in-one-wp-content-security')), 'ip_blocked' => array('protection', __('IP address blocked', 'all-in-one-wp-content-security')), 'ip_unblocked' => array('protection', __('IP address unblocked', 'all-in-one-wp-content-security')), 'probe' => array('traffic', __('Probing request', 'all-in-one-wp-content-security')), 'exploit_attempt' => array('traffic', __('Exploit attempt', 'all-in-one-wp-content-security')), 'scan_404_burst' => array('traffic', __('Burst of 404 responses', 'all-in-one-wp-content-security')), 'rest_burst' => array('traffic', __('Excessive REST API requests', 'all-in-one-wp-content-security')), 'xmlrpc_blocked' => array('protection', __('XML-RPC request blocked', 'all-in-one-wp-content-security')), 'crawler_spoofed' => array('traffic', __('Fake search engine crawler', 'all-in-one-wp-content-security')), 'admin_created' => array('audit', __('Administrator created', 'all-in-one-wp-content-security')), 'admin_granted' => array('audit', __('Administrator role granted', 'all-in-one-wp-content-security')), 'user_created' => array('audit', __('User created', 'all-in-one-wp-content-security')), 'role_changed' => array('audit', __('Role changed', 'all-in-one-wp-content-security')), 'user_deleted' => array('audit', __('User deleted', 'all-in-one-wp-content-security')), 'app_password_created' => array('audit', __('Application password created', 'all-in-one-wp-content-security')), 'option_changed' => array('audit', __('Important setting changed', 'all-in-one-wp-content-security')), 'plugin_activated' => array('audit', __('Plugin activated', 'all-in-one-wp-content-security')), 'plugin_deactivated' => array('audit', __('Plugin deactivated', 'all-in-one-wp-content-security')), 'plugin_deleted' => array('audit', __('Plugin deleted', 'all-in-one-wp-content-security')), 'theme_switched' => array('audit', __('Theme switched', 'all-in-one-wp-content-security')), 'software_updated' => array('audit', __('Software installed or updated', 'all-in-one-wp-content-security')), 'settings_changed' => array('system', __('Security settings changed', 'all-in-one-wp-content-security')), 'fix_applied' => array('system', __('Fix applied', 'all-in-one-wp-content-security')), 'fix_rolled_back' => array('system', __('Fix rolled back', 'all-in-one-wp-content-security')), 'scan_started' => array('scan', __('Scan started', 'all-in-one-wp-content-security')), 'scan_completed' => array('scan', __('Scan completed', 'all-in-one-wp-content-security')), 'scan_partial' => array('scan', __('Scan ended early', 'all-in-one-wp-content-security')), 'finding_accepted' => array('scan', __('Risk accepted', 'all-in-one-wp-content-security')), 'finding_reopened' => array('scan', __('Issue reopened', 'all-in-one-wp-content-security')), 'uploads_probe' => array('scan', __('Uploads execution test', 'all-in-one-wp-content-security')), 'vuln_data_updated' => array('scan', __('Vulnerability data updated', 'all-in-one-wp-content-security')), 'vuln_data_failed' => array('scan', __('Vulnerability data update failed', 'all-in-one-wp-content-security')), 'notification_sent' => array('system', __('Notification sent', 'all-in-one-wp-content-security')), 'logs_cleared' => array('system', __('Logs cleared', 'all-in-one-wp-content-security')), ); } public static function type_label($type) { $types = self::types(); return isset($types[$type]) ? $types[$type][1] : $type; } public static function action_labels() { return array( 'logged' => __('Logged', 'all-in-one-wp-content-security'), 'blocked' => __('Blocked', 'all-in-one-wp-content-security'), 'throttled' => __('Throttled', 'all-in-one-wp-content-security'), 'ip_blocked' => __('IP blocked', 'all-in-one-wp-content-security'), 'notified' => __('Notified', 'all-in-one-wp-content-security'), ); } /** * Safe description of the current request: ip (as logged), method, path without query string, user agent */ public static function request_context() { $uri = isset($_SERVER['REQUEST_URI']) ? wp_unslash($_SERVER['REQUEST_URI']) : ''; $path = (string) wp_parse_url($uri, PHP_URL_PATH); return array( 'ip' => AOWPCS_IP::client_ip(), 'method' => isset($_SERVER['REQUEST_METHOD']) ? substr(strtoupper(sanitize_key(wp_unslash($_SERVER['REQUEST_METHOD']))), 0, 10) : '', 'path' => self::clean_path($path), 'user_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? substr(sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])), 0, 255) : '', ); } public static function clean_path($path) { $path = preg_replace('/[\x00-\x1F\x7F]/', '', (string) $path); return substr($path, 0, 255); } /** * Record an event. Args: category, severity, ip (raw, anonymised here), method, path, * status_code, user_id, rule, action, classification, user_agent, message, data (array), request (bool: fill from the request) */ public static function log($type, $args = array()) { global $wpdb; $types = self::types(); if (!empty($args['request'])) { $args = array_merge(self::request_context(), $args); } $data = isset($args['data']) ? AOWPCS_Redactor::evidence($args['data']) : array(); $row = array( 'created_at' => AOWPCS_Plugin::now(), 'event_type' => substr($type, 0, 40), 'category' => isset($args['category']) ? $args['category'] : (isset($types[$type]) ? $types[$type][0] : ''), 'severity' => isset($args['severity']) && isset(AOWPCS_Plugin::severities()[$args['severity']]) ? $args['severity'] : 'low', 'ip' => isset($args['ip']) ? AOWPCS_IP::for_log($args['ip']) : '', 'method' => isset($args['method']) ? $args['method'] : '', 'path' => isset($args['path']) ? self::clean_path($args['path']) : '', 'status_code' => isset($args['status_code']) ? (int) $args['status_code'] : 0, 'user_id' => isset($args['user_id']) ? (int) $args['user_id'] : 0, 'rule' => isset($args['rule']) ? substr($args['rule'], 0, 64) : '', 'action_taken' => isset($args['action']) ? $args['action'] : 'logged', 'classification' => isset($args['classification']) ? $args['classification'] : '', 'user_agent' => isset($args['user_agent']) ? substr($args['user_agent'], 0, 255) : '', 'message' => isset($args['message']) ? substr(AOWPCS_Redactor::text($args['message']), 0, 255) : '', 'data' => $data ? wp_json_encode($data) : null, ); $suppress = $wpdb->suppress_errors(true); $ok = $wpdb->insert(AOWPCS_Plugin::table('events'), $row); $wpdb->suppress_errors($suppress); if ($ok) { $row['id'] = (int) $wpdb->insert_id; do_action('aowpcs_event_logged', $type, $row); } return $ok ? (int) $wpdb->insert_id : 0; } /** * Log at most $max events per key and window (protects the database during floods) */ public static function log_throttled($type, $key, $max, $window, $args) { if (AOWPCS_Rate_Limiter::hit('log:' . $type . ':' . $key, $window) > $max) { return 0; } return self::log($type, $args); } /** * Build the WHERE clause for event queries. * Args: event_type, category, severity, ip, action, since, until, search, rule */ private static function where($args) { global $wpdb; $where = array('1=1'); $params = array(); $map = array('event_type' => 'event_type', 'category' => 'category', 'severity' => 'severity', 'action' => 'action_taken', 'rule' => 'rule', 'classification' => 'classification'); foreach ($map as $arg => $column) { if (!empty($args[$arg])) { $values = (array) $args[$arg]; $where[] = "$column IN (" . implode(',', array_fill(0, count($values), '%s')) . ')'; $params = array_merge($params, array_map('strval', $values)); } } if (!empty($args['ip'])) { $where[] = 'ip LIKE %s'; $params[] = $wpdb->esc_like($args['ip']) . '%'; } if (!empty($args['since'])) { $where[] = 'created_at >= %s'; $params[] = $args['since']; } if (!empty($args['until'])) { $where[] = 'created_at <= %s'; $params[] = $args['until']; } if (!empty($args['search'])) { $like = '%' . $wpdb->esc_like($args['search']) . '%'; $where[] = '(message LIKE %s OR path LIKE %s OR user_agent LIKE %s)'; array_push($params, $like, $like, $like); } return array(implode(' AND ', $where), $params); } public static function query($args = array()) { global $wpdb; list($where, $params) = self::where($args); $orderby = isset($args['orderby']) && in_array($args['orderby'], array('created_at', 'severity', 'event_type', 'ip', 'status_code'), true) ? $args['orderby'] : 'created_at'; $order = isset($args['order']) && strtolower($args['order']) === 'asc' ? 'ASC' : 'DESC'; $limit = isset($args['limit']) ? max(1, min(5000, (int) $args['limit'])) : 50; $offset = isset($args['offset']) ? max(0, (int) $args['offset']) : 0; $sql = 'SELECT * FROM ' . AOWPCS_Plugin::table('events') . " WHERE $where ORDER BY $orderby $order, id DESC LIMIT %d OFFSET %d"; return $wpdb->get_results($wpdb->prepare($sql, array_merge($params, array($limit, $offset)))); } public static function count($args = array()) { global $wpdb; list($where, $params) = self::where($args); $sql = 'SELECT COUNT(*) FROM ' . AOWPCS_Plugin::table('events') . " WHERE $where"; return (int) ($params ? $wpdb->get_var($wpdb->prepare($sql, $params)) : $wpdb->get_var($sql)); } public static function get($id) { global $wpdb; return $wpdb->get_row($wpdb->prepare('SELECT * FROM ' . AOWPCS_Plugin::table('events') . ' WHERE id = %d', $id)); } /* ---------------------------------------------------------------- counters */ /** * Increment hourly counters in one query. $metrics: list of array(metric, dimension) */ /** * Dimensions whose values come from the request (address, path, user agent, REST route) and * the number of new values each may add per hour. Beyond that, new values are counted as * "(other)", so random paths or rotating addresses cannot grow the table without limit. */ const DIM_BUDGET = array('ip' => 200, 'path' => 200, 'ua' => 50, 'rest_route' => 50); const OTHER = '(other)'; public static function count_metrics($metrics) { global $wpdb; if (empty($metrics)) { return; } $table = AOWPCS_Plugin::table('counters'); $bucket = gmdate('Y-m-d H:00:00'); $rows = array(); $capped = array(); foreach ($metrics as $metric) { $row = array(substr($metric[0], 0, 32), substr((string) $metric[1], 0, 191)); if ($row[1] !== '' && isset(self::DIM_BUDGET[$row[0]])) { $capped[] = $row; } else { $rows[] = $row; } } if ($capped) { // One lookup: which values already have a row this hour, and how much budget is used $where = array(); $params = array($bucket); foreach ($capped as $row) { $where[] = '(metric = %s AND dim = %s)'; array_push($params, $row[0], $row[1]); } foreach (array_unique(array_column($capped, 0)) as $name) { $where[] = "(metric = %s AND dim = '')"; $params[] = 'dims:' . $name; } $existing = array(); foreach ((array) $wpdb->get_results($wpdb->prepare("SELECT metric, dim, hits FROM $table WHERE bucket = %s AND (" . implode(' OR ', $where) . ')', $params)) as $found) { $existing[strtolower($found->metric . "\n" . $found->dim)] = (int) $found->hits; } foreach ($capped as $row) { if (!isset($existing[strtolower($row[0] . "\n" . $row[1])])) { $used_key = 'dims:' . $row[0] . "\n"; $used = isset($existing[$used_key]) ? $existing[$used_key] : 0; if ($used >= self::DIM_BUDGET[$row[0]]) { $row[1] = self::OTHER; } else { $existing[$used_key] = $used + 1; $rows[] = array('dims:' . $row[0], ''); } } $rows[] = $row; } } $values = array(); $params = array(); foreach ($rows as $row) { $values[] = '(%s, %s, %s, 1)'; array_push($params, $bucket, $row[0], $row[1]); } $sql = 'INSERT INTO ' . $table . ' (bucket, metric, dim, hits) VALUES ' . implode(',', $values) . ' ON DUPLICATE KEY UPDATE hits = hits + 1'; $suppress = $wpdb->suppress_errors(true); $wpdb->query($wpdb->prepare($sql, $params)); $wpdb->suppress_errors($suppress); } /** * Number of distinct values of a dimension; array(count, true when some values were only * counted as "(other)" and the real number is higher) */ public static function counter_distinct($metric, $since) { global $wpdb; $table = AOWPCS_Plugin::table('counters'); $count = (int) $wpdb->get_var($wpdb->prepare("SELECT COUNT(DISTINCT dim) FROM $table WHERE metric = %s AND dim <> '' AND dim <> %s AND bucket >= %s", $metric, self::OTHER, $since)); return array($count, self::counter_total($metric, $since, self::OTHER) > 0); } public static function counter_total($metric, $since, $dim = null) { global $wpdb; $table = AOWPCS_Plugin::table('counters'); if ($dim === null) { return (int) $wpdb->get_var($wpdb->prepare("SELECT COALESCE(SUM(hits),0) FROM $table WHERE metric = %s AND dim = '' AND bucket >= %s", $metric, $since)); } return (int) $wpdb->get_var($wpdb->prepare("SELECT COALESCE(SUM(hits),0) FROM $table WHERE metric = %s AND dim = %s AND bucket >= %s", $metric, $dim, $since)); } /** * Top dimensions of a metric: list of objects (dim, hits) */ public static function counter_top($metric, $since, $limit = 10) { global $wpdb; return $wpdb->get_results($wpdb->prepare('SELECT dim, SUM(hits) AS hits FROM ' . AOWPCS_Plugin::table('counters') . " WHERE metric = %s AND dim <> '' AND dim <> %s AND bucket >= %s GROUP BY dim ORDER BY hits DESC LIMIT %d", $metric, self::OTHER, $since, $limit)); } /** * Hourly (or daily) series of a metric: bucket => hits, with empty buckets filled in */ public static function counter_series($metric, $hours, $daily = false) { global $wpdb; $since = gmdate('Y-m-d H:00:00', time() - ($hours - 1) * HOUR_IN_SECONDS); $format = $daily ? '%Y-%m-%d 00:00:00' : '%Y-%m-%d %H:00:00'; $rows = $wpdb->get_results($wpdb->prepare('SELECT DATE_FORMAT(bucket, %s) AS b, SUM(hits) AS hits FROM ' . AOWPCS_Plugin::table('counters') . " WHERE metric = %s AND dim = '' AND bucket >= %s GROUP BY b", $format, $metric, $since)); $series = array(); $step = $daily ? DAY_IN_SECONDS : HOUR_IN_SECONDS; $start = $daily ? strtotime(gmdate('Y-m-d 00:00:00', strtotime($since . ' UTC')) . ' UTC') : strtotime($since . ' UTC'); for ($t = $start; $t <= time(); $t += $step) { $series[gmdate($daily ? 'Y-m-d 00:00:00' : 'Y-m-d H:00:00', $t)] = 0; } foreach ($rows as $row) { $series[$row->b] = (int) $row->hits; } return $series; } /* ---------------------------------------------------------------- maintenance */ public static function prune($days) { global $wpdb; $cutoff = AOWPCS_Plugin::gmt_ago(max(1, (int) $days) * DAY_IN_SECONDS); // Delete in chunks to keep locks short do { $deleted = $wpdb->query($wpdb->prepare('DELETE FROM ' . AOWPCS_Plugin::table('events') . ' WHERE created_at < %s LIMIT 5000', $cutoff)); } while ($deleted === 5000); do { $deleted = $wpdb->query($wpdb->prepare('DELETE FROM ' . AOWPCS_Plugin::table('counters') . ' WHERE bucket < %s LIMIT 5000', $cutoff)); } while ($deleted === 5000); } /** * Remove events (all, or one category) — an audited administrator action */ public static function clear($category = '') { global $wpdb; $table = AOWPCS_Plugin::table('events'); if ($category !== '') { $wpdb->query($wpdb->prepare("DELETE FROM $table WHERE category = %s", $category)); } else { $wpdb->query("DELETE FROM $table"); $wpdb->query('DELETE FROM ' . AOWPCS_Plugin::table('counters')); } /* translators: %s: category */ self::log('logs_cleared', array('category' => 'system', 'severity' => 'medium', 'user_id' => get_current_user_id(), 'message' => $category !== '' ? sprintf(__('Security events of category "%s" were deleted.', 'all-in-one-wp-content-security'), $category) : __('All security events and traffic statistics were deleted.', 'all-in-one-wp-content-security'))); } }