PluginProbe
Vigilant – 100% Free Security Suite: Firewall, 2FA, Login, Headers, Scanner… / 2.11.5
Vigilant – 100% Free Security Suite: Firewall, 2FA, Login, Headers, Scanner… v2.11.5
2.11.11 2.11.10 2.11.9 2.11.7 2.11.8 2.11.6 2.11.5 2.11.4 2.11.3 2.11.1 2.11.2 2.11.0 2.10.5 2.10.4 2.10.3 2.10.2 2.10.1 2.10.0 2.9.9 2.9.8 2.9.6 2.9.7 2.9.5 2.9.4 2.9.3 All 86 releases
vigilante / vigilante.php

vigilante.php in Vigilant – 100% Free Security Suite: Firewall, 2FA, Login, Headers, Scanner… 2.11.5, at vigilante.php

895 lines 35.7 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Plugin Name: Vigilant - 100% Free Security Suite: Firewall, 2FA, Login, Headers, Scanner…
4 * Plugin URI: https://servicios.ayudawp.com
5 * Description: Complete security solution for WordPress. Firewall, 2FA, security headers, login protection, file integrity monitoring, activity logging and more.
6 * Version: 2.11.5
7 * Author: Fernando Tellado
8 * Author URI: https://ayudawp.com
9 * Text Domain: vigilante
10 * Requires at least: 6.2
11 * Tested up to: 7.1
12 * Requires PHP: 7.4
13 * License: GPL v2 or later
14 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
15 *
16 * @package Vigilante
17 */
18
19 // Prevent direct access
20 if ( ! defined( 'ABSPATH' ) ) {
21 exit;
22 }
23
24 /**
25 * Plugin constants
26 */
27 define( 'VIGILANTE_VERSION', '2.11.5' );
28 define( 'VIGILANTE_PLUGIN_FILE', __FILE__ );
29 define( 'VIGILANTE_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
30 define( 'VIGILANTE_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
31 define( 'VIGILANTE_PLUGIN_BASENAME', plugin_basename( __FILE__ ) );
32 define( 'VIGILANTE_INCLUDES_DIR', VIGILANTE_PLUGIN_DIR . 'includes/' );
33 define( 'VIGILANTE_ADMIN_DIR', VIGILANTE_PLUGIN_DIR . 'admin/' );
34 define( 'VIGILANTE_ASSETS_URL', VIGILANTE_PLUGIN_URL . 'assets/' );
35
36 // Backup directory outside plugin folder (persists through updates)
37 define( 'VIGILANTE_BACKUP_DIR', WP_CONTENT_DIR . '/vigilante-backups/' );
38
39 // Minimum requirements
40 define( 'VIGILANTE_MIN_PHP_VERSION', '7.4' );
41 define( 'VIGILANTE_MIN_WP_VERSION', '5.0' );
42
43 /**
44 * Check minimum requirements before loading
45 *
46 * @return bool True if requirements are met
47 */
48 function vigilante_check_requirements() {
49 $meets_requirements = true;
50
51 // Check PHP version
52 if ( version_compare( PHP_VERSION, VIGILANTE_MIN_PHP_VERSION, '<' ) ) {
53 $meets_requirements = false;
54 }
55
56 // Check WordPress version
57 global $wp_version;
58 if ( version_compare( $wp_version, VIGILANTE_MIN_WP_VERSION, '<' ) ) {
59 $meets_requirements = false;
60 }
61
62 if ( ! $meets_requirements ) {
63 add_action( 'admin_notices', 'vigilante_requirements_notice' );
64 }
65
66 return $meets_requirements;
67 }
68
69 /**
70 * Display requirements notice - called at admin_notices (after init)
71 */
72 function vigilante_requirements_notice() {
73 global $wp_version;
74 $errors = array();
75
76 if ( version_compare( PHP_VERSION, VIGILANTE_MIN_PHP_VERSION, '<' ) ) {
77 $errors[] = sprintf(
78 /* translators: 1: Current PHP version, 2: Required PHP version */
79 __( 'Vigilant requires PHP %2$s or higher. You are running PHP %1$s.', 'vigilante' ),
80 PHP_VERSION,
81 VIGILANTE_MIN_PHP_VERSION
82 );
83 }
84
85 if ( version_compare( $wp_version, VIGILANTE_MIN_WP_VERSION, '<' ) ) {
86 $errors[] = sprintf(
87 /* translators: 1: Current WordPress version, 2: Required WordPress version */
88 __( 'Vigilant requires WordPress %2$s or higher. You are running WordPress %1$s.', 'vigilante' ),
89 $wp_version,
90 VIGILANTE_MIN_WP_VERSION
91 );
92 }
93
94 foreach ( $errors as $error ) {
95 printf(
96 '<div class="notice notice-error"><p>%s</p></div>',
97 esc_html( $error )
98 );
99 }
100 }
101
102 /**
103 * Load plugin files
104 */
105 function vigilante_load_plugin() {
106 // Check requirements first
107 if ( ! vigilante_check_requirements() ) {
108 return;
109 }
110
111 // Load core classes (no translations used in these)
112 require_once VIGILANTE_INCLUDES_DIR . 'class-database.php';
113 require_once VIGILANTE_INCLUDES_DIR . 'class-settings.php';
114 require_once VIGILANTE_INCLUDES_DIR . 'class-ip-utils.php';
115 require_once VIGILANTE_INCLUDES_DIR . 'class-backup-manager.php';
116 require_once VIGILANTE_INCLUDES_DIR . 'class-activator.php';
117 require_once VIGILANTE_INCLUDES_DIR . 'class-deactivator.php';
118
119 // Load security module files (just loading, not initializing)
120 require_once VIGILANTE_INCLUDES_DIR . 'class-firewall.php';
121 require_once VIGILANTE_INCLUDES_DIR . 'class-security-headers.php';
122 require_once VIGILANTE_INCLUDES_DIR . 'class-htaccess-protection.php';
123 require_once VIGILANTE_INCLUDES_DIR . 'class-htaccess-recovery.php';
124 require_once VIGILANTE_INCLUDES_DIR . 'class-wpconfig-security.php';
125 require_once VIGILANTE_INCLUDES_DIR . 'class-https-enforcer.php';
126 require_once VIGILANTE_INCLUDES_DIR . 'class-rest-api-security.php';
127 require_once VIGILANTE_INCLUDES_DIR . 'class-user-security.php';
128 require_once VIGILANTE_INCLUDES_DIR . 'class-login-security.php';
129 require_once VIGILANTE_INCLUDES_DIR . 'trait-two-factor-session.php';
130 require_once VIGILANTE_INCLUDES_DIR . 'class-two-factor-email.php';
131 require_once VIGILANTE_INCLUDES_DIR . 'class-two-factor-totp.php';
132 require_once VIGILANTE_INCLUDES_DIR . 'class-email-template.php';
133 require_once VIGILANTE_INCLUDES_DIR . 'class-comment-security.php';
134 require_once VIGILANTE_INCLUDES_DIR . 'class-head-cleaner.php';
135 require_once VIGILANTE_INCLUDES_DIR . 'class-feed-manager.php';
136 require_once VIGILANTE_INCLUDES_DIR . 'class-activity-log.php';
137 require_once VIGILANTE_INCLUDES_DIR . 'class-audit-alerts.php';
138 require_once VIGILANTE_INCLUDES_DIR . 'class-file-integrity.php';
139 require_once VIGILANTE_INCLUDES_DIR . 'class-plugin-status.php';
140 require_once VIGILANTE_INCLUDES_DIR . 'class-under-attack.php';
141 require_once VIGILANTE_INCLUDES_DIR . 'class-database-backup.php';
142 require_once VIGILANTE_INCLUDES_DIR . 'class-database-prefix.php';
143 require_once VIGILANTE_INCLUDES_DIR . 'class-security-analyzer.php';
144
145 // Load admin classes
146 if ( is_admin() ) {
147 require_once VIGILANTE_ADMIN_DIR . 'class-admin-analyzer-ajax.php';
148 require_once VIGILANTE_ADMIN_DIR . 'class-admin-recovery-ajax.php';
149 require_once VIGILANTE_ADMIN_DIR . 'class-admin-audit-alerts-ajax.php';
150 require_once VIGILANTE_ADMIN_DIR . 'class-admin.php';
151 }
152
153 // Weekly Security Analyzer cron (registered even outside admin so it fires on cron hit).
154 add_action( 'vigilante_analyzer_weekly_scan', 'vigilante_run_analyzer_cron' );
155
156 // Daily plugin status check (closed-in-wp.org detection).
157 add_action( 'vigilante_plugin_status_check', 'vigilante_run_plugin_status_check' );
158
159 // Post-Under Attack scan (one-shot, scheduled by Vigilante_Under_Attack::deactivate).
160 add_action( 'vigilante_under_attack_post_scan', 'vigilante_run_post_under_attack_scan' );
161
162 // Initialize core components only - modules will be initialized at init
163 add_action( 'init', 'vigilante_init_plugin', 1 );
164 }
165
166 /**
167 * Initialize plugin at init hook (translations are ready)
168 */
169 function vigilante_init_plugin() {
170 Vigilante_Main::get_instance();
171 }
172
173 /**
174 * Main plugin class - Singleton pattern
175 */
176 final class Vigilante_Main {
177
178 /**
179 * Single instance of the class
180 *
181 * @var Vigilante_Main|null
182 */
183 private static $instance = null;
184
185 /**
186 * Settings instance
187 *
188 * @var Vigilante_Settings
189 */
190 public $settings;
191
192 /**
193 * Database instance
194 *
195 * @var Vigilante_Database
196 */
197 public $database;
198
199 /**
200 * Activity log instance
201 *
202 * @var Vigilante_Activity_Log
203 */
204 public $activity_log;
205
206 /**
207 * Get single instance of the class
208 *
209 * @return Vigilante_Main
210 */
211 public static function get_instance() {
212 if ( null === self::$instance ) {
213 self::$instance = new self();
214 }
215 return self::$instance;
216 }
217
218 /**
219 * Constructor - private to enforce singleton
220 */
221 private function __construct() {
222 $this->init_core();
223 $this->init_modules();
224 $this->init_hooks();
225 }
226
227 /**
228 * Prevent cloning
229 */
230 private function __clone() {}
231
232 /**
233 * Prevent unserializing
234 *
235 * @throws Exception Always throws exception.
236 */
237 public function __wakeup() {
238 throw new Exception( 'Cannot unserialize singleton' );
239 }
240
241 /**
242 * Initialize core components
243 */
244 private function init_core() {
245 $this->database = new Vigilante_Database();
246 $this->settings = new Vigilante_Settings();
247 $this->activity_log = new Vigilante_Activity_Log( $this->settings, $this->database );
248
249 // Auto-create/update tables when DB version is outdated (handles file-only updates)
250 if ( $this->database->needs_update() ) {
251 $this->database->create_tables();
252 }
253
254 // One-time cleanup: versions before 2.7.0 wrote config backups (including
255 // wp-config.php) as files under wp-content/vigilante-backups/. Those now
256 // live in the database, so remove anything left on disk.
257 if ( ! get_option( 'vigilante_legacy_backups_cleaned' ) ) {
258 Vigilante_Backup_Manager::cleanup_legacy_files();
259 update_option( 'vigilante_legacy_backups_cleaned', 1, false );
260 }
261
262 // One-time migration (2.9.0): add '.css' to File Integrity's excluded
263 // extensions on existing installs. Stylesheets are rewritten so often by
264 // themes and optimizer plugins that they were the main post-update false
265 // positive. New installs get it from the defaults; this brings existing
266 // sites in line without touching any other setting. Additive, idempotent.
267 if ( ! get_option( 'vigilante_css_exclusion_migrated' ) ) {
268 $fi = $this->settings->get_section( 'file_integrity' );
269 if ( is_array( $fi ) ) {
270 $ext = ( isset( $fi['excluded_extensions'] ) && is_array( $fi['excluded_extensions'] ) )
271 ? $fi['excluded_extensions']
272 : array();
273 if ( ! in_array( '.css', $ext, true ) ) {
274 $ext[] = '.css';
275 $fi['excluded_extensions'] = $ext;
276 $this->settings->update_section( 'file_integrity', $fi );
277 }
278 }
279 update_option( 'vigilante_css_exclusion_migrated', 1, false );
280 }
281
282 // One-time on upgrade to 2.9.0: drop any cached WordPress.org checksum
283 // manifests. The new comparison is array-aware and self-corrects a cached
284 // array-md5 value, but a manifest cached by an older version while wp.org
285 // was still propagating a new release could otherwise keep producing
286 // false "modified" results until it expires (up to 24h). Flushing on
287 // upgrade guarantees a clean slate on the very release that fixes them;
288 // the next scan refetches fresh manifests. One-time, bulk, no caching.
289 if ( ! get_option( 'vigilante_checksum_cache_flushed_290' ) ) {
290 global $wpdb;
291 $wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- one-time 2.9.0 migration dropping stale checksum transients so the new comparison starts clean.
292 "DELETE FROM {$wpdb->options}
293 WHERE option_name LIKE '\\_transient\\_vigilante\\_plugin\\_checksums\\_%'
294 OR option_name LIKE '\\_transient\\_timeout\\_vigilante\\_plugin\\_checksums\\_%'
295 OR option_name LIKE '\\_transient\\_vigilante\\_theme\\_checksums\\_%'
296 OR option_name LIKE '\\_transient\\_timeout\\_vigilante\\_theme\\_checksums\\_%'
297 OR option_name LIKE '\\_transient\\_vigilante\\_core\\_checksums\\_%'
298 OR option_name LIKE '\\_transient\\_timeout\\_vigilante\\_core\\_checksums\\_%'"
299 );
300 update_option( 'vigilante_checksum_cache_flushed_290', 1, false );
301 }
302 }
303
304 /**
305 * Initialize security modules based on settings
306 */
307 private function init_modules() {
308 $options = $this->settings->get_all_options();
309
310 // Self-heal: a UI bug in earlier 2.4.x betas could leave a section's
311 // top-level 'enabled' flag set to false because the section forms do
312 // not render a checkbox for that field — saving any tab caused the
313 // generic save handler to treat the missing field as "unchecked" and
314 // store it as false. If the master module toggle on the Dashboard is
315 // on but the section flag is off, restore it here so the module's
316 // hooks can attach. Idempotent: noop on healthy installs.
317 $sections = array(
318 'firewall',
319 'security_headers',
320 'login_security',
321 'rest_api_security',
322 'user_security',
323 'wp_hardening',
324 'file_integrity',
325 'activity_log',
326 );
327 $heal_changed = false;
328 foreach ( $sections as $section_name ) {
329 if ( ! empty( $options['modules'][ $section_name ] )
330 && isset( $options[ $section_name ] )
331 && is_array( $options[ $section_name ] )
332 && array_key_exists( 'enabled', $options[ $section_name ] )
333 && empty( $options[ $section_name ]['enabled'] ) ) {
334 $options[ $section_name ]['enabled'] = true;
335 $heal_changed = true;
336 }
337 }
338 if ( $heal_changed ) {
339 update_option( Vigilante_Settings::OPTION_NAME, $options );
340 $this->settings->clear_cache();
341 $options = $this->settings->get_all_options();
342 }
343
344 // Firewall - runs early to block threats
345 if ( ! empty( $options['modules']['firewall'] ) ) {
346 new Vigilante_Firewall( $this->settings, $this->activity_log );
347 }
348
349 // Security Headers - rules are applied via .htaccess, no runtime hooks needed
350 // HTTPS Enforcer still needs runtime hooks
351 if ( ! empty( $options['modules']['security_headers'] ) ) {
352 new Vigilante_Https_Enforcer( $this->settings );
353 }
354
355 // REST API Security
356 if ( ! empty( $options['modules']['rest_api_security'] ) ) {
357 new Vigilante_Rest_Api_Security( $this->settings );
358 }
359
360 // User Security
361 if ( ! empty( $options['modules']['user_security'] ) ) {
362 new Vigilante_User_Security( $this->settings, $this->activity_log );
363 }
364
365 // Login Security
366 if ( ! empty( $options['modules']['login_security'] ) ) {
367 $login_security = new Vigilante_Login_Security( $this->settings, $this->database, $this->activity_log );
368
369 // Two-Factor Authentication (only if login security module is active)
370 new Vigilante_Two_Factor_Email( $this->settings, $this->database, $this->activity_log, $login_security );
371 new Vigilante_Two_Factor_TOTP( $this->settings, $this->database, $this->activity_log, $login_security );
372 }
373
374 // WordPress Hardening (includes comments, head cleaner, feeds)
375 if ( ! empty( $options['modules']['wp_hardening'] ) ) {
376 new Vigilante_Comment_Security( $this->settings );
377 new Vigilante_Head_Cleaner( $this->settings );
378 new Vigilante_Feed_Manager( $this->settings );
379 }
380
381 // File Integrity Scanner
382 if ( ! empty( $options['modules']['file_integrity'] ) ) {
383 $file_integrity = new Vigilante_File_Integrity( $this->settings, $this->database, $this->activity_log );
384 $file_integrity->init_hooks();
385 $file_integrity->init_cleanup_hooks();
386
387 new Vigilante_Plugin_Status( $this->settings, $this->activity_log );
388 } elseif ( is_admin() ) {
389 /*
390 * The module is off, and the cleanup goes on anyway. It is not
391 * integrity monitoring: it takes out of the database the copy of
392 * wp-config.php that earlier versions stored, credentials and all.
393 * Turning the module off is not a decision to keep them.
394 *
395 * Two holes closed here, both reported by @calzbert after reading the
396 * 2.11.3 diff. A site with the module off cleaned itself by neither
397 * of its own two paths, because both hang off this class. And with
398 * the module off on the MAIN site, the network sweep was not
399 * registered either, which is what would have reached every other
400 * site: the sweep removes each site's option without asking whether
401 * the module is on over there.
402 *
403 * Only in the admin, because both hooks are admin_init and there is
404 * nothing to gain from building this on a front-end request. Note
405 * that admin-ajax.php fires admin_init too (wp-admin/admin-ajax.php
406 * :45), so this also runs on wp_ajax_nopriv_* requests from
407 * visitors with no session. That is deliberate and it is what the
408 * module has been doing since 2.11.2: the cleanup asks for no
409 * capability because it also runs under wp-cron with nobody logged
410 * in, and all it does is take the plugin's own copy out of the
411 * database. The network sweep, which does reach across sites, is
412 * the one that demands manage_network_options.
413 */
414 $file_integrity = new Vigilante_File_Integrity( $this->settings, $this->database, $this->activity_log );
415 $file_integrity->init_cleanup_hooks();
416 }
417
418 // Activity Log is always initialized (core component)
419 // Logging is gated by the modules.activity_log toggle and per-type flags
420
421 // Audit Alerts engine - an alerting layer on top of Security Audit.
422 // Only instantiated when Security Audit is on, because it reacts to the
423 // events the activity log records (a passive subscriber, no per-module
424 // coupling). Both alert legs are opt-in, off by default.
425 if ( ! empty( $options['modules']['activity_log'] ) ) {
426 new Vigilante_Audit_Alerts( $this->settings, $this->activity_log );
427 }
428
429 // Under Attack mode - always loaded (independent of modules)
430 new Vigilante_Under_Attack( $this->settings, $this->activity_log );
431
432 // Admin interface
433 if ( is_admin() ) {
434 new Vigilante_Admin( $this->settings, $this->database, $this->activity_log );
435 }
436 }
437
438 /**
439 * Initialize WordPress hooks
440 */
441 private function init_hooks() {
442 // Plugin action links
443 add_filter( 'plugin_action_links_' . VIGILANTE_PLUGIN_BASENAME, array( $this, 'add_action_links' ) );
444
445 // Scheduled tasks
446 add_action( 'vigilante_daily_maintenance', array( $this, 'daily_maintenance' ) );
447 add_action( 'vigilante_hourly_checks', array( $this, 'hourly_checks' ) );
448
449 // AJAX handlers
450 add_action( 'wp_ajax_vigilante_dismiss_notice', array( $this, 'ajax_dismiss_notice' ) );
451
452 // Regenerate critical file baseline after Vigilante modifies wp-config.php or .htaccess
453 add_action( 'vigilante_critical_file_written', array( $this, 'on_critical_file_written' ) );
454
455 // Keep the server layer in step with the installed version.
456 add_action( 'init', array( $this, 'maybe_sync_server_files' ), 20 );
457 }
458
459 /**
460 * Rewrite the .htaccess block when the installed version has moved on
461 *
462 * Updating the plugin did not touch the file: the block was only rewritten
463 * on activation or when the Headers or Firewall tab was saved. So a fix
464 * that lives inside those rules never reached a site that merely updated,
465 * which is exactly what happened with the connect-src of 2.9.6: the browser
466 * kept receiving the old policy, and image uploads kept failing on
467 * WordPress 7.1 until someone pressed Save. This rewrites the block once
468 * per version, and picks up the rules that an activation from WP-CLI had to
469 * leave pending because it could not tell what server it was on.
470 *
471 * Only the content between the plugin markers is rewritten, the same part
472 * any save has always rewritten.
473 *
474 * @since 2.9.9
475 */
476 public function maybe_sync_server_files() {
477 $pending = (bool) get_option( 'vigilante_server_files_pending' );
478
479 if ( ! $pending && VIGILANTE_VERSION === get_option( 'vigilante_server_files_version' ) ) {
480 return;
481 }
482
483 // A failed write is not retried on every request.
484 if ( (int) get_option( 'vigilante_server_files_retry_after' ) > time() ) {
485 return;
486 }
487
488 /*
489 * A subsite has nothing to do here, ever: the file belongs to the main
490 * site. Marking it done keeps every request from re-checking.
491 *
492 * 2.10.0 asked the wrong question at this point and it cost the whole
493 * feature on networks. can_write_shared_files() ends in a capability
494 * check, and this runs on init for every request, so on a network the
495 * branch below was the one nearly every visitor took: it retired the job
496 * without having written a thing. The .htaccess was never refreshed after
497 * an update, and the one-shot snapshot behind it was consumed without
498 * being taken, so not even a network administrator visiting afterwards
499 * retried, because the version had already been marked. Reported by
500 * @calzbert, who found it reading the code.
501 */
502 if ( ! Vigilante_Settings::owns_shared_files() ) {
503 $this->mark_server_files_synced();
504 return;
505 }
506
507 require_once VIGILANTE_INCLUDES_DIR . 'class-htaccess-manager.php';
508 $manager = Vigilante_Htaccess_Manager::get_instance();
509
510 if ( ! $manager->is_apache() ) {
511 // Still on the command line with nothing to learn from: stay pending.
512 if ( $manager->server_is_unknown() ) {
513 return;
514 }
515
516 // Not Apache: there is no block to keep in step.
517 $this->mark_server_files_synced();
518 return;
519 }
520
521 $options = get_option( Vigilante_Settings::OPTION_NAME, array() );
522 $headers = isset( $options['security_headers'] ) ? (array) $options['security_headers'] : array();
523 $failed = false;
524 $rewrote = false;
525
526 /*
527 * Last chance to keep what the file still says. The rewrites below are
528 * precisely what overwrites it, and on a site whose header settings the
529 * 2.9.8 migration reset, this file is the only remaining copy of what the
530 * owner had actually chosen. Captured here rather than inside the write
531 * path so it only ever happens on a version change: an ordinary save also
532 * leaves the file describing the previous values for an instant, and
533 * capturing there would spend the single slot on a difference the owner
534 * made deliberately.
535 */
536 $wrote_last = (string) get_option( 'vigilante_server_files_version' );
537
538 /*
539 * And only on the very first sync that arrives from a version older than
540 * this one. That is the whole window: the file still describes what the
541 * owner chose, and the rewrite below is what ends it. Gating on the
542 * version also keeps a future release, one that legitimately changes what
543 * the block contains, from reading its own improvement as damage and
544 * offering to undo it.
545 */
546 /*
547 * 2.10.1 and not 2.10.0, deliberately: it gives the networks a second
548 * chance. On a network 2.10.0 marked this done without writing anything,
549 * so the window closed with the snapshot untaken. But nothing was
550 * written, which means the .htaccess on those sites still describes the
551 * configuration its owner actually chose. Reopening the window one
552 * version wide is what lets them be recovered after all.
553 *
554 * Harmless where it already worked: a site that took a snapshot is
555 * skipped because one exists, and a site that found nothing to take has
556 * had its file rewritten to match its settings, so there is still no
557 * difference to find.
558 */
559 if ( '' === $wrote_last || version_compare( $wrote_last, '2.10.1', '<' ) ) {
560 require_once VIGILANTE_INCLUDES_DIR . 'class-htaccess-recovery.php';
561 Vigilante_Htaccess_Recovery::maybe_capture( $manager->get_content(), $this->settings );
562 }
563
564 $needs_protection_block = ! empty( $options['modules']['firewall'] )
565 || ! empty( $headers['hide_server_signature'] )
566 || ! empty( $headers['remove_fingerprinting_headers'] );
567
568 /*
569 * A 'locked' result is not a failure: another request is doing this very
570 * work right now. Returning without marking anything leaves the pending
571 * state alone, so whichever request wins finishes the job and this one
572 * stays out of the way. Treating it as a failure would arm the one hour
573 * backoff for something that is already being handled.
574 */
575 $locked = false;
576
577 if ( $needs_protection_block ) {
578 require_once VIGILANTE_INCLUDES_DIR . 'class-htaccess-protection.php';
579 $result = ( new Vigilante_Htaccess_Protection( $this->settings ) )->apply_rules( true );
580 $locked = $locked || ( is_wp_error( $result ) && 'locked' === $result->get_error_code() );
581 $failed = $failed || ( is_wp_error( $result ) && 'locked' !== $result->get_error_code() );
582 $rewrote = true;
583 }
584
585 if ( ! $locked && ! empty( $options['modules']['security_headers'] ) ) {
586 require_once VIGILANTE_INCLUDES_DIR . 'class-security-headers.php';
587 $result = ( new Vigilante_Security_Headers( $this->settings ) )->apply_rules( true );
588 $locked = $locked || ( is_wp_error( $result ) && 'locked' === $result->get_error_code() );
589 $failed = $failed || ( is_wp_error( $result ) && 'locked' !== $result->get_error_code() );
590 $rewrote = true;
591 }
592
593 if ( $locked ) {
594 return;
595 }
596
597 if ( $failed ) {
598 update_option( 'vigilante_server_files_retry_after', time() + HOUR_IN_SECONDS );
599
600 // A refusal to write the server rules is exactly the kind of thing
601 // that used to happen in silence, so it is recorded and retried in
602 // an hour instead of being forgotten.
603 if ( $this->activity_log ) {
604 $this->activity_log->log(
605 'system',
606 'server_rules_write_failed',
607 __( 'The .htaccess rules could not be rewritten after the update. Vigilant will try again in an hour; if the file is read only, fix its permissions or save the Firewall or Headers tab once.', 'vigilante' ),
608 array( 'version' => VIGILANTE_VERSION ),
609 'warning'
610 );
611 }
612
613 return;
614 }
615
616 $this->mark_server_files_synced();
617
618 if ( $rewrote && $this->activity_log ) {
619 $this->activity_log->log(
620 'system',
621 'server_rules_refreshed',
622 sprintf(
623 /* translators: %s: plugin version. */
624 __( 'The .htaccess rules were rewritten to match Vigilant %s.', 'vigilante' ),
625 VIGILANTE_VERSION
626 ),
627 array( 'version' => VIGILANTE_VERSION ),
628 'info'
629 );
630 }
631 }
632
633 /**
634 * Record that the server layer matches the installed version
635 *
636 * @since 2.9.9
637 */
638 private function mark_server_files_synced() {
639 update_option( 'vigilante_server_files_version', VIGILANTE_VERSION );
640 delete_option( 'vigilante_server_files_pending' );
641 delete_option( 'vigilante_server_files_retry_after' );
642 }
643
644 /**
645 * Update the critical file baseline after Vigilante writes to a monitored file
646 *
647 * @param string $filename File that was modified (e.g. 'wp-config.php').
648 */
649 public function on_critical_file_written( $filename ) {
650 if ( ! class_exists( 'Vigilante_File_Integrity' ) ) {
651 require_once VIGILANTE_INCLUDES_DIR . 'class-file-integrity.php';
652 }
653
654 $fi = new Vigilante_File_Integrity( $this->settings, $this->database, $this->activity_log );
655 $fi->update_critical_file_baseline( $filename );
656 }
657
658 /**
659 * Add plugin action links
660 *
661 * @param array $links Existing links.
662 * @return array Modified links.
663 */
664 public function add_action_links( $links ) {
665 $plugin_links = array(
666 '<a href="' . esc_url( admin_url( 'admin.php?page=vigilante' ) ) . '">' . esc_html__( 'Security Settings', 'vigilante' ) . '</a>',
667 );
668 return array_merge( $plugin_links, $links );
669 }
670
671 /**
672 * Daily maintenance tasks
673 */
674 public function daily_maintenance() {
675 // Clean old activity logs
676 $this->activity_log->cleanup_old_logs();
677
678 // Clean old login attempts
679 $this->database->cleanup_old_login_attempts();
680
681 // Clean expired 2FA codes and trusted devices
682 $this->database->cleanup_expired_2fa_codes();
683 $this->database->cleanup_expired_trusted_devices();
684
685 // Remove sensitive files (readme.html, license.txt, licencia.txt)
686 // WordPress core updates recreate these files, so we clean them daily
687 $advanced = $this->settings->get_section( 'advanced' );
688 if ( ! empty( $advanced['remove_readme'] ) ) {
689 $readme_path = ABSPATH . 'readme.html';
690 if ( file_exists( $readme_path ) ) {
691 wp_delete_file( $readme_path );
692 }
693 }
694 if ( ! empty( $advanced['remove_license'] ) ) {
695 $license_files = array( 'license.txt', 'licencia.txt' );
696 foreach ( $license_files as $license_file ) {
697 $license_path = ABSPATH . $license_file;
698 if ( file_exists( $license_path ) ) {
699 wp_delete_file( $license_path );
700 }
701 }
702 }
703
704 // Log maintenance
705 $this->activity_log->log( 'system', 'maintenance', __( 'Daily maintenance completed', 'vigilante' ) );
706 }
707
708 /**
709 * Hourly checks
710 */
711 public function hourly_checks() {
712 // File integrity scans are handled by the File_Integrity class own cron schedule
713 // based on the configured scan_frequency (daily/weekly).
714 }
715
716 /**
717 * AJAX handler for dismissing notices
718 */
719 public function ajax_dismiss_notice() {
720 check_ajax_referer( 'vigilante_dismiss_notice', 'nonce' );
721
722 if ( ! current_user_can( 'manage_options' ) ) {
723 wp_die( -1 );
724 }
725
726 $notice_id = isset( $_POST['notice_id'] ) ? sanitize_key( $_POST['notice_id'] ) : '';
727
728 if ( $notice_id ) {
729 $dismissed = get_option( 'vigilante_dismissed_notices', array() );
730 $dismissed[ $notice_id ] = time();
731 update_option( 'vigilante_dismissed_notices', $dismissed );
732 }
733
734 wp_send_json_success();
735 }
736 }
737
738 /**
739 * Cron handler for the weekly Security Analyzer scan.
740 *
741 * Resolves the shared Vigilante_Security_Analyzer (lazily; no cost when the
742 * cron is not firing) and lets it run the scan + regression email logic.
743 */
744 function vigilante_run_analyzer_cron() {
745 if ( ! class_exists( 'Vigilante_Security_Analyzer' ) ) {
746 require_once VIGILANTE_INCLUDES_DIR . 'class-security-analyzer.php';
747 }
748 if ( ! class_exists( 'Vigilante_Settings' ) ) {
749 require_once VIGILANTE_INCLUDES_DIR . 'class-settings.php';
750 }
751
752 $settings = new Vigilante_Settings();
753 $activity_log = null;
754 if ( class_exists( 'Vigilante_Activity_Log' ) && class_exists( 'Vigilante_Database' ) ) {
755 $database = new Vigilante_Database();
756 $activity_log = new Vigilante_Activity_Log( $settings, $database );
757 }
758
759 $analyzer = new Vigilante_Security_Analyzer( $settings, $activity_log );
760 $analyzer->cron_weekly_scan();
761 }
762
763 /**
764 * Cron handler for the daily plugin status check.
765 *
766 * Resolves the shared Vigilante_Plugin_Status lazily so the daily cron has no
767 * cost while it is not firing.
768 */
769 function vigilante_run_plugin_status_check() {
770 if ( ! class_exists( 'Vigilante_Plugin_Status' ) ) {
771 require_once VIGILANTE_INCLUDES_DIR . 'class-plugin-status.php';
772 }
773 if ( ! class_exists( 'Vigilante_Settings' ) ) {
774 require_once VIGILANTE_INCLUDES_DIR . 'class-settings.php';
775 }
776
777 $settings = new Vigilante_Settings();
778 $activity_log = null;
779 if ( class_exists( 'Vigilante_Activity_Log' ) && class_exists( 'Vigilante_Database' ) ) {
780 $database = new Vigilante_Database();
781 $activity_log = new Vigilante_Activity_Log( $settings, $database );
782 }
783
784 $checker = new Vigilante_Plugin_Status( $settings, $activity_log );
785 $checker->run_scheduled_check();
786 }
787
788 /**
789 * Run a Security Analyzer full scan after Under Attack mode deactivates.
790 *
791 * Scheduled one-shot from Vigilante_Under_Attack::deactivate() so the dashboard
792 * reflects the restored configuration with the slow HTTP/header probes the
793 * mode prevented from running safely while it was active.
794 */
795 function vigilante_run_post_under_attack_scan() {
796 if ( ! class_exists( 'Vigilante_Under_Attack' ) ) {
797 require_once VIGILANTE_INCLUDES_DIR . 'class-under-attack.php';
798 }
799 if ( ! class_exists( 'Vigilante_Settings' ) ) {
800 require_once VIGILANTE_INCLUDES_DIR . 'class-settings.php';
801 }
802
803 $settings = new Vigilante_Settings();
804 $activity_log = null;
805 if ( class_exists( 'Vigilante_Activity_Log' ) && class_exists( 'Vigilante_Database' ) ) {
806 $database = new Vigilante_Database();
807 $activity_log = new Vigilante_Activity_Log( $settings, $database );
808 }
809
810 $under_attack = new Vigilante_Under_Attack( $settings, $activity_log );
811 $under_attack->run_analyzer_scan( 'all' );
812 }
813
814 /**
815 * Plugin activation hook
816 */
817 function vigilante_activate() {
818 require_once VIGILANTE_INCLUDES_DIR . 'class-database.php';
819 require_once VIGILANTE_INCLUDES_DIR . 'class-settings.php';
820 require_once VIGILANTE_INCLUDES_DIR . 'class-backup-manager.php';
821 require_once VIGILANTE_INCLUDES_DIR . 'class-activator.php';
822
823 Vigilante_Activator::activate();
824 }
825 register_activation_hook( __FILE__, 'vigilante_activate' );
826
827 /**
828 * Plugin deactivation hook
829 */
830 function vigilante_deactivate() {
831 require_once VIGILANTE_INCLUDES_DIR . 'class-database.php';
832 require_once VIGILANTE_INCLUDES_DIR . 'class-settings.php';
833 require_once VIGILANTE_INCLUDES_DIR . 'class-backup-manager.php';
834 require_once VIGILANTE_INCLUDES_DIR . 'class-deactivator.php';
835
836 Vigilante_Deactivator::deactivate();
837 }
838 register_deactivation_hook( __FILE__, 'vigilante_deactivate' );
839
840 /**
841 * Initialize plugin after WordPress loads
842 */
843 add_action( 'plugins_loaded', 'vigilante_load_plugin' );
844
845 /*
846 * The hidden wp-admin is answered as early as the request can be judged with
847 * certainty, before the theme and the other plugins load. The modules are built
848 * on init priority 1, so until 2.9.9 a request that was going to be refused had
849 * already paid for the whole boot.
850 */
851 add_action( 'plugins_loaded', 'vigilante_block_hidden_admin_early', 1 );
852
853 /**
854 * Cheap gate for the early hidden wp-admin rejection
855 *
856 * Everything that can be decided without loading a single plugin class is
857 * decided here, so the usual request pays nothing more than a couple of
858 * comparisons and one option read that WordPress has already cached.
859 *
860 * @since 2.9.9
861 */
862 function vigilante_block_hidden_admin_early() {
863 if ( ! is_admin() ) {
864 return;
865 }
866
867 $method = isset( $_SERVER['REQUEST_METHOD'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) : 'GET';
868
869 // POST is how remote managers authenticate, and the later path lets it through too.
870 if ( 'GET' !== $method ) {
871 return;
872 }
873
874 $options = get_option( 'vigilante_options', array() );
875
876 if ( ! is_array( $options )
877 || empty( $options['modules']['login_security'] )
878 || empty( $options['login_security']['custom_login_url'] ) ) {
879 return;
880 }
881
882 require_once VIGILANTE_INCLUDES_DIR . 'class-ip-utils.php';
883 require_once VIGILANTE_INCLUDES_DIR . 'class-login-security.php';
884
885 Vigilante_Login_Security::maybe_block_hidden_admin_early( $options );
886 }
887
888 /**
889 * Helper function to get plugin instance
890 *
891 * @return Vigilante_Main
892 */
893 function vigilante() {
894 return Vigilante_Main::get_instance();
895 }