PluginProbe
Vigilant – 100% Free Security Suite: Firewall, 2FA, Login, Headers, Scanner… / 2.11.8
Vigilant – 100% Free Security Suite: Firewall, 2FA, Login, Headers, Scanner… v2.11.8
2.11.12 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 All 87 releases
vigilante / includes / class-settings.php

class-settings.php in Vigilant – 100% Free Security Suite: Firewall, 2FA, Login, Headers, Scanner… 2.11.8, at includes/class-settings.php

1,505 lines 65.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Settings Class
4 *
5 * Centralized settings management with default values
6 *
7 * @package Vigilante
8 */
9
10 // Prevent direct access
11 if ( ! defined( 'ABSPATH' ) ) {
12 exit;
13 }
14
15 /**
16 * Class Vigilante_Settings
17 *
18 * Handles all plugin settings with defaults, getters and setters
19 */
20 class Vigilante_Settings {
21
22 /**
23 * Option name in database
24 */
25 const OPTION_NAME = 'vigilante_options';
26
27 /**
28 * Cached options
29 *
30 * @var array|null
31 */
32 private $options = null;
33
34 /**
35 * Default options structure
36 *
37 * @var array
38 */
39 private $defaults;
40
41 /**
42 * Constructor
43 */
44 public function __construct() {
45 $this->defaults = $this->get_default_options();
46 }
47
48 /**
49 * Get all default options
50 *
51 * @return array Complete default options array
52 */
53 public function get_default_options() {
54 return array(
55 // Module toggles - 8 modules that match tabs
56 'modules' => array(
57 'firewall' => true,
58 'security_headers' => true,
59 'login_security' => true,
60 'rest_api_security'=> true,
61 'user_security' => true,
62 'wp_hardening' => true,
63 'file_integrity' => true,
64 'activity_log' => true,
65 ),
66
67 // Firewall settings (includes htaccess, rate limiting, file protection)
68 'firewall' => array(
69 // Request filtering (PHP-based)
70 'block_bad_query_strings' => true,
71 'block_sql_injection' => true,
72 'block_xss_attacks' => true,
73 'block_file_inclusion' => true,
74 'block_directory_traversal' => true,
75
76 // Bot protection
77 'block_bad_bots' => true,
78 'block_empty_user_agent' => false,
79
80 // Rate limiting
81 'rate_limiting' => array(
82 'enabled' => true,
83 'requests_per_minute' => 120,
84 'block_duration' => 300,
85 'progressive' => false,
86 'max_block_duration' => 86400,
87 ),
88
89 // IP management
90 'ip_whitelist' => array(),
91 'ip_blacklist' => array(),
92
93 // Proxy / CDN: forwarded header to trust for the visitor IP.
94 // Empty = trust only REMOTE_ADDR (the real connection, unspoofable).
95 'trusted_proxy_header' => '',
96
97 // User-Agent management
98 'ua_whitelist' => array(),
99 'ua_blacklist' => array(),
100
101 // File protection (htaccess-based)
102 'disable_directory_browsing' => true,
103 'protect_wp_config' => true,
104 'protect_wp_includes' => true,
105 'protect_uploads_php' => true,
106 'protect_sensitive_files' => true,
107 // Off by default — only safe when host has a real server-side cron job
108 // calling wp-cron.php; otherwise scheduled tasks stop running silently.
109 'protect_wp_cron' => false,
110 'block_php_in_plugins' => false,
111 'block_php_in_themes' => false,
112 'limit_http_methods' => true,
113 // All methods needed for WordPress core, Gutenberg, REST API, and page builders
114 'allowed_http_methods' => array( 'GET', 'POST', 'HEAD', 'OPTIONS', 'PUT', 'PATCH', 'DELETE' ),
115 ),
116
117 // Security Headers settings (includes HTTPS enforcer)
118 'security_headers' => array(
119 'enabled' => true,
120
121 // Basic headers
122 'x_frame_options' => 'SAMEORIGIN',
123 'x_content_type_options' => true,
124 'referrer_policy' => 'strict-origin-when-cross-origin',
125
126 // HSTS
127 'hsts' => array(
128 'enabled' => false,
129 'max_age' => 31536000,
130 'include_subdomains' => false,
131 'preload' => false,
132 ),
133
134 // Permissions Policy
135 'permissions_policy' => array(
136 'enabled' => true,
137 'geolocation' => '()',
138 'microphone' => '()',
139 'camera' => '()',
140 'payment' => '(self)',
141 'usb' => '()',
142 ),
143
144 // CSP - WordPress/Gutenberg compatible defaults
145 // Note: blob: is required in frame-src and worker-src for the block editor,
146 // and in connect-src for the client-side media processing WordPress 7.1
147 // introduced: @wordpress/vips puts its WebAssembly binary in a blob: URL and
148 // fetches it, and fetch() is governed by connect-src, where 'self' does not
149 // cover blob:. Without it the editor cannot process images before upload.
150 'csp' => array(
151 'enabled' => true,
152 'report_only' => false,
153 'report_uri' => '',
154 'directives' => array(
155 'default-src' => "'self'",
156 'script-src' => "'self' 'unsafe-inline' 'unsafe-eval' https:",
157 'style-src' => "'self' 'unsafe-inline' https:",
158 'img-src' => "'self' data: https: blob:",
159 'font-src' => "'self' data: https:",
160 'connect-src' => "'self' https: wss: blob:",
161 'media-src' => "'self' https: blob:",
162 'frame-src' => "'self' https: blob:",
163 'frame-ancestors' => "'self'",
164 'base-uri' => "'self'",
165 'form-action' => "'self' https:",
166 'object-src' => "'none'",
167 'worker-src' => "'self' blob:",
168 'upgrade-insecure-requests'=> true,
169 ),
170 ),
171
172 // Cross-origin policies
173 'cross_origin_policies' => array(
174 'embedder_policy' => 'unsafe-none',
175 'opener_policy' => 'same-origin-allow-popups',
176 'resource_policy' => 'cross-origin',
177 ),
178
179 // HTTPS Enforcer (moved from separate module)
180 //
181 // force_https rewrites siteurl/home to https on activation, so it
182 // ships off: a site without working HTTPS would end up pointing at
183 // an address that does not answer. It is an opt-in decision per
184 // site, made from the Security Headers tab. Sites whose URLs a
185 // previous version already rewrote keep them; nothing reverts them.
186 'force_https' => false,
187 // Off by default for the same reason as force_https above: the
188 // plugin does not decide that a site is on HTTPS. It only
189 // redirects when the site's own home URL already says https, so
190 // shipping it on was harmless in practice, but it is still a
191 // decision that belongs to the site owner, not to us. Sites that
192 // already have it on keep it.
193 'redirect_http_to_https' => false,
194 // Rewrites http:// URLs of this same site to https://, and only
195 // on a site already served over HTTPS, so it cannot reach a third
196 // party and cannot make a resource fail. It still ships off: a
197 // setting whose own description says it rewrites http to https
198 // does not belong in the factory configuration of a plugin that
199 // deliberately does not decide whether a site is on HTTPS. Every
200 // https-related setting here is the owner's call, and this one is
201 // one click away for anyone who has just migrated and wants their
202 // old content rewritten.
203 'fix_mixed_content' => false,
204 // The Content-Security-Policy directive that tells the browser to
205 // upgrade every http:// request, including the ones pointing at
206 // other people's servers. If any of those has no HTTPS the
207 // resource simply stops loading, so this is the one piece of
208 // mixed content handling that can break a page, and it is off by
209 // default like everything else here that forces HTTPS. It used to
210 // ride along with fix_mixed_content with no way to separate them.
211 'upgrade_insecure_requests' => false,
212
213 // Server Protection (moved from firewall in v2.0.0)
214 'hide_server_signature' => true,
215 'remove_fingerprinting_headers' => true,
216 ),
217
218 // Login Security settings
219 'login_security' => array(
220 'enabled' => true,
221 'max_attempts' => 5,
222 'lockout_duration' => 1800,
223 'lockout_increment' => true,
224 'max_lockout_duration' => 86400,
225 'hide_login_errors' => true,
226 // XML-RPC se movio a wp_hardening en la 2.9.7; lo resuelve
227 // Vigilante_Comment_Security::resolve_xmlrpc_mode(), que
228 // sustituye a las dos casillas anteriores (disable_xmlrpc y
229 // disable_xmlrpc_pingback), que podian estar activas a la vez y
230 // contradecirse. A proposito NO se declara aqui ningun default: si se
231 // declarara, el merge con los defaults lo rellenaria siempre y taparia el
232 // respaldo que lee el ajuste antiguo de los sitios que aun no han vuelto a
233 // guardar la pestana. Sin nada guardado, el resolutor devuelve 'full', que
234 // es lo que hacia el default anterior.
235 'disable_application_passwords' => false,
236 'notify_on_lockout' => false,
237 'notify_on_admin_login' => false,
238 'ip_whitelist' => array(),
239 'custom_login_url' => '',
240 'notify_on_login_url_change' => true,
241 // Two-Factor Authentication
242 'two_factor' => array(
243 'enabled' => false,
244 'method' => 'email',
245 'enforced_roles' => array( 'administrator', 'editor' ),
246 'excluded_users' => array(),
247 'remember_device_days' => 30,
248 'allow_remember_device' => false,
249 'code_expiry_minutes' => 10,
250 'max_attempts' => 3,
251 'email_from_name' => '',
252 'notify_on_enable' => true,
253 'grace_period_days' => 3,
254 ),
255 ),
256
257 // REST API Security settings
258 'rest_api_security' => array(
259 'enabled' => true,
260 'mode' => 'selective',
261 'block_user_enumeration' => true,
262 'disable_jsonp' => true,
263 // Empty by default: /wp/v2/users used to live here, but that
264 // duplicated the dedicated "Block user enumeration" toggle.
265 // Now there is one knob = one behaviour. If you want to
266 // protect additional endpoints in selective mode, add them
267 // explicitly via this setting (or via a filter).
268 'protected_endpoints' => array(),
269 'allowed_public_endpoints' => array(
270 '/wp/v2/posts',
271 '/wp/v2/pages',
272 '/wp/v2/categories',
273 '/wp/v2/tags',
274 '/oembed/',
275 ),
276 'plugin_compatibility' => array(
277 'woocommerce' => true,
278 'contact_form_7' => true,
279 'elementor' => true,
280 ),
281 ),
282
283 // User Security settings
284 'user_security' => array(
285 'enabled' => true,
286 'block_insecure_usernames'=> true,
287 'insecure_usernames' => array(
288 'admin', 'administrator', 'user', 'test', 'guest',
289 'info', 'root', 'adm', 'sysadmin', 'support',
290 'webmaster', 'master', 'owner', 'manager', 'demo',
291 ),
292 'block_author_scanning' => true,
293 'force_strong_passwords' => true,
294 'min_password_length' => 12,
295
296 // Granular password policy. Applies only while
297 // force_strong_passwords is on. The defaults follow current
298 // guidance (NIST SP 800-63B): what makes a password weak is being
299 // guessable, not lacking a symbol, and composition rules push
300 // people towards predictable substitutions and towards writing
301 // the password down. So out of the box only the two rules that
302 // block genuinely guessable passwords are on, and the four
303 // character-class requirements ship off for anyone to turn on.
304 // Existing sites keep whatever they have stored.
305 // affected_roles empty = all roles.
306 'password_policy' => array(
307 'require_uppercase' => false,
308 'require_lowercase' => false,
309 'require_number' => false,
310 'require_special' => false,
311 'block_common' => true,
312 'block_username' => true,
313 'affected_roles' => array(),
314 ),
315
316 'prevent_display_name_login_match' => true,
317
318 // Admin monitoring
319 // The two alerts that report someone gaining power ship on: a
320 // new administrator and a role being raised are the signature of
321 // an account takeover, and they are rare enough not to be noise.
322 // The other two are ordinary admin housekeeping and stay opt-in.
323 'admin_monitoring' => array(
324 'alert_new_admin' => true,
325 'alert_admin_email_change' => false,
326 'alert_permission_elevation' => true,
327 'alert_admin_password_change' => false,
328 ),
329
330 // Force password reset (no options, uses native WordPress flow)
331
332 // Registration approval
333 'registration_approval' => array(
334 'enabled' => false,
335 'notify_admin' => false,
336 'auto_reject_days' => 0,
337 'affected_roles' => array( 'subscriber' ),
338 ),
339
340 // Session management
341 'session_management' => array(
342 'enabled' => true,
343 'show_in_profile' => true,
344 ),
345
346 // Session limits
347 'session_limits' => array(
348 'enabled' => true,
349 'max_sessions' => 3,
350 'behavior' => 'close_oldest',
351 'exclude_admins' => false,
352 ),
353
354 // Password expiration ships OFF. Forced rotation is no longer
355 // recommended (NIST SP 800-63B advises against it) and it is by
356 // far the biggest source of support here: people locked out mid
357 // task, cron reminders that never arrive, roles nobody meant to
358 // include. The feature stays for anyone who has to comply with a
359 // policy that still demands it, and the Configuration Score keeps
360 // pointing at it, which is what that score is for.
361 'password_expiration' => array(
362 'enabled' => false,
363 'expire_days' => 90,
364 'warning_days' => 14,
365 'affected_roles' => array( 'administrator', 'editor' ),
366 'excluded_users' => array(),
367 'password_history' => 3,
368 'send_reminder' => false,
369 ),
370
371 // Email verification
372 'email_verification' => array(
373 'enabled' => false,
374 'token_expiry_hours' => 24,
375 'allow_resend' => true,
376 'auto_delete_days' => 7,
377 ),
378 ),
379
380 // WordPress Hardening (combines wp-config, comments, feeds, head cleaner)
381 'wp_hardening' => array(
382 'enabled' => true,
383
384 // wp-config security
385 'disallow_file_edit' => true,
386 'disallow_file_mods' => false,
387 // Off by default. This one writes FORCE_SSL_ADMIN into
388 // wp-config.php, and it used to do so on activation with no
389 // check that the site answers over HTTPS at all, which locks the
390 // owner out of their own admin. Forcing HTTPS is an opt-in
391 // decision per site, consistent with force_https and with HSTS,
392 // both of which already ship off.
393 'force_ssl_admin' => false,
394 'wp_debug' => true,
395 // Off by default — only safe when host has a real server-side cron job;
396 // pairs with firewall.protect_wp_cron to block both internal triggering
397 // (this constant) and external HTTP abuse (the .htaccess rule).
398 'disable_wp_cron' => false,
399
400 // Comment security
401 'disable_pingbacks' => true,
402 'disable_trackbacks' => true,
403 'require_comment_moderation' => true,
404 'close_old_comments' => false,
405 'close_comments_after_days' => 30,
406 'honeypot_comments' => true,
407
408 // Head cleaner
409 'remove_wp_generator' => true,
410 'remove_wp_version_assets' => false,
411 'remove_rsd_link' => true,
412 'remove_wlw_manifest' => true,
413 'remove_shortlink' => true,
414 'remove_rest_api_link' => false,
415
416 // Feed manager
417 'disable_feeds' => false,
418 'disable_if_no_content' => true,
419 'remove_feed_version' => true,
420 ),
421
422 // File Integrity settings
423 'file_integrity' => array(
424 'enabled' => true,
425 'scan_core' => true,
426 'scan_plugins' => true,
427 'scan_themes' => true,
428 'scan_uploads' => true,
429 'scan_critical_config' => true,
430 'check_closed_plugins' => true,
431 'auto_scan' => true,
432 'scan_frequency' => 'daily',
433 'notify_level' => 'suspicious_only',
434 'instant_alert' => false,
435 'excluded_paths' => array(
436 'wp-content/cache',
437 ),
438 'excluded_extensions' => array(
439 // Translations (regenerated per-locale, never in checksums).
440 '.po', '.mo', '.pot',
441 // Binary images (cosmetic, not executable; often rewritten by image-optimizer plugins).
442 '.jpg', '.jpeg', '.png', '.gif', '.ico', '.webp', '.avif',
443 // Stylesheets: frequently rewritten by themes and optimizer
444 // plugins, a common source of post-update false positives.
445 // Strict-mode users can remove it (CSS injection is still a
446 // vector, defended primarily by CSP in the headers module).
447 '.css',
448 ),
449 ),
450
451 // Activity Log settings
452 'activity_log' => array(
453 'retention_days' => 30,
454 'max_entries' => 10000,
455 'log_logins' => true,
456 'log_failed_logins' => true,
457 'log_user_changes' => true,
458 'log_post_changes' => true,
459 'log_plugin_changes' => true,
460 'log_theme_changes' => true,
461 'log_option_changes' => false,
462 'log_file_changes' => true,
463 'log_comments' => true,
464 'log_media' => true,
465 'excluded_users' => array(),
466 'excluded_ips' => array(),
467 'tracked_options' => array(),
468 ),
469
470 // Backup settings
471 'backup' => array(
472 'keep_backups' => 5,
473 ),
474
475 // Notification settings (centralized recipients for all admin emails)
476 'email' => array(
477 'send_to_admin_email' => true,
478 'additional_recipients' => array(),
479 'send_deactivation_email' => true,
480 ),
481
482 // Advanced settings
483 'advanced' => array(
484 'remove_readme' => true,
485 'remove_license' => true,
486 ),
487
488 // Security Analyzer (v2.1.0) — on-demand + weekly Security Check
489 'security_analyzer' => array(
490 'weekly_scan_enabled' => true,
491 'email_on_regression' => false,
492 ),
493
494 // Audit Alerts (v2.8.0) — alerting layer on top of Security Audit.
495 // The engine subscribes to logged events and only runs when the
496 // Security Audit (activity_log) module is enabled. Opt-in: both
497 // legs start OFF so it never duplicates the per-module emails that
498 // already exist (User Security admin monitoring, Plugin Status...).
499 'audit_alerts' => array(
500 // Shared anti-repeat cooldown (minutes). After an alert, do not
501 // send another about the same thing (same event type for
502 // immediate, same category for threshold) until this passes.
503 // Prevents a flood during a sustained attack.
504 'cooldown_minutes' => 60,
505 // #38 Immediate alerts: selected event types email right away.
506 'immediate' => array(
507 'enabled' => false,
508 // Alert on any logged event at or above this severity. A new
509 // admin, a closed plugin or a privilege escalation are all
510 // logged as "critical", so "critical" already covers them.
511 'min_severity' => 'critical', // 'critical' | 'warning'
512 ),
513 // #10 Threshold alerts: N events of a category within a window.
514 'threshold' => array(
515 'enabled' => false,
516 'window' => '1h', // 30m | 1h | 6h | 24h
517 // Per-category trigger counts (warning/critical events only);
518 // 0 disables that category. Covers every event type that can
519 // log a warning or critical. Keep in sync with
520 // Vigilante_Audit_Alerts::category_labels().
521 'categories' => array(
522 'firewall' => 50,
523 'login' => 20,
524 'user' => 5,
525 'plugin' => 0,
526 'file' => 0,
527 'security' => 0,
528 'system' => 0,
529 'settings' => 0,
530 'theme' => 0,
531 'content' => 0,
532 'comment' => 0,
533 'media' => 0,
534 ),
535 ),
536 ),
537 );
538 }
539
540 /**
541 * Get all options (merged with defaults)
542 *
543 * @return array All options
544 */
545 public function get_all_options() {
546 if ( null === $this->options ) {
547 $saved = get_option( self::OPTION_NAME, array() );
548 $this->options = $this->array_merge_deep( $this->get_default_options(), $saved );
549 }
550 return $this->options;
551 }
552
553 /**
554 * Deep merge arrays
555 *
556 * @param array $defaults Default values.
557 * @param array $saved Saved values.
558 * @return array Merged array.
559 */
560 private function array_merge_deep( $defaults, $saved ) {
561 $result = $defaults;
562
563 foreach ( $saved as $key => $value ) {
564 if ( is_array( $value ) && isset( $result[ $key ] ) && is_array( $result[ $key ] ) ) {
565 $result[ $key ] = $this->array_merge_deep( $result[ $key ], $value );
566 } else {
567 $result[ $key ] = $value;
568 }
569 }
570
571 return $result;
572 }
573
574 /**
575 * Get a specific section
576 *
577 * @param string $section Section name.
578 * @return array Section options.
579 */
580 public function get_section( $section ) {
581 $options = $this->get_all_options();
582 return isset( $options[ $section ] ) ? $options[ $section ] : array();
583 }
584
585 /**
586 * Get a specific option
587 *
588 * @param string $section Section name.
589 * @param string $key Option key.
590 * @param mixed $default Default value.
591 * @return mixed Option value.
592 */
593 public function get_option( $section, $key, $default = null ) {
594 $options = $this->get_all_options();
595
596 if ( isset( $options[ $section ][ $key ] ) ) {
597 return $options[ $section ][ $key ];
598 }
599
600 return $default;
601 }
602
603 /**
604 * Check if a module is enabled
605 *
606 * @param string $module Module name.
607 * @return bool Whether module is enabled.
608 */
609 public function is_module_enabled( $module ) {
610 $options = $this->get_all_options();
611 return ! empty( $options['modules'][ $module ] );
612 }
613
614 /**
615 * Save options
616 *
617 * @param array $options Options to save.
618 * @return bool Success status.
619 */
620 public function save_options( $options ) {
621 $this->options = null;
622 return update_option( self::OPTION_NAME, $options );
623 }
624
625 /**
626 * Update a section
627 *
628 * @param string $section Section name.
629 * @param array $data Section data.
630 * @return bool Success status.
631 */
632 public function update_section( $section, $data ) {
633 $options = get_option( self::OPTION_NAME, array() );
634 $options[ $section ] = $data;
635 $this->options = null;
636 return update_option( self::OPTION_NAME, $options );
637 }
638
639 /**
640 * Update multiple sections at once
641 *
642 * @param array $sections Associative array of section => data.
643 * @return bool Success status.
644 */
645 public function update_options( $sections ) {
646 $options = get_option( self::OPTION_NAME, array() );
647
648 foreach ( $sections as $section => $data ) {
649 $options[ $section ] = $data;
650 }
651
652 $this->options = null;
653 return update_option( self::OPTION_NAME, $options );
654 }
655
656 /**
657 * Clear the options cache
658 */
659 public function clear_cache() {
660 $this->options = null;
661 wp_cache_delete( self::OPTION_NAME, 'options' );
662 }
663
664 /**
665 * Whether this context is allowed to write the files a network shares
666 *
667 * wp-config.php and the root .htaccess are single files for the whole
668 * network, while Vigilant's settings are per site. Without a gate, every
669 * save, activation and deactivation from any site rewrites those files from
670 * that site's own options, so the last one to save wins and silently undoes
671 * the rest. Measured on a real network: the main site enables "disable file
672 * editing", a subsite admin presses Save on their own screen without
673 * touching it, and the constant disappears from wp-config.php while the main
674 * site's screen keeps showing the box ticked.
675 *
676 * So on a network only the main site decides, and only a network
677 * administrator. WP-CLI on the main site counts too: there is no user to ask
678 * there, but the site is the right one, and a network admin running
679 * `wp plugin activate --network` expects the files to be written.
680 *
681 * On a single site this is always true and nothing changes.
682 *
683 * @since 2.9.8
684 *
685 * @return bool
686 */
687 /**
688 * Whether this site is the one that owns the files a network shares.
689 *
690 * Pure site identity, with no capability in it, and that is the point. A
691 * refresh that Vigilant performs by itself, such as rewriting its own
692 * .htaccess block after an update, decides nothing: the content comes from
693 * this site's own options whoever happens to be visiting. What must not
694 * happen is a *different* site writing the shared file, and that is exactly
695 * what this answers.
696 *
697 * can_write_shared_files() below adds the capability on top, and is the
698 * right question for anything a person initiates from a settings screen.
699 *
700 * @since 2.10.1
701 * @return bool
702 */
703 public static function owns_shared_files() {
704 // One wp-config.php and one root .htaccess per installation, even with
705 // several networks in it: is_main_site() alone is true on the main site
706 // of every network. Since 2.11.8, found by the audit of the network.
707 return ! is_multisite() || ( is_main_site() && is_main_network() );
708 }
709
710 public static function can_write_shared_files() {
711 if ( ! is_multisite() ) {
712 return true;
713 }
714
715 // See owns_shared_files(): the main site of a secondary network, and
716 // its network administrator, do not own the installation's files.
717 if ( ! is_main_site() || ! is_main_network() ) {
718 return false;
719 }
720
721 // WP-CLI with nobody logged in: there is no user to ask, and the site is
722 // the right one, so a network admin running `wp plugin activate --network`
723 // gets the files written. With a user set (wp --user=...) the capability
724 // is checked like anywhere else, so the gate cannot be side-stepped by
725 // running as a subsite administrator.
726 if ( defined( 'WP_CLI' ) && WP_CLI && ! get_current_user_id() ) {
727 return true;
728 }
729
730 return current_user_can( 'manage_network_options' );
731 }
732
733 /**
734 * The one message shown wherever a shared-file setting is out of reach
735 *
736 * Deliberately a single string reused by every section, instead of one per
737 * section: it says the same thing everywhere and there is no reason to make
738 * translators write it four times.
739 *
740 * @since 2.9.8
741 *
742 * @return string
743 */
744 public static function get_shared_files_notice() {
745 return __( 'These settings are written to wp-config.php and .htaccess, files the whole network shares. So that one site cannot overwrite another, they are managed from the main site of the network by a network administrator.', 'vigilante' );
746 }
747
748 /**
749 * Apply the tweaks a brand new installation gets on top of the raw defaults
750 *
751 * A few keys are deliberately missing from get_default_options() because
752 * declaring them would break something else. XML-RPC is the one case today:
753 * declaring wp_hardening.xmlrpc_mode would make the defaults merge fill it in
754 * always and hide the fallback that reads the old pair of settings on sites
755 * that have not re-saved the tab. With nothing stored the resolver answers
756 * 'full', which blocks XML-RPC completely, and that is not what we want a new
757 * site to get.
758 *
759 * Everything that seeds a clean configuration has to run this: the activation
760 * hook, the per-section reset and the global reset to defaults. Otherwise the
761 * defaults you get by pressing a button are not the defaults you get by
762 * installing the plugin, which is exactly what happened until 2.9.8.
763 *
764 * @since 2.9.8
765 *
766 * @param array $options Options array to adjust.
767 * @return array
768 */
769 public static function apply_install_tweaks( $options ) {
770 if ( ! isset( $options['wp_hardening'] ) || ! is_array( $options['wp_hardening'] ) ) {
771 $options['wp_hardening'] = array();
772 }
773
774 $options['wp_hardening']['xmlrpc_mode'] = 'pingback';
775
776 return $options;
777 }
778
779 /**
780 * Keys that hold what the site owner typed in, never wiped by a restore
781 *
782 * Putting the security posture back to its defaults is one thing; deleting
783 * an IP whitelist, the secret login address, the two factor setup or the
784 * addresses that receive the alerts is another, and nobody presses a button
785 * called "restore defaults" expecting that. Both the Standard preset and the
786 * two reset buttons leave these alone.
787 *
788 * @since 2.9.8
789 *
790 * @return array<string,string[]>
791 */
792 public static function get_user_data_keys() {
793 return array(
794 'firewall' => array( 'ip_whitelist', 'ip_blacklist', 'ua_whitelist', 'ua_blacklist', 'trusted_proxy_header' ),
795 'login_security' => array( 'ip_whitelist', 'custom_login_url', 'two_factor' ),
796 'user_security' => array( 'insecure_usernames' ),
797 'file_integrity' => array( 'excluded_paths', 'excluded_extensions' ),
798 'email' => array( 'additional_recipients' ),
799 );
800 }
801
802 /**
803 * Settings whose only effect is written to a file the network shares
804 *
805 * true for a whole section, or the list of keys inside it. Used to keep a
806 * subsite from resetting settings it does not control: the file is written
807 * from the main site, so resetting the local copy would only make the two
808 * disagree.
809 *
810 * Note this is not every setting that reaches .htaccess. Blocking bad bots
811 * or empty user agents also runs in PHP, per site, so those stay editable on
812 * a subsite: the PHP half protects that site and the .htaccess half is
813 * refused, leaving the main site's rules standing. On the main site they
814 * are locked too, see get_main_site_file_settings().
815 *
816 * The PHP blocks for plugins and themes have no field on the settings
817 * screen, but an imported file carries them, and readme.html and
818 * license.txt are removed from the root the whole network shares.
819 *
820 * @since 2.9.8
821 *
822 * @return array<string,true|string[]>
823 */
824 public static function get_shared_file_settings() {
825 return array(
826 'security_headers' => true,
827 'wp_hardening' => array( 'disallow_file_edit', 'disallow_file_mods', 'force_ssl_admin', 'force_ssl_login', 'wp_debug', 'disable_wp_cron' ),
828 'firewall' => array( 'disable_directory_browsing', 'protect_wp_config', 'protect_wp_includes', 'protect_uploads_php', 'protect_sensitive_files', 'protect_wp_cron', 'limit_http_methods', 'block_php_in_plugins', 'block_php_in_themes' ),
829 'advanced' => array( 'remove_readme', 'remove_license' ),
830 );
831 }
832
833 /**
834 * Settings the shared files are built from that also act on the site storing them
835 *
836 * get_shared_file_settings() lists what does nothing but end up in a shared
837 * file. These do both: blocking bad bots and bad query strings, the visitor
838 * IP detection and the two whitelists run in PHP for the site that stores
839 * them, and on the main site of a network they are also what the .htaccess
840 * rules of every site are generated from; the three writing module switches
841 * (firewall, security_headers, wp_hardening) decide whether the .htaccess
842 * blocks and the wp-config.php constants exist at all.
843 *
844 * Since 2.11.8 it also locks what decides whether the shared files are
845 * WATCHED, not built: the File Integrity module and its scan_critical_config
846 * switch. On the main site the critical-file scan is the network's canary
847 * for a change to wp-config.php or the root .htaccess, which only a network
848 * administrator can approve, so a main-site administrator without network
849 * rights must not be able to silence it by turning either one off. Closing
850 * the ignore list and the clear-results button in 2.11.8 left these two as
851 * the remaining routes; found by the audit of the admin surface.
852 *
853 * On a subsite all of them only act on that site, so they stay editable
854 * there (get_locked_file_settings() adds this set only when owns_shared_files()).
855 *
856 * Until 2.11.6 an administrator of the main site without network rights
857 * could change any of them, and the file-only ones too: the write to the
858 * file was refused at that moment, but the value stayed stored, and the
859 * refresh after the next update, or the next save by a network
860 * administrator, published it to the whole network.
861 *
862 * @since 2.11.6
863 * @since 2.11.8 The file_integrity module and scan_critical_config.
864 *
865 * @return array<string,string[]>
866 */
867 public static function get_main_site_file_settings() {
868 return array(
869 'modules' => array( 'firewall', 'security_headers', 'wp_hardening', 'file_integrity' ),
870 'firewall' => array( 'block_bad_bots', 'block_bad_query_strings', 'trusted_proxy_header', 'ip_whitelist', 'ua_whitelist' ),
871 'file_integrity' => array( 'scan_critical_config' ),
872 );
873 }
874
875 /**
876 * Shared file settings the current user may not change on this site
877 *
878 * Empty when the user can write the shared files. Otherwise the file-only
879 * settings on every site, plus, on the main site, the ones it also builds
880 * the shared files from.
881 *
882 * @since 2.11.6
883 *
884 * @return array<string,true|string[]>
885 */
886 public static function get_locked_file_settings() {
887 if ( self::can_write_shared_files() ) {
888 return array();
889 }
890
891 $locked = self::get_shared_file_settings();
892
893 if ( self::owns_shared_files() ) {
894 foreach ( self::get_main_site_file_settings() as $section => $keys ) {
895 if ( ! isset( $locked[ $section ] ) ) {
896 $locked[ $section ] = $keys;
897 } elseif ( is_array( $locked[ $section ] ) ) {
898 $locked[ $section ] = array_values( array_unique( array_merge( $locked[ $section ], $keys ) ) );
899 }
900 }
901 }
902
903 return $locked;
904 }
905
906 /**
907 * Put back the stored value of every shared file setting the user may not change
908 *
909 * For every writer of the whole configuration: saving a tab, importing a
910 * file, applying a preset, restoring the defaults. Hiding a field on the
911 * screen decides nothing, because the request can carry the key anyway. A
912 * key that was not stored is dropped, so its default keeps applying.
913 *
914 * @since 2.11.6
915 *
916 * @param array $options Configuration about to be stored.
917 * @param array $stored Configuration stored now, as read from the option.
918 * @return array
919 */
920 public static function keep_locked_file_settings( $options, $stored ) {
921 $options = is_array( $options ) ? $options : array();
922 $stored = is_array( $stored ) ? $stored : array();
923 $locked = self::get_locked_file_settings();
924
925 if ( ! $locked ) {
926 return $options;
927 }
928
929 /*
930 * A key that was never stored takes its default, which is what it was
931 * worth before. Until 2.11.8 it was dropped instead, and the sanitize
932 * callback of the option filled it in again, but validate_options()
933 * fills a missing module switch with false, not with its default.
934 */
935 $instance = new self();
936 $defaults = $instance->get_default_options();
937
938 foreach ( $locked as $section => $keys ) {
939 if ( true === $keys ) {
940 if ( array_key_exists( $section, $stored ) ) {
941 $options[ $section ] = $stored[ $section ];
942 } elseif ( isset( $defaults[ $section ] ) ) {
943 $options[ $section ] = $defaults[ $section ];
944 } else {
945 unset( $options[ $section ] );
946 }
947 continue;
948 }
949
950 $stored_section = ( isset( $stored[ $section ] ) && is_array( $stored[ $section ] ) ) ? $stored[ $section ] : array();
951 $default_section = ( isset( $defaults[ $section ] ) && is_array( $defaults[ $section ] ) ) ? $defaults[ $section ] : array();
952
953 foreach ( $keys as $key ) {
954 if ( array_key_exists( $key, $stored_section ) ) {
955 $value = $stored_section[ $key ];
956 } elseif ( array_key_exists( $key, $default_section ) ) {
957 $value = $default_section[ $key ];
958 } else {
959 if ( isset( $options[ $section ] ) && is_array( $options[ $section ] ) ) {
960 unset( $options[ $section ][ $key ] );
961 }
962 continue;
963 }
964
965 if ( ! isset( $options[ $section ] ) || ! is_array( $options[ $section ] ) ) {
966 $options[ $section ] = array();
967 }
968 $options[ $section ][ $key ] = $value;
969 }
970 }
971
972 return $options;
973 }
974
975 /**
976 * Take a lock kept as a row of the options table, or report that another request holds it
977 *
978 * add_option() cannot be a lock: it runs INSERT ... ON DUPLICATE KEY UPDATE
979 * (wp-includes/option.php:1142 in WP 7.1), so two requests that both find
980 * the option missing both "create" it and both believe they hold it. INSERT
981 * IGNORE creates the row for exactly one of them, which is what core does in
982 * WP_Upgrader::create_lock() (wp-admin/includes/class-wp-upgrader.php:1065).
983 * A lock older than the timeout counts as abandoned, by a fatal error between
984 * taking and releasing it, and only one request takes it over.
985 *
986 * @since 2.11.8
987 *
988 * @param string $name Option name of the lock, in the current site's table.
989 * @param int $timeout Seconds after which a held lock counts as abandoned.
990 * @return bool True if this request now holds the lock.
991 */
992 public static function acquire_option_lock( $name, $timeout ) {
993 global $wpdb;
994
995 // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- an atomic lock needs INSERT IGNORE, which the options API does not offer; same query as WP_Upgrader::create_lock().
996 if ( $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO {$wpdb->options} ( option_name, option_value, autoload ) VALUES ( %s, %s, 'no' )", $name, (string) time() ) ) ) {
997 wp_cache_delete( $name, 'options' );
998 return true;
999 }
1000
1001 // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- the lock row as stored right now, not a cached copy.
1002 $held = $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s", $name ) );
1003
1004 if ( null === $held || ( time() - (int) $held ) < $timeout ) {
1005 return false;
1006 }
1007
1008 // Abandoned: the delete only matches the value that was read, and only one
1009 // request wins the insert that follows.
1010 // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- removes an abandoned lock row.
1011 $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name = %s AND option_value = %s", $name, $held ) );
1012
1013 // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- same atomic insert as above.
1014 return (bool) $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO {$wpdb->options} ( option_name, option_value, autoload ) VALUES ( %s, %s, 'no' )", $name, (string) time() ) );
1015 }
1016
1017 /**
1018 * Release a lock taken with acquire_option_lock()
1019 *
1020 * @since 2.11.8
1021 *
1022 * @param string $name Option name of the lock.
1023 */
1024 public static function release_option_lock( $name ) {
1025 global $wpdb;
1026
1027 // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- removes the row acquire_option_lock() inserted.
1028 $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name = %s", $name ) );
1029 wp_cache_delete( $name, 'options' );
1030 }
1031
1032 /**
1033 * Put a configuration back to the defaults without deleting what the owner typed
1034 *
1035 * @since 2.9.8
1036 *
1037 * @param array $current Configuration being replaced.
1038 * @return array
1039 */
1040 public static function get_defaults_preserving_user_data( $current ) {
1041 $instance = new self();
1042 $defaults = self::apply_install_tweaks( $instance->get_default_options() );
1043
1044 foreach ( self::get_user_data_keys() as $section => $keys ) {
1045 foreach ( $keys as $key ) {
1046 if ( isset( $current[ $section ] ) && array_key_exists( $key, (array) $current[ $section ] ) ) {
1047 $defaults[ $section ][ $key ] = $current[ $section ][ $key ];
1048 }
1049 }
1050 }
1051
1052 return $defaults;
1053 }
1054
1055 /**
1056 * The values the Standard preset applies
1057 *
1058 * Standard is the configuration a new installation gets, with every module
1059 * on. It is built from the defaults rather than written out by hand, because
1060 * a hand-written copy drifts: until 2.9.8 Standard named a dozen fields and
1061 * left everything else alone, so applying it after Maximum kept Maximum's
1062 * password rules, its administrator alerts, its session limits and its
1063 * password expiry, and the preset that says it applies sensible defaults
1064 * applied almost none of them.
1065 *
1066 * The only thing it does not touch is what the site owner typed in: IP and
1067 * user agent lists, the custom login address, two factor configuration, the
1068 * integrity scan exclusions and the extra notification recipients. Putting
1069 * the security posture back to the defaults is one thing, throwing away
1070 * someone's whitelist is another, and "Reset to Defaults" is right there for
1071 * that.
1072 *
1073 * @since 2.9.8
1074 *
1075 * @return array
1076 */
1077 private function get_standard_preset_values() {
1078 $values = self::apply_install_tweaks( $this->get_default_options() );
1079
1080 foreach ( array_keys( $values['modules'] ) as $module ) {
1081 $values['modules'][ $module ] = true;
1082 }
1083
1084 foreach ( self::get_user_data_keys() as $section => $keys ) {
1085 foreach ( $keys as $key ) {
1086 unset( $values[ $section ][ $key ] );
1087 }
1088 }
1089
1090 unset( $values['user_security']['password_expiration']['excluded_users'] );
1091
1092 return $values;
1093 }
1094
1095 /**
1096 * Merge a preset over a configuration
1097 *
1098 * Not array_replace_recursive(), which is wrong for this in two ways. A list
1099 * of roles in the preset is merged position by position instead of replacing
1100 * the stored one, so applying Standard over Maximum turned the two roles
1101 * Standard expires passwords for into Maximum's five with the first two
1102 * overwritten. And an empty list in the preset clears nothing at all,
1103 * because there is no element to replace with.
1104 *
1105 * So: associative arrays are merged key by key, and lists and scalars are
1106 * replaced outright.
1107 *
1108 * @since 2.9.8
1109 *
1110 * @param array $base Current configuration.
1111 * @param array $overlay Preset values.
1112 * @return array
1113 */
1114 public static function merge_preset( $base, $overlay ) {
1115 foreach ( $overlay as $key => $value ) {
1116 if ( is_array( $value ) && isset( $base[ $key ] ) && is_array( $base[ $key ] ) && ! self::is_list( $value ) ) {
1117 $base[ $key ] = self::merge_preset( $base[ $key ], $value );
1118 continue;
1119 }
1120
1121 $base[ $key ] = $value;
1122 }
1123
1124 return $base;
1125 }
1126
1127 /**
1128 * Whether an array is a plain list (0..n-1 keys)
1129 *
1130 * array_is_list() is PHP 8.1 and this plugin supports 7.4.
1131 *
1132 * @since 2.9.8
1133 *
1134 * @param array $value Array to inspect.
1135 * @return bool
1136 */
1137 private static function is_list( $value ) {
1138 if ( array() === $value ) {
1139 return true;
1140 }
1141
1142 return array_keys( $value ) === range( 0, count( $value ) - 1 );
1143 }
1144
1145 /**
1146 * Get presets with descriptions
1147 *
1148 * @return array Presets configuration.
1149 */
1150 public function get_presets() {
1151 return array(
1152 'standard' => array_merge(
1153 array(
1154 'name' => __( 'Standard', 'vigilante' ),
1155 'description' => __( 'Balanced security suitable for most websites. Enables every module and puts every setting back to the value a new installation gets.', 'vigilante' ),
1156 ),
1157 $this->get_standard_preset_values()
1158 ),
1159
1160 'maximum' => array(
1161 'name' => __( 'Maximum Security', 'vigilante' ),
1162 'description' => __( 'Strictest settings for high-security sites. CSP is set to report-only mode to prevent breaking the admin interface.', 'vigilante' ),
1163 'modules' => array(
1164 'firewall' => true,
1165 'security_headers' => true,
1166 'login_security' => true,
1167 'rest_api_security'=> true,
1168 'user_security' => true,
1169 'wp_hardening' => true,
1170 'file_integrity' => true,
1171 'activity_log' => true,
1172 ),
1173 'firewall' => array(
1174 'block_bad_query_strings' => true,
1175 'block_sql_injection' => true,
1176 'block_xss_attacks' => true,
1177 'block_file_inclusion' => true,
1178 'block_directory_traversal' => true,
1179 'block_bad_bots' => true,
1180 'block_empty_user_agent' => true,
1181 'rate_limiting' => array(
1182 'enabled' => true,
1183 'requests_per_minute' => 60,
1184 'block_duration' => 600,
1185 'progressive' => true,
1186 'max_block_duration' => 86400,
1187 ),
1188 ),
1189 'security_headers' => array(
1190 'x_frame_options' => 'DENY',
1191 // HSTS is intentionally NOT enabled by Maximum: forcing HSTS on a site
1192 // that doesn't have a healthy HTTPS setup (or temporarily falls back to
1193 // HTTP) locks visitors out for the full max_age. Leaving HSTS off keeps
1194 // it as an explicit opt-in decision per site.
1195 'csp' => array(
1196 'enabled' => true,
1197 'report_only' => false,
1198 'directives' => array(
1199 'default-src' => "'self'",
1200 'script-src' => "'self' 'unsafe-inline' 'unsafe-eval'",
1201 'style-src' => "'self' 'unsafe-inline'",
1202 'img-src' => "'self' data: https: blob:",
1203 'font-src' => "'self' data:",
1204 'connect-src' => "'self' https: blob:",
1205 'frame-src' => "'self' blob:",
1206 'frame-ancestors' => "'none'",
1207 'worker-src' => "'self' blob:",
1208 'object-src' => "'none'",
1209 'base-uri' => "'self'",
1210 ),
1211 ),
1212 ),
1213 'rest_api_security' => array(
1214 'mode' => 'authenticated_only',
1215 ),
1216 'login_security' => array(
1217 'max_attempts' => 3,
1218 'lockout_duration' => 3600,
1219 'lockout_increment' => true,
1220 'notify_on_lockout' => true,
1221 'notify_on_admin_login' => true,
1222 ),
1223 'wp_hardening' => array(
1224 'xmlrpc_mode' => 'full',
1225 'disallow_file_edit' => true,
1226 'disallow_file_mods' => true,
1227 // close_old_comments is intentionally NOT touched by Maximum:
1228 // it would unilaterally close discussion on every old post,
1229 // which is a content decision, not a security one.
1230 ),
1231 'user_security' => array(
1232 'prevent_display_name_login_match' => true,
1233 'min_password_length' => 16,
1234 'password_policy' => array(
1235 'require_uppercase' => true,
1236 'require_lowercase' => true,
1237 'require_number' => true,
1238 'require_special' => true,
1239 'block_common' => true,
1240 'block_username' => true,
1241 'affected_roles' => array(),
1242 ),
1243 'admin_monitoring' => array(
1244 'alert_new_admin' => true,
1245 'alert_admin_email_change' => true,
1246 'alert_permission_elevation' => true,
1247 'alert_admin_password_change' => true,
1248 ),
1249 'registration_approval' => array(
1250 'enabled' => true,
1251 'notify_admin' => true,
1252 'auto_reject_days' => 7,
1253 'affected_roles' => array( 'subscriber', 'contributor', 'author', 'editor' ),
1254 ),
1255 'session_limits' => array(
1256 'enabled' => true,
1257 'max_sessions' => 1,
1258 'behavior' => 'close_oldest',
1259 'exclude_admins' => false,
1260 ),
1261 'password_expiration' => array(
1262 'enabled' => true,
1263 'expire_days' => 30,
1264 'warning_days' => 7,
1265 'affected_roles' => array( 'administrator', 'editor', 'author', 'contributor', 'subscriber' ),
1266 'password_history' => 5,
1267 'send_reminder' => true,
1268 ),
1269 'email_verification' => array(
1270 'enabled' => true,
1271 'token_expiry_hours' => 24,
1272 'allow_resend' => true,
1273 'auto_delete_days' => 3,
1274 ),
1275 ),
1276 'file_integrity' => array(
1277 'scan_core' => true,
1278 'scan_plugins' => true,
1279 'scan_themes' => true,
1280 'scan_uploads' => true,
1281 'scan_critical_config' => true,
1282 'auto_scan' => true,
1283 'scan_frequency' => 'daily',
1284 'notify_level' => 'all',
1285 'instant_alert' => true,
1286 ),
1287 // A configuration called Maximum Security that never tells you
1288 // anything happened is half a product, so the audit alerts ship
1289 // on with it. The shared cooldown keeps a sustained attack from
1290 // turning into a flood. Under Attack mode builds on this preset,
1291 // so it inherits them for as long as it is on and gives them back
1292 // when it is switched off.
1293 'audit_alerts' => array(
1294 'immediate' => array(
1295 'enabled' => true,
1296 'min_severity' => 'critical',
1297 ),
1298 'threshold' => array(
1299 'enabled' => true,
1300 ),
1301 ),
1302 'activity_log' => array(
1303 'log_logins' => true,
1304 'log_failed_logins' => true,
1305 'log_user_changes' => true,
1306 'log_post_changes' => true,
1307 'log_plugin_changes' => true,
1308 'log_theme_changes' => true,
1309 'log_option_changes' => true,
1310 'log_file_changes' => true,
1311 'log_comments' => true,
1312 'log_media' => true,
1313 ),
1314 ),
1315 );
1316 }
1317
1318 /**
1319 * Get module labels for display
1320 *
1321 * @return array Module labels.
1322 */
1323 public function get_module_labels() {
1324 return array(
1325 'firewall' => __( 'Firewall', 'vigilante' ),
1326 'security_headers' => __( 'Security Headers', 'vigilante' ),
1327 'login_security' => __( 'Login Security', 'vigilante' ),
1328 'rest_api_security'=> __( 'REST API Security', 'vigilante' ),
1329 'user_security' => __( 'User Security', 'vigilante' ),
1330 'wp_hardening' => __( 'WordPress Hardening', 'vigilante' ),
1331 'file_integrity' => __( 'File Integrity', 'vigilante' ),
1332 'activity_log' => __( 'Security Audit', 'vigilante' ),
1333 );
1334 }
1335
1336 /**
1337 * Get module descriptions for display
1338 *
1339 * @return array Module descriptions.
1340 */
1341 public function get_module_descriptions() {
1342 return array(
1343 'firewall' => __( 'Blocks malicious requests, SQL injection, XSS attacks, and bad bots. Includes rate limiting and file protection.', 'vigilante' ),
1344 'security_headers' => __( 'Adds HTTP security headers like CSP, HSTS, X-Frame-Options. Forces HTTPS and fixes mixed content.', 'vigilante' ),
1345 'login_security' => __( 'Brute force protection, 2FA, login attempt limits, XML-RPC control, and notifications.', 'vigilante' ),
1346 'rest_api_security'=> __( 'Controls REST API access, blocks user enumeration, and protects sensitive endpoints.', 'vigilante' ),
1347 'user_security' => __( 'Blocks insecure usernames, enforces strong passwords, and prevents author scanning.', 'vigilante' ),
1348 'wp_hardening' => __( 'Hardens wp-config.php, manages comments, cleans header output, and controls feeds.', 'vigilante' ),
1349 'file_integrity' => __( 'Scans WordPress core, plugins, and themes for unauthorized changes and suspicious code.', 'vigilante' ),
1350 'activity_log' => __( 'Records user actions, logins, content changes, and security events for security auditing.', 'vigilante' ),
1351 );
1352 }
1353
1354 /**
1355 * Validate options before saving
1356 *
1357 * @param array $input Raw input to validate.
1358 * @return array Validated options.
1359 */
1360 public function validate_options( $input ) {
1361 $validated = array();
1362 $defaults = $this->get_default_options();
1363
1364 // Validate each section that exists in input
1365 foreach ( $input as $section => $data ) {
1366 if ( ! is_array( $data ) ) {
1367 continue;
1368 }
1369
1370 if ( 'modules' === $section ) {
1371 // Validate modules (booleans)
1372 foreach ( $defaults['modules'] as $module => $default_value ) {
1373 $validated['modules'][ $module ] = isset( $data[ $module ] )
1374 ? (bool) $data[ $module ]
1375 : false;
1376 }
1377 } elseif ( isset( $defaults[ $section ] ) ) {
1378 // Validate other sections using generic validator
1379 $validated[ $section ] = $this->validate_section( $data, $defaults[ $section ] );
1380
1381 // The few keys that live outside get_default_options() on
1382 // purpose (see apply_install_tweaks()) survive with their own
1383 // validation, or an import would silently lose them and the
1384 // XML-RPC resolver would fall back to blocking everything.
1385 foreach ( self::undeclared_keys( $section ) as $key => $type ) {
1386 if ( ! array_key_exists( $key, $data ) ) {
1387 continue;
1388 }
1389 if ( 'bool' === $type ) {
1390 $validated[ $section ][ $key ] = (bool) $data[ $key ];
1391 } elseif ( is_array( $type ) && in_array( $data[ $key ], $type, true ) ) {
1392 $validated[ $section ][ $key ] = $data[ $key ];
1393 }
1394 }
1395 }
1396 }
1397
1398 return apply_filters( 'vigilante_validate_options', $validated, $input );
1399 }
1400
1401 /**
1402 * Keys deliberately absent from get_default_options(), with how to validate them
1403 *
1404 * Declaring them as defaults would break the fallback they exist for (see
1405 * apply_install_tweaks()), but the validator still has to know them, or a
1406 * settings import drops them (found in the 2.11.0 cross review).
1407 *
1408 * @since 2.11.0
1409 *
1410 * @param string $section Section name.
1411 * @return array key => 'bool' or list of allowed values.
1412 */
1413 private static function undeclared_keys( $section ) {
1414 $keys = array(
1415 'wp_hardening' => array( 'xmlrpc_mode' => array( 'full', 'pingback', 'none' ) ),
1416 'login_security' => array(
1417 'disable_xmlrpc' => 'bool',
1418 'disable_xmlrpc_pingback' => 'bool',
1419 ),
1420 );
1421
1422 return isset( $keys[ $section ] ) ? $keys[ $section ] : array();
1423 }
1424
1425 /**
1426 * Whether a default value describes a free list rather than a schema
1427 *
1428 * An empty array or sequential numeric keys (an IP whitelist, a list of
1429 * roles) is a list: every entry the user typed is kept. Anything else is a
1430 * schema: only its keys survive validation.
1431 *
1432 * @since 2.11.0
1433 *
1434 * @param array $defaults Default value of a setting.
1435 * @return bool
1436 */
1437 private function is_list_default( $defaults ) {
1438 if ( array() === $defaults ) {
1439 return true;
1440 }
1441
1442 return array_keys( $defaults ) === range( 0, count( $defaults ) - 1 );
1443 }
1444
1445 /**
1446 * Validate a section based on defaults
1447 *
1448 * Since 2.11.0 the result only holds keys the defaults know. The loop that
1449 * used to reincorporate unknown keys "sanitized" meant a settings import
1450 * could merge any key it liked into vigilante_options (S7 of the 28 Aug
1451 * 2026 audit). Lists are the exception, handled first: their entries are
1452 * data, not keys.
1453 *
1454 * @param array $input Input values.
1455 * @param array $defaults Default values.
1456 * @return array Validated values.
1457 */
1458 private function validate_section( $input, $defaults ) {
1459 $validated = array();
1460
1461 if ( $this->is_list_default( $defaults ) ) {
1462 if ( ! is_array( $input ) ) {
1463 return array();
1464 }
1465
1466 $list = array();
1467 foreach ( $input as $value ) {
1468 if ( is_scalar( $value ) ) {
1469 $list[] = sanitize_text_field( (string) $value );
1470 } elseif ( is_array( $value ) ) {
1471 $list[] = map_deep( $value, 'sanitize_text_field' );
1472 }
1473 }
1474
1475 return $list;
1476 }
1477
1478 foreach ( $defaults as $key => $default_value ) {
1479 if ( ! isset( $input[ $key ] ) ) {
1480 $validated[ $key ] = $default_value;
1481 continue;
1482 }
1483
1484 $value = $input[ $key ];
1485
1486 if ( is_bool( $default_value ) ) {
1487 $validated[ $key ] = (bool) $value;
1488 } elseif ( is_int( $default_value ) ) {
1489 $validated[ $key ] = intval( $value );
1490 } elseif ( is_array( $default_value ) ) {
1491 if ( is_array( $value ) ) {
1492 $validated[ $key ] = $this->validate_section( $value, $default_value );
1493 } else {
1494 $validated[ $key ] = $default_value;
1495 }
1496 } else {
1497 $validated[ $key ] = sanitize_text_field( $value );
1498 }
1499 }
1500
1501 // Keys the defaults do not declare are dropped on purpose (S7).
1502
1503 return $validated;
1504 }
1505 }