PluginProbe
Vigilant – 100% Free Security Suite: Firewall, 2FA, Login, Headers, Scanner… / 2.10.0
Vigilant – 100% Free Security Suite: Firewall, 2FA, Login, Headers, Scanner… v2.10.0
3.0.0 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 All 88 releases
vigilante / includes / class-login-security.php

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

1,560 lines 53.4 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Login Security Class
4 *
5 * Handles login protection, brute force prevention and lockouts
6 *
7 * @package Vigilante
8 */
9
10 // Prevent direct access
11 if ( ! defined( 'ABSPATH' ) ) {
12 exit;
13 }
14
15 /**
16 * Class Vigilante_Login_Security
17 *
18 * Manages login security features
19 */
20 class Vigilante_Login_Security {
21
22 /**
23 * Settings instance
24 *
25 * @var Vigilante_Settings
26 */
27 private $settings;
28
29 /**
30 * Database instance
31 *
32 * @var Vigilante_Database
33 */
34 private $database;
35
36 /**
37 * Activity log instance
38 *
39 * @var Vigilante_Activity_Log
40 */
41 private $activity_log;
42
43 /**
44 * Login security options
45 *
46 * @var array
47 */
48 private $options;
49
50 /**
51 * Custom login slug
52 *
53 * @var string
54 */
55 private $custom_login_slug = '';
56
57 /**
58 * Whether the current login error carries a Vigilant-specific code
59 * that must bypass the generic-message mask in hide_login_errors().
60 * Set by detect_specific_login_error() (hooked to wp_login_errors).
61 *
62 * @var bool
63 */
64 private $show_specific_login_error = false;
65
66 /**
67 * Whether we are rendering the login action specifically.
68 *
69 * The login_errors filter that hide_login_errors() masks is fired by
70 * login_header() on every wp-login.php screen (login, register,
71 * lostpassword, resetpass). Only the login action also fires
72 * wp_login_errors, so detect_specific_login_error() runs solely there
73 * and flips this flag. When it stays false the generic mask is skipped,
74 * so registration / lost-password / reset-password keep their real
75 * validation errors instead of "Invalid username or password".
76 *
77 * @var bool
78 */
79 private $in_login_context = false;
80
81 /**
82 * Constructor
83 *
84 * @param Vigilante_Settings $settings Settings instance.
85 * @param Vigilante_Database $database Database instance.
86 * @param Vigilante_Activity_Log $activity_log Activity log instance.
87 */
88 public function __construct( $settings, $database, $activity_log ) {
89 $this->settings = $settings;
90 $this->database = $database;
91 $this->activity_log = $activity_log;
92 $this->options = $settings->get_section( 'login_security' );
93
94 $this->init_hooks();
95 }
96
97 /**
98 * Initialize hooks
99 */
100 private function init_hooks() {
101 // Check lockout before authentication
102 add_filter( 'authenticate', array( $this, 'check_lockout' ), 30, 3 );
103
104 // Track login attempts
105 add_action( 'wp_login_failed', array( $this, 'handle_failed_login' ) );
106 add_action( 'wp_login', array( $this, 'handle_successful_login' ), 10, 2 );
107
108 // Hide login errors
109 if ( ! empty( $this->options['hide_login_errors'] ) ) {
110 add_filter( 'wp_login_errors', array( $this, 'detect_specific_login_error' ), 10, 2 );
111 add_filter( 'login_errors', array( $this, 'hide_login_errors' ) );
112 add_filter( 'shake_error_codes', array( $this, 'remove_shake_errors' ) );
113 }
114
115 // Disable application passwords
116 if ( ! empty( $this->options['disable_application_passwords'] ) ) {
117 add_filter( 'wp_is_application_passwords_available', '__return_false' );
118 }
119
120 // Notify on admin login
121 if ( ! empty( $this->options['notify_on_admin_login'] ) ) {
122 add_action( 'wp_login', array( $this, 'notify_admin_login' ), 10, 2 );
123 }
124
125 // Add lockout info to login form
126 add_action( 'login_form', array( $this, 'show_remaining_attempts' ) );
127
128 // Custom login URL
129 if ( ! empty( $this->options['custom_login_url'] ) ) {
130 $this->init_custom_login();
131 }
132 }
133
134 /**
135 * Initialize custom login URL functionality
136 *
137 * Uses request interception instead of rewrite rules for reliability
138 */
139 private function init_custom_login() {
140 $custom_url = sanitize_title( $this->options['custom_login_url'] );
141
142 if ( empty( $custom_url ) ) {
143 return;
144 }
145
146 // Store custom URL for use in other methods
147 $this->custom_login_slug = $custom_url;
148
149 // Intercept requests early - this is the key hook
150 add_action( 'wp_loaded', array( $this, 'wp_loaded_handler' ) );
151
152 // Filter login URL
153 add_filter( 'login_url', array( $this, 'filter_login_url' ), 10, 3 );
154 add_filter( 'logout_url', array( $this, 'filter_logout_url' ), 10, 2 );
155 add_filter( 'lostpassword_url', array( $this, 'filter_lostpassword_url' ), 10, 2 );
156 add_filter( 'register_url', array( $this, 'filter_register_url' ) );
157
158 // After requesting "lost password", core redirects to wp-login.php?checkemail=confirm
159 // which is blocked by block_wp_login_access (no whitelisted action) and yields a 404.
160 // Send the user to the custom login URL instead so the confirmation message renders.
161 add_filter( 'lostpassword_redirect', array( $this, 'filter_lostpassword_redirect' ) );
162
163 // Block direct wp-login.php access (always when custom URL is set)
164 add_action( 'login_init', array( $this, 'block_wp_login_access' ), 1 );
165
166 // Site URL filter for login form action
167 add_filter( 'site_url', array( $this, 'filter_site_url' ), 10, 4 );
168
169 // Redirect to home after logout instead of wp-login.php
170 add_filter( 'logout_redirect', array( $this, 'filter_logout_redirect' ), 10, 3 );
171
172 // Block wp-admin access for non-logged users - execute immediately
173 $this->block_wp_admin_access();
174
175 // Intercept redirects to wp-login.php from wp-admin and show 404 instead
176 add_filter( 'wp_redirect', array( $this, 'intercept_admin_redirect' ), 1, 2 );
177
178 // Block core's /login and /wp-login.php pretty-URL shortcuts.
179 // Priority 1: must win over redirect_canonical() (10) and
180 // wp_redirect_admin_locations() (1000), which would 302 the
181 // shortcut to wp_login_url() — the hidden URL — leaking the slug.
182 add_action( 'template_redirect', array( $this, 'block_login_shortcuts' ), 1 );
183 }
184
185 /**
186 * Intercept redirects to wp-login.php from wp-admin
187 * Shows 404 instead of redirecting to login
188 *
189 * @param string $location The redirect location.
190 * @param int $status The redirect status code.
191 * @return string
192 */
193 public function intercept_admin_redirect( $location, $status ) {
194
195 // Only intercept if custom login URL is set
196 if ( empty( $this->options['custom_login_url'] ) ) {
197 return $location;
198 }
199
200 // Check if this is a redirect to the login screen. Besides literal
201 // wp-login.php, auth_redirect() targets wp_login_url(), which the
202 // login_url filter has already rewritten to the hidden slug — so a
203 // redirect to the custom login URL must be caught too, or an
204 // anonymous POST to /wp-admin would leak the slug in the Location
205 // header (the login_url filter runs for every wp_login_url() call).
206 if ( strpos( $location, 'wp-login.php' ) === false && ! $this->is_hidden_login_url( $location ) ) {
207 return $location;
208 }
209
210 // Check if the redirect is coming from wp-admin area
211 $request = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
212
213
214 // If accessing wp-admin and being redirected to login, show 404 instead
215 if ( self::is_wp_admin_request() ) {
216 // Don't intercept admin-ajax.php or admin-post.php
217 if ( self::is_open_admin_endpoint() ) {
218 return $location;
219 }
220
221 // Allow whitelisted IPs (e.g. remote managers like MainWP/ManageWP).
222 if ( $this->is_ip_exempt_from_hiding() ) {
223 return $location;
224 }
225
226
227 // Log the attempt
228 if ( $this->activity_log ) {
229 $this->activity_log->log(
230 'login',
231 'hidden_admin_access',
232 __( 'Attempt to access hidden wp-admin', 'vigilante' ),
233 array( 'request_uri' => $request ),
234 'warning'
235 );
236 }
237
238 $this->serve_404();
239 }
240
241 return $location;
242 }
243
244 /**
245 * Whether a URL points at the hidden custom login screen.
246 *
247 * Matches the exact URL, with or without trailing slash, and with a
248 * query string. Prefix-matching the bare slug is deliberately avoided
249 * so a slug like "acceso" does not match "accesorios".
250 *
251 * @since 2.9.3
252 * @param string $url URL to test.
253 * @return bool
254 */
255 private function is_hidden_login_url( $url ) {
256 if ( empty( $this->custom_login_slug ) ) {
257 return false;
258 }
259
260 $hidden = home_url( $this->custom_login_slug . '/' );
261 $bare = untrailingslashit( $hidden );
262
263 return 0 === strpos( $url, $hidden )
264 || $url === $bare
265 || 0 === strpos( $url, $bare . '?' );
266 }
267
268 /**
269 * The request path as sent by the client, query string stripped.
270 *
271 * Unlike get_request_path(), the result is NOT made relative to
272 * home_url(): the admin area can hang from a different path than the
273 * site itself (WP_SITEURL vs WP_HOME), so wp-admin matching needs the
274 * raw path.
275 *
276 * @since 2.9.4
277 * @return string
278 */
279 private static function get_request_uri_path() {
280 $request = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
281
282 if ( '' === $request ) {
283 return '';
284 }
285
286 if ( false !== strpos( $request, '?' ) ) {
287 $request = strstr( $request, '?', true );
288 }
289
290 return untrailingslashit( $request );
291 }
292
293 /**
294 * Whether the current request targets the real wp-admin area.
295 *
296 * Replaces a strpos() for "/wp-admin" over the whole REQUEST_URI. That
297 * test also matched the query string, so /?redirect_to=/wp-admin/ turned
298 * the home page into a 404 and an un-encoded redirect_to broke the hidden
299 * login screen itself; it matched any front-end path merely starting with
300 * those characters (/wp-admin-tips/); and it dragged scanner hits on
301 * non-existent subdirectories (/blog/wp-admin/) into the blocking path,
302 * where they were answered from 'init' instead of by WordPress' own 404.
303 *
304 * Two independent signals, ORed so neither is a single point of failure:
305 * is_admin(), set by the wp-admin bootstrap and immune to filters, and a
306 * path comparison against admin_url() for the rare setup that serves the
307 * admin directory through the front controller. Prefix matching requires
308 * a following slash, the same precaution is_hidden_login_url() takes.
309 *
310 * @since 2.9.4
311 * @return bool
312 */
313 private static function is_wp_admin_request() {
314 if ( is_admin() ) {
315 return true;
316 }
317
318 $path = self::get_request_uri_path();
319
320 if ( '' === $path ) {
321 return false;
322 }
323
324 $admin_path = wp_parse_url( admin_url(), PHP_URL_PATH );
325
326 if ( empty( $admin_path ) ) {
327 return false;
328 }
329
330 $admin_path = untrailingslashit( $admin_path );
331
332 return $path === $admin_path || 0 === strpos( $path, $admin_path . '/' );
333 }
334
335 /**
336 * Whether the request targets an admin entry point that must stay open.
337 *
338 * admin-ajax.php and admin-post.php are used by logged-out visitors on
339 * the front end (WooCommerce fragments, form handlers), so hiding
340 * wp-admin must never touch them. Matched as the exact admin path plus
341 * the file name: the old check ran over the whole REQUEST_URI, so
342 * /wp-admin/edit.php?x=admin-ajax.php slipped past the block, and a bare
343 * basename() would do the same for a PATH_INFO style request such as
344 * /wp-admin/options-general.php/admin-ajax.php. Falls back to the file
345 * name only when admin_url() gives nothing to compare against, so a
346 * broken filter can never take AJAX down for logged-out visitors.
347 *
348 * @since 2.9.4
349 * @return bool
350 */
351 private static function is_open_admin_endpoint() {
352 $path = self::get_request_uri_path();
353
354 if ( '' === $path ) {
355 return false;
356 }
357
358 $endpoints = array( 'admin-ajax.php', 'admin-post.php' );
359 $admin_path = wp_parse_url( admin_url(), PHP_URL_PATH );
360
361 if ( empty( $admin_path ) ) {
362 return in_array( basename( $path ), $endpoints, true );
363 }
364
365 $admin_path = untrailingslashit( $admin_path );
366
367 foreach ( $endpoints as $endpoint ) {
368 if ( $path === $admin_path . '/' . $endpoint ) {
369 return true;
370 }
371 }
372
373 return false;
374 }
375
376 /**
377 * Block access to wp-admin for non-logged users
378 * Shows 404 instead of redirecting to login
379 */
380 public function block_wp_admin_access() {
381 // Only if custom login URL is set
382 if ( empty( $this->options['custom_login_url'] ) ) {
383 return;
384 }
385
386 // Get the request URI
387 $request = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
388
389
390 // Check if accessing wp-admin
391 if ( ! self::is_wp_admin_request() ) {
392 return;
393 }
394
395 // Allow admin-ajax.php and admin-post.php
396 if ( self::is_open_admin_endpoint() ) {
397 return;
398 }
399
400 // Allow if user is logged in
401 if ( is_user_logged_in() ) {
402 return;
403 }
404
405 // Allow POST requests
406 $request_method = isset( $_SERVER['REQUEST_METHOD'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) : '';
407 if ( 'POST' === $request_method ) {
408 return;
409 }
410
411 // Allow whitelisted IPs (e.g. remote managers like MainWP/ManageWP).
412 if ( $this->is_ip_exempt_from_hiding() ) {
413 return;
414 }
415
416
417 // Log the attempt
418 if ( $this->activity_log ) {
419 $this->activity_log->log(
420 'login',
421 'hidden_admin_access',
422 __( 'Attempt to access hidden wp-admin', 'vigilante' ),
423 array( 'request_uri' => $request ),
424 'warning'
425 );
426 }
427
428 $this->serve_404();
429 }
430
431 /**
432 * Handle requests on wp_loaded
433 * This intercepts requests to our custom login URL
434 */
435 public function wp_loaded_handler() {
436 global $pagenow;
437
438 // Get the request path
439 $request = $this->get_request_path();
440
441
442 // Check if accessing our custom login URL
443 if ( $this->is_custom_login_request( $request ) ) {
444
445 // Set flag that we're coming from custom login
446 if ( ! defined( 'VIGILANTE_CUSTOM_LOGIN' ) ) {
447 define( 'VIGILANTE_CUSTOM_LOGIN', true );
448 }
449
450 // Set pagenow to wp-login.php for compatibility
451 $pagenow = 'wp-login.php';
452
453 // Initialize global variables expected by wp-login.php (PHP 8.x strict)
454 // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Required by WordPress core wp-login.php
455 global $user_login, $error;
456 $user_login = '';
457 $error = '';
458
459 // Load the login page
460 require_once ABSPATH . 'wp-login.php';
461 exit;
462 }
463 }
464
465 /**
466 * Block direct access to wp-login.php
467 * Uses login_init hook which fires inside wp-login.php
468 */
469 public function block_wp_login_access() {
470
471 // If we came from our custom login URL, allow access
472 if ( defined( 'VIGILANTE_CUSTOM_LOGIN' ) && VIGILANTE_CUSTOM_LOGIN ) {
473 return;
474 }
475
476 // Allow POST requests (form submissions)
477 $request_method = isset( $_SERVER['REQUEST_METHOD'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) : '';
478 if ( 'POST' === $request_method ) {
479 return;
480 }
481
482 // Allow AJAX requests
483 if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
484 return;
485 }
486
487 // Check for specific allowed actions that need wp-login.php
488 // phpcs:ignore WordPress.Security.NonceVerification.Recommended
489 $action = isset( $_GET['action'] ) ? sanitize_key( $_GET['action'] ) : '';
490 $allowed_actions = array( 'postpass', 'logout', 'rp', 'resetpass', 'confirmaction', 'lostpassword', 'retrievepassword' );
491
492
493 if ( in_array( $action, $allowed_actions, true ) ) {
494 return;
495 }
496
497 // Allow informational query strings that core appends without an action,
498 // e.g. ?checkemail=confirm after a lost-password request and ?password=changed
499 // after a successful reset. These render the corresponding success message
500 // inside wp-login.php and would otherwise 404.
501 // phpcs:ignore WordPress.Security.NonceVerification.Recommended
502 if ( isset( $_GET['checkemail'] ) || isset( $_GET['password'] ) ) {
503 return;
504 }
505
506 // Check if user already logged in - redirect to admin
507 if ( is_user_logged_in() ) {
508 wp_safe_redirect( admin_url() );
509 exit;
510 }
511
512 // Log the attempt
513 if ( $this->activity_log ) {
514 $request = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
515 $this->activity_log->log(
516 'login',
517 'hidden_login_access',
518 __( 'Attempt to access hidden wp-login.php', 'vigilante' ),
519 array( 'request_uri' => $request ),
520 'warning'
521 );
522 }
523
524 // Return 404
525 $this->serve_404();
526 }
527
528 /**
529 * Block WordPress' pretty-URL login shortcuts (/login, /wp-login.php).
530 *
531 * Core's wp_redirect_admin_locations() (template_redirect, priority
532 * 1000) turns a 404 on those paths into wp_redirect( wp_login_url() ).
533 * With a custom login URL active wp_login_url() IS the hidden slug, so
534 * that 302 would hand the secret to anyone typing /login, while /admin
535 * correctly ends in a 404. Runs only when the request is already a 404:
536 * if a real page named "login" exists, core does not redirect either
537 * and this must not interfere.
538 *
539 * @since 2.9.3
540 */
541 public function block_login_shortcuts() {
542 if ( ! is_404() ) {
543 return;
544 }
545
546 $request = strtolower( $this->get_request_path() );
547
548 if ( ! in_array( $request, array( 'login', 'wp-login.php' ), true ) ) {
549 return;
550 }
551
552 if ( $this->activity_log ) {
553 $request_uri = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
554 $this->activity_log->log(
555 'login',
556 'hidden_login_access',
557 __( 'Attempt to access hidden wp-login.php', 'vigilante' ),
558 array( 'request_uri' => $request_uri ),
559 'warning'
560 );
561 }
562
563 $this->serve_404();
564 }
565
566 /**
567 * Get the request path without query string
568 *
569 * @return string
570 */
571 private function get_request_path() {
572 $request = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
573
574 // Remove query string
575 if ( false !== strpos( $request, '?' ) ) {
576 $request = strstr( $request, '?', true );
577 }
578
579 // Get path relative to home URL
580 $home_path = wp_parse_url( home_url(), PHP_URL_PATH );
581 if ( ! empty( $home_path ) ) {
582 $request = str_replace( $home_path, '', $request );
583 }
584
585 // Clean up the path
586 $request = ltrim( $request, '/' );
587 $request = rtrim( $request, '/' );
588
589 return $request;
590 }
591
592 /**
593 * Check if this is a request to our custom login URL
594 *
595 * @param string $request The request path.
596 * @return bool
597 */
598 private function is_custom_login_request( $request ) {
599 return $request === $this->custom_login_slug;
600 }
601
602 /**
603 * Filter the login URL
604 *
605 * @param string $login_url The login URL.
606 * @param string $redirect The redirect URL.
607 * @param bool $force_reauth Whether to force reauth.
608 * @return string
609 */
610 public function filter_login_url( $login_url, $redirect = '', $force_reauth = false ) {
611 $login_url = home_url( $this->custom_login_slug . '/' );
612
613 if ( ! empty( $redirect ) ) {
614 $login_url = add_query_arg( 'redirect_to', rawurlencode( $redirect ), $login_url );
615 }
616
617 if ( $force_reauth ) {
618 $login_url = add_query_arg( 'reauth', '1', $login_url );
619 }
620
621 return $login_url;
622 }
623
624 /**
625 * Filter logout URL
626 *
627 * @param string $logout_url The logout URL.
628 * @param string $redirect The redirect URL.
629 * @return string
630 */
631 public function filter_logout_url( $logout_url, $redirect = '' ) {
632 $args = array( 'action' => 'logout' );
633
634 if ( ! empty( $redirect ) ) {
635 $args['redirect_to'] = rawurlencode( $redirect );
636 }
637
638 $logout_url = add_query_arg( $args, home_url( $this->custom_login_slug . '/' ) );
639 $logout_url = wp_nonce_url( $logout_url, 'log-out' );
640
641 return $logout_url;
642 }
643
644 /**
645 * Filter lost password URL
646 *
647 * @param string $lostpassword_url The lost password URL.
648 * @param string $redirect The redirect URL.
649 * @return string
650 */
651 public function filter_lostpassword_url( $lostpassword_url, $redirect = '' ) {
652 $args = array( 'action' => 'lostpassword' );
653
654 if ( ! empty( $redirect ) ) {
655 $args['redirect_to'] = rawurlencode( $redirect );
656 }
657
658 return add_query_arg( $args, home_url( $this->custom_login_slug . '/' ) );
659 }
660
661 /**
662 * Filter register URL
663 *
664 * @param string $register_url The register URL.
665 * @return string
666 */
667 public function filter_register_url( $register_url ) {
668 return add_query_arg( 'action', 'register', home_url( $this->custom_login_slug . '/' ) );
669 }
670
671 /**
672 * Redirect after a successful lost-password request to the custom login URL
673 *
674 * Without this filter, core sends the user to wp-login.php?checkemail=confirm,
675 * which 404s when the custom login URL is enabled (block_wp_login_access only
676 * whitelists requests with a known action= parameter). Sending the user back
677 * to the custom login URL with the same query string lets wp-login.php render
678 * the "Check your email" confirmation correctly.
679 *
680 * @param string $redirect_to The default redirect URL.
681 * @return string
682 */
683 public function filter_lostpassword_redirect( $redirect_to ) {
684 return add_query_arg( 'checkemail', 'confirm', home_url( $this->custom_login_slug . '/' ) );
685 }
686
687 /**
688 * Filter site_url to replace wp-login.php in login form action
689 *
690 * @param string $url The complete site URL.
691 * @param string $path Path relative to the site URL.
692 * @param string|null $scheme Scheme to give the site URL context.
693 * @param int|null $blog_id Site ID, or null for the current site.
694 * @return string
695 */
696 public function filter_site_url( $url, $path, $scheme, $blog_id ) {
697 if ( 'login_post' === $scheme || 'login' === $scheme ) {
698 if ( strpos( $path, 'wp-login.php' ) !== false ) {
699 $url = str_replace( 'wp-login.php', $this->custom_login_slug . '/', $url );
700 }
701 }
702 return $url;
703 }
704
705 /**
706 * Filter logout redirect to go to home instead of wp-login.php
707 *
708 * @param string $redirect_to The redirect destination URL.
709 * @param string $requested_redirect_to The requested redirect destination URL.
710 * @param WP_User $user The WP_User object for the logged out user.
711 * @return string
712 */
713 public function filter_logout_redirect( $redirect_to, $requested_redirect_to, $user ) {
714 // If no specific redirect requested, go to home page
715 if ( empty( $requested_redirect_to ) || strpos( $redirect_to, 'wp-login.php' ) !== false ) {
716 return home_url( '/' );
717 }
718 return $redirect_to;
719 }
720
721 /**
722 * Show 404 page (full version with theme template)
723 * Use this only when WordPress is fully loaded (login_init, template_redirect, etc.)
724 */
725 private function show_404() {
726
727 global $wp_query;
728
729 // Set 404 status
730 status_header( 404 );
731 nocache_headers();
732
733 // $wp_query always exists by now: wp-settings.php creates it before
734 // 'init' fires, and serve_404() only routes here once 'wp_loaded' has
735 // passed. Earlier versions called wp() when it was missing, a branch
736 // that was never reachable and that misled a performance analysis into
737 // blaming the main query for the cost of the render.
738 if ( isset( $wp_query ) && is_object( $wp_query ) ) {
739 $wp_query->set_404();
740 }
741
742 // Try to get the theme's 404 template
743 $template = get_query_template( '404' );
744
745
746 if ( $template && file_exists( $template ) ) {
747 include $template;
748 exit;
749 }
750
751 // Block themes have no 404.php; resolve their 404 template the same
752 // way core's template-loader does, so those sites also get the
753 // theme's 404 instead of the plain fallback page.
754 if ( function_exists( 'locate_block_template' ) ) {
755 $template = locate_block_template( '', '404', array( '404' ) );
756
757 if ( $template && file_exists( $template ) ) {
758 include $template;
759 exit;
760 }
761 }
762
763 // Fallback to simple 404
764 $this->show_404_simple();
765 }
766
767 /**
768 * Serve the hidden-URL 404 through a single decision point.
769 *
770 * All blocking paths call this helper so the response never diverges by
771 * accident. Rendering a theme template is only safe once 'wp_loaded' has
772 * fired: that is the point the rest of the stack assumes has passed
773 * before any template runs, and WooCommerce for one does not set up the
774 * cart until then. block_wp_login_access() runs at 'login_init' and
775 * block_login_shortcuts() at 'template_redirect', both after 'wp_loaded',
776 * so those keep the themed 404; block_wp_admin_access() runs inside
777 * 'init' and gets the simple page.
778 *
779 * 2.9.3 gated this on 'after_setup_theme', which has already fired by
780 * 'init'. The wp-admin path therefore included the theme's 404.php from
781 * inside 'init' on every blocked request, filling debug.log with
782 * _doing_it_wrong notices and costing a full page render per rejection.
783 *
784 * @since 2.9.3
785 */
786 private function serve_404() {
787 if ( did_action( 'wp_loaded' ) && ! is_admin() ) {
788 $this->show_404();
789 }
790
791 $this->show_404_simple();
792 }
793
794 /**
795 * Show simple 404 page (for early execution before WordPress is fully loaded)
796 * Use this when intercepting requests very early (plugins_loaded, admin init, etc.)
797 */
798 private function show_404_simple() {
799 status_header( 404 );
800 nocache_headers();
801
802 // Use wp_die which is the WordPress standard for early termination
803 wp_die(
804 sprintf(
805 '<h1>%s</h1><p>%s</p><p><a href="%s">%s</a></p>',
806 esc_html__( 'Page not found', 'vigilante' ),
807 esc_html__( 'The page you are looking for does not exist.', 'vigilante' ),
808 esc_url( home_url( '/' ) ),
809 esc_html__( 'Go to homepage', 'vigilante' )
810 ),
811 esc_html__( '404 Not Found', 'vigilante' ),
812 array(
813 'response' => 404,
814 'back_link' => false,
815 )
816 );
817 }
818
819 /**
820 * Check if user is locked out
821 *
822 * @param WP_User|WP_Error|null $user User object or error.
823 * @param string $username Username.
824 * @param string $password Password.
825 * @return WP_User|WP_Error
826 */
827 public function check_lockout( $user, $username, $password ) {
828 // Skip if already error or empty credentials
829 if ( empty( $username ) || empty( $password ) ) {
830 return $user;
831 }
832
833 $ip = $this->database->get_client_ip();
834
835 // Check IP whitelist
836 if ( $this->is_ip_whitelisted( $ip ) ) {
837 return $user;
838 }
839
840 // Check if locked out
841 $lockout = $this->database->is_locked_out( $ip );
842
843 if ( $lockout ) {
844 $remaining = strtotime( $lockout['lockout_until'] ) - time();
845 $minutes = ceil( $remaining / 60 );
846
847 // Log the blocked attempt
848 if ( $this->activity_log ) {
849 $this->activity_log->log(
850 'login',
851 'lockout_blocked',
852 sprintf(
853 /* translators: %s: Username */
854 __( 'Login attempt blocked due to lockout: %s', 'vigilante' ),
855 $username
856 ),
857 array(
858 'ip' => $ip,
859 'username' => $username,
860 'lockout_until' => $lockout['lockout_until'],
861 ),
862 'warning'
863 );
864 }
865
866 return new WP_Error(
867 'vigilante_lockout',
868 sprintf(
869 /* translators: %d: Minutes remaining */
870 __( '<strong>Error</strong>: Too many failed login attempts. Please try again in %d minutes.', 'vigilante' ),
871 $minutes
872 )
873 );
874 }
875
876 return $user;
877 }
878
879 /**
880 * Handle failed login attempt
881 *
882 * @param string $username Username that failed.
883 */
884 public function handle_failed_login( $username ) {
885 // Skip counting if this is a Vigilante-controlled rejection
886 // (pending approval, session limit, email verification, etc.)
887 if ( apply_filters( 'vigilante_skip_failed_login_count', false ) ) {
888 return;
889 }
890
891 $ip = $this->database->get_client_ip();
892
893 // Skip whitelisted IPs
894 if ( $this->is_ip_whitelisted( $ip ) ) {
895 return;
896 }
897
898 // Record the attempt
899 $this->database->record_login_attempt( $ip, $username, 'failed' );
900
901 // Log the attempt
902 if ( $this->activity_log ) {
903 $this->activity_log->log(
904 'login',
905 'failed',
906 sprintf(
907 /* translators: %s: Username */
908 __( 'Failed login attempt for username: %s', 'vigilante' ),
909 $username
910 ),
911 array(
912 'ip' => $ip,
913 'username' => $username,
914 ),
915 'warning'
916 );
917 }
918
919 // Check if should be locked out
920 $this->maybe_lockout( $ip, $username );
921 }
922
923 /**
924 * Check if IP should be locked out
925 *
926 * @param string $ip IP address.
927 * @param string $username Username.
928 */
929 public function maybe_lockout( $ip, $username ) {
930 $max_attempts = absint( $this->options['max_attempts'] ?? 5 );
931 $lockout_duration = absint( $this->options['lockout_duration'] ?? 1800 );
932
933 // Get failed attempts in the last hour
934 $failed_count = $this->database->get_failed_attempt_count( $ip, 60 );
935
936 if ( $failed_count >= $max_attempts ) {
937 // Calculate lockout duration with increment
938 if ( ! empty( $this->options['lockout_increment'] ) ) {
939 $previous_lockouts = $this->get_previous_lockout_count( $ip );
940 $lockout_duration = min(
941 $lockout_duration * pow( 2, $previous_lockouts ),
942 absint( $this->options['max_lockout_duration'] ?? 86400 )
943 );
944 }
945
946 // Set lockout
947 $this->database->set_lockout( $ip, $lockout_duration );
948
949 // Log the lockout
950 if ( $this->activity_log ) {
951 $this->activity_log->log(
952 'login',
953 'lockout',
954 sprintf(
955 /* translators: 1: IP address, 2: Duration in minutes */
956 __( 'IP %1$s locked out for %2$d minutes', 'vigilante' ),
957 $ip,
958 ceil( $lockout_duration / 60 )
959 ),
960 array(
961 'ip' => $ip,
962 'username' => $username,
963 'attempts' => $failed_count,
964 'duration' => $lockout_duration,
965 ),
966 'critical'
967 );
968 }
969
970 // Send notification if enabled
971 if ( ! empty( $this->options['notify_on_lockout'] ) ) {
972 $this->send_lockout_notification( $ip, $username, $failed_count, $lockout_duration );
973 }
974 }
975 }
976
977 /**
978 * Record a failed login attempt (public wrapper)
979 *
980 * Use this method from external modules (like 2FA) to integrate with the lockout system.
981 *
982 * @param string $username Username or identifier.
983 * @param string $context Context for logging (e.g., 'password', '2fa').
984 */
985 public function record_failed_attempt( $username, $context = 'password' ) {
986 $ip = $this->database->get_client_ip();
987
988 // Skip whitelisted IPs
989 if ( $this->is_ip_whitelisted( $ip ) ) {
990 return;
991 }
992
993 // Record the attempt
994 $this->database->record_login_attempt( $ip, $username, 'failed' );
995
996 // Log the attempt
997 if ( $this->activity_log ) {
998 $this->activity_log->log(
999 'login',
1000 'failed',
1001 sprintf(
1002 /* translators: 1: Username, 2: Context (password/2fa) */
1003 __( 'Failed login attempt for %1$s (%2$s verification)', 'vigilante' ),
1004 $username,
1005 $context
1006 ),
1007 array(
1008 'ip' => $ip,
1009 'username' => $username,
1010 'context' => $context,
1011 ),
1012 'warning'
1013 );
1014 }
1015
1016 // Check if should be locked out
1017 $this->maybe_lockout( $ip, $username );
1018 }
1019
1020 /**
1021 * Get remaining attempts before lockout
1022 *
1023 * @return int Remaining attempts, or -1 if whitelisted
1024 */
1025 public function get_remaining_attempts() {
1026 $ip = $this->database->get_client_ip();
1027
1028 if ( $this->is_ip_whitelisted( $ip ) ) {
1029 return -1;
1030 }
1031
1032 $max_attempts = absint( $this->options['max_attempts'] ?? 5 );
1033 $failed_count = $this->database->get_failed_attempt_count( $ip, 60 );
1034
1035 return max( 0, $max_attempts - $failed_count );
1036 }
1037
1038 /**
1039 * Get count of previous lockouts for an IP
1040 *
1041 * @param string $ip IP address.
1042 * @return int
1043 */
1044 private function get_previous_lockout_count( $ip ) {
1045 $transient_key = 'vigilante_lockout_count_' . md5( $ip );
1046 $count = get_transient( $transient_key );
1047
1048 if ( false === $count ) {
1049 $count = 0;
1050 }
1051
1052 // Increment and store
1053 set_transient( $transient_key, $count + 1, DAY_IN_SECONDS );
1054
1055 return $count;
1056 }
1057
1058 /**
1059 * Handle successful login
1060 *
1061 * @param string $user_login Username.
1062 * @param WP_User $user User object.
1063 */
1064 public function handle_successful_login( $user_login, $user ) {
1065 $ip = $this->database->get_client_ip();
1066
1067 // Clear any failed attempts for this IP
1068 $this->database->reset_login_attempts( $ip );
1069
1070 // Log the successful login
1071 if ( $this->activity_log ) {
1072 $this->activity_log->log(
1073 'login',
1074 'success',
1075 sprintf(
1076 /* translators: %s: Username */
1077 __( 'Successful login: %s', 'vigilante' ),
1078 $user_login
1079 ),
1080 array(
1081 'ip' => $ip,
1082 'user_id' => $user->ID,
1083 'role' => implode( ', ', $user->roles ),
1084 ),
1085 'info'
1086 );
1087 }
1088 }
1089
1090 /**
1091 * Detect Vigilant-specific error codes on the login page
1092 *
1093 * Hooked to 'wp_login_errors' (which receives the full WP_Error object,
1094 * unlike 'login_errors' that only sees the rendered message string).
1095 * If any of the codes we recognize is present, sets a flag so that
1096 * hide_login_errors() lets the message through. Matching by code is
1097 * locale-independent — checking the message string would break on
1098 * translated sites because __() returns the translation, not the
1099 * original English text.
1100 *
1101 * @param WP_Error $errors Errors object.
1102 * @param string $redirect_to Redirect URL.
1103 * @return WP_Error
1104 */
1105 public function detect_specific_login_error( $errors, $redirect_to ) {
1106 // wp_login_errors only fires for the login action, so reaching this
1107 // method means we are on the login screen — not register, lost-password
1108 // or reset-password, where masking the message makes no sense.
1109 $this->in_login_context = true;
1110
1111 if ( ! ( $errors instanceof WP_Error ) || ! $errors->has_errors() ) {
1112 return $errors;
1113 }
1114
1115 $allowed_codes = array(
1116 // Login Security
1117 'vigilante_lockout',
1118 // User Security
1119 'vigilante_force_reset',
1120 'pending_approval',
1121 'email_not_verified',
1122 'session_limit_exceeded',
1123 // Two-Factor Email
1124 'no_code',
1125 'code_expired',
1126 'code_used',
1127 // Two-Factor TOTP
1128 'code_reused',
1129 'invalid_format',
1130 'not_configured',
1131 'decrypt_failed',
1132 'invalid_backup',
1133 'no_backup_codes',
1134 'corrupt_data',
1135 );
1136
1137 foreach ( $errors->get_error_codes() as $code ) {
1138 if ( in_array( $code, $allowed_codes, true ) ) {
1139 $this->show_specific_login_error = true;
1140 break;
1141 }
1142 }
1143
1144 return $errors;
1145 }
1146
1147 /**
1148 * Hide login error messages
1149 *
1150 * Only masks errors on the login action. Register, lost-password and
1151 * reset-password share the login_errors filter but must keep their real
1152 * validation messages.
1153 *
1154 * @param string $error Error message.
1155 * @return string
1156 */
1157 public function hide_login_errors( $error ) {
1158 // The login_errors filter is fired by login_header() on every
1159 // wp-login.php screen, not just the login form. On register,
1160 // lost-password and reset-password the generic "Invalid username or
1161 // password" is meaningless, so only mask when we are actually on the
1162 // login action (detect_specific_login_error, hooked to the
1163 // login-only wp_login_errors filter, sets this flag).
1164 if ( ! $this->in_login_context ) {
1165 return $error;
1166 }
1167
1168 // Primary check: a recognized Vigilant error code was seen on the
1169 // wp_login_errors filter — let the message through verbatim.
1170 if ( $this->show_specific_login_error ) {
1171 return $error;
1172 }
1173
1174 // Fallback: English string match. Kept for cases where the message
1175 // arrives without going through wp_login_errors (e.g. a third-party
1176 // plugin filtering 'login_errors' directly), and as a safety net for
1177 // any allowed code we may have missed in detect_specific_login_error().
1178 // Note: this fallback won't match on translated sites — the
1179 // code-based check above is the locale-safe path.
1180 $allowed_patterns = array(
1181 'vigilante_lockout',
1182 'Account pending',
1183 'pending_approval',
1184 'email_not_verified',
1185 'verify your email',
1186 'session_limit',
1187 'too many active',
1188 'verification code',
1189 'authenticator app',
1190 'two-factor',
1191 'grace period',
1192 'Password reset required',
1193 );
1194
1195 foreach ( $allowed_patterns as $pattern ) {
1196 if ( stripos( $error, $pattern ) !== false ) {
1197 return $error;
1198 }
1199 }
1200
1201 return __( '<strong>Error</strong>: Invalid username or password.', 'vigilante' );
1202 }
1203
1204 /**
1205 * Remove shake animation error codes
1206 *
1207 * Keeps Vigilante-specific error codes to show the shake animation
1208 *
1209 * @param array $codes Error codes.
1210 * @return array
1211 */
1212 public function remove_shake_errors( $codes ) {
1213 // Keep shake for Vigilante-specific errors that indicate real problems
1214 // Do NOT include 2FA codes - the form transition should be smooth
1215 return array(
1216 'vigilante_lockout',
1217 'vigilante_force_reset',
1218 'pending_approval',
1219 'email_not_verified',
1220 'session_limit_exceeded',
1221 );
1222 }
1223
1224
1225 /**
1226 * Disable XML-RPC pingback method
1227 *
1228 * @param array $methods XML-RPC methods.
1229 * @return array
1230 */
1231 /**
1232 * Notify admin of admin login
1233 *
1234 * @param string $user_login Username.
1235 * @param WP_User $user User object.
1236 */
1237 public function notify_admin_login( $user_login, $user ) {
1238 // Only notify for admin users
1239 if ( ! user_can( $user, 'administrator' ) ) {
1240 return;
1241 }
1242
1243 $ip = $this->database->get_client_ip();
1244 $to = $this->get_notification_email();
1245
1246 $site_name = get_bloginfo( 'name' );
1247 $subject = sprintf(
1248 /* translators: 1: Site name, 2: Username */
1249 __( '[%1$s] Administrator login: %2$s', 'vigilante' ),
1250 $site_name,
1251 $user_login
1252 );
1253
1254 $body = Vigilante_Email_Template::p( __( 'An administrator login has been detected on your site.', 'vigilante' ) );
1255 $body .= Vigilante_Email_Template::data_table( array(
1256 __( 'User', 'vigilante' ) => $user_login,
1257 __( 'IP address', 'vigilante' ) => $ip,
1258 __( 'Date/Time', 'vigilante' ) => wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ) ),
1259 ) );
1260 $body .= Vigilante_Email_Template::warning_box( __( 'If this was not you, please check your site security immediately.', 'vigilante' ) );
1261
1262 Vigilante_Email_Template::send( $to, $subject, __( 'Administrator login detected', 'vigilante' ), $body );
1263 }
1264
1265 /**
1266 * Send lockout notification email
1267 *
1268 * @param string $ip IP address.
1269 * @param string $username Username.
1270 * @param int $attempts Number of attempts.
1271 * @param int $duration Lockout duration in seconds.
1272 */
1273 private function send_lockout_notification( $ip, $username, $attempts, $duration ) {
1274 $to = $this->get_notification_email();
1275 $site_name = get_bloginfo( 'name' );
1276
1277 $subject = sprintf(
1278 /* translators: %s: Site name */
1279 __( '[%s] Login lockout triggered', 'vigilante' ),
1280 $site_name
1281 );
1282
1283 $body = Vigilante_Email_Template::alert_box( __( 'A login lockout has been triggered on your site. The IP address has been temporarily blocked.', 'vigilante' ) );
1284 $body .= Vigilante_Email_Template::data_table( array(
1285 __( 'IP address', 'vigilante' ) => $ip,
1286 __( 'Username attempted', 'vigilante' ) => $username,
1287 __( 'Failed attempts', 'vigilante' ) => (string) $attempts,
1288 __( 'Lockout duration', 'vigilante' ) => ceil( $duration / 60 ) . ' ' . __( 'minutes', 'vigilante' ),
1289 __( 'Date/Time', 'vigilante' ) => wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ) ),
1290 ) );
1291 $body .= Vigilante_Email_Template::button( admin_url( 'admin.php?page=vigilante&tab=login' ), __( 'View lockouts', 'vigilante' ) );
1292
1293 Vigilante_Email_Template::send( $to, $subject, __( 'Login lockout triggered', 'vigilante' ), $body, true );
1294 }
1295
1296 /**
1297 * Show remaining attempts on login form
1298 */
1299 public function show_remaining_attempts() {
1300 $ip = $this->database->get_client_ip();
1301
1302 if ( $this->is_ip_whitelisted( $ip ) ) {
1303 return;
1304 }
1305
1306 $max_attempts = absint( $this->options['max_attempts'] ?? 5 );
1307 $failed_count = $this->database->get_failed_attempt_count( $ip, 60 );
1308
1309 if ( $failed_count > 0 && $failed_count < $max_attempts ) {
1310 $remaining = $max_attempts - $failed_count;
1311 ?>
1312 <p class="vigilante-login-warning" style="background: #fff3cd; border-left: 4px solid #ffc107; padding: 10px; margin-bottom: 15px;">
1313 <?php
1314 printf(
1315 /* translators: %d: Number of remaining attempts */
1316 esc_html( _n(
1317 'Warning: %d login attempt remaining before lockout.',
1318 'Warning: %d login attempts remaining before lockout.',
1319 $remaining,
1320 'vigilante'
1321 ) ),
1322 absint( $remaining )
1323 );
1324 ?>
1325 </p>
1326 <?php
1327 }
1328 }
1329
1330 /**
1331 * Check if IP is whitelisted
1332 *
1333 * @param string $ip IP address.
1334 * @return bool
1335 */
1336 private function is_ip_whitelisted( $ip ) {
1337 $whitelist = $this->options['ip_whitelist'] ?? array();
1338
1339 return Vigilante_IP_Utils::in_list( $ip, $whitelist );
1340 }
1341
1342 /**
1343 * Turn away an anonymous wp-admin request before WordPress finishes booting
1344 *
1345 * The modules are built on init priority 1, so a request that was going to
1346 * be refused had already paid for the whole boot: the theme, every plugin
1347 * and every init callback. Measured on a real site, a rejected
1348 * /wp-admin/index.php cost as much as serving a page.
1349 *
1350 * Only the case that can be judged with certainty this early is handled
1351 * here, an anonymous GET with no session cookie at all; everything else
1352 * falls through to the usual path untouched. The cookie is only checked for
1353 * presence: resolving the user here would run is_user_logged_in() before
1354 * other plugins register their determine_current_user filters, which is how
1355 * token, JWT and SSO logins are wired.
1356 *
1357 * @since 2.9.9
1358 *
1359 * @param array $options The plugin options, already read by the caller.
1360 */
1361 public static function maybe_block_hidden_admin_early( $options ) {
1362 if ( self::is_open_admin_endpoint() ) {
1363 return;
1364 }
1365
1366 if ( '' === sanitize_title( $options['login_security']['custom_login_url'] ) ) {
1367 return;
1368 }
1369
1370 if ( self::has_session_cookie() ) {
1371 return;
1372 }
1373
1374 $whitelist = isset( $options['firewall']['ip_whitelist'] ) ? (array) $options['firewall']['ip_whitelist'] : array();
1375
1376 if ( ! empty( $whitelist ) && Vigilante_IP_Utils::in_list( Vigilante_IP_Utils::get_client_ip(), $whitelist ) ) {
1377 return;
1378 }
1379
1380 self::log_early_hidden_admin_attempt();
1381
1382 status_header( 404 );
1383 nocache_headers();
1384
1385 /*
1386 * Deliberately not translated. This runs on plugins_loaded, where asking
1387 * for a translation triggers the just in time text domain notice of
1388 * WordPress 6.7 and returns the English string anyway. The reader is an
1389 * anonymous request to an address that is supposed to look absent.
1390 */
1391 wp_die(
1392 '<h1>Page not found</h1><p>The page you are looking for does not exist.</p>',
1393 '404 Not Found',
1394 array(
1395 'response' => 404,
1396 'back_link' => false,
1397 )
1398 );
1399 }
1400
1401 /**
1402 * Whether the request carries a WordPress session cookie, without resolving it
1403 *
1404 * @since 2.9.9
1405 *
1406 * @return bool
1407 */
1408 private static function has_session_cookie() {
1409 if ( defined( 'LOGGED_IN_COOKIE' ) && isset( $_COOKIE[ LOGGED_IN_COOKIE ] ) ) {
1410 return true;
1411 }
1412
1413 foreach ( array_keys( (array) $_COOKIE ) as $name ) {
1414 if ( 0 === strpos( (string) $name, 'wordpress_logged_in_' ) || 0 === strpos( (string) $name, 'wordpress_sec_' ) ) {
1415 return true;
1416 }
1417 }
1418
1419 return false;
1420 }
1421
1422 /**
1423 * Record an early rejection in the activity log
1424 *
1425 * @since 2.9.9
1426 */
1427 private static function log_early_hidden_admin_attempt() {
1428 require_once VIGILANTE_INCLUDES_DIR . 'class-settings.php';
1429 require_once VIGILANTE_INCLUDES_DIR . 'class-database.php';
1430 require_once VIGILANTE_INCLUDES_DIR . 'class-activity-log.php';
1431
1432 $request = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
1433
1434 $activity_log = new Vigilante_Activity_Log( new Vigilante_Settings(), new Vigilante_Database() );
1435 $activity_log->log(
1436 'login',
1437 'hidden_admin_access',
1438 'Attempt to access hidden wp-admin',
1439 array( 'request_uri' => $request ),
1440 'warning'
1441 );
1442 }
1443
1444 /**
1445 * Whether the current request comes from an IP that may bypass the
1446 * hidden wp-admin masking.
1447 *
1448 * Reads the firewall's global IP whitelist (the visible "IP whitelist"
1449 * box) so trusted services such as MainWP or ManageWP, which reach
1450 * wp-admin without a WordPress session cookie, are not turned away with
1451 * a 404. This relaxes only the URL masking, never authentication: an
1452 * exempt IP still has to log in normally.
1453 *
1454 * wp-admin only, and that is the point. Until 2.9.9 the same exemption
1455 * also applied to the two wp-login.php paths, where it did not serve that
1456 * purpose and did real harm: block_wp_login_access() handed the real login
1457 * form to any whitelisted IP with the custom login URL active, and
1458 * block_login_shortcuts() is precisely what stops core's
1459 * wp_redirect_admin_locations() from answering /login with a 302 to
1460 * wp_login_url(), which under a custom login URL is the secret slug. So
1461 * exempting it did not merely expose the form, it handed the slug over in
1462 * the Location header. Remote managers never needed either one: both
1463 * blockers already let every POST through, which is how they authenticate.
1464 *
1465 * @return bool
1466 */
1467 private function is_ip_exempt_from_hiding() {
1468 $whitelist = $this->settings->get_option( 'firewall', 'ip_whitelist', array() );
1469
1470 if ( empty( $whitelist ) ) {
1471 return false;
1472 }
1473
1474 return Vigilante_IP_Utils::in_list( $this->database->get_client_ip(), $whitelist );
1475 }
1476
1477 /**
1478 * Get notification email
1479 *
1480 * @return string
1481 */
1482 /**
1483 * Get notification recipients (centralized)
1484 *
1485 * @return array Array of email addresses.
1486 */
1487 private function get_notification_email() {
1488 return Vigilante_Email_Template::get_admin_recipients();
1489 }
1490
1491 /**
1492 * Manually clear lockout for an IP
1493 *
1494 * @param string $ip IP address.
1495 * @return bool
1496 */
1497 public function clear_lockout( $ip ) {
1498 return $this->database->clear_lockout( $ip );
1499 }
1500
1501 /**
1502 * Get currently locked out IPs
1503 *
1504 * @return array
1505 */
1506 public function get_locked_out_ips() {
1507 return $this->database->get_locked_out_ips();
1508 }
1509
1510 /**
1511 * Get login statistics
1512 *
1513 * @param int $days Days to look back.
1514 * @return array
1515 */
1516 public function get_statistics( $days = 7 ) {
1517 global $wpdb;
1518
1519 $table = esc_sql( $this->database->get_login_attempts_table() );
1520 $since = gmdate( 'Y-m-d H:i:s', strtotime( "-{$days} days" ) );
1521
1522 // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
1523 $stats = $wpdb->get_row(
1524 $wpdb->prepare(
1525 "SELECT
1526 COUNT(CASE WHEN status = 'failed' THEN 1 END) as failed_attempts,
1527 COUNT(CASE WHEN status = 'lockout' THEN 1 END) as lockouts,
1528 COUNT(DISTINCT ip_address) as unique_ips,
1529 COUNT(DISTINCT username) as unique_usernames
1530 FROM `{$table}`
1531 WHERE last_attempt >= %s",
1532 $since
1533 ),
1534 ARRAY_A
1535 );
1536 // phpcs:enable
1537
1538 return $stats ? $stats : array(
1539 'failed_attempts' => 0,
1540 'lockouts' => 0,
1541 'unique_ips' => 0,
1542 'unique_usernames' => 0,
1543 );
1544 }
1545 }
1546
1547 /**
1548 * Disabled XML-RPC Server class
1549 */
1550 class Vigilante_Disabled_XMLRPC_Server {
1551 /**
1552 * Constructor - return error for any request
1553 */
1554 public function __construct() {
1555 // Return error for any XML-RPC request
1556 header( 'HTTP/1.1 403 Forbidden' );
1557 header( 'Content-Type: text/plain' );
1558 die( 'XML-RPC is disabled' );
1559 }
1560 }