getTimestamp(), $schedule, 'aowpcs_cron_scheduled_scan'); } } public static function scheduled_scan() { $scan_id = self::start(AOWPCS_Settings::get('scan_schedule_profile'), '', 'scheduled'); if (!is_wp_error($scan_id)) { self::cron_step($scan_id, 0); } } /** * Start a scan. Returns the scan id or WP_Error (for example when a scan is already running). */ public static function start($profile, $scope = '', $trigger = 'manual') { if (!in_array($profile, array('quick', 'full', 'category', 'check'), true)) { return new WP_Error('aowpcs_profile', __('Unknown scan type.', 'all-in-one-wp-content-security')); } self::recover_stale(); $plan = AOWPCS_Check_Registry::plan($profile, $scope); if (empty($plan)) { return new WP_Error('aowpcs_empty_plan', __('There is nothing to scan for this selection.', 'all-in-one-wp-content-security')); } if (!add_option(self::LOCK, 'starting:' . time(), '', 'no')) { $running = AOWPCS_Scan_Store::running_scan(); return new WP_Error('aowpcs_scan_running', __('Another scan is already running. Wait for it to finish or cancel it.', 'all-in-one-wp-content-security'), array('scan_id' => $running ? (int) $running->id : 0)); } $scan_id = AOWPCS_Scan_Store::create_scan($profile, $scope, $trigger, $plan); if (!$scan_id) { delete_option(self::LOCK); return new WP_Error('aowpcs_scan_create', __('The scan could not be created (database error).', 'all-in-one-wp-content-security')); } update_option(self::LOCK, $scan_id, false); AOWPCS_Loopback::flush(); /* translators: 1: profile, 2: trigger */ AOWPCS_Event_Log::log('scan_started', array('category' => 'scan', 'severity' => 'low', 'user_id' => get_current_user_id(), 'message' => sprintf(__('%1$s scan started (%2$s)', 'all-in-one-wp-content-security'), ucfirst($profile), $trigger), 'data' => array('scan' => $scan_id, 'scope' => $scope))); // WP-Cron continues the scan if nobody drives it from the admin screen wp_schedule_single_event(time() + 30, 'aowpcs_scan_step', array($scan_id, 0)); return $scan_id; } /** * WP-Cron / scheduled driver: run steps for up to ~40 seconds, then hand over to the next event */ public static function cron_step($scan_id, $counter = 0) { $limit = (int) ini_get('max_execution_time'); $budget = $limit > 0 ? max(10, min(40, (int) ($limit * 0.6))) : 40; $until = microtime(true) + $budget; do { $progress = self::step($scan_id); if (is_wp_error($progress) || !empty($progress['busy'])) { break; } } while ($progress['status'] === 'running' && microtime(true) < $until); if (!is_wp_error($progress) && $progress['status'] === 'running') { wp_schedule_single_event(time() + 5, 'aowpcs_scan_step', array((int) $scan_id, (int) $counter + 1)); } } /** * Run checks until the time budget is used up. Returns the progress array. */ public static function step($scan_id) { $scan = AOWPCS_Scan_Store::get_scan($scan_id); if (!$scan) { return new WP_Error('aowpcs_scan_missing', __('Scan not found.', 'all-in-one-wp-content-security')); } if ($scan->status !== 'running') { return self::progress($scan); } if (!self::acquire_step_lock()) { $progress = self::progress($scan); $progress['busy'] = true; return $progress; } try { if ($scan->cancel_requested) { self::finalize($scan, 'partial', __('Cancelled by an administrator.', 'all-in-one-wp-content-security')); return self::progress(AOWPCS_Scan_Store::get_scan($scan_id)); } @set_time_limit(120); $deadline = microtime(true) + self::budget(); $context = new AOWPCS_Scan_Context($scan->id, $scan->profile, $deadline); $cursor = $scan->cursor; $plan = $cursor['plan']; $done = (int) $scan->checks_done; register_shutdown_function(array(__CLASS__, 'shutdown_handler'), (int) $scan->id); while ($cursor['index'] < count($plan) && !$context->out_of_time()) { $check_id = $plan[$cursor['index']]; $check = AOWPCS_Check_Registry::get($check_id); if (!$check) { $cursor['skipped'][$check_id] = 'missing'; $cursor['index']++; $cursor['check_cursor'] = null; continue; } $skip = self::skip_reason($check, $context); if ($skip !== '') { $findings = array(); foreach (array_keys($check->rules()) as $rule_id) { $finding = new AOWPCS_Finding($rule_id, 'unknown'); $rule = $check->rule($rule_id); $finding->category = $rule['category']; $finding->title = $rule['title']; $finding->summary = $skip; $findings[] = $finding; } AOWPCS_Scan_Store::record($scan->id, $check, $findings, $cursor['rules']); $cursor['skipped'][$check_id] = $skip; $cursor['index']++; $cursor['check_cursor'] = null; $done++; continue; } // Remember which check runs, so a fatal error inside it can be attributed and skipped $cursor['inflight'] = $check_id; self::$inflight = array('cursor' => $cursor, 'done' => $done); AOWPCS_Scan_Store::update_scan($scan->id, array('cursor' => $cursor, 'heartbeat_at' => AOWPCS_Plugin::now())); $next = null; try { if ($check->is_batched()) { list($findings, $next) = $check->run_batch($context, $cursor['check_cursor']); } else { $findings = $check->run($context); } } catch (Throwable $e) { $findings = self::error_findings($check, $e->getMessage()); $cursor['failed'][] = $check_id; $next = null; } AOWPCS_Scan_Store::record($scan->id, $check, (array) $findings, $cursor['rules']); if ($next === null) { AOWPCS_Scan_Store::complete_check($scan->id, $check, $cursor['rules']); $cursor['index']++; $cursor['check_cursor'] = null; $done++; } else { $cursor['check_cursor'] = $next; } $cursor['inflight'] = null; self::$inflight = null; } $status_fields = array('cursor' => $cursor, 'checks_done' => $done, 'heartbeat_at' => AOWPCS_Plugin::now()); AOWPCS_Scan_Store::update_scan($scan->id, $status_fields); if ($cursor['index'] >= count($plan)) { $scan = AOWPCS_Scan_Store::get_scan($scan->id); if (!empty($cursor['failed'])) { /* translators: Placeholder is a number or value shown in the message */ self::finalize($scan, 'partial', sprintf(_n('%d check failed and was skipped.', '%d checks failed and were skipped.', count($cursor['failed']), 'all-in-one-wp-content-security'), count($cursor['failed']))); } else { self::finalize($scan, 'completed', ''); } } } finally { self::$inflight = null; self::release_step_lock(); } return self::progress(AOWPCS_Scan_Store::get_scan($scan_id)); } /** * Seconds of work per step */ private static function budget() { $budget = (int) AOWPCS_Settings::get('scan_time_budget'); $limit = (int) ini_get('max_execution_time'); if ($limit > 0) { $budget = min($budget, max(3, (int) ($limit * 0.4))); } return max(3, $budget); } /** * Why a check cannot run in this environment ('' when it can) */ private static function skip_reason($check, $context) { foreach ($check->requires() as $service) { if (!$context->allows($service)) { if ($service === 'wporg') { return __('Skipped: WordPress.org lookups are disabled in Settings.', 'all-in-one-wp-content-security'); } if ($service === 'vuln') { return __('Skipped: no vulnerability data source is configured in Settings.', 'all-in-one-wp-content-security'); } return __('Skipped: a required service is not enabled.', 'all-in-one-wp-content-security'); } } if ($check->needs_loopback()) { $available = AOWPCS_Loopback::available(); if (is_wp_error($available)) { return __('Could not verify:', 'all-in-one-wp-content-security') . ' ' . $available->get_error_message(); } } return ''; } private static function error_findings($check, $message) { $findings = array(); foreach (array_keys($check->rules()) as $rule_id) { $finding = new AOWPCS_Finding($rule_id, 'error'); $rule = $check->rule($rule_id); $finding->category = $rule['category']; $finding->title = $rule['title']; /* translators: %s: message */ $finding->summary = sprintf(__('The check failed: %s', 'all-in-one-wp-content-security'), AOWPCS_Redactor::text($message)); $findings[] = $finding; } return $findings; } /** * A fatal error inside a check: record it, move past the check and release the step lock */ public static function shutdown_handler($scan_id) { if (self::$inflight === null) { return; } $error = error_get_last(); if (!$error || !in_array($error['type'], array(E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR), true)) { return; } $state = self::$inflight; self::$inflight = null; $cursor = $state['cursor']; $check = AOWPCS_Check_Registry::get($cursor['inflight']); if ($check) { AOWPCS_Scan_Store::record($scan_id, $check, self::error_findings($check, $error['message']), $cursor['rules']); } $cursor['failed'][] = $cursor['inflight']; $cursor['inflight'] = null; $cursor['index']++; $cursor['check_cursor'] = null; AOWPCS_Scan_Store::update_scan($scan_id, array('cursor' => $cursor, 'checks_done' => $state['done'] + 1, 'heartbeat_at' => AOWPCS_Plugin::now())); self::release_step_lock(); } private static function finalize($scan, $status, $reason) { $cursor = $scan->cursor; $counts = array('pass' => 0, 'issue' => 0, 'unknown' => 0, 'error' => 0); foreach ($cursor['rules'] as $rule_status) { if (isset($counts[$rule_status])) { $counts[$rule_status]++; } } $severity = AOWPCS_Scan_Store::severity_counts('open'); $fields = array( 'status' => $status, 'status_reason' => $reason, 'finished_at' => AOWPCS_Plugin::now(), 'rules_passed' => $counts['pass'], 'rules_failed' => $counts['issue'], 'rules_unknown' => $counts['unknown'], 'rules_error' => $counts['error'], 'count_critical' => $severity['critical'], 'count_high' => $severity['high'], 'count_medium' => $severity['medium'], 'count_low' => $severity['low'], 'coverage' => AOWPCS_Score::coverage($cursor['rules']), ); // Only scans that looked at the whole site produce a score for the history if (in_array($scan->profile, array('full', 'quick'), true)) { $fields['score'] = AOWPCS_Score::current(); } AOWPCS_Scan_Store::update_scan($scan->id, $fields); if ((string) get_option(self::LOCK) === (string) $scan->id) { delete_option(self::LOCK); } if (in_array($scan->profile, array('full', 'quick'), true)) { AOWPCS_Settings::set_state('last_' . $scan->profile . '_scan', (int) $scan->id); } wp_clear_scheduled_hook('aowpcs_scan_step', array((int) $scan->id, 0)); AOWPCS_Event_Log::log($status === 'completed' ? 'scan_completed' : 'scan_partial', array( 'category' => 'scan', 'severity' => $status === 'completed' ? 'low' : 'medium', 'message' => $status === 'completed' /* translators: 1: scan profile, 2: counts issue, 3: counts pass */ ? sprintf(__('%1$s scan completed: %2$d issues, %3$d checks passed', 'all-in-one-wp-content-security'), ucfirst($scan->profile), $counts['issue'], $counts['pass']) /* translators: 1: scan profile, 2: reason */ : sprintf(__('%1$s scan ended early: %2$s', 'all-in-one-wp-content-security'), ucfirst($scan->profile), $reason), 'data' => array('scan' => (int) $scan->id), )); do_action('aowpcs_scan_finished', (int) $scan->id, $status); } public static function cancel($scan_id) { $scan = AOWPCS_Scan_Store::get_scan($scan_id); if (!$scan || $scan->status !== 'running') { return new WP_Error('aowpcs_not_running', __('This scan is not running.', 'all-in-one-wp-content-security')); } AOWPCS_Scan_Store::update_scan($scan_id, array('cancel_requested' => 1)); // When no step is in progress, finish the cancellation right away if (self::acquire_step_lock()) { try { self::finalize(AOWPCS_Scan_Store::get_scan($scan_id), 'partial', __('Cancelled by an administrator.', 'all-in-one-wp-content-security')); } finally { self::release_step_lock(); } } return true; } /** * Continue a partial scan from where it stopped */ public static function resume($scan_id) { $scan = AOWPCS_Scan_Store::get_scan($scan_id); if (!$scan || $scan->status !== 'partial' || $scan->cursor['index'] >= count($scan->cursor['plan'])) { return new WP_Error('aowpcs_not_resumable', __('This scan cannot be resumed.', 'all-in-one-wp-content-security')); } self::recover_stale(); if (!add_option(self::LOCK, $scan_id, '', 'no')) { return new WP_Error('aowpcs_scan_running', __('Another scan is already running.', 'all-in-one-wp-content-security')); } AOWPCS_Scan_Store::update_scan($scan_id, array('status' => 'running', 'status_reason' => '', 'cancel_requested' => 0, 'finished_at' => null, 'heartbeat_at' => AOWPCS_Plugin::now())); wp_schedule_single_event(time() + 30, 'aowpcs_scan_step', array((int) $scan_id, 0)); return (int) $scan_id; } /** * A scan whose last heartbeat is older than 10 minutes was interrupted: mark it partial */ public static function recover_stale() { $running = AOWPCS_Scan_Store::running_scan(); if ($running && strtotime($running->heartbeat_at . ' UTC') < time() - self::STALE_AFTER) { self::finalize($running, 'partial', __('Interrupted (no progress for 10 minutes). You can resume it.', 'all-in-one-wp-content-security')); } $lock = get_option(self::LOCK); if ($lock !== false) { $lock_scan = ctype_digit((string) $lock) ? AOWPCS_Scan_Store::get_scan((int) $lock) : null; $starting = strpos((string) $lock, 'starting:') === 0 && (int) substr($lock, 9) < time() - 60; if ($starting || (ctype_digit((string) $lock) && (!$lock_scan || $lock_scan->status !== 'running'))) { delete_option(self::LOCK); } } $step = get_option(self::STEP_LOCK); if ($step !== false && (int) $step < time() - 300) { delete_option(self::STEP_LOCK); } } private static function acquire_step_lock() { if (add_option(self::STEP_LOCK, time(), '', 'no')) { return true; } $held_since = (int) get_option(self::STEP_LOCK); if ($held_since < time() - 300) { delete_option(self::STEP_LOCK); return add_option(self::STEP_LOCK, time(), '', 'no'); } return false; } private static function release_step_lock() { delete_option(self::STEP_LOCK); } /** * Progress data for the admin screen and the REST API */ public static function progress($scan) { if (!$scan) { return array('status' => 'missing'); } $cursor = $scan->cursor; $plan = isset($cursor['plan']) ? $cursor['plan'] : array(); $index = isset($cursor['index']) ? (int) $cursor['index'] : 0; $stage = ''; if ($scan->status === 'running' && isset($plan[$index])) { $check = AOWPCS_Check_Registry::get($plan[$index]); if ($check) { $rules = $check->rules(); $first = reset($rules); $stage = AOWPCS_Plugin::category_label($check->category()) . ': ' . (isset($first['title']) ? $first['title'] : $check->id()); } } $counts = array('pass' => 0, 'issue' => 0, 'unknown' => 0, 'error' => 0); foreach ((array) $cursor['rules'] as $rule_status) { if (isset($counts[$rule_status])) { $counts[$rule_status]++; } } $start = strtotime($scan->started_at . ' UTC'); $end = $scan->finished_at ? strtotime($scan->finished_at . ' UTC') : time(); return array( 'id' => (int) $scan->id, 'profile' => $scan->profile, 'scope' => $scan->scope, 'status' => $scan->status, 'status_reason' => $scan->status_reason, 'checks_total' => count($plan), 'checks_done' => (int) $scan->checks_done, 'percent' => count($plan) ? (int) floor(min($index, count($plan)) * 100 / count($plan)) : 100, 'stage' => $stage, 'passed' => $counts['pass'], 'issues' => $counts['issue'], 'unknown' => $counts['unknown'], 'errors' => $counts['error'], 'skipped' => count((array) $cursor['skipped']), 'elapsed' => max(0, $end - $start), 'score' => $scan->score === null ? null : (int) $scan->score, 'cancel_requested' => (bool) $scan->cancel_requested, ); } /** * Run a scan to completion in the current process (WP-CLI) */ public static function run_to_completion($scan_id, $callback = null) { do { $progress = self::step($scan_id); if (is_wp_error($progress)) { return $progress; } if ($callback) { call_user_func($callback, $progress); } if (!empty($progress['busy'])) { sleep(1); } } while ($progress['status'] === 'running'); return $progress; } }