-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathforcefield-auth.php
1773 lines (1475 loc) · 60.9 KB
/
forcefield-auth.php
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
// ========================================
// === ForceField Authentication Module ===
// ========================================
// === Login Role Protection ===
// - Block Unwhitelisted SuperAdmin Logins
// - Block Unwhitelisted Administrator Logins
// === Action Tokenizer ===
// - Check for Existing Token
// - Add Token Fields to Forms
// - Add Form Field Abstract
// - AJAX to Create and Return Token
// - Token Output Abstract
// - Create a Token
// - Delete a Token
// === Authentication ===
// - XML RPC Authentication
// - XML RPC Error Message (Banned)
// - XML RPC Error Message (Blocked)
// - XML RPC requires SSL Message
// - Login Token Authentication
// - Registration Token Authentication
// - Blog Signup Authenticate
// - Lost Password Token Authentication
// - Commenting Authenticate
// - BuddyPress Registration Authenticate
// -----------------------------
// === Login Role Protection ===
// -----------------------------
// -------------------------------------
// Block Unwhitelisted SuperAdmin Logins
// -------------------------------------
// 0.9.6: added whitelist check for super admin role (multisite only)
// 1.0.1: temporarily disabled for further testing
// (this really needs has be in Network Activated plugin settings page only)
// add_action( 'init', 'forcefield_superadmin_validation', 0 );
function forcefield_superadmin_validation() {
// --- bug out if not logged in ---
if ( !is_user_logged_in() ) {
return;
}
// --- get current user ---
$user = wp_get_current_user();
$userid = $user->data->ID;
$userlogin = $user->data->user_login;
// 1.0.3: fix to variable typo usermail
$useremail = $user->data->user_email;
// --- get login settings ---
if ( !is_multisite() ) {
return;
}
$superadmins = get_super_admins();
$blocksuper = forcefield_get_setting( 'super_block' );
// --- check for superadmin role ---
if ( ( 'yes' === (string) $blocksuper ) && ( count( $superadmins ) > 0 ) && is_super_admin( $userid ) ) {
// --- get whitelist ---
$whitelisted = array();
$whitelist = forcefield_get_setting( 'super_whitelist' );
if ( strstr( $whitelist, ',' ) ) {
$whitelisted = explode( ",", $whitelist );
// 1.0.3: fix to duplicate variable name usage
foreach ( $whitelisted as $i => $wlisted ) {
$whitelisted[$i] = trim( $wlisted );
}
} elseif ( '' != trim( $whitelist ) ) {
// 1.0.3: fix to mismatched variable name
$whitelisted = array( trim( $whitelist ) );
}
// --- check if in whitelist ---
if ( ( count( $whitelisted ) > 0 ) && !in_array( $userlogin, $whitelisted ) ) {
// --- maybe send admin alert email ---
$adminemail = forcefield_get_setting( 'super_email' );
$alertemail = forcefield_get_setting( 'super_alert' );
$blockaction = forcefield_get_setting( 'super_blockaction' );
// ---- handle block action ---
if ( 'delete' == $blockaction ) {
// --- delete the user completely ---
if ( !function_exists( 'wp_delete_user' ) ) {
include ABSPATH . WPINC . '/user.php';
}
wp_delete_user( $userid );
} elseif ( 'revoke' == $blockaction ) {
// --- remove administrator role ---
revoke_super_admin( $userid );
} elseif ( 'demote' == $blockaction ) {
// --- remove all roles and add subscriber only ---
revoke_super_admin( $userid );
foreach ( $user->roles as $role ) {
$user->remove_role( $role );
}
$user->add_role( 'subscriber' );
}
// --- maybe send alert email ---
if ( ( 'yes' == $alertemail ) && ( '' != $adminemail ) ) {
// --- set mail from name ---
add_filter( 'wp_mail_from_name', 'forcefield_email_from_name' );
// --- set email subject ---
$subject = '[ForceField] Warning: Unwhitelisted Super-Admin Login!';
// --- set email subject body ---
// 1.0.1: added user email to message
$blogname = get_bloginfo( 'name' );
$siteurl = site_url();
$body = 'ForceField plugin has blocked an unwhitelisted super-admin login' . "\n";
$body .= 'to WordPress site ' . $blogname . ' (' . $siteurl . ')' . "\n\n";
$body .= 'Username Blocked: "' . $userlogin . '" (' . $useremail . ')' . "\n\n";
$body .= 'If this username is familiar, add it to your whitelist to stop further alerts.' . "\n";
$body .= 'But if it is unfamiliar, your site security may be compromised.' . "\n\n";
// --- maybe add block action info ---
if ( 'delete' === (string) $blockaction ) {
$body .= 'Additionally, according to your ForceField plugin settings,' . "\n";
$body .= 'the user "' . $userlogin . '" was automatically deleted.' . "\n\n";
} elseif ( 'revoke' === (string) $blockaction ) {
$body .= 'Additionally, according to your ForceField plugin settings,' . "\n";
$body .= 'the super-admin role has been revoked from user "' . $userlogin . '.' . "\n\n";
} elseif ( 'demote' === (string) $blockaction ) {
$body .= 'Additionally, according to your ForceField plugin settings,' . "\n";
$body .= 'the user "' . $userlogin . ' has been demoted to a subscriber.' . "\n\n";
}
// --- add dump user object ---
$body .= 'Below is a dump of the user object for "' . $userlogin . '"' . "\n";
$body .= '----------' . "\n";
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_print_r
$body .= print_r( $user, true );
// 1.0.1: added email subject and body filtering
$subject = apply_filters( 'forcefield_superadmin_blocked_subject', $subject, $userid, $blockaction );
$body = apply_filters( 'forcefield_superadmin_blocked_message', $body, $userid, $blockaction );
// --- send the alert email now ---
// 0.9.7: allow for multiple alert emails
if ( strstr( $adminemail, ',' ) ) {
$emails = explode( ',', $adminemail );
}else {
$emails = array( trim( $adminemail ) );
}
foreach ( $emails as $email ) {
$email = trim( $email );
wp_mail( $email, $subject, $body );
}
}
// --- add IP address to blocklist ---
forcefield_blocklist_record_ip( 'admin_bad' );
// --- clear the login cache ---
wp_cache_delete( $userid, 'users' );
wp_cache_delete( $userlogin, 'userlogins' );
wp_logout();
exit;
}
}
}
// ----------------------------------------
// Block Unwhitelisted Administrator Logins
// ----------------------------------------
add_action( 'init', 'forcefield_administrator_validation', 0 );
function forcefield_administrator_validation() {
// --- bug out if not logged in ---
if ( !is_user_logged_in() ) {
return;
}
// --- get current user ---
$user = wp_get_current_user();
$userid = $user->data->ID;
$userlogin = $user->data->user_login;
// 1.0.3: fix to variable typo usermail
$useremail = $user->data->user_email;
// --- get login settings ---
$blockadmins = forcefield_get_setting( 'admin_block' );
// --- check for administrator role ---
if ( ( 'yes' === (string) $blockadmins ) && in_array( 'administrator', (array) $user->roles ) ) {
// --- get whitelist ---
$whitelisted = array();
$whitelist = forcefield_get_setting( 'admin_whitelist' );
if ( strstr( $whitelist, ',' ) ) {
$whitelisted = explode( ',', $whitelist );
foreach ( $whitelisted as $i => $admin ) {
$whitelisted[$i] = trim( $admin );
}
} elseif ( '' != trim( $whitelist ) ) {
$whitelisted = array( trim( $whitelist ) );
}
// --- check if not in whitelist ---
if ( ( count( $whitelisted ) > 0 ) && !in_array( $userlogin, $whitelisted ) ) {
// --- maybe send admin alert email ---
// 0.9.6: shift get setting up so available in email body
// 0.9.6: change admin_autodelete to admin_blockaction setting
$adminemail = forcefield_get_setting( 'admin_email' );
$alertemail = forcefield_get_setting( 'admin_alert' );
$blockaction = forcefield_get_setting( 'admin_blockaction' );
// ---- handle block action ---
if ( 'delete' === (string) $blockaction ) {
// --- delete the user completely ---
if ( !function_exists( 'wp_delete_user' ) ) {
include ABSPATH . WPINC . '/user.php';
}
wp_delete_user( $userid );
} elseif ( 'revoke' === (string) $blockaction ) {
// --- remove administrator role ---
$user->remove_role( 'administrator' );
} elseif ( 'demote' == (string) $blockaction ) {
// --- remove all roles and add subscriber only ---
foreach ( $user->roles as $role ) {
$user->remove_role( $role );
}
$user->add_role( 'subscriber' );
}
// --- maybe send alert email ---
if ( ( 'yes' === (string) $alertemail ) && ( '' != $adminemail ) ) {
// --- set mail from name ---
add_filter( 'wp_mail_from_name', 'forcefield_email_from_name' );
// --- set email subject ---
$subject = '[ForceField] Warning: Unwhitelisted Administrator Login!';
// --- set email body ---
// 1.0.1: added user email to message
$blogname = get_bloginfo( 'name' );
$siteurl = site_url();
$body = 'ForceField plugin has blocked an unwhitelisted administrator login' . "\n";
$body .= 'to WordPress site ' . $blogname . ' (' . $siteurl . ')' . "\n\n";
$body .= 'Username Blocked: "' . $userlogin . '" (' . $useremail . ')' . "\n\n";
$body .= 'If this username is familiar, add it to your whitelist to stop further alerts.' . "\n";
$body .= 'But if it is unfamiliar, your site security may be compromised.' . "\n\n";
// --- maybe add block action info ---
if ( 'delete' === (string) $blockaction ) {
$body .= 'Additionally, according to your ForceField plugin settings,' . "\n";
$body .= 'the user "' . $userlogin . '" was automatically deleted.' . "\n\n";
} elseif ( 'revoke' === (string) $blockaction ) {
$body .= 'Additionally, according to your ForceField plugin settings,' . "\n";
$body .= 'the administrator role has been revoked from user "' . $userlogin . '.' . "\n\n";
} elseif ( 'demote' === (string) $blockaction ) {
$body .= 'Additionally, according to your ForceField plugin settings,' . "\n";
$body .= 'the user "' . $userlogin . ' has been demoted to a subscriber.' . "\n\n";
}
// --- add dump user object ---
// 1.0.1: fix to user_login variable name
$body .= 'Below is a dump of the user object for "' . $userlogin . '"' . "\n";
$body .= '----------' . "\n";
// phpcs:ignore WordPress.PHP.DevelopmentFunctions
$body .= print_r( $user, true );
// 1.0.1: added email subject and body filtering
$subject = apply_filters( 'forcefield_admin_blocked_subject', $subject, $userid, $blockaction );
$body = apply_filters( 'forcefield_admin_blocked_message', $body, $userid, $blockaction );
// --- send the alert email now ---
// 0.9.6: fix to incorrect message variable typo
// 0.9.7: allow for multiple alert emails
if ( strstr( $adminemail, ',' ) ) {
$emails = explode( ',', $adminemail );
} else {
$emails = array( $adminemail );
}
foreach ( $emails as $email ) {
$email = trim( $email );
wp_mail( $email, $subject, $body );
}
}
// --- add IP address to blocklist ---
forcefield_blocklist_record_ip( 'super_bad' );
// --- clear the login cache ---
wp_cache_delete( $userid, 'users' );
wp_cache_delete( $userlogin, 'userlogins' );
wp_logout();
exit;
}
}
}
// ------------------------
// === Action Tokenizer ===
// ------------------------
// ------------------------
// Check for Existing Token
// ------------------------
function forcefield_check_token( $context, $getexpiry = false ) {
global $forcefield;
// $debug = true;
$debug = false;
// --- validate IP address to IP key ---
$iptype = forcefield_get_ip_type( $forcefield['ip'] );
// 0.9.4: allow for localhost IP type
if ( 'localhost' === (string) $iptype ) {
$ipaddress = str_replace( '.', '-', $forcefield['ip'] );
} elseif ( 'ip4' === (string) $iptype ) {
$ipaddress = str_replace( '.', '-', $forcefield['ip'] );
} elseif ( 'ip6' === (string) $iptype ) {
$ipaddress = str_replace( ':', '--', $forcefield['ip'] );
} else {
return false;
}
// --- get transient token value by token key ---
$token = array();
$transientid = $context . '_token_' . $ipaddress;
if ( $debug ) {
echo "<!-- Transient ID: " . esc_html( $transientid ) . " -->" . PHP_EOL;
}
$tokenvalue = get_transient( $transientid );
if ( $tokenvalue ) {
$token['value'] = $tokenvalue;
}
// 0.9.5: maybe return transient expiry time also for consistency
if ( $getexpiry ) {
$timeout = forcefield_get_transient_timeout( $transientid );
if ( $timeout ) {
$time = time();
if ( $debug ) {
echo "<!-- Current Time: " . esc_html( $time ) . " -->" . PHP_EOL;
echo "<!-- Expiry Time: " . esc_html( $timeout ) . " -->" . PHP_EOL;
}
$expiry = $timeout - $time;
$token['expiry'] = $expiry;
}
}
if ( $debug ) {
// phpcs:ignore WordPress.PHP.DevelopmentFunctions
echo "<!-- Token: " . esc_html( print_r( $token, true ) ) . " -->";
}
return $token;
}
// -------------------------
// Add Token Fields to Forms
// -------------------------
// 0.9.5: add token field to BuddyPress registration form
// 0.9.7: fix to incorrect function suffixes for signup and lostpass
add_action( 'login_form', 'forcefield_login_field' );
add_action( 'register_form', 'forcefield_register_field' );
add_action( 'signup_extra_fields', 'forcefield_signup_field' );
add_action( 'signup_blogform', 'forcefield_signup_field' );
add_action( 'lostpassword_form', 'forcefield_lostpass_field' );
add_action( 'comment_form', 'forcefield_comment_field' );
function forcefield_login_field() {
forcefield_add_field( 'login' );
}
function forcefield_register_field() {
forcefield_add_field( 'register' );
}
function forcefield_signup_field() {
forcefield_add_field( 'signup' );
}
function forcefield_lostpass_field() {
forcefield_add_field( 'lostpass' );
}
function forcefield_comment_field() {
forcefield_add_field( 'comment' );
}
// 0.9.5: add token field to BuddyPress registration form
add_action( 'bp_after_account_details_fields', 'forcefield_buddypress_field' );
function forcefield_buddypress_field() {
forcefield_add_field( 'buddypress' );
do_action( 'bp_auth_token_errors' );
}
// -----------------------
// Add Form Field Abstract
// -----------------------
// 1.0.1: remove argument and get context from action
function forcefield_add_field( $context ) {
// --- check setting for context ---
$tokenize = forcefield_get_setting( $context . '_token' );
if ( 'yes' != $tokenize ) {
return;
}
// --- output tokenizer javascript ---
// 0.9.3: add input via dynamic javascript instead of hardcoding
// echo '<input type="hidden" id="auth_token" name="auth_token_'.$context.'" value="" />';
echo '<span id="dynamic-tokenizer"></span>';
echo "<script>var tokeninput = document.createElement('input');
tokeninput.setAttribute('type', 'hidden'); tokeninput.setAttribute('value', '');
tokeninput.setAttribute('id', 'auth_token_" . esc_js( $context ) . "');
tokeninput.setAttribute('name', 'auth_token_" . esc_js( $context ) . "');
document.getElementById('dynamic-tokenizer').appendChild(tokeninput);</script>";
// --- output tokenizer iframe ---
$adminajax = admin_url( 'admin-ajax.php' );
$src = add_query_arg( 'action', 'forcefield_' . $context, $adminajax );
echo '<iframe style="display:none;" name="auth_frame" id="auth_frame" src="' . esc_url( $src ) . '"></iframe>';
}
// -------------------------------
// AJAX to Create and Return Token
// -------------------------------
// 0.9.5: add token field to BuddyPress registration form
// 1.0.1: remove separate functions and get context from action
add_action( 'wp_ajax_nopriv_forcefield_login', 'forcefield_output_token' );
add_action( 'wp_ajax_nopriv_forcefield_register', 'forcefield_output_token' );
add_action( 'wp_ajax_nopriv_forcefield_signup', 'forcefield_output_token' );
add_action( 'wp_ajax_forcefield_signup', 'forcefield_output_token' );
add_action( 'wp_ajax_nopriv_forcefield_lostpass', 'forcefield_output_token' );
add_action( 'wp_ajax_nopriv_forcefield_comment', 'forcefield_output_token' );
add_action( 'wp_ajax_forcefield_comment', 'forcefield_output_token' );
add_action( 'wp_ajax_nopriv_forcefield_buddypress', 'forcefield_output_token' );
// ---------------------
// Token Output Abstract
// ---------------------
// 1.0.1: remove argument and check context from action
function forcefield_output_token() {
// 1.0.5: added sanitize_title to request variable
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$action = sanitize_title( $_REQUEST['action'] );
// 1.0.4: added validation of action possibilities
$actions = array(
'forcefield_login',
'forcefield_register',
'forcefield_signup',
'forcefield_lostpass',
'forcefield_comment',
'forcefield_buddypress',
);
if ( !in_array( $action, $actions ) ) {
exit;
}
$context = str_replace( 'forcefield_', '', $action );
$token = forcefield_create_token( $context );
if ( $token ) {
// 0.9.3: added some extra javascript obfuscation of token value
$tokenchars = str_split( $token['value'], 1 );
// --- output token characters via script ---
echo "<script>var bits = new Array(); ";
foreach ( $tokenchars as $i => $char ) {
echo "bits[" . esc_js( $i ) . "] = '" . esc_js( $char ) . "'; ";
}
echo "bytes = bits.join(''); ";
echo "parent.document.getElementById('auth_token_" . esc_js( $context ) . "').value = bytes; ";
echo "</script>" . PHP_EOL;
// --- auto-refresh expired tokens ---
// 0.9.4: add a timer for token auto-refresh
if ( isset( $token['expiry'] ) ) {
$cycle = $token['expiry'] * 1000;
echo "<script>setTimeout(function() {window.location.reload();}, " . esc_js( $cycle ) . ");</script>";
}
} else {
// 1.0.4: added missing esc_html wrapper
echo esc_html( __( 'Error. No Token was generated.', 'forcefield' ) );
}
exit;
}
// --------------
// Create a Token
// --------------
function forcefield_create_token( $context ) {
global $forcefield;
$debug = false;
// $debug = true;
// --- check token setting for context ----
$tokenize = forcefield_get_setting( $context . '_token' );
if ( $debug ) {
echo "<!-- Tokenize? " . esc_html( $tokenize ) . " (" . esc_html( $context ) . ") -->";
}
if ( 'yes' != $tokenize ) {
return false;
}
// --- maybe return existing token ---
// 0.9.5: also check and return token expiry if found
// 1.0.0: ad logic to extend token expiry if not yet expired
$token = forcefield_check_token( $context, true );
if ( isset( $token['value'] ) ) {
if ( $debug ) {
// phpcs:ignore WordPress.PHP.DevelopmentFunctions
echo "<!-- Existing Token: " . esc_html( print_r( $token, true ) ) . " -->";
}
$tokenvalue = $token['value'];
} else {
$tokenvalue = wp_generate_password( 12, false, false );
}
// --- validate IP address and make IP key ---
// 0.9.4: allow for localhost IP type
$iptype = forcefield_get_ip_type( $forcefield['ip'] );
if ( 'localhost' === (string) $iptype ) {
$ip = str_replace( '.', '-', $forcefield['ip'] );
} elseif ( 'ip4' === (string) $iptype ) {
$ip = str_replace( '.', '-', $forcefield['ip'] );
} elseif ( 'ip6' === (string) $iptype ) {
$ip = str_replace( ':', '--', $forcefield['ip'] );
} else {
if ( $debug ) {
echo "<!-- No token generated for IP type '" . esc_html( $iptype ) . "' -->";
}
return false;
}
if ( $debug ) {
echo "<!-- IP: " . esc_html( $ip ) . " -->";
}
// --- get and set token expiry length ---
// 0.9.4: added context-specific expiry time filtering
// 0.9.4: set a bare minimum token usage time
// 0.9.6: fix to expirytime filter variable
$expirytime = forcefield_get_setting( 'blocklist_tokenexpiry' );
$expirytime = apply_filters( 'blocklist_tokenexpiry_' . $context, $expirytime );
$expirytime = absint( $expirytime );
if ( $expirytime < 0 ) {
$expirytime = 300;
}
if ( $expirytime < 30 ) {
$expirytime = 30;
}
if ( ( 'comment' === (string) $context ) && ( $expirytime < 300 ) ) {
$expirytime = 300;
}
// --- create token and set transient ---
$transientid = $context . '_token_' . $ip;
set_transient( $transientid, $tokenvalue, $expirytime );
// 0.9.4: return expiry time value also, for auto-refresh
$token = array( 'value' => $tokenvalue, 'expiry' => $expirytime );
$token = apply_filters( 'forcefield_token', $token, $context );
return $token;
}
// --------------
// Delete a Token
// --------------
function forcefield_delete_token( $context ) {
global $forcefield;
// --- validate IP address and make IP key ---
// 1.0.1: use check IP type function for consistency
$iptype = forcefield_get_ip_type( $forcefield['ip'] );
if ( 'localhost' === (string) $iptype ) {
$ip = str_replace( '.', '-', $forcefield['ip'] );
} elseif ( 'ip4' === (string) $iptype ) {
$ip = str_replace( '.', '-', $forcefield['ip'] );
} elseif ( 'ip6' === (string) $iptype ) {
$ip = str_replace( ':', '--', $forcefield['ip'] );
} else {
return false;
}
// --- delete token transient ---
$transientid = $context . '_token_' . $ip;
delete_transient( $transientid );
}
// ----------------------
// === Authentication ===
// ----------------------
// ----------------------
// XML RPC Authentication
// ----------------------
add_filter( 'authenticate', 'forcefield_xmlrpc_authentication', 9, 3 );
function forcefield_xmlrpc_authentication( $user, $username, $password ) {
// note: XMLRPC_REQUEST is defined in xmlrpc.php
if ( !defined( 'XMLRPC_REQUEST' ) || !XMLRPC_REQUEST ) {
return $user;
}
// --- filter general error message ---
$errormessage = forcefield_get_error_message();
$errormessage = apply_filters( 'forcefield_error_message_xmlrpc', $errormessage );
// --- check IP whitelist and blacklist ---
// 0.9.1: check IP whitelist
// 0.9.2: check IP blacklist
if ( forcefield_whitelist_check( 'apis' ) ) {
return $user;
}
if ( forcefield_blacklist_check( 'apis' ) ) {
forcefield_forbidden_exit();
}
// --- check for authentication block ---
$authblock = forcefield_get_setting( 'xmlrpc_authblock' );
$authban = forcefield_get_setting( 'xmlrpc_authban' );
if ( 'yes' === (string) $authban ) {
// --- ban this IP for XML RPC authentication violation ---
forcefield_blocklist_record_ip( 'xmlrpc_login' );
add_filter( 'xmlrpc_login_error', 'forcefield_xmlrpc_error_message_banned' );
do_action( 'xmlrpc_login_banned' );
return forcefield_filtered_error( 'xmlrpc_ban', $errormessage );
} elseif ( 'yes' === (string) $authblock ) {
// --- block this XML RPC attempt ---
// 0.9.1: record anyway so a changed ban setting can take effect
forcefield_blocklist_record_ip( 'xmlrpc_login' );
add_filter( 'xmlrpc_login_error', 'forcefield_xmlrpc_error_message_blocked' );
do_action( 'xmlrpc_login_blocked' );
return forcefield_filtered_error( 'xmlrpc_block', $errormessage );
} elseif ( is_wp_error( $user ) ) {
// --- record authentication fail ---
$transgressions = forcefield_blocklist_record_ip( 'xmlrpc_authfail' );
// 0.9.1: check against XML RPC authentication attempts limit
$blocked = forcefield_blocklist_check_transgressions( 'xmlrpc_authfail', $transgressions );
if ( $blocked ) {
do_action( 'xmlrpc_login_toomany' );
$status = 429; // 'too many requests'
return forcefield_filtered_error( 'xmlrpc_toomany', $errormessage, $status );
}
}
// --- check for SSL connection requirement ---
$requiressl = forcefield_get_setting( 'xmlrpc_requiressl' );
// 0.9.8: honour require SSL constant override
if ( defined( 'FORCEFIELD_REQUIRE_SSL' ) ) {
// 1.0.4: simplify logic to single line
$requiressl = ( (bool) FORCEFIELD_REQUIRE_SSL ) ? 'yes' : '';
}
if ( ( 'yes' === (string) $requiressl ) && !is_ssl() ) {
add_filter( 'xmlrpc_login_error', 'forcefield_xmlrpc_require_ssl_message' );
// note: we need to return an error here so that the xmlrpc_login_error filter is called
$errormessage = __( 'XML RPC requires SSL Connection.', 'forcefield' );
return forcefield_filtered_error( 'xmlrpc_ssl_required', $errormessage );
}
return $user;
}
// ------------------------------
// XML RPC Error Message (Banned)
// ------------------------------
function forcefield_xmlrpc_error_message_banned( $error ) {
$errormessage = __( 'Access denied. XML RPC authentication is disabled.', 'forcefield' );
$errormessage = apply_filters( 'forcefield_error_message_xmlrpc_banned', $errormessage );
$status = 405; // HTTP 405: Method Not Allowed
return new IXR_Error( $status, $errormessage );
}
// -------------------------------
// XML RPC Error Message (Blocked)
// ------------------------------
function forcefield_xmlrpc_error_message_blocked( $error ) {
$errormessage = __( 'Access denied. XML RPC authentication is disabled.', 'forcefield' );
$errormessage = apply_filters( 'forcefield_error_message_xmlrpc_blocked', $errormessage );
$status = 405; // HTTP 405: Method Not Allowed
return new IXR_Error( $status, $errormessage );
}
// ----------------------------
// XML RPC requires SSL Message
// ----------------------------
function forcefield_xmlrpc_require_ssl_message() {
$errormessage = __( 'XML RPC authentication requires an SSL Connection.', 'forcefield' );
$errormessage = apply_filters( 'forcefield_error_message_xmlrpc_requiressl', $errormessage );
$status = 426; // HTTP 426: Upgrade Required
return new IXR_Error( $status, $errormessage );
}
// --------------------------
// Login Token Authentication
// --------------------------
add_filter( 'authenticate', 'forcefield_login_validate', 11, 3 );
function forcefield_login_validate( $user, $username, $password ) {
// --- filter general error message ---
$errormessage = forcefield_get_error_message();
$errormessage = apply_filters( 'forcefield_error_message_login', $errormessage );
// --- check whitelist and blacklist ---
// 0.9.1: check IP whitelist
// 0.9.2: check IP blacklist
if ( forcefield_whitelist_check( 'actions' ) ) {
return $user;
}
if ( forcefield_blacklist_check( 'actions' ) ) {
forcefield_forbidden_exit();
}
// --- recheck failed user ---
// 0.9.1: for a failed login, check if an admin account
if ( $username && $password && is_wp_error( $user ) ) {
$checkuser = get_user_by( 'login', $username );
// --- check for super admin role ---
// 0.9.6: add check for super admin
if ( is_multisite() && is_super_admin( $checkuser->ID ) ) {
// --- add a record of failed super admin login attempt ---
$transgressions = forcefield_blocklist_record_ip( 'super_fail' );
$blocked = forcefield_blocklist_check_transgressions( 'super_fail', $transgressions );
if ( $blocked ) {
do_action( 'forcefield_login_super_toomany' );
$status = 429; // HTTP 429: Too Many Requests
return forcefield_filtered_error( 'login_super_toomany', $errormessage, $status );
}
}
// --- check for admin role ---
if ( in_array( 'administrator', (array) $checkuser->roles ) ) {
// --- add a record of failed admin login attempt ---
$transgressions = forcefield_blocklist_record_ip( 'admin_fail' );
$blocked = forcefield_blocklist_check_transgressions( 'admin_fail', $transgressions );
if ( $blocked ) {
do_action( 'forcefield_login_admin_toomany' );
$status = 429; // HTTP 429: Too Many Requests
return forcefield_filtered_error( 'login_admin_toomany', $errormessage, $status );
}
}
// TODO: maybe add check for other significant roles (eg. editor, author) ?
}
// --- return for existing errors ---
if ( !$username || !$password || is_wp_error( $user ) ) {
return $user;
}
// --- maybe require SSL connection to login ---
$requiressl = forcefield_get_setting( 'login_requiressl' );
// 0.9.8: allow for constant override to prevent self-lockout
if ( defined( 'FORCEFIELD_REQUIRE_SSL' ) ) {
// 1.0.4: simplify logic to single line
$requiressl = ( (bool) FORCEFIELD_REQUIRE_SSL ) ? 'yes' : '';
}
if ( ( 'yes' === (string) $requiressl ) && !is_ssl() ) {
// --- redirect if not secure ---
add_filter( 'secure_auth_redirect', '__return_true' );
auth_redirect();
exit;
}
// --- check for empty referer field ---
// 0.9.7: added isset check as may not be set if empty
if ( !isset( $_SERVER['HTTP_REFERER'] ) || ( '' == $_SERVER['HTTP_REFERER'] ) ) {
do_action( 'forcefield_login_noreferer' );
do_action( 'forcefield_no_referer' );
// --- check ban setting ---
// 0.9.1: separate general no referer recording
$norefban = forcefield_get_setting( 'blocklist_norefban' );
if ( 'yes' === (string) $norefban ) {
$transgressions = forcefield_blocklist_record_ip( 'no_referer' );
$blocked = forcefield_blocklist_check_transgressions( 'no_referer', $transgressions );
if ( $blocked ) {
$block = true;
}
}
// --- check block setting ---
$norefblock = forcefield_get_setting( 'login_norefblock' );
if ( 'yes' === (string) $norefblock ) {
$block = true;
}
if ( isset( $block ) && $block ) {
do_action( 'forcefield_login_failed' );
$status = 400; // HTTP 400: Bad Request
return forcefield_filtered_error( 'login_no_referer', $errormessage, $status );
}
}
// --- login form field to check token ---
// phpcs:ignore WordPress.Security.NonceVerification.Missing
// 1.0.4: fix to variable typo (POST)
// phpcs:ignore WordPress.Security.NonceVerification.Missing
if ( isset( $_POST['log'] ) && isset( $_POST['pwd'] ) ) {
$tokenize = forcefield_get_setting( 'login_token' );
if ( 'yes' !== (string) $tokenize ) {
return $user;
}
// --- maybe record the IP if missing the token form field ---
// phpcs:ignore WordPress.Security.NonceVerification.Missing
if ( !isset( $_POST['auth_token_login'] ) ) {
// --- record no token ---
// 0.9.1: separate instaban and no token recording
$recordnotoken = forcefield_get_setting( 'blocklist_notoken' );
if ( 'yes' === (string) $recordnotoken ) {
forcefield_blocklist_record_ip( 'no_token' );
}
// --- check ban setting ---
$instaban = forcefield_get_setting( 'login_notokenban' );
if ( 'yes' === (string) $instaban ) {
forcefield_blocklist_record_ip( 'no_login_token' );
}
do_action( 'forcefield_login_notoken' );
do_action( 'forcefield_login_failed' );
$status = 400; // HTTP 400: Bad Request
return forcefield_filtered_error( 'login_token_missing', $errormessage, $status );
} else {
// --- sanitize posted token ---
// 0.9.9: added check for valid token
// 1.0.0: fix to variable posted and preg_match check
// phpcs:ignore WordPress.Security.NonceVerification.Missing
$authtoken = sanitize_text_field( $_POST['auth_token_login'] );
$checkposted = preg_match( '/^[a-zA-Z0-9]+$/', $authtoken );
if ( empty( $authtoken ) || ( 12 != strlen( $authtoken ) ) || !$checkposted ) {
do_action( 'forcefield_login_invalid' );
do_action( 'forcefield_login_failed' );
$status = 400; // HTTP 400: Bad Request
return forcefield_filtered_error( 'login_token_invalid', $errormessage, $status );
}
// --- valid token provided so clear old records ---
// 0.9.1: maybe clear no token records
forcefield_blocklist_delete_record( false, 'no_token' );
forcefield_blocklist_delete_record( false, 'no_login_token' );
}
// --- get login token for IP ---
$checktoken = forcefield_check_token( 'login' );
// --- check token ---
// 0.9.5: check now returns an array so we check 'value' key
if ( !$checktoken ) {
// --- token expired ---
do_action( 'forcefield_login_oldtoken' );
do_action( 'forcefield_login_failed' );
$status = 403; // HTTP 403: Forbidden
return forcefield_filtered_error( 'login_token_expired', $errormessage, $status );
} elseif ( $authtoken != $checktoken['value'] ) {
// --- fail, token is a mismatch ---
// 0.9.1: record general token usage failure
$recordbadtokens = forcefield_get_setting( 'blocklist_badtoken' );
if ( 'yes' === (string) $recordbadtokens ) {
forcefield_blocklist_record_ip( 'bad_token' );
}
do_action( 'forcefield_login_mismatch' );
do_action( 'forcefield_login_failed' );
$status = 401; // HTTP 401: Unauthorized
return forcefield_filtered_error( 'login_token_mismatch', $errormessage, $status );
} else {
// --- success, allow user to login ---
// 0.9.1: clear any bad token records
forcefield_blocklist_delete_record( false, 'bad_token' );
// --- remove used login token ---
forcefield_delete_token( 'login' );
do_action( 'forcefield_login_success' );
}
}
// --- clear admin fail records ---
// 0.9.1: clear possible admin_fail records on successful login
if ( !is_wp_error( $user ) ) {
// 0.9.6: get user object via username
$checkuser = get_user_by( 'login', $username );
// 0.9.6: also clear super admin fail records
if ( is_multisite() && is_super_admin( $checkuser->ID ) ) {
forcefield_blocklist_delete_record( false, 'super_fail' );
}
if ( in_array( 'administrator', (array) $checkuser->roles ) ) {
forcefield_blocklist_delete_record( false, 'admin_fail' );
}
// TODO: maybe do similar for other significant roles (eg. editor?)
}
return $user;
}
// ---------------------------------
// Registration Token Authentication
// ---------------------------------
add_filter( 'register_post', 'forcefield_registration_authenticate', 9, 3 );
function forcefield_registration_authenticate( $errors, $sanitized_user_login, $user_email ) {
// --- filtered general error message ---
$errormessage = forcefield_get_error_message();
$errormessage = apply_filters( 'forcefield_error_message_register', $errormessage );
// --- check IP whitelist and blacklist ---
// 0.9.2: check IP blacklist
if ( forcefield_whitelist_check( 'actions' ) ) {
return $errors;
}
if ( forcefield_blacklist_check( 'actions' ) ) {
forcefield_forbidden_exit();
}
// --- check if user is logged in ---
// 0.9.7: added this error message to logout first
if ( is_user_logged_in() ) {
$errormessage = __( 'Please logout to register a new account.', 'forcefield' );
$status = 400; // HTTP 400: Bad Request
return forcefield_filtered_error( 'register_logged_in', $errormessage, $status, $errors );
}
// --- maybe require SSL connection for registration ---
$requiressl = forcefield_get_setting( 'register_requiressl' );
// 0.9.8: honour require SSL constant override
if ( defined( 'FORCEFIELD_REQUIRE_SSL' ) ) {
$requiressl = ( (bool) FORCEFIELD_REQUIRE_SSL ) ? 'yes' : '';
}
if ( ( 'yes' == $requiressl ) && !is_ssl() ) {
// note: compressed version of auth_redirect function
// 1.0.4: use wp_safe_redirect instead of wp_redirect
if ( 0 === strpos( $_SERVER['REQUEST_URI'], 'http' ) ) {
wp_safe_redirect( set_url_scheme( $_SERVER['REQUEST_URI'], 'https' ) );
} else {
wp_safe_redirect( 'https://' . sanitize_text_field( $_SERVER['HTTP_HOST'] ) . $_SERVER['REQUEST_URI'] );
}
exit;
}
// --- check for empty referer field ---
// 0.9.7: added isset check as may not be set if empty
if ( !isset( $_SERVER['HTTP_REFERER'] ) || ( '' == $_SERVER['HTTP_REFERER'] ) ) {
do_action( 'forcefield_register_noreferer' );
do_action( 'forcefield_no_referer' );
// --- record no referer ---
// 0.9.1: separate general no referer recording
$norefban = forcefield_get_setting( 'blocklist_norefban' );
if ( 'yes' === (string) $norefban ) {
$transgressions = forcefield_blocklist_record_ip( 'no_referer' );
$blocked = forcefield_blocklist_check_transgressions( 'no_referer', $transgressions );
if ( $blocked ) {
$block = true;
}