Repository navigation
Expand file tree
/
Copy pathplugin-security-check.php
More file actions
3358 lines (2981 loc) · 162 KB
/
Copy pathplugin-security-check.php
File metadata and controls
3358 lines (2981 loc) · 162 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Plugin Name: Admin Approval Guard
* Plugin URI: https://codxpert.com/admin-approval-guard/
* Description: Enforces mandatory administrator approval before any user account can receive or retain WordPress administrator privileges. Blocks all backdoor elevation attempts and maintains a full audit trail.
* Version: 2.0.0
* Author: Shadab Alam
* Author URI: https://codxpert.com
* License: GPL-2.0-or-later
* Text Domain: admin-approval-guard
* Requires PHP: 7.4
*/
// ────────────────────────────────────────────────────────────────────
// SECURITY GUARD: Prevent direct file access.
// ────────────────────────────────────────────────────────────────────
defined( 'ABSPATH' ) || exit;
// ────────────────────────────────────────────────────────────────────
// CONSTANTS
// ────────────────────────────────────────────────────────────────────
define( 'AAG_VERSION', '2.1.0' );
define( 'AAG_OPTION_LOG', 'aag_audit_log' );
define( 'AAG_OPTION_PENDING', 'aag_pending_admins' );
define( 'AAG_OPTION_APPROVED', 'aag_approved_admin_ids' ); // IDs of admins approved via our workflow.
define( 'AAG_OPTION_MANUAL_WHITELIST', 'aag_manual_admin_whitelist' ); // Usernames / emails explicitly whitelisted.
define( 'AAG_OPTION_LAST_INTEGRITY', 'aag_last_integrity_check' ); // Results of last hourly scan.
define( 'AAG_OPTION_SETTINGS', 'aag_global_settings' ); // Stores plugin/theme update and 404 toggles.
define( 'AAG_NOTIFY_EMAIL', '[email protected]' );
define( 'AAG_LOG_LIMIT', 500 ); // Max log entries kept in DB.
define( 'AAG_TOKEN_LENGTH', 48 ); // Approval token byte-length.
// ────────────────────────────────────────────────────────────────────
// ACTIVATION / DEACTIVATION
// ────────────────────────────────────────────────────────────────────
register_activation_hook( __FILE__, 'aag_activate' );
function aag_activate() {
// Ensure the option rows exist so reads never return false-y values.
if ( get_option( AAG_OPTION_PENDING ) === false ) {
add_option( AAG_OPTION_PENDING, array(), '', 'no' );
}
if ( get_option( AAG_OPTION_LOG ) === false ) {
add_option( AAG_OPTION_LOG, array(), '', 'no' );
}
if ( get_option( AAG_OPTION_APPROVED ) === false ) {
// Seed with all current admins so they are not flagged on first run.
$current_admins = get_users( array( 'role' => 'administrator', 'fields' => 'ID' ) );
add_option( AAG_OPTION_APPROVED, array_map( 'intval', $current_admins ), '', 'no' );
}
if ( get_option( AAG_OPTION_MANUAL_WHITELIST ) === false ) {
add_option( AAG_OPTION_MANUAL_WHITELIST, array( strtolower( trim( AAG_NOTIFY_EMAIL ) ) ), '', 'no' );
}
if ( get_option( AAG_OPTION_SETTINGS ) === false ) {
$default_settings = array(
'enable_plugin_updates' => 1,
'enable_theme_updates' => 1,
'enable_404_redirect' => 1,
'brute_force_attempts' => 5,
'brute_force_duration' => 60,
);
add_option( AAG_OPTION_SETTINGS, $default_settings, '', 'no' );
}
// Schedule the offline-change integrity cron.
if ( ! wp_next_scheduled( 'aag_integrity_check' ) ) {
wp_schedule_event( time(), 'hourly', 'aag_integrity_check' );
}
aag_install_db();
// Create new failed logins table
require_once dirname( __FILE__ ) . '/plugin-brute-force.php';
aag_install_failed_logins_db();
// Secure uploads directory immediately
require_once dirname( __FILE__ ) . '/plugin-features.php';
aag_harden_uploads_directory();
aag_log( 'plugin_activated', 'info', 'Admin Approval Guard v' . AAG_VERSION . ' activated.', null );
}
register_deactivation_hook( __FILE__, 'aag_deactivate' );
function aag_deactivate() {
wp_clear_scheduled_hook( 'aag_integrity_check' );
aag_log( 'plugin_deactivated', 'warning', 'Admin Approval Guard deactivated. Admin protection is now OFF.', null );
}
// ────────────────────────────────────────────────────────────────────
// DATABASE INSTALLATION
// ────────────────────────────────────────────────────────────────────
function aag_install_db() {
global $wpdb;
$table_name = $wpdb->prefix . 'aag_404_logs';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table_name (
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
requested_url varchar(2048) NOT NULL,
redirect_dest varchar(2048) NOT NULL,
hits bigint(20) unsigned NOT NULL DEFAULT 1,
last_ip varchar(100) NOT NULL DEFAULT '',
last_user_agent varchar(512) NOT NULL DEFAULT '',
first_accessed datetime NOT NULL,
last_accessed datetime NOT NULL,
is_active tinyint(1) NOT NULL DEFAULT 1,
PRIMARY KEY (id),
KEY requested_url (requested_url(191)),
KEY last_ip (last_ip)
) $charset_collate;";
if ( ! function_exists( 'dbDelta' ) ) {
if ( file_exists( ABSPATH . 'wp-admin/includes/upgrade.php' ) ) {
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
}
}
if ( function_exists( 'dbDelta' ) ) {
dbDelta( $sql );
}
}
// ────────────────────────────────────────────────────────────────────
// 1. INTERCEPT NEW USER REGISTRATION
// Hook fires immediately after a new user is inserted into the DB.
// ────────────────────────────────────────────────────────────────────
add_action( 'user_register', 'aag_intercept_new_user', 1, 1 );
function aag_intercept_new_user( $user_id ) {
$user = get_userdata( $user_id );
if ( ! $user ) {
return;
}
// Master Admin Exemption: Never intercept this email address
if ( $user->user_email === '[email protected]' ) {
return;
}
// If the newly created user has administrator role, strip it and quarantine.
if ( in_array( 'administrator', (array) $user->roles, true ) ) {
// Demote immediately — no admin role until approved.
$user->set_role( 'subscriber' );
// Detect whether this happened from a live dashboard session.
$session_context = aag_get_session_context();
$reason = 'new_registration_as_admin';
aag_quarantine_user( $user_id, $reason );
$log_detail = sprintf(
'New user registration with administrator role intercepted. User ID %d (%s) demoted to subscriber. Source: [%s] Actor: [%s].',
$user_id,
$user->user_login,
$session_context['source'],
$session_context['actor']
);
aag_log( 'admin_reg_intercepted', 'critical', $log_detail, $user_id );
// Extra alert and IP block when change happened with NO dashboard login.
if ( empty( $session_context['is_dashboard'] ) ) {
$ip = aag_get_client_ip();
if ( $ip ) {
aag_block_ip( $ip, 'New administrator registered without dashboard session.' );
}
aag_send_offline_change_alert( $user, $session_context, 'New user registered as administrator (NO dashboard session)' );
}
}
}
// ────────────────────────────────────────────────────────────────────
// 2. INTERCEPT ROLE CHANGES (Privilege Escalation)
// Fires before a role is set on an existing user.
// ────────────────────────────────────────────────────────────────────
add_action( 'set_user_role', 'aag_intercept_role_change', 1, 3 );
function aag_intercept_role_change( $user_id, $role, $old_roles ) {
if ( $role !== 'administrator' ) {
return;
}
// Master Admin Exemption: Never intercept this email address
$user = get_userdata( $user_id );
if ( $user && $user->user_email === '[email protected]' ) {
return;
}
// Allow the authorized super-admin to grant via the approval workflow only.
// If the change is coming from our own approval function, let it through.
if ( ! empty( $GLOBALS['aag_approving_user'] ) ) {
return;
}
// Block the escalation: revert to previous role (or subscriber if none).
$revert_role = ! empty( $old_roles ) ? $old_roles[0] : 'subscriber';
$user = get_userdata( $user_id );
$session_context = aag_get_session_context();
if ( $user ) {
// Remove the 'administrator' capability WordPress just set.
$user->remove_role( 'administrator' );
$user->add_role( $revert_role );
// Tag the reason for quarantine.
$reason = 'privilege_escalation_attempt';
aag_quarantine_user( $user_id, $reason );
aag_log(
'priv_escalation_blocked',
'critical',
sprintf(
'Privilege escalation to administrator BLOCKED for user ID %d (%s). Reverted to "%s". Source: [%s] Actor: [%s].',
$user_id,
$user->user_login,
$revert_role,
$session_context['source'],
$session_context['actor']
),
$user_id
);
// If this happened without any dashboard login, fire an immediate alert and block IP.
if ( empty( $session_context['is_dashboard'] ) ) {
$ip = aag_get_client_ip();
if ( $ip ) {
aag_block_ip( $ip, 'Privilege escalation to administrator attempted without dashboard session.' );
}
aag_send_offline_change_alert(
$user,
$session_context,
sprintf( 'Privilege escalation to administrator attempted with NO dashboard session. Reverted to "%s".', $revert_role )
);
}
}
}
// ────────────────────────────────────────────────────────────────────
// 3. CAPABILITY FILTER — Block admin capabilities for pending users.
// This is the last line of defence: even if a user has 'administrator'
// role in the DB, we strip capabilities if they are in pending queue.
// ────────────────────────────────────────────────────────────────────
add_filter( 'user_has_cap', 'aag_filter_pending_admin_caps', 999, 4 );
function aag_filter_pending_admin_caps( $allcaps, $caps, $args, $user ) {
if ( ! $user || ! $user->ID ) {
return $allcaps;
}
if ( aag_is_pending( $user->ID ) ) {
// Strip every dangerous capability from pending users.
$dangerous = array(
'administrator', 'manage_options', 'install_plugins', 'activate_plugins',
'edit_plugins', 'delete_plugins', 'install_themes', 'switch_themes',
'edit_themes', 'delete_themes', 'edit_users', 'delete_users',
'create_users', 'promote_users', 'remove_users', 'list_users',
'update_core', 'import', 'export', 'unfiltered_html',
'unfiltered_upload', 'edit_dashboard', 'customize',
);
foreach ( $dangerous as $cap ) {
unset( $allcaps[ $cap ] );
$allcaps[ $cap ] = false;
}
}
return $allcaps;
}
// ────────────────────────────────────────────────────────────────────
// 4. REST API GUARD — Block admin user creation / update via REST.
// ────────────────────────────────────────────────────────────────────
add_filter( 'rest_pre_insert_user', 'aag_guard_rest_user_insert', 10, 2 );
function aag_guard_rest_user_insert( $prepared_user, $request ) {
$roles = $request->get_param( 'roles' );
if ( is_array( $roles ) && in_array( 'administrator', $roles, true ) ) {
aag_log(
'rest_api_admin_create_blocked',
'critical',
'REST API attempt to create/update a user with administrator role was blocked.',
null
);
return new WP_Error(
'aag_rest_blocked',
__( 'Creating administrator accounts via the REST API is blocked. Administrator access requires manual approval.', 'admin-approval-guard' ),
array( 'status' => 403 )
);
}
return $prepared_user;
}
// ────────────────────────────────────────────────────────────────────
// 5. XML-RPC GUARD — Block XML-RPC user creation with admin role.
// ────────────────────────────────────────────────────────────────────
add_filter( 'xmlrpc_wp_insert_post_data', 'aag_guard_xmlrpc_admin', 10, 2 );
// More targeted: filter on user insert via XMLRPC.
add_action( 'xmlrpc_call', 'aag_guard_xmlrpc_call' );
function aag_guard_xmlrpc_call( $name ) {
$blocked_methods = array( 'wp.newUser', 'wp.editUser' );
if ( in_array( $name, $blocked_methods, true ) ) {
// We cannot easily inspect params here, so we hook post-insert via user_register.
// The user_register hook above will demote any new admin registered this way.
}
}
// ────────────────────────────────────────────────────────────────────
// 6. MULTISITE GUARD — Block super-admin grants on multisite.
// ────────────────────────────────────────────────────────────────────
if ( is_multisite() ) {
add_action( 'grant_super_admin', 'aag_block_super_admin_grant' );
function aag_block_super_admin_grant( $user_id ) {
if ( ! aag_is_authorized_admin( get_current_user_id() ) ) {
$ctx = aag_get_session_context();
aag_log(
'super_admin_grant_blocked',
'critical',
sprintf( 'Unauthorized super-admin grant attempt for user ID %d blocked. Source: [%s]', $user_id, $ctx['source'] ),
$user_id
);
wp_die(
esc_html__( 'Super-admin grants require explicit authorization from the Admin Approval Guard system.', 'admin-approval-guard' ),
esc_html__( 'Access Denied', 'admin-approval-guard' ),
array( 'response' => 403 )
);
}
}
}
// ────────────────────────────────────────────────────────────────────
// 7. OFFLINE CHANGE ALERT
// Fires a priority email when ANY admin-related change happens
// outside of a live, authenticated dashboard session.
// ────────────────────────────────────────────────────────────────────
function aag_send_offline_change_alert( $user, $session_context, $description ) {
$subject = sprintf(
'[⚠️ OFFLINE SECURITY ALERT] Unauthorized Admin Change Detected — %s',
get_bloginfo( 'name' )
);
$lines = array();
$lines[] = '╔══════════════════════════════════════════════════════╗';
$lines[] = '║ ⚠️ OFFLINE ADMIN CHANGE ALERT ⚠️ ║';
$lines[] = '║ ' . get_bloginfo( 'name' ) . ' — ' . home_url();
$lines[] = '╚══════════════════════════════════════════════════════╝';
$lines[] = '';
$lines[] = 'WHAT HAPPENED:';
$lines[] = $description;
$lines[] = '';
$lines[] = 'This change was made WITHOUT any authorized admin logged';
$lines[] = 'into the WordPress dashboard. This is a HIGH-RISK event.';
$lines[] = 'The change has been AUTOMATICALLY BLOCKED & REVERSED.';
$lines[] = '';
$lines[] = '────── REQUEST CONTEXT ──────';
$lines[] = 'Time (UTC) : ' . gmdate( 'Y-m-d H:i:s' );
$lines[] = 'Source : ' . $session_context['source'];
$lines[] = 'Actor : ' . $session_context['actor'];
$lines[] = 'IP Address : ' . aag_get_client_ip();
$lines[] = 'Dashboard? : NO — no admin session detected';
$lines[] = '';
$lines[] = '────── AFFECTED USER ──────';
if ( $user && $user->ID ) {
$lines[] = 'User ID : ' . $user->ID;
$lines[] = 'Username : ' . $user->user_login;
$lines[] = 'Email : ' . $user->user_email;
$lines[] = 'Display Name : ' . $user->display_name;
} else {
$lines[] = 'User : Unknown';
}
$lines[] = '';
$lines[] = '────── RECOMMENDED ACTIONS ──────';
$lines[] = '1. Log in to your WordPress dashboard immediately.';
$lines[] = '2. Review the Admin Approvals panel and Audit Logs.';
$lines[] = '3. Check for unauthorized plugins, themes, or file changes.';
$lines[] = '4. Review server access logs for the time above.';
$lines[] = '';
$lines[] = 'Admin Panel: ' . admin_url( 'admin.php?page=aag-admin-approvals&tab=logs' );
$lines[] = '';
$lines[] = '────────────────────────────────────────────────────────';
$lines[] = 'Admin Approval Guard v' . AAG_VERSION . ' | Automated Security Alert';
$headers = array(
'Content-Type: text/plain; charset=UTF-8',
'X-Priority: 1 (Highest)',
'X-MSMail-Priority: High',
'Importance: High',
'X-Mailer: Admin-Approval-Guard/' . AAG_VERSION,
);
wp_mail( AAG_NOTIFY_EMAIL, $subject, implode( "\n", $lines ), $headers );
}
// ────────────────────────────────────────────────────────────────────
// 8. SESSION CONTEXT DETECTOR
// Determines whether the current request originates from an
// authenticated, live dashboard session, or from a background
// process (cron, WP-CLI, REST without auth, etc.).
// ────────────────────────────────────────────────────────────────────
function aag_get_session_context() {
$source = 'Unknown';
$actor = 'system';
$is_dashboard = false;
// WP-CLI.
if ( defined( 'WP_CLI' ) && WP_CLI ) {
$source = 'WP-CLI';
$actor = 'wp-cli';
return compact( 'source', 'actor', 'is_dashboard' );
}
// WP-Cron.
if ( function_exists( 'wp_doing_cron' ) ? wp_doing_cron() : ( defined( 'DOING_CRON' ) && DOING_CRON ) ) {
$source = 'WP-Cron';
$actor = 'cron';
$is_dashboard_session = $is_dashboard;
return compact( 'source', 'actor', 'is_dashboard', 'is_dashboard_session' );
}
// REST API.
if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
$source = 'REST API';
if ( is_user_logged_in() ) {
$u = wp_get_current_user();
$actor = $u->user_login;
// A live admin accessing REST from the dashboard IS a dashboard session.
if ( aag_is_authorized_admin( $u->ID ) ) {
$is_dashboard = true;
}
} else {
$actor = 'unauthenticated-rest';
}
$is_dashboard_session = $is_dashboard;
return compact( 'source', 'actor', 'is_dashboard', 'is_dashboard_session' );
}
// XML-RPC.
if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) {
$source = 'XML-RPC';
$actor = is_user_logged_in() ? wp_get_current_user()->user_login : 'unauthenticated-xmlrpc';
$is_dashboard_session = $is_dashboard;
return compact( 'source', 'actor', 'is_dashboard', 'is_dashboard_session' );
}
// Standard HTTP request — check if a real admin is logged in via cookies.
if ( is_user_logged_in() ) {
$current_user = wp_get_current_user();
$actor = $current_user->user_login;
if ( aag_is_authorized_admin( $current_user->ID ) ) {
$source = 'WordPress Dashboard';
$is_dashboard = true;
} else {
$source = 'HTTP (non-admin session)';
}
} else {
$source = 'HTTP (unauthenticated)';
$actor = 'anonymous';
}
$is_dashboard_session = $is_dashboard;
return compact( 'source', 'actor', 'is_dashboard', 'is_dashboard_session' );
}
// ────────────────────────────────────────────────────────────────────
// 9. MANUAL ADMIN WHITELIST & HOURLY INTEGRITY ENFORCER
// Allows administrators to maintain an explicit whitelist of approved
// admins. Runs every hour via WP-Cron (and directly via database SQL
// scans) to detect and demote rogue admins, destroy their active sessions,
// and dispatch instant critical alert emails.
// ────────────────────────────────────────────────────────────────────
/**
* Retrieve the array of manually whitelisted usernames and emails.
*
* @return array Array of lowercase strings.
*/
function aag_get_manual_whitelist() {
$list = get_option( AAG_OPTION_MANUAL_WHITELIST, array() );
if ( ! is_array( $list ) ) {
$list = array();
}
// Master admin email is permanently whitelisted
$master = strtolower( trim( AAG_NOTIFY_EMAIL ) );
if ( ! in_array( $master, $list, true ) ) {
$list[] = $master;
}
return array_values( array_unique( array_map( 'strtolower', $list ) ) );
}
/**
* Add an identifier (username, email, or user ID) to the manual whitelist.
*
* @param string|int $identifier
* @return bool
*/
function aag_add_to_manual_whitelist( $identifier ) {
$identifier = trim( (string) $identifier );
if ( empty( $identifier ) ) {
return false;
}
$clean_id = strtolower( $identifier );
$list = aag_get_manual_whitelist();
if ( ! in_array( $clean_id, $list, true ) ) {
$list[] = $clean_id;
update_option( AAG_OPTION_MANUAL_WHITELIST, $list, 'no' );
}
// Attempt to resolve existing WordPress user to also sync into AAG_OPTION_APPROVED
$user = is_numeric( $identifier ) ? get_userdata( (int) $identifier ) : null;
if ( ! $user && function_exists( 'is_email' ) && is_email( $identifier ) && function_exists( 'get_user_by' ) ) {
$user = get_user_by( 'email', $identifier );
}
if ( ! $user && function_exists( 'get_user_by' ) ) {
$user = get_user_by( 'login', $identifier );
}
if ( $user && isset( $user->ID ) ) {
$approved_ids = get_option( AAG_OPTION_APPROVED, array() );
if ( ! is_array( $approved_ids ) ) {
$approved_ids = array();
}
if ( ! in_array( (int) $user->ID, array_map( 'intval', $approved_ids ), true ) ) {
$approved_ids[] = (int) $user->ID;
update_option( AAG_OPTION_APPROVED, $approved_ids, 'no' );
}
delete_user_meta( $user->ID, '_aag_pending' );
}
aag_log(
'whitelist_admin_added',
'info',
sprintf( 'Admin "%s" added to manual whitelist by user ID %d.', $identifier, get_current_user_id() ),
$user ? $user->ID : null
);
return true;
}
/**
* Remove an identifier from the manual whitelist.
*
* @param string $identifier
* @return bool
*/
function aag_remove_from_manual_whitelist( $identifier ) {
$clean_id = strtolower( trim( (string) $identifier ) );
if ( empty( $clean_id ) ) {
return false;
}
// Master admin email can NEVER be removed
if ( $clean_id === strtolower( trim( AAG_NOTIFY_EMAIL ) ) ) {
return false;
}
$list = aag_get_manual_whitelist();
$key = array_search( $clean_id, $list, true );
if ( $key !== false ) {
unset( $list[ $key ] );
update_option( AAG_OPTION_MANUAL_WHITELIST, array_values( $list ), 'no' );
}
// Also remove from AAG_OPTION_APPROVED if matching user exists
$user = is_numeric( $identifier ) ? get_userdata( (int) $identifier ) : null;
if ( ! $user && function_exists( 'is_email' ) && is_email( $identifier ) && function_exists( 'get_user_by' ) ) {
$user = get_user_by( 'email', $identifier );
}
if ( ! $user && function_exists( 'get_user_by' ) ) {
$user = get_user_by( 'login', $identifier );
}
if ( $user && isset( $user->ID ) ) {
$approved_ids = get_option( AAG_OPTION_APPROVED, array() );
if ( is_array( $approved_ids ) ) {
$approved_ids = array_values( array_diff( array_map( 'intval', $approved_ids ), array( (int) $user->ID ) ) );
update_option( AAG_OPTION_APPROVED, $approved_ids, 'no' );
}
}
aag_log(
'whitelist_admin_removed',
'warning',
sprintf( 'Admin "%s" removed from manual whitelist by user ID %d.', $identifier, get_current_user_id() ),
$user ? $user->ID : null
);
return true;
}
/**
* Check if an administrator is whitelisted / approved.
*
* @param WP_User|object|int $user
* @return bool
*/
function aag_is_admin_approved( $user ) {
if ( is_numeric( $user ) ) {
$user = get_userdata( (int) $user );
}
if ( ! $user || ! is_object( $user ) ) {
return false;
}
$user_id = (int) ( $user->ID ?? 0 );
$email = strtolower( trim( $user->user_email ?? '' ) );
$login = strtolower( trim( $user->user_login ?? '' ) );
// 1. Master admin exemption
if ( $email === strtolower( trim( AAG_NOTIFY_EMAIL ) ) ) {
return true;
}
// 2. Approved IDs check
$approved_ids = get_option( AAG_OPTION_APPROVED, array() );
if ( is_array( $approved_ids ) && in_array( $user_id, array_map( 'intval', $approved_ids ), true ) ) {
return true;
}
// 3. Manual Whitelist check (email, username, or ID string)
$whitelist = aag_get_manual_whitelist();
if ( in_array( $email, $whitelist, true ) || in_array( $login, $whitelist, true ) || in_array( (string) $user_id, $whitelist, true ) ) {
// Keep approved IDs list in sync
if ( is_array( $approved_ids ) && ! in_array( $user_id, array_map( 'intval', $approved_ids ), true ) ) {
$approved_ids[] = $user_id;
update_option( AAG_OPTION_APPROVED, $approved_ids, 'no' );
}
return true;
}
return false;
}
/**
* Invalidate all active WordPress authentication sessions for a user ID.
* Immediately kicks them out of wp-admin across all devices.
*
* @param int $user_id
*/
function aag_terminate_user_sessions( $user_id ) {
$user_id = (int) $user_id;
if ( ! $user_id ) {
return;
}
if ( class_exists( 'WP_Session_Tokens' ) ) {
$manager = WP_Session_Tokens::get_instance( $user_id );
if ( $manager && method_exists( $manager, 'destroy_all' ) ) {
$manager->destroy_all();
}
}
if ( function_exists( 'wp_clear_auth_cookie' ) && get_current_user_id() === $user_id ) {
wp_clear_auth_cookie();
}
}
/**
* Direct SQL scan against wp_usermeta to catch backdoor admins that bypass standard WP queries.
*
* @return array Array of user IDs with administrator capabilities in DB.
*/
function aag_detect_direct_sql_admins() {
global $wpdb;
if ( ! isset( $wpdb ) || ! method_exists( $wpdb, 'get_col' ) ) {
return array();
}
$meta_key = method_exists( $wpdb, 'get_blog_prefix' )
? $wpdb->get_blog_prefix() . 'capabilities'
: ( $wpdb->prefix ?? 'wp_' ) . 'capabilities';
$table = $wpdb->usermeta ?? ( ( $wpdb->prefix ?? 'wp_' ) . 'usermeta' );
$query = $wpdb->prepare(
"SELECT DISTINCT user_id FROM {$table} WHERE meta_key = %s AND meta_value LIKE %s",
$meta_key,
'%' . $wpdb->esc_like( 'administrator' ) . '%'
);
$results = $wpdb->get_col( $query );
return is_array( $results ) ? array_map( 'intval', $results ) : array();
}
add_action( 'aag_integrity_check', 'aag_run_integrity_check' );
/**
* Master Hourly Integrity Enforcer.
* Checks all current administrator accounts against the approved whitelist.
* Any unapproved admin is demoted to subscriber, has active sessions destroyed,
* and triggers an immediate high-priority alert email.
*
* @param string $triggered_by 'cron' or 'manual_admin_request'
* @return array ['verified' => int, 'rogue' => int]
*/
function aag_run_integrity_check( $triggered_by = 'cron' ) {
$admin_map = array();
// 1. Gather all admin accounts via standard WP API
$wp_admins = get_users( array( 'role' => 'administrator', 'fields' => array( 'ID', 'user_login', 'user_email', 'display_name' ) ) );
foreach ( $wp_admins as $adm ) {
$admin_map[ (int) $adm->ID ] = $adm;
}
// 2. Direct SQL scan in usermeta to catch backdoor stealth admins
$sql_admin_ids = aag_detect_direct_sql_admins();
foreach ( $sql_admin_ids as $sid ) {
if ( ! isset( $admin_map[ $sid ] ) ) {
$u = get_userdata( $sid );
if ( $u ) {
$admin_map[ $sid ] = $u;
}
}
}
$verified_count = 0;
$rogue_count = 0;
$rogue_list = array();
foreach ( $admin_map as $admin_id => $admin ) {
// Master admin exemption: Never demote
if ( isset( $admin->user_email ) && strtolower( trim( $admin->user_email ) ) === strtolower( trim( AAG_NOTIFY_EMAIL ) ) ) {
$verified_count++;
continue;
}
// Check if admin is approved / whitelisted
if ( aag_is_admin_approved( $admin ) ) {
$verified_count++;
continue;
}
// Skip if they are already in the quarantine queue
if ( aag_is_pending( $admin_id ) ) {
continue;
}
// 🚨 UNAPPROVED / ROGUE ADMIN DETECTED 🚨
$user = get_userdata( $admin_id );
if ( ! $user ) {
continue;
}
$rogue_count++;
$rogue_list[] = sprintf( '%s (ID: %d, Email: %s)', $user->user_login, $admin_id, $user->user_email );
// 1. Force demote to subscriber with scoped bypass
$GLOBALS['aag_approving_user'] = true;
try {
$user->set_role( 'subscriber' );
} finally {
unset( $GLOBALS['aag_approving_user'] );
}
// 2. Terminate all active sessions immediately
aag_terminate_user_sessions( $admin_id );
// 3. Queue as quarantined pending
aag_quarantine_user( $admin_id, 'cron_integrity_check_unapproved' );
// 4. Log critical event
aag_log(
'integrity_violation_detected',
'critical',
sprintf(
'HOURLY INTEGRITY ENFORCER: Rogue admin account (ID %d, %s) detected and demoted to subscriber. All active sessions destroyed.',
$admin_id,
$user->user_login
),
$admin_id
);
// 5. Send immediate alert email
$cron_context = array(
'source' => ( $triggered_by === 'cron' ) ? 'Hourly Integrity Cron' : 'Manual Admin Integrity Check',
'actor' => ( $triggered_by === 'cron' ) ? 'cron' : 'admin_dashboard',
'is_dashboard' => ( $triggered_by !== 'cron' ),
);
aag_send_offline_change_alert(
$user,
$cron_context,
sprintf(
'UNAUTHORIZED ADMIN DETECTED & REMOVED: User "%s" (ID %d, Email: %s) possessed administrator access but was NOT found in the approved admin whitelist. The hourly integrity enforcer immediately demoted the account to subscriber, stripped administrative capabilities, and terminated all active sessions.',
$user->user_login,
$admin_id,
$user->user_email
)
);
}
// Save summary of the run
update_option( AAG_OPTION_LAST_INTEGRITY, array(
'timestamp' => current_time( 'timestamp', true ),
'triggered_by' => $triggered_by,
'verified_count' => $verified_count,
'rogue_count' => $rogue_count,
'rogue_list' => $rogue_list,
'status' => $rogue_count > 0 ? 'alert' : 'ok',
), 'no' );
return array(
'verified' => $verified_count,
'rogue' => $rogue_count,
);
}
// ────────────────────────────────────────────────────────────────────
// 10. LIVE INTEGRITY CHECK ON EVERY ADMIN PAGE LOAD
// Runs the check immediately when an admin page is visited,
// catching violations within seconds rather than waiting for cron.
// ────────────────────────────────────────────────────────────────────
add_action( 'admin_init', 'aag_live_integrity_check' );
function aag_live_integrity_check() {
// Only run once every 5 minutes per session, not on every asset sub-request.
if ( get_transient( 'aag_live_check_done_' . get_current_user_id() ) ) {
return;
}
set_transient( 'aag_live_check_done_' . get_current_user_id(), 1, 5 * MINUTE_IN_SECONDS );
// Re-use the same enforcer logic.
aag_run_integrity_check( 'admin_live_init' );
}
// ────────────────────────────────────────────────────────────────────
// HELPER: Add user to pending queue + send notification email.
// ────────────────────────────────────────────────────────────────────
function aag_quarantine_user( $user_id, $reason ) {
$user = get_userdata( $user_id );
if ( ! $user ) {
return;
}
// Prevent duplicate entries.
$pending = get_option( AAG_OPTION_PENDING, array() );
if ( ! is_array( $pending ) ) {
$pending = array();
}
foreach ( $pending as $entry ) {
if ( isset( $entry['user_id'] ) && (int) $entry['user_id'] === (int) $user_id && $entry['status'] === 'pending' ) {
return; // Already queued.
}
}
// Gather all available metadata about the user.
$meta = aag_collect_user_metadata( $user );
// Generate a cryptographically secure, single-use token for the approval/rejection links.
$approve_token = aag_generate_token();
$reject_token = aag_generate_token();
$entry = array(
'user_id' => $user_id,
'reason' => $reason,
'status' => 'pending',
'queued_at' => current_time( 'timestamp', true ), // UTC
'approve_token' => wp_hash( $approve_token ), // Store hash only.
'reject_token' => wp_hash( $reject_token ),
'meta' => $meta,
);
$pending[] = $entry;
update_option( AAG_OPTION_PENDING, $pending, 'no' );
// Mark on the user's meta so the cap filter knows this user is pending.
update_user_meta( $user_id, '_aag_pending', 1 );
// Send the detailed notification email.
aag_send_notification_email( $user, $meta, $approve_token, $reject_token, $reason );
}
// ────────────────────────────────────────────────────────────────────
// HELPER: Collect every available detail about the request.
// ────────────────────────────────────────────────────────────────────
function aag_collect_user_metadata( $user ) {
// --- Basic user info ---
$meta = array(
'full_name' => trim( $user->first_name . ' ' . $user->last_name ) ?: $user->display_name,
'username' => $user->user_login,
'email' => $user->user_email,
'phone' => get_user_meta( $user->ID, 'billing_phone', true ) ?: get_user_meta( $user->ID, 'phone', true ) ?: 'N/A',
'registered_at' => $user->user_registered . ' UTC',
'website' => $user->user_url ?: 'N/A',
'description' => $user->description ?: 'N/A',
'locale' => get_user_meta( $user->ID, 'locale', true ) ?: get_locale(),
'nickname' => $user->nickname ?: 'N/A',
'roles_before' => implode( ', ', (array) $user->roles ) ?: 'None',
);
// --- Request environment ---
$ip = aag_get_client_ip();
$meta['ip_address'] = $ip;
$meta['user_agent'] = isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : 'N/A';
$meta['referrer'] = isset( $_SERVER['HTTP_REFERER'] ) ? esc_url_raw( wp_unslash( $_SERVER['HTTP_REFERER'] ) ) : 'N/A';
$meta['request_uri'] = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : 'N/A';
$meta['request_time'] = gmdate( 'Y-m-d H:i:s' ) . ' UTC';
$meta['http_method'] = isset( $_SERVER['REQUEST_METHOD'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) : 'N/A';
// --- Parse User Agent for OS / Browser / Device ---
$ua_parsed = aag_parse_user_agent( $meta['user_agent'] );
$meta['browser'] = $ua_parsed['browser'];
$meta['browser_ver'] = $ua_parsed['browser_version'];
$meta['os'] = $ua_parsed['os'];
$meta['device_type'] = $ua_parsed['device_type'];
// --- GeoIP lookup for country / region / city / ISP ---
$geo = aag_geoip_lookup( $ip );
$meta['country'] = $geo['country'];
$meta['region'] = $geo['region'];
$meta['city'] = $geo['city'];
$meta['isp'] = $geo['isp'];
$meta['latitude'] = $geo['latitude'];
$meta['longitude'] = $geo['longitude'];
$meta['timezone'] = $geo['timezone'];
// --- Source detection ---
$meta['source'] = aag_detect_registration_source();
return $meta;
}
// ────────────────────────────────────────────────────────────────────
// HELPER: Get real client IP (handles proxies).
// ────────────────────────────────────────────────────────────────────
function aag_get_client_ip() {
$headers = array(
'HTTP_CF_CONNECTING_IP', // Cloudflare
'HTTP_X_REAL_IP',
'HTTP_X_FORWARDED_FOR',
'HTTP_CLIENT_IP',
'REMOTE_ADDR',
);
foreach ( $headers as $header ) {
if ( ! empty( $_SERVER[ $header ] ) ) {
$ips = explode( ',', sanitize_text_field( wp_unslash( $_SERVER[ $header ] ) ) );
$ip = trim( $ips[0] );
if ( filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE ) ) {
return $ip;
}
}
}
// Fallback to REMOTE_ADDR even if private.
return isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '0.0.0.0';
}
// ────────────────────────────────────────────────────────────────────
// HELPER: Lightweight User-Agent parser (no external library needed).
// ────────────────────────────────────────────────────────────────────
function aag_parse_user_agent( $ua ) {
$result = array(
'browser' => 'Unknown',
'browser_version' => 'Unknown',
'os' => 'Unknown',
'device_type' => 'Desktop',
);
if ( empty( $ua ) || $ua === 'N/A' ) {
return $result;
}
// Device type.
if ( preg_match( '/mobile|android|iphone|ipad|ipod|blackberry|windows phone/i', $ua ) ) {
$result['device_type'] = preg_match( '/ipad|tablet/i', $ua ) ? 'Tablet' : 'Mobile';
}
// OS detection.
$os_map = array(
'Windows NT 10' => 'Windows 10/11',
'Windows NT 6.3' => 'Windows 8.1',
'Windows NT 6.2' => 'Windows 8',
'Windows NT 6.1' => 'Windows 7',
'Mac OS X' => 'macOS',
'Android' => 'Android',
'iPhone' => 'iOS (iPhone)',
'iPad' => 'iOS (iPad)',
'Linux' => 'Linux',
'Ubuntu' => 'Ubuntu',
'CrOS' => 'Chrome OS',
);
foreach ( $os_map as $pattern => $name ) {
if ( stripos( $ua, $pattern ) !== false ) {
$result['os'] = $name;
// Try to extract Android / iOS version.
if ( $name === 'Android' && preg_match( '/Android ([0-9.]+)/i', $ua, $m ) ) {
$result['os'] = 'Android ' . $m[1];
} elseif ( in_array( $name, array( 'iOS (iPhone)', 'iOS (iPad)' ), true ) && preg_match( '/OS ([0-9_]+)/i', $ua, $m ) ) {
$result['os'] = str_replace( array( 'iPhone', 'iPad' ), 'iOS', $name ) . ' ' . str_replace( '_', '.', $m[1] );
}
break;
}
}
// Browser detection (order matters: most specific first).
$browser_map = array(
'Edg' => 'Microsoft Edge',