-
Notifications
You must be signed in to change notification settings - Fork 183
Expand file tree
/
Copy pathclass-two-factor-backup-codes.php
More file actions
486 lines (441 loc) · 13.2 KB
/
Copy pathclass-two-factor-backup-codes.php
File metadata and controls
486 lines (441 loc) · 13.2 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
<?php
/**
* Class for creating a backup codes provider.
*
* @package Two_Factor
*/
/**
* Class for creating a backup codes provider.
*
* @since 0.1-dev
*
* @package Two_Factor
*/
class Two_Factor_Backup_Codes extends Two_Factor_Provider {
/**
* The user meta backup codes key.
*
* @type string
*/
const BACKUP_CODES_META_KEY = '_two_factor_backup_codes';
/**
* The number backup codes.
*
* @type int
*/
const NUMBER_OF_CODES = 10;
/**
* Class constructor.
*
* @since 0.1-dev
*
* @codeCoverageIgnore
*/
protected function __construct() {
add_action( 'rest_api_init', array( $this, 'register_rest_routes' ) );
add_action( 'two_factor_user_options_' . __CLASS__, array( $this, 'user_options' ) );
add_action( 'admin_notices', array( $this, 'admin_notices' ) );
add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_assets' ) );
parent::__construct();
}
/**
* Enqueue scripts for backup codes.
*
* @since 0.10.0
*
* @codeCoverageIgnore
*
* @param string $hook_suffix Optional. The current admin page hook suffix.
*/
public function enqueue_assets( $hook_suffix = '' ) {
wp_register_script(
'two-factor-backup-codes-admin',
plugins_url( 'js/backup-codes-admin.js', __FILE__ ),
array( 'jquery', 'wp-api-request' ),
TWO_FACTOR_VERSION,
true
);
}
/**
* Register the rest-api endpoints required for this provider.
*
* @since 0.8.0
*
* @codeCoverageIgnore
*/
public function register_rest_routes() {
register_rest_route(
Two_Factor_Core::REST_NAMESPACE,
'/generate-backup-codes',
array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => array( $this, 'rest_generate_codes' ),
'permission_callback' => function ( $request ) {
return Two_Factor_Core::rest_api_can_edit_user_and_update_two_factor_options( $request['user_id'] );
},
'args' => array(
'user_id' => array(
'required' => true,
'type' => 'integer',
),
'enable_provider' => array(
'required' => false,
'type' => 'boolean',
'default' => false,
),
),
)
);
}
/**
* Displays an admin notice when backup codes have run out.
*
* @since 0.1-dev
*
* @codeCoverageIgnore
*/
public function admin_notices() {
$user = wp_get_current_user();
// Return if the provider is not enabled.
if ( ! in_array( __CLASS__, Two_Factor_Core::get_enabled_providers_for_user( $user->ID ), true ) ) {
return;
}
// Return if we are not out of codes.
if ( $this->is_available_for_user( $user ) ) {
return;
}
?>
<div class="error">
<p>
<span>
<?php
echo wp_kses(
sprintf(
/* translators: %s: URL for code regeneration */
__( 'Two-Factor: You are out of recovery codes and need to <a href="%s">regenerate!</a>', 'two-factor' ),
esc_url( get_edit_user_link( $user->ID ) . '#two-factor-backup-codes' )
),
array( 'a' => array( 'href' => true ) )
);
?>
</span>
</p>
</div>
<?php
}
/**
* Returns the name of the provider.
*
* @since 0.1-dev
*/
public function get_label() {
return _x( 'Recovery Codes', 'Provider Label', 'two-factor' );
}
/**
* Returns the "continue with" text provider for the login screen.
*
* @since 0.9.0
*/
public function get_alternative_provider_label() {
return __( 'Use a recovery code', 'two-factor' );
}
/**
* Whether this Two Factor provider is configured and codes are available for the user specified.
*
* @since 0.1-dev
*
* @param WP_User $user WP_User object of the logged-in user.
* @return boolean
*/
public function is_available_for_user( $user ) {
// Does this user have available codes?
if ( 0 < self::codes_remaining_for_user( $user ) ) {
return true;
}
return false;
}
/**
* Inserts markup at the end of the user profile field for this provider.
*
* @since 0.1-dev
*
* @param WP_User $user WP_User object of the logged-in user.
*/
public function user_options( $user ) {
wp_localize_script(
'two-factor-backup-codes-admin',
'twoFactorBackupCodes',
array(
'restPath' => Two_Factor_Core::REST_NAMESPACE . '/generate-backup-codes',
'userId' => $user->ID,
)
);
wp_enqueue_script( 'two-factor-backup-codes-admin' );
$count = self::codes_remaining_for_user( $user );
?>
<div id="two-factor-backup-codes">
<p class="two-factor-backup-codes-count">
<?php
echo esc_html(
sprintf(
/* translators: %s: count */
_n( '%s unused code remaining, each recovery code can only be used once.', '%s unused codes remaining, each recovery code can only be used once.', $count, 'two-factor' ),
$count
)
);
?>
</p>
<p>
<button type="button" class="button button-two-factor-backup-codes-generate button-secondary hide-if-no-js">
<?php esc_html_e( 'Generate new recovery codes', 'two-factor' ); ?>
</button>
<em><?php esc_html_e( 'This invalidates all currently stored codes.', 'two-factor' ); ?></em>
</p>
</div>
<div class="two-factor-backup-codes-wrapper" style="display:none;">
<div class="two-factor-backup-codes-list-wrap">
<ol class="two-factor-backup-codes-unused-codes"></ol>
</div>
<p class="description"><?php esc_html_e( 'Write these down! Once you navigate away from this page, you will not be able to view these codes again.', 'two-factor' ); ?></p>
<p>
<button type="button" class="button button-two-factor-backup-codes-copy button-secondary hide-if-no-js" id="two-factor-backup-codes-copy-link"><?php esc_html_e( 'Copy Codes', 'two-factor' ); ?></button>
<a class="button button-two-factor-backup-codes-download button-secondary hide-if-no-js" href="#" id="two-factor-backup-codes-download-link" download="two-factor-backup-codes.txt"><?php esc_html_e( 'Download Codes', 'two-factor' ); ?></a>
</p>
</div>
<?php
}
/**
* Get the backup code length for a user.
*
* @since 0.11.0
*
* @param WP_User $user User object.
*
* @return int Number of characters.
*/
private function get_backup_code_length( $user ) {
/**
* Filters the character count of the backup codes.
*
* @since 0.11.0
*
* @param int $code_length Length of the backup code. Default 8.
* @param WP_User $user User object.
*/
$code_length = (int) apply_filters( 'two_factor_backup_code_length', 8, $user );
return $code_length;
}
/**
* Generates backup codes & updates the user meta.
*
* @since 0.1-dev
*
* @param WP_User $user WP_User object of the logged-in user.
* @param array $args Optional arguments for assigning new codes.
* @return array
*/
public function generate_codes( $user, $args = array() ) {
$codes = array();
$codes_hashed = array();
// Check for arguments.
if ( isset( $args['number'] ) ) {
$num_codes = (int) $args['number'];
} else {
$num_codes = self::NUMBER_OF_CODES;
}
// Append or replace (default).
if ( isset( $args['method'] ) && 'append' === $args['method'] ) {
$codes_hashed = (array) get_user_meta( $user->ID, self::BACKUP_CODES_META_KEY, true );
}
$code_length = $this->get_backup_code_length( $user );
for ( $i = 0; $i < $num_codes; $i++ ) {
$code = $this->get_code( $code_length );
$codes_hashed[] = wp_hash_password( $code );
$codes[] = $code;
unset( $code );
}
update_user_meta( $user->ID, self::BACKUP_CODES_META_KEY, $codes_hashed );
// Unhashed.
return $codes;
}
/**
* Generates Backup Codes for returning through the WordPress Rest API.
*
* @since 0.8.0
* @param WP_REST_Request $request Request object.
* @return array|WP_Error
*/
public function rest_generate_codes( $request ) {
$user_id = $request['user_id'];
$user = get_user_by( 'id', $user_id );
// Hardcode these, the user shouldn't be able to choose them.
$args = array(
'number' => self::NUMBER_OF_CODES,
'method' => 'replace',
);
// Setup the return data.
$codes = $this->generate_codes( $user, $args );
$count = self::codes_remaining_for_user( $user );
$title = sprintf(
/* translators: %s: the site's domain */
__( 'Two-Factor Recovery Codes for %s', 'two-factor' ),
home_url( '/' )
);
// Generate download content.
$download_link = 'data:application/text;charset=utf-8,';
$download_link .= rawurlencode( "{$title}\r\n\r\n" );
$i = 1;
foreach ( $codes as $code ) {
$download_link .= rawurlencode( "{$i}. {$code}\r\n" );
++$i;
}
$i18n = array(
/* translators: %s: count */
'count' => esc_html( sprintf( _n( '%s unused code remaining, each recovery code can only be used once.', '%s unused codes remaining, each recovery code can only be used once.', $count, 'two-factor' ), $count ) ),
);
if ( $request->get_param( 'enable_provider' ) && ! Two_Factor_Core::enable_provider_for_user( $user_id, 'Two_Factor_Backup_Codes' ) ) {
return new WP_Error( 'db_error', __( 'Unable to enable recovery codes for this user.', 'two-factor' ), array( 'status' => 500 ) );
}
return array(
'codes' => $codes,
'download_link' => $download_link,
'remaining' => $count,
'i18n' => $i18n,
);
}
/**
* Returns the number of unused codes for the specified user
*
* @since 0.2.0
*
* @param WP_User $user WP_User object of the logged-in user.
* @return int $int The number of unused codes remaining
*/
public static function codes_remaining_for_user( $user ) {
$backup_codes = get_user_meta( $user->ID, self::BACKUP_CODES_META_KEY, true );
if ( is_array( $backup_codes ) && ! empty( $backup_codes ) ) {
return count( $backup_codes );
}
return 0;
}
/**
* Prints the form that prompts the user to authenticate.
*
* @since 0.1-dev
*
* @param WP_User $user WP_User object of the logged-in user.
*/
public function authentication_page( $user ) {
require_once ABSPATH . '/wp-admin/includes/template.php';
$code_length = $this->get_backup_code_length( $user );
$code_placeholder = str_repeat( 'X', $code_length );
?>
<?php
/**
* Fires before the two-factor authentication prompt text.
*
* @since 0.15.0
*
* @param Two_Factor_Provider $provider The two-factor provider instance.
*/
do_action( 'two_factor_before_authentication_prompt', $this );
?>
<p class="two-factor-prompt"><?php esc_html_e( 'Enter a recovery code.', 'two-factor' ); ?></p>
<?php
/**
* Fires after the two-factor authentication prompt text.
*
* @since 0.15.0
*
* @param Two_Factor_Provider $provider The two-factor provider instance.
*/
do_action( 'two_factor_after_authentication_prompt', $this );
?>
<p>
<label for="authcode"><?php esc_html_e( 'Recovery Code:', 'two-factor' ); ?></label>
<input type="text" inputmode="numeric" name="two-factor-backup-code" id="authcode" class="input authcode" value="" size="20" pattern="[0-9 ]*" placeholder="<?php echo esc_attr( $code_placeholder ); ?>" data-digits="<?php echo esc_attr( $code_length ); ?>">
</p>
<?php
/**
* Fires after the two-factor authentication input field.
*
* @since 0.15.0
*
* @param Two_Factor_Provider $provider The two-factor provider instance.
*/
do_action( 'two_factor_after_authentication_input', $this );
?>
<?php
submit_button( __( 'Verify', 'two-factor' ) );
}
/**
* Validates the users input token.
*
* In this class we just return true.
*
* @since 0.1-dev
*
* @param WP_User $user WP_User object of the logged-in user.
* @return boolean
*/
public function validate_authentication( $user ) {
$backup_code = $this->sanitize_code_from_request( 'two-factor-backup-code' );
if ( ! $backup_code ) {
return false;
}
return $this->validate_code( $user, $backup_code );
}
/**
* Validates a backup code.
*
* Backup Codes are single use and are deleted upon a successful validation.
*
* @since 0.1-dev
*
* @param WP_User $user WP_User object of the logged-in user.
* @param int $code The backup code.
* @return boolean
*/
public function validate_code( $user, $code ) {
$backup_codes = get_user_meta( $user->ID, self::BACKUP_CODES_META_KEY, true );
if ( is_array( $backup_codes ) && ! empty( $backup_codes ) ) {
foreach ( $backup_codes as $code_index => $code_hashed ) {
if ( wp_check_password( $code, $code_hashed, $user->ID ) ) {
$this->delete_code( $user, $code_hashed );
return true;
}
}
}
return false;
}
/**
* Deletes a backup code.
*
* @since 0.1-dev
*
* @param WP_User $user WP_User object of the logged-in user.
* @param string $code_hashed The hashed the backup code.
*/
public function delete_code( $user, $code_hashed ) {
$backup_codes = get_user_meta( $user->ID, self::BACKUP_CODES_META_KEY, true );
// Delete the current code from the list since it's been used.
$backup_codes = array_flip( $backup_codes );
unset( $backup_codes[ $code_hashed ] );
$backup_codes = array_values( array_flip( $backup_codes ) );
// Update the backup code master list.
update_user_meta( $user->ID, self::BACKUP_CODES_META_KEY, $backup_codes );
}
/**
* Return user meta keys to delete during plugin uninstall.
*
* @since 0.10.0
*
* @return array
*/
public static function uninstall_user_meta_keys() {
return array(
self::BACKUP_CODES_META_KEY,
);
}
}