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

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

1,603 lines 56.3 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 // This rejection is ours, not a wrong password. wp_authenticate()
867 // still fires wp_login_failed for it, and until 2.11.0 that counted
868 // the blocked attempt as one more failure, which rewrote the row's
869 // status and produced a fresh lockout, with its critical entry and
870 // its email, on every POST made during the lockout (S8).
871 add_filter( 'vigilante_skip_failed_login_count', '__return_true' );
872
873 return new WP_Error(
874 'vigilante_lockout',
875 sprintf(
876 /* translators: %d: Minutes remaining */
877 __( '<strong>Error</strong>: Too many failed login attempts. Please try again in %d minutes.', 'vigilante' ),
878 $minutes
879 )
880 );
881 }
882
883 return $user;
884 }
885
886 /**
887 * Handle failed login attempt
888 *
889 * @param string $username Username that failed.
890 */
891 public function handle_failed_login( $username ) {
892 // Skip counting if this is a Vigilante-controlled rejection
893 // (pending approval, session limit, email verification, etc.)
894 if ( apply_filters( 'vigilante_skip_failed_login_count', false ) ) {
895 return;
896 }
897
898 $ip = $this->database->get_client_ip();
899
900 // Skip whitelisted IPs
901 if ( $this->is_ip_whitelisted( $ip ) ) {
902 return;
903 }
904
905 // Record the attempt
906 $this->database->record_login_attempt( $ip, $username, 'failed' );
907
908 // Log the attempt
909 if ( $this->activity_log ) {
910 $this->activity_log->log(
911 'login',
912 'failed',
913 sprintf(
914 /* translators: %s: Username */
915 __( 'Failed login attempt for username: %s', 'vigilante' ),
916 $username
917 ),
918 array(
919 'ip' => $ip,
920 'username' => $username,
921 ),
922 'warning'
923 );
924 }
925
926 // Check if should be locked out
927 $this->maybe_lockout( $ip, $username );
928 }
929
930 /**
931 * Check if IP should be locked out
932 *
933 * @param string $ip IP address.
934 * @param string $username Username.
935 */
936 public function maybe_lockout( $ip, $username ) {
937 $max_attempts = absint( $this->options['max_attempts'] ?? 5 );
938 $lockout_duration = absint( $this->options['lockout_duration'] ?? 1800 );
939
940 // Get failed attempts in the last hour
941 $failed_count = $this->database->get_failed_attempt_count( $ip, 60 );
942
943 if ( $failed_count >= $max_attempts ) {
944 // Already locked out: every further POST during the lockout used to
945 // write another critical entry and send another email (S8). The
946 // lockout itself is what check_lockout() enforces; nothing to add.
947 if ( $this->database->is_locked_out( $ip ) ) {
948 return;
949 }
950
951 // Calculate lockout duration with increment
952 if ( ! empty( $this->options['lockout_increment'] ) ) {
953 $previous_lockouts = $this->get_previous_lockout_count( $ip );
954 $lockout_duration = min(
955 $lockout_duration * pow( 2, $previous_lockouts ),
956 absint( $this->options['max_lockout_duration'] ?? 86400 )
957 );
958 }
959
960 // Set lockout
961 $this->database->set_lockout( $ip, $lockout_duration );
962
963 // Log the lockout
964 if ( $this->activity_log ) {
965 $this->activity_log->log(
966 'login',
967 'lockout',
968 sprintf(
969 /* translators: 1: IP address, 2: Duration in minutes */
970 __( 'IP %1$s locked out for %2$d minutes', 'vigilante' ),
971 $ip,
972 ceil( $lockout_duration / 60 )
973 ),
974 array(
975 'ip' => $ip,
976 'username' => $username,
977 'attempts' => $failed_count,
978 'duration' => $lockout_duration,
979 ),
980 'critical'
981 );
982 }
983
984 // Send notification if enabled
985 if ( ! empty( $this->options['notify_on_lockout'] ) ) {
986 $this->send_lockout_notification( $ip, $username, $failed_count, $lockout_duration );
987 }
988 }
989 }
990
991 /**
992 * Record a failed login attempt (public wrapper)
993 *
994 * Use this method from external modules (like 2FA) to integrate with the lockout system.
995 *
996 * @param string $username Username or identifier.
997 * @param string $context Context for logging (e.g., 'password', '2fa').
998 */
999 public function record_failed_attempt( $username, $context = 'password' ) {
1000 $ip = $this->database->get_client_ip();
1001
1002 // Skip whitelisted IPs
1003 if ( $this->is_ip_whitelisted( $ip ) ) {
1004 return;
1005 }
1006
1007 // Record the attempt
1008 $this->database->record_login_attempt( $ip, $username, 'failed' );
1009
1010 // Log the attempt
1011 if ( $this->activity_log ) {
1012 $this->activity_log->log(
1013 'login',
1014 'failed',
1015 sprintf(
1016 /* translators: 1: Username, 2: Context (password/2fa) */
1017 __( 'Failed login attempt for %1$s (%2$s verification)', 'vigilante' ),
1018 $username,
1019 $context
1020 ),
1021 array(
1022 'ip' => $ip,
1023 'username' => $username,
1024 'context' => $context,
1025 ),
1026 'warning'
1027 );
1028 }
1029
1030 // Check if should be locked out
1031 $this->maybe_lockout( $ip, $username );
1032 }
1033
1034 /**
1035 * Get remaining attempts before lockout
1036 *
1037 * @return int Remaining attempts, or -1 if whitelisted
1038 */
1039 public function get_remaining_attempts() {
1040 $ip = $this->database->get_client_ip();
1041
1042 if ( $this->is_ip_whitelisted( $ip ) ) {
1043 return -1;
1044 }
1045
1046 $max_attempts = absint( $this->options['max_attempts'] ?? 5 );
1047 $failed_count = $this->database->get_failed_attempt_count( $ip, 60 );
1048
1049 return max( 0, $max_attempts - $failed_count );
1050 }
1051
1052 /**
1053 * Get count of previous lockouts for an IP
1054 *
1055 * @param string $ip IP address.
1056 * @return int
1057 */
1058 private function get_previous_lockout_count( $ip ) {
1059 $transient_key = 'vigilante_lockout_count_' . md5( $ip );
1060 $count = get_transient( $transient_key );
1061
1062 if ( false === $count ) {
1063 $count = 0;
1064 }
1065
1066 // Increment and store
1067 set_transient( $transient_key, $count + 1, DAY_IN_SECONDS );
1068
1069 return $count;
1070 }
1071
1072 /**
1073 * Handle successful login
1074 *
1075 * @param string $user_login Username.
1076 * @param WP_User $user User object.
1077 */
1078 public function handle_successful_login( $user_login, $user ) {
1079 $ip = $this->database->get_client_ip();
1080
1081 // Clear any failed attempts for this IP
1082 $this->database->reset_login_attempts( $ip );
1083
1084 // Log the successful login
1085 if ( $this->activity_log ) {
1086 $this->activity_log->log(
1087 'login',
1088 'success',
1089 sprintf(
1090 /* translators: %s: Username */
1091 __( 'Successful login: %s', 'vigilante' ),
1092 $user_login
1093 ),
1094 array(
1095 'ip' => $ip,
1096 'user_id' => $user->ID,
1097 'role' => implode( ', ', $user->roles ),
1098 ),
1099 'info'
1100 );
1101 }
1102 }
1103
1104 /**
1105 * Detect Vigilant-specific error codes on the login page
1106 *
1107 * Hooked to 'wp_login_errors' (which receives the full WP_Error object,
1108 * unlike 'login_errors' that only sees the rendered message string).
1109 * If any of the codes we recognize is present, sets a flag so that
1110 * hide_login_errors() lets the message through. Matching by code is
1111 * locale-independent — checking the message string would break on
1112 * translated sites because __() returns the translation, not the
1113 * original English text.
1114 *
1115 * @param WP_Error $errors Errors object.
1116 * @param string $redirect_to Redirect URL.
1117 * @return WP_Error
1118 */
1119 public function detect_specific_login_error( $errors, $redirect_to ) {
1120 // wp_login_errors only fires for the login action, so reaching this
1121 // method means we are on the login screen — not register, lost-password
1122 // or reset-password, where masking the message makes no sense.
1123 $this->in_login_context = true;
1124
1125 if ( ! ( $errors instanceof WP_Error ) || ! $errors->has_errors() ) {
1126 return $errors;
1127 }
1128
1129 $allowed_codes = array(
1130 // Login Security
1131 'vigilante_lockout',
1132 // User Security
1133 'vigilante_force_reset',
1134 // pending_approval, email_not_verified and session_limit_exceeded
1135 // are deliberately NOT here since 2.11.0: they are only raised once
1136 // the password is correct, so letting them through told an
1137 // unauthenticated visitor which accounts exist (S10). Those users
1138 // learn their status from the registration and verification emails.
1139 // Two-Factor Email
1140 'no_code',
1141 'code_expired',
1142 'code_used',
1143 // Two-Factor TOTP
1144 'code_reused',
1145 'invalid_format',
1146 'not_configured',
1147 'decrypt_failed',
1148 'invalid_backup',
1149 'no_backup_codes',
1150 'corrupt_data',
1151 );
1152
1153 foreach ( $errors->get_error_codes() as $code ) {
1154 if ( in_array( $code, $allowed_codes, true ) ) {
1155 $this->show_specific_login_error = true;
1156 break;
1157 }
1158 }
1159
1160 return $errors;
1161 }
1162
1163 /**
1164 * Hide login error messages
1165 *
1166 * Only masks errors on the login action. Register, lost-password and
1167 * reset-password share the login_errors filter but must keep their real
1168 * validation messages.
1169 *
1170 * @param string $error Error message.
1171 * @return string
1172 */
1173 public function hide_login_errors( $error ) {
1174 // The login_errors filter is fired by login_header() on every
1175 // wp-login.php screen, not just the login form. On register,
1176 // lost-password and reset-password the generic "Invalid username or
1177 // password" is meaningless, so only mask when we are actually on the
1178 // login action (detect_specific_login_error, hooked to the
1179 // login-only wp_login_errors filter, sets this flag).
1180 if ( ! $this->in_login_context ) {
1181 return $error;
1182 }
1183
1184 // Primary check: a recognized Vigilant error code was seen on the
1185 // wp_login_errors filter — let the message through verbatim.
1186 if ( $this->show_specific_login_error ) {
1187 return $error;
1188 }
1189
1190 // Fallback: English string match. Kept for cases where the message
1191 // arrives without going through wp_login_errors (e.g. a third-party
1192 // plugin filtering 'login_errors' directly), and as a safety net for
1193 // any allowed code we may have missed in detect_specific_login_error().
1194 // Note: this fallback won't match on translated sites — the
1195 // code-based check above is the locale-safe path.
1196 $allowed_patterns = array(
1197 'vigilante_lockout',
1198 // The pending-approval, unverified-email and session-limit strings
1199 // were removed in 2.11.0 for the same reason as their codes above (S10).
1200 'verification code',
1201 'authenticator app',
1202 'two-factor',
1203 'grace period',
1204 'Password reset required',
1205 );
1206
1207 foreach ( $allowed_patterns as $pattern ) {
1208 if ( stripos( $error, $pattern ) !== false ) {
1209 return $error;
1210 }
1211 }
1212
1213 return __( '<strong>Error</strong>: Invalid username or password.', 'vigilante' );
1214 }
1215
1216 /**
1217 * Remove shake animation error codes
1218 *
1219 * Keeps Vigilante-specific error codes to show the shake animation
1220 *
1221 * @param array $codes Error codes.
1222 * @return array
1223 */
1224 public function remove_shake_errors( $codes ) {
1225 // Keep shake for Vigilante-specific errors that indicate real problems
1226 // Do NOT include 2FA codes - the form transition should be smooth.
1227 // The three account-status codes are not here either since 2.11.0: a
1228 // shake that only plays for existing accounts is the same tell as the
1229 // message it replaced (S10).
1230 return array(
1231 'vigilante_lockout',
1232 'vigilante_force_reset',
1233 );
1234 }
1235
1236
1237 /**
1238 * Disable XML-RPC pingback method
1239 *
1240 * @param array $methods XML-RPC methods.
1241 * @return array
1242 */
1243 /**
1244 * Notify admin of admin login
1245 *
1246 * @param string $user_login Username.
1247 * @param WP_User $user User object.
1248 */
1249 public function notify_admin_login( $user_login, $user ) {
1250 // Only notify for admin users
1251 if ( ! user_can( $user, 'administrator' ) ) {
1252 return;
1253 }
1254
1255 $ip = $this->database->get_client_ip();
1256 $to = $this->get_notification_email();
1257
1258 $site_name = get_bloginfo( 'name' );
1259 $subject = sprintf(
1260 /* translators: 1: Site name, 2: Username */
1261 __( '[%1$s] Administrator login: %2$s', 'vigilante' ),
1262 $site_name,
1263 $user_login
1264 );
1265
1266 $body = Vigilante_Email_Template::p( __( 'An administrator login has been detected on your site.', 'vigilante' ) );
1267 $body .= Vigilante_Email_Template::data_table( array(
1268 __( 'User', 'vigilante' ) => $user_login,
1269 __( 'IP address', 'vigilante' ) => $ip,
1270 __( 'Date/Time', 'vigilante' ) => wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ) ),
1271 ) );
1272 $body .= Vigilante_Email_Template::warning_box( __( 'If this was not you, please check your site security immediately.', 'vigilante' ) );
1273
1274 Vigilante_Email_Template::send( $to, $subject, __( 'Administrator login detected', 'vigilante' ), $body );
1275 }
1276
1277 /**
1278 * Send lockout notification email
1279 *
1280 * @param string $ip IP address.
1281 * @param string $username Username.
1282 * @param int $attempts Number of attempts.
1283 * @param int $duration Lockout duration in seconds.
1284 */
1285 private function send_lockout_notification( $ip, $username, $attempts, $duration ) {
1286 $to = $this->get_notification_email();
1287 $site_name = get_bloginfo( 'name' );
1288
1289 $subject = sprintf(
1290 /* translators: %s: Site name */
1291 __( '[%s] Login lockout triggered', 'vigilante' ),
1292 $site_name
1293 );
1294
1295 $body = Vigilante_Email_Template::alert_box( __( 'A login lockout has been triggered on your site. The IP address has been temporarily blocked.', 'vigilante' ) );
1296 $body .= Vigilante_Email_Template::data_table( array(
1297 __( 'IP address', 'vigilante' ) => $ip,
1298 __( 'Username attempted', 'vigilante' ) => $username,
1299 __( 'Failed attempts', 'vigilante' ) => (string) $attempts,
1300 __( 'Lockout duration', 'vigilante' ) => ceil( $duration / 60 ) . ' ' . __( 'minutes', 'vigilante' ),
1301 __( 'Date/Time', 'vigilante' ) => wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ) ),
1302 ) );
1303 $body .= Vigilante_Email_Template::button( admin_url( 'admin.php?page=vigilante&tab=login#vigilante-section-login-status' ), __( 'View lockouts', 'vigilante' ) );
1304
1305 Vigilante_Email_Template::send( $to, $subject, __( 'Login lockout triggered', 'vigilante' ), $body, true );
1306 }
1307
1308 /**
1309 * Show remaining attempts on login form
1310 */
1311 public function show_remaining_attempts() {
1312 $ip = $this->database->get_client_ip();
1313
1314 if ( $this->is_ip_whitelisted( $ip ) ) {
1315 return;
1316 }
1317
1318 $max_attempts = absint( $this->options['max_attempts'] ?? 5 );
1319 $failed_count = $this->database->get_failed_attempt_count( $ip, 60 );
1320
1321 if ( $failed_count > 0 && $failed_count < $max_attempts ) {
1322 $remaining = $max_attempts - $failed_count;
1323 ?>
1324 <p class="vigilante-login-warning" style="background: #fff3cd; border-left: 4px solid #ffc107; padding: 10px; margin-bottom: 15px;">
1325 <?php
1326 printf(
1327 /* translators: %d: Number of remaining attempts */
1328 esc_html( _n(
1329 'Warning: %d login attempt remaining before lockout.',
1330 'Warning: %d login attempts remaining before lockout.',
1331 $remaining,
1332 'vigilante'
1333 ) ),
1334 absint( $remaining )
1335 );
1336 ?>
1337 </p>
1338 <?php
1339 }
1340 }
1341
1342 /**
1343 * Check if IP is whitelisted
1344 *
1345 * @param string $ip IP address.
1346 * @return bool
1347 */
1348 private function is_ip_whitelisted( $ip ) {
1349 $whitelist = $this->options['ip_whitelist'] ?? array();
1350
1351 return Vigilante_IP_Utils::in_list( $ip, $whitelist );
1352 }
1353
1354 /**
1355 * Turn away an anonymous wp-admin request before WordPress finishes booting
1356 *
1357 * The modules are built on init priority 1, so a request that was going to
1358 * be refused had already paid for the whole boot: the theme, every plugin
1359 * and every init callback. Measured on a real site, a rejected
1360 * /wp-admin/index.php cost as much as serving a page.
1361 *
1362 * Only the case that can be judged with certainty this early is handled
1363 * here, an anonymous GET with no session cookie at all; everything else
1364 * falls through to the usual path untouched. The cookie is only checked for
1365 * presence: resolving the user here would run is_user_logged_in() before
1366 * other plugins register their determine_current_user filters, which is how
1367 * token, JWT and SSO logins are wired.
1368 *
1369 * @since 2.9.9
1370 *
1371 * @param array $options The plugin options, already read by the caller.
1372 */
1373 public static function maybe_block_hidden_admin_early( $options ) {
1374 if ( self::is_open_admin_endpoint() ) {
1375 return;
1376 }
1377
1378 if ( '' === sanitize_title( $options['login_security']['custom_login_url'] ) ) {
1379 return;
1380 }
1381
1382 if ( self::has_session_cookie() ) {
1383 return;
1384 }
1385
1386 $whitelist = isset( $options['firewall']['ip_whitelist'] ) ? (array) $options['firewall']['ip_whitelist'] : array();
1387
1388 if ( ! empty( $whitelist ) && Vigilante_IP_Utils::in_list( Vigilante_IP_Utils::get_client_ip(), $whitelist ) ) {
1389 return;
1390 }
1391
1392 /*
1393 * Last, and only for a request that was about to be turned away: whether
1394 * anybody is actually there.
1395 *
1396 * A remote manager signs its own call with a token and asks for the
1397 * dashboard before holding any cookie; its connector resolves the user
1398 * through determine_current_user and only then, on 'init', sets the
1399 * cookie and redirects. Turning the request away here, three hooks
1400 * earlier, means the connector never reaches the point where it would
1401 * have logged itself in, so it reads the 404 as a site that is broken
1402 * and retries the whole job. Observed in the wild with
1403 * ModularConnector/3.2.1, whose every request landed here.
1404 *
1405 * Which is also why this went unnoticed for two releases: a connector
1406 * that already holds a cookie by the time it asks for the dashboard
1407 * leaves at has_session_cookie() above and never reaches this line. How
1408 * many connectors work that way is not something to guess at here; what
1409 * is certain is that reports only came from sites where one did not.
1410 *
1411 * The criterion is the one block_wp_admin_access() has always applied,
1412 * brought to the door 2.9.9 put in front of it. It costs nothing on the
1413 * ordinary request, which left long before reaching this line, and
1414 * nothing on the database either: with no cookie to validate, the three
1415 * core determine_current_user callbacks all decline without a query. The
1416 * rejection below already pays for an INSERT into the activity log, and
1417 * resolves this very same user one step later to record who was refused.
1418 */
1419 if ( get_current_user_id() ) {
1420 return;
1421 }
1422
1423 self::log_early_hidden_admin_attempt();
1424
1425 status_header( 404 );
1426 nocache_headers();
1427
1428 /*
1429 * Deliberately not translated. This runs on plugins_loaded, where asking
1430 * for a translation triggers the just in time text domain notice of
1431 * WordPress 6.7 and returns the English string anyway. The reader is an
1432 * anonymous request to an address that is supposed to look absent.
1433 */
1434 wp_die(
1435 '<h1>Page not found</h1><p>The page you are looking for does not exist.</p>',
1436 '404 Not Found',
1437 array(
1438 'response' => 404,
1439 'back_link' => false,
1440 )
1441 );
1442 }
1443
1444 /**
1445 * Whether the request carries a WordPress session cookie, without resolving it
1446 *
1447 * @since 2.9.9
1448 *
1449 * @return bool
1450 */
1451 private static function has_session_cookie() {
1452 if ( defined( 'LOGGED_IN_COOKIE' ) && isset( $_COOKIE[ LOGGED_IN_COOKIE ] ) ) {
1453 return true;
1454 }
1455
1456 foreach ( array_keys( (array) $_COOKIE ) as $name ) {
1457 if ( 0 === strpos( (string) $name, 'wordpress_logged_in_' ) || 0 === strpos( (string) $name, 'wordpress_sec_' ) ) {
1458 return true;
1459 }
1460 }
1461
1462 return false;
1463 }
1464
1465 /**
1466 * Record an early rejection in the activity log
1467 *
1468 * @since 2.9.9
1469 */
1470 private static function log_early_hidden_admin_attempt() {
1471 require_once VIGILANTE_INCLUDES_DIR . 'class-settings.php';
1472 require_once VIGILANTE_INCLUDES_DIR . 'class-database.php';
1473 require_once VIGILANTE_INCLUDES_DIR . 'class-activity-log.php';
1474
1475 $request = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
1476
1477 $activity_log = new Vigilante_Activity_Log( new Vigilante_Settings(), new Vigilante_Database() );
1478 $activity_log->log(
1479 'login',
1480 'hidden_admin_access',
1481 'Attempt to access hidden wp-admin',
1482 array( 'request_uri' => $request ),
1483 'warning'
1484 );
1485 }
1486
1487 /**
1488 * Whether the current request comes from an IP that may bypass the
1489 * hidden wp-admin masking.
1490 *
1491 * Reads the firewall's global IP whitelist (the visible "IP whitelist"
1492 * box) so trusted services such as MainWP or ManageWP, which reach
1493 * wp-admin without a WordPress session cookie, are not turned away with
1494 * a 404. This relaxes only the URL masking, never authentication: an
1495 * exempt IP still has to log in normally.
1496 *
1497 * wp-admin only, and that is the point. Until 2.9.9 the same exemption
1498 * also applied to the two wp-login.php paths, where it did not serve that
1499 * purpose and did real harm: block_wp_login_access() handed the real login
1500 * form to any whitelisted IP with the custom login URL active, and
1501 * block_login_shortcuts() is precisely what stops core's
1502 * wp_redirect_admin_locations() from answering /login with a 302 to
1503 * wp_login_url(), which under a custom login URL is the secret slug. So
1504 * exempting it did not merely expose the form, it handed the slug over in
1505 * the Location header. Remote managers never needed either one: both
1506 * blockers already let every POST through, which is how they authenticate.
1507 *
1508 * @return bool
1509 */
1510 private function is_ip_exempt_from_hiding() {
1511 $whitelist = $this->settings->get_option( 'firewall', 'ip_whitelist', array() );
1512
1513 if ( empty( $whitelist ) ) {
1514 return false;
1515 }
1516
1517 return Vigilante_IP_Utils::in_list( $this->database->get_client_ip(), $whitelist );
1518 }
1519
1520 /**
1521 * Get notification email
1522 *
1523 * @return string
1524 */
1525 /**
1526 * Get notification recipients (centralized)
1527 *
1528 * @return array Array of email addresses.
1529 */
1530 private function get_notification_email() {
1531 return Vigilante_Email_Template::get_admin_recipients();
1532 }
1533
1534 /**
1535 * Manually clear lockout for an IP
1536 *
1537 * @param string $ip IP address.
1538 * @return bool
1539 */
1540 public function clear_lockout( $ip ) {
1541 return $this->database->clear_lockout( $ip );
1542 }
1543
1544 /**
1545 * Get currently locked out IPs
1546 *
1547 * @return array
1548 */
1549 public function get_locked_out_ips() {
1550 return $this->database->get_locked_out_ips();
1551 }
1552
1553 /**
1554 * Get login statistics
1555 *
1556 * @param int $days Days to look back.
1557 * @return array
1558 */
1559 public function get_statistics( $days = 7 ) {
1560 global $wpdb;
1561
1562 $table = esc_sql( $this->database->get_login_attempts_table() );
1563 $since = gmdate( 'Y-m-d H:i:s', strtotime( "-{$days} days" ) );
1564
1565 // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
1566 $stats = $wpdb->get_row(
1567 $wpdb->prepare(
1568 "SELECT
1569 COUNT(CASE WHEN status = 'failed' THEN 1 END) as failed_attempts,
1570 COUNT(CASE WHEN status = 'lockout' THEN 1 END) as lockouts,
1571 COUNT(DISTINCT ip_address) as unique_ips,
1572 COUNT(DISTINCT username) as unique_usernames
1573 FROM `{$table}`
1574 WHERE last_attempt >= %s",
1575 $since
1576 ),
1577 ARRAY_A
1578 );
1579 // phpcs:enable
1580
1581 return $stats ? $stats : array(
1582 'failed_attempts' => 0,
1583 'lockouts' => 0,
1584 'unique_ips' => 0,
1585 'unique_usernames' => 0,
1586 );
1587 }
1588 }
1589
1590 /**
1591 * Disabled XML-RPC Server class
1592 */
1593 class Vigilante_Disabled_XMLRPC_Server {
1594 /**
1595 * Constructor - return error for any request
1596 */
1597 public function __construct() {
1598 // Return error for any XML-RPC request
1599 header( 'HTTP/1.1 403 Forbidden' );
1600 header( 'Content-Type: text/plain' );
1601 die( 'XML-RPC is disabled' );
1602 }
1603 }