-
Notifications
You must be signed in to change notification settings - Fork 153
/
class-two-factor-core.php
2111 lines (1818 loc) · 68 KB
/
class-two-factor-core.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
/**
* Two Factore Core Class.
*
* @package Two_Factor
*/
/**
* Class for creating two factor authorization.
*
* @since 0.1-dev
*
* @package Two_Factor
*/
class Two_Factor_Core {
/**
* The user meta provider key.
*
* @type string
*/
const PROVIDER_USER_META_KEY = '_two_factor_provider';
/**
* The user meta enabled providers key.
*
* @type string
*/
const ENABLED_PROVIDERS_USER_META_KEY = '_two_factor_enabled_providers';
/**
* The user meta nonce key.
*
* @type string
*/
const USER_META_NONCE_KEY = '_two_factor_nonce';
/**
* The user meta key to store the last failed timestamp.
*
* @type string
*/
const USER_RATE_LIMIT_KEY = '_two_factor_last_login_failure';
/**
* The user meta key to store the number of failed login attempts.
*
* @var string
*/
const USER_FAILED_LOGIN_ATTEMPTS_KEY = '_two_factor_failed_login_attempts';
/**
* The user meta key to store whether or not the password was reset.
*
* @var string
*/
const USER_PASSWORD_WAS_RESET_KEY = '_two_factor_password_was_reset';
/**
* URL query parameter used for our custom actions.
*
* @var string
*/
const USER_SETTINGS_ACTION_QUERY_VAR = 'two_factor_action';
/**
* Nonce key for user settings.
*
* @var string
*/
const USER_SETTINGS_ACTION_NONCE_QUERY_ARG = '_two_factor_action_nonce';
/**
* Namespace for plugin rest api endpoints.
*
* @var string
*/
const REST_NAMESPACE = 'two-factor/1.0';
/**
* Keep track of all the password-based authentication sessions that
* need to invalidated before the second factor authentication.
*
* @var array
*/
private static $password_auth_tokens = array();
/**
* Set up filters and actions.
*
* @param object $compat A compatibility layer for plugins.
*
* @since 0.1-dev
*/
public static function add_hooks( $compat ) {
add_action( 'init', array( __CLASS__, 'get_providers' ) ); // @phpstan-ignore return.void
add_action( 'wp_login', array( __CLASS__, 'wp_login' ), 10, 2 );
add_filter( 'wp_login_errors', array( __CLASS__, 'maybe_show_reset_password_notice' ) );
add_action( 'after_password_reset', array( __CLASS__, 'clear_password_reset_notice' ) );
add_action( 'login_form_validate_2fa', array( __CLASS__, 'login_form_validate_2fa' ) );
add_action( 'login_form_revalidate_2fa', array( __CLASS__, 'login_form_revalidate_2fa' ) );
add_action( 'show_user_profile', array( __CLASS__, 'user_two_factor_options' ) );
add_action( 'edit_user_profile', array( __CLASS__, 'user_two_factor_options' ) );
add_action( 'personal_options_update', array( __CLASS__, 'user_two_factor_options_update' ) );
add_action( 'edit_user_profile_update', array( __CLASS__, 'user_two_factor_options_update' ) );
add_filter( 'manage_users_columns', array( __CLASS__, 'filter_manage_users_columns' ) );
add_filter( 'wpmu_users_columns', array( __CLASS__, 'filter_manage_users_columns' ) );
add_filter( 'manage_users_custom_column', array( __CLASS__, 'manage_users_custom_column' ), 10, 3 );
/**
* Keep track of all the user sessions for which we need to invalidate the
* authentication cookies set during the initial password check.
*
* Is there a better way of doing this?
*/
add_action( 'set_auth_cookie', array( __CLASS__, 'collect_auth_cookie_tokens' ) );
add_action( 'set_logged_in_cookie', array( __CLASS__, 'collect_auth_cookie_tokens' ) );
// Run only after the core wp_authenticate_username_password() check.
add_filter( 'authenticate', array( __CLASS__, 'filter_authenticate' ), 50 );
// Run as late as possible to prevent other plugins from unintentionally bypassing.
add_filter( 'authenticate', array( __CLASS__, 'filter_authenticate_block_cookies' ), PHP_INT_MAX );
add_filter( 'attach_session_information', array( __CLASS__, 'filter_session_information' ), 10, 2 );
add_action( 'admin_init', array( __CLASS__, 'trigger_user_settings_action' ) );
add_filter( 'two_factor_providers', array( __CLASS__, 'enable_dummy_method_for_debug' ) );
$compat->init();
}
/**
* Delete all plugin data on uninstall.
*
* @return void
*/
public static function uninstall() {
// Keep this updated as user meta keys are added or removed.
$user_meta_keys = array(
self::PROVIDER_USER_META_KEY,
self::ENABLED_PROVIDERS_USER_META_KEY,
self::USER_META_NONCE_KEY,
self::USER_RATE_LIMIT_KEY,
self::USER_FAILED_LOGIN_ATTEMPTS_KEY,
self::USER_PASSWORD_WAS_RESET_KEY,
);
$option_keys = array();
foreach ( self::get_providers_classes() as $provider_class ) {
// Merge with provider-specific user meta keys.
if ( method_exists( $provider_class, 'uninstall_user_meta_keys' ) ) {
try {
$user_meta_keys = array_merge(
$user_meta_keys,
call_user_func( array( $provider_class, 'uninstall_user_meta_keys' ) )
);
} catch ( Exception $e ) {
// Do nothing.
}
}
// Merge with provider-specific option keys.
if ( method_exists( $provider_class, 'uninstall_options' ) ) {
try {
$option_keys = array_merge(
$option_keys,
call_user_func( array( $provider_class, 'uninstall_options' ) )
);
} catch ( Exception $e ) {
// Do nothing.
}
}
}
// Delete options first since that is faster.
if ( ! empty( $option_keys ) ) {
foreach ( $option_keys as $option_key ) {
delete_option( $option_key );
}
}
foreach ( $user_meta_keys as $meta_key ) {
delete_metadata( 'user', null, $meta_key, null, true );
}
}
/**
* Get the registered providers of which some might not be enabled.
*
* @return array List of provider keys and paths to class files.
*/
public static function get_providers_registered() {
$providers = array(
'Two_Factor_Email' => TWO_FACTOR_DIR . 'providers/class-two-factor-email.php',
'Two_Factor_Totp' => TWO_FACTOR_DIR . 'providers/class-two-factor-totp.php',
'Two_Factor_FIDO_U2F' => TWO_FACTOR_DIR . 'providers/class-two-factor-fido-u2f.php',
'Two_Factor_Backup_Codes' => TWO_FACTOR_DIR . 'providers/class-two-factor-backup-codes.php',
'Two_Factor_Dummy' => TWO_FACTOR_DIR . 'providers/class-two-factor-dummy.php',
);
/**
* Filter the supplied providers.
*
* @param array $providers A key-value array where the key is the class name, and
* the value is the path to the file containing the class.
*/
$additional_providers = apply_filters( 'two_factor_providers', $providers );
// Merge them with the default providers.
if ( ! empty( $additional_providers ) ) {
return array_merge( $providers, $additional_providers );
}
return $providers;
}
/**
* Get the classnames for all registered providers.
*
* Note some of these providers might not be enabled.
*
* @return array List of provider keys and classnames.
*/
private static function get_providers_classes() {
$providers = self::get_providers_registered();
foreach ( $providers as $provider_key => $path ) {
require_once $path;
$class = $provider_key;
/**
* Filters the classname for a provider. The dynamic portion of the filter is the defined providers key.
*
* @param string $class The PHP Classname of the provider.
* @param string $path The provided provider path to be included.
*/
$class = apply_filters( "two_factor_provider_classname_{$provider_key}", $class, $path );
/**
* Confirm that it's been successfully included before instantiating.
*/
if ( method_exists( $class, 'get_instance' ) ) {
$providers[ $provider_key ] = $class;
} else {
unset( $providers[ $provider_key ] );
}
}
return $providers;
}
/**
* Get all enabled two-factor providers.
*
* @since 0.1-dev
*
* @return array
*/
public static function get_providers() {
$providers = self::get_providers_registered();
/**
* Filter the supplied providers.
*
* This lets third-parties either remove providers (such as Email), or
* add their own providers (such as text message or Clef).
*
* @param array $providers A key-value array where the key is the class name, and
* the value is the path to the file containing the class.
*/
$providers = apply_filters( 'two_factor_providers', $providers );
// FIDO U2F is PHP 5.3+ only.
if ( isset( $providers['Two_Factor_FIDO_U2F'] ) && version_compare( PHP_VERSION, '5.3.0', '<' ) ) {
unset( $providers['Two_Factor_FIDO_U2F'] );
trigger_error( // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_trigger_error
sprintf(
/* translators: %s: version number */
__( 'FIDO U2F is not available because you are using PHP %s. (Requires 5.3 or greater)', 'two-factor' ), // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
PHP_VERSION
)
);
}
// Map provider keys to classes so that we can instantiate them.
$providers = array_intersect_key( self::get_providers_classes(), $providers );
foreach ( $providers as $provider_key => $provider_class ) {
if ( method_exists( $provider_class, 'get_instance' ) ) {
try {
$providers[ $provider_key ] = call_user_func( array( $provider_class, 'get_instance' ) );
} catch ( Exception $e ) {
unset( $providers[ $provider_key ] );
}
}
}
return $providers;
}
/**
* Enable the dummy method only during debugging.
*
* @param array $methods List of enabled methods.
*
* @return array
*/
public static function enable_dummy_method_for_debug( $methods ) {
if ( ! self::is_wp_debug() ) {
unset( $methods['Two_Factor_Dummy'] );
}
return $methods;
}
/**
* Check if the debug mode is enabled.
*
* @return boolean
*/
protected static function is_wp_debug() {
return ( defined( 'WP_DEBUG' ) && WP_DEBUG );
}
/**
* Get the user settings page URL.
*
* Fetch this from the plugin core after we introduce proper dependency injection
* and get away from the singletons at the provider level (should be handled by core).
*
* @param integer $user_id User ID.
*
* @return string
*/
protected static function get_user_settings_page_url( $user_id ) {
if ( defined( 'IS_PROFILE_PAGE' ) && IS_PROFILE_PAGE ) {
return self_admin_url( 'profile.php' );
}
return add_query_arg(
array(
'user_id' => intval( $user_id ),
),
self_admin_url( 'user-edit.php' )
);
}
/**
* Get the URL for resetting the secret token.
*
* @param integer $user_id User ID.
* @param string $action Custom two factor action key.
*
* @return string
*/
public static function get_user_update_action_url( $user_id, $action ) {
return wp_nonce_url(
add_query_arg(
array(
self::USER_SETTINGS_ACTION_QUERY_VAR => $action,
),
self::get_user_settings_page_url( $user_id )
),
sprintf( '%d-%s', $user_id, $action ),
self::USER_SETTINGS_ACTION_NONCE_QUERY_ARG
);
}
/**
* Get the two-factor revalidate URL.
*
* @param bool $interim If the URL should load the interim login iframe modal.
* @return string
*/
public static function get_user_two_factor_revalidate_url( $interim = false ) {
$args = array(
'action' => 'revalidate_2fa',
);
if ( $interim ) {
$args['interim-login'] = 1;
}
return self::login_url( $args );
}
/**
* Check if a user action is valid.
*
* @param integer $user_id User ID.
* @param string $action User action ID.
*
* @return boolean
*/
public static function is_valid_user_action( $user_id, $action ) {
$request_nonce = isset( $_REQUEST[ self::USER_SETTINGS_ACTION_NONCE_QUERY_ARG ] ) ? wp_unslash( $_REQUEST[ self::USER_SETTINGS_ACTION_NONCE_QUERY_ARG ] ) : '';
if ( ! $user_id || ! $action || ! $request_nonce ) {
return false;
}
return wp_verify_nonce(
$request_nonce,
sprintf( '%d-%s', $user_id, $action )
);
}
/**
* Get the ID of the user being edited.
*
* @return integer
*/
public static function current_user_being_edited() {
// Try to resolve the user ID from the request first.
if ( ! empty( $_REQUEST['user_id'] ) ) {
$user_id = intval( $_REQUEST['user_id'] );
if ( current_user_can( 'edit_user', $user_id ) ) {
return $user_id;
}
}
return get_current_user_id();
}
/**
* Trigger our custom update action if a valid
* action request is detected and passes the nonce check.
*
* @return void
*/
public static function trigger_user_settings_action() {
$action = isset( $_REQUEST[ self::USER_SETTINGS_ACTION_QUERY_VAR ] ) ? wp_unslash( $_REQUEST[ self::USER_SETTINGS_ACTION_QUERY_VAR ] ) : '';
$user_id = self::current_user_being_edited();
if ( self::is_valid_user_action( $user_id, $action ) ) {
/**
* This action is triggered when a valid Two Factor settings
* action is detected and it passes the nonce validation.
*
* @param integer $user_id User ID.
* @param string $action Settings action.
*/
do_action( 'two_factor_user_settings_action', $user_id, $action );
}
}
/**
* Keep track of all the authentication cookies that need to be
* invalidated before the second factor authentication.
*
* @param string $cookie Cookie string.
*
* @return void
*/
public static function collect_auth_cookie_tokens( $cookie ) {
$parsed = wp_parse_auth_cookie( $cookie );
if ( ! empty( $parsed['token'] ) ) {
self::$password_auth_tokens[] = $parsed['token'];
}
}
/**
* Fetch the WP_User object for a provided input.
*
* @since 0.8.0
*
* @param int|WP_User $user Optional. The WP_User or user ID. Defaults to current user.
*
* @return false|WP_User WP_User on success, false on failure.
*/
public static function fetch_user( $user = null ) {
if ( null === $user ) {
$user = wp_get_current_user();
} elseif ( ! ( $user instanceof WP_User ) ) {
$user = get_user_by( 'id', $user );
}
if ( ! $user || ! $user->exists() ) {
return false;
}
return $user;
}
/**
* Get all Two-Factor Auth providers that are enabled for the specified|current user.
*
* @param int|WP_User $user Optional. User ID, or WP_User object of the the user. Defaults to current user.
* @return array
*/
public static function get_enabled_providers_for_user( $user = null ) {
$user = self::fetch_user( $user );
if ( ! $user ) {
return array();
}
$providers = self::get_providers();
$enabled_providers = get_user_meta( $user->ID, self::ENABLED_PROVIDERS_USER_META_KEY, true );
if ( empty( $enabled_providers ) ) {
$enabled_providers = array();
}
$enabled_providers = array_intersect( $enabled_providers, array_keys( $providers ) );
/**
* Filter the enabled two-factor authentication providers for this user.
*
* @param array $enabled_providers The enabled providers.
* @param int $user_id The user ID.
*/
return apply_filters( 'two_factor_enabled_providers_for_user', $enabled_providers, $user->ID );
}
/**
* Get all Two-Factor Auth providers that are both enabled and configured for the specified|current user.
*
* @param int|WP_User $user Optional. User ID, or WP_User object of the the user. Defaults to current user.
* @return array
*/
public static function get_available_providers_for_user( $user = null ) {
$user = self::fetch_user( $user );
if ( ! $user ) {
return array();
}
$providers = self::get_providers();
$enabled_providers = self::get_enabled_providers_for_user( $user );
$configured_providers = array();
foreach ( $providers as $provider_key => $provider ) {
if ( in_array( $provider_key, $enabled_providers, true ) && $provider->is_available_for_user( $user ) ) {
$configured_providers[ $provider_key ] = $provider;
}
}
return $configured_providers;
}
/**
* Fetch the provider for the request based on the user preferences.
*
* @param int|WP_User $user Optional. User ID, or WP_User object of the the user. Defaults to current user.
* @param null|string|object $preferred_provider Optional. The name of the provider, the provider, or empty.
* @return null|object The provider
*/
public static function get_provider_for_user( $user = null, $preferred_provider = null ) {
$user = self::fetch_user( $user );
if ( ! $user ) {
return null;
}
// If a specific provider instance is passed, process it just as the key.
if ( $preferred_provider && $preferred_provider instanceof Two_Factor_Provider ) {
$preferred_provider = $preferred_provider->get_key();
}
// Default to the currently logged in provider.
if ( ! $preferred_provider && get_current_user_id() === $user->ID ) {
$session = self::get_current_user_session();
if ( ! empty( $session['two-factor-provider'] ) ) {
$preferred_provider = $session['two-factor-provider'];
}
}
if ( is_string( $preferred_provider ) ) {
$providers = self::get_available_providers_for_user( $user );
if ( isset( $providers[ $preferred_provider ] ) ) {
return $providers[ $preferred_provider ];
}
}
return self::get_primary_provider_for_user( $user );
}
/**
* Gets the Two-Factor Auth provider for the specified|current user.
*
* @since 0.1-dev
*
* @param int|WP_User $user Optional. User ID, or WP_User object of the the user. Defaults to current user.
* @return object|null
*/
public static function get_primary_provider_for_user( $user = null ) {
$user = self::fetch_user( $user );
if ( ! $user ) {
return null;
}
$providers = self::get_providers();
$available_providers = self::get_available_providers_for_user( $user );
// If there's only one available provider, force that to be the primary.
if ( empty( $available_providers ) ) {
return null;
} elseif ( 1 === count( $available_providers ) ) {
$provider = key( $available_providers );
} else {
$provider = get_user_meta( $user->ID, self::PROVIDER_USER_META_KEY, true );
// If the provider specified isn't enabled, just grab the first one that is.
if ( ! isset( $available_providers[ $provider ] ) ) {
$provider = key( $available_providers );
}
}
/**
* Filter the two-factor authentication provider used for this user.
*
* @param string $provider The provider currently being used.
* @param int $user_id The user ID.
*/
$provider = apply_filters( 'two_factor_primary_provider_for_user', $provider, $user->ID );
if ( isset( $providers[ $provider ] ) ) {
return $providers[ $provider ];
}
return null;
}
/**
* Quick boolean check for whether a given user is using two-step.
*
* @since 0.1-dev
*
* @param int|WP_User $user Optional. User ID, or WP_User object of the the user. Defaults to current user.
* @return bool
*/
public static function is_user_using_two_factor( $user = null ) {
$provider = self::get_primary_provider_for_user( $user );
return ! empty( $provider );
}
/**
* Handle the browser-based login.
*
* @since 0.1-dev
*
* @param string $user_login Username.
* @param WP_User $user WP_User object of the logged-in user.
*/
public static function wp_login( $user_login, $user ) {
if ( ! self::is_user_using_two_factor( $user->ID ) ) {
return;
}
// Invalidate the current login session to prevent from being re-used.
self::destroy_current_session_for_user( $user );
// Also clear the cookies which are no longer valid.
wp_clear_auth_cookie();
self::show_two_factor_login( $user );
exit;
}
/**
* Destroy the known password-based authentication sessions for the current user.
*
* Is there a better way of finding the current session token without
* having access to the authentication cookies which are just being set
* on the first password-based authentication request.
*
* @param \WP_User $user User object.
*
* @return void
*/
public static function destroy_current_session_for_user( $user ) {
$session_manager = WP_Session_Tokens::get_instance( $user->ID );
foreach ( self::$password_auth_tokens as $auth_token ) {
$session_manager->destroy( $auth_token );
}
}
/**
* Prevent login through XML-RPC and REST API for users with at least one
* two-factor method enabled.
*
* @param WP_User|WP_Error $user Valid WP_User only if the previous filters
* have verified and confirmed the
* authentication credentials.
*
* @return WP_User|WP_Error
*/
public static function filter_authenticate( $user ) {
if ( $user instanceof WP_User && self::is_api_request() && self::is_user_using_two_factor( $user->ID ) && ! self::is_user_api_login_enabled( $user->ID ) ) {
return new WP_Error(
'invalid_application_credentials',
__( 'Error: API login for user disabled.', 'two-factor' )
);
}
return $user;
}
/**
* Prevent login cookies being set on login for Two Factor users.
*
* This makes it so that Core never sends the auth cookies. `login_form_validate_2fa()` will send them manually once the 2nd factor has been verified.
*
* @param WP_User|WP_Error $user Valid WP_User only if the previous filters
* have verified and confirmed the
* authentication credentials.
*
* @return WP_User|WP_Error
*/
public static function filter_authenticate_block_cookies( $user ) {
/*
* NOTE: The `login_init` action is checked for here to ensure we're within the regular login flow,
* rather than through an unsupported 3rd-party login process which this plugin doesn't support.
*/
if ( $user instanceof WP_User && self::is_user_using_two_factor( $user->ID ) && did_action( 'login_init' ) ) {
add_filter( 'send_auth_cookies', '__return_false', PHP_INT_MAX );
}
return $user;
}
/**
* If the current user can login via API requests such as XML-RPC and REST.
*
* @param integer $user_id User ID.
*
* @return boolean
*/
public static function is_user_api_login_enabled( $user_id ) {
return (bool) apply_filters( 'two_factor_user_api_login_enable', false, $user_id );
}
/**
* Is the current request an XML-RPC or REST request.
*
* @return boolean
*/
public static function is_api_request() {
if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) {
return true;
}
if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
return true;
}
return false;
}
/**
* Display the login form.
*
* @since 0.1-dev
*
* @param WP_User $user WP_User object of the logged-in user.
*/
public static function show_two_factor_login( $user ) {
if ( ! $user ) {
$user = wp_get_current_user();
}
$login_nonce = self::create_login_nonce( $user->ID );
if ( ! $login_nonce ) {
wp_die( esc_html__( 'Failed to create a login nonce.', 'two-factor' ) );
}
$redirect_to = isset( $_REQUEST['redirect_to'] ) ? $_REQUEST['redirect_to'] : admin_url();
self::login_html( $user, $login_nonce['key'], $redirect_to );
}
/**
* Displays a message informing the user that their account has had failed login attempts.
*
* @param WP_User $user WP_User object of the logged-in user.
*/
public static function maybe_show_last_login_failure_notice( $user ) {
$last_failed_two_factor_login = (int) get_user_meta( $user->ID, self::USER_RATE_LIMIT_KEY, true );
$failed_login_count = (int) get_user_meta( $user->ID, self::USER_FAILED_LOGIN_ATTEMPTS_KEY, true );
if ( $last_failed_two_factor_login ) {
echo '<div id="login_notice" class="message"><strong>';
printf(
_n(
'WARNING: Your account has attempted to login without providing a valid two factor token. The last failed login occurred %2$s ago. If this wasn\'t you, you should reset your password.',
'WARNING: Your account has attempted to login %1$s times without providing a valid two factor token. The last failed login occurred %2$s ago. If this wasn\'t you, you should reset your password.',
$failed_login_count,
'two-factor'
),
number_format_i18n( $failed_login_count ),
human_time_diff( $last_failed_two_factor_login, time() )
);
echo '</strong></div>';
}
}
/**
* Show the password reset notice if the user's password was reset.
*
* They were also sent an email notification in `send_password_reset_email()`, but email sent from a typical
* web server is not reliable enough to trust completely.
*
* @param WP_Error $errors
*/
public static function maybe_show_reset_password_notice( $errors ) {
if ( 'incorrect_password' !== $errors->get_error_code() ) {
return $errors;
}
if ( ! isset( $_POST['log'] ) ) {
return $errors;
}
$user_name = sanitize_user( wp_unslash( $_POST['log'] ) );
$attempted_user = get_user_by( 'login', $user_name );
if ( ! $attempted_user && str_contains( $user_name, '@' ) ) {
$attempted_user = get_user_by( 'email', $user_name );
}
if ( ! $attempted_user ) {
return $errors;
}
$password_was_reset = get_user_meta( $attempted_user->ID, self::USER_PASSWORD_WAS_RESET_KEY, true );
if ( ! $password_was_reset ) {
return $errors;
}
$errors->remove( 'incorrect_password' );
$errors->add(
'two_factor_password_reset',
sprintf(
__( 'Your password was reset because of too many failed Two Factor attempts. You will need to <a href="%s">create a new password</a> to regain access. Please check your email for more information.', 'two-factor' ),
esc_url( add_query_arg( 'action', 'lostpassword', wp_login_url() ) )
)
);
return $errors;
}
/**
* Clear the password reset notice after the user resets their password.
*
* @param WP_User $user
*/
public static function clear_password_reset_notice( $user ) {
delete_user_meta( $user->ID, self::USER_PASSWORD_WAS_RESET_KEY );
}
/**
* Generates the html form for the second step of the authentication process.
*
* @since 0.1-dev
*
* @param WP_User $user WP_User object of the logged-in user.
* @param string $login_nonce A string nonce stored in usermeta.
* @param string $redirect_to The URL to which the user would like to be redirected.
* @param string $error_msg Optional. Login error message.
* @param string|object $provider An override to the provider.
*/
public static function login_html( $user, $login_nonce, $redirect_to, $error_msg = '', $provider = null, $action = 'validate_2fa' ) {
$provider = self::get_provider_for_user( $user, $provider );
if ( ! $provider ) {
wp_die( __( 'Cheatin’ uh?', 'two-factor' ) );
}
$provider_key = $provider->get_key();
$available_providers = self::get_available_providers_for_user( $user );
$backup_providers = array_diff_key( $available_providers, array( $provider_key => null ) );
$interim_login = isset( $_REQUEST['interim-login'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$rememberme = intval( self::rememberme() );
if ( ! function_exists( 'login_header' ) ) {
// We really should migrate login_header() out of `wp-login.php` so it can be called from an includes file.
require_once TWO_FACTOR_DIR . 'includes/function.login-header.php';
}
// Disable the language switcher.
add_filter( 'login_display_language_dropdown', '__return_false' );
login_header();
if ( ! empty( $error_msg ) ) {
echo '<div id="login_error"><strong>' . esc_html( $error_msg ) . '</strong><br /></div>';
} elseif ( 'validate_2fa' === $action ) {
self::maybe_show_last_login_failure_notice( $user );
}
?>
<form name="validate_2fa_form" id="loginform" action="<?php echo esc_url( self::login_url( array( 'action' => $action ), 'login_post' ) ); ?>" method="post" autocomplete="off">
<input type="hidden" name="provider" id="provider" value="<?php echo esc_attr( $provider_key ); ?>" />
<input type="hidden" name="wp-auth-id" id="wp-auth-id" value="<?php echo esc_attr( $user->ID ); ?>" />
<input type="hidden" name="wp-auth-nonce" id="wp-auth-nonce" value="<?php echo esc_attr( $login_nonce ); ?>" />
<?php if ( $interim_login ) { ?>
<input type="hidden" name="interim-login" value="1" />
<?php } else { ?>
<input type="hidden" name="redirect_to" value="<?php echo esc_attr( $redirect_to ); ?>" />
<?php } ?>
<input type="hidden" name="rememberme" id="rememberme" value="<?php echo esc_attr( $rememberme ); ?>" />
<?php $provider->authentication_page( $user ); ?>
</form>
<?php if ( $backup_providers ) :
$backup_link_args = array(
'action' => $action,
'wp-auth-id' => $user->ID,
'wp-auth-nonce' => $login_nonce,
);
if ( $rememberme ) {
$backup_link_args['rememberme'] = $rememberme;
}
if ( $redirect_to ) {
$backup_link_args['redirect_to'] = $redirect_to;
}
if ( $interim_login ) {
$backup_link_args['interim-login'] = 1;
}
?>
<div class="backup-methods-wrap">
<p>
<?php esc_html_e( 'Having Problems?', 'two-factor' ); ?>
</p>
<ul>
<?php
foreach ( $backup_providers as $backup_provider_key => $backup_provider ) :
$backup_link_args['provider'] = $backup_provider_key;
?>
<li>
<a href="<?php echo esc_url( self::login_url( $backup_link_args ) ); ?>">
<?php echo esc_html( $backup_provider->get_alternative_provider_label() ); ?>
</a>
</li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<style>
/* @todo: migrate to an external stylesheet. */
.backup-methods-wrap {
margin-top: 16px;
padding: 0 24px;
}
.backup-methods-wrap a {
text-decoration: none;
}
.backup-methods-wrap ul {
list-style-position: inside;
}
/* Prevent Jetpack from hiding our controls, see https://github.com/Automattic/jetpack/issues/3747 */
.jetpack-sso-form-display #loginform > p,
.jetpack-sso-form-display #loginform > div {
display: block;
}
#login form p.two-factor-prompt {
margin-bottom: 1em;
}
.input.authcode {
letter-spacing: .3em;
}
.input.authcode::placeholder {
opacity: 0.5;
}
</style>
<script>
(function() {
// Enforce numeric-only input for numeric inputmode elements.
const form = document.querySelector( '#loginform' ),
inputEl = document.querySelector( 'input.authcode[inputmode="numeric"]' ),
expectedLength = inputEl?.dataset.digits || 0;
if ( inputEl ) {
let spaceInserted = false;
inputEl.addEventListener(
'input',
function() {
let value = this.value.replace( /[^0-9 ]/g, '' ).trimStart();
if ( ! spaceInserted && expectedLength && value.length === Math.floor( expectedLength / 2 ) ) {
value += ' ';
spaceInserted = true;
} else if ( spaceInserted && ! this.value ) {
spaceInserted = false;
}
this.value = value;
// Auto-submit if it's the expected length.
if ( expectedLength && value.replace( / /g, '' ).length == expectedLength ) {
if ( undefined !== form.requestSubmit ) {
form.requestSubmit();
form.submit.disabled = "disabled";
}
}
}