This repository has been archived by the owner on Jul 18, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
/
duo_wordpress.php
858 lines (749 loc) · 31.3 KB
/
duo_wordpress.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
<?php
defined('ABSPATH') or die('Direct Access Denied');
/*
Plugin Name: Duo Two-Factor Authentication
Plugin URI: http://wordpress.org/extend/plugins/duo-wordpress/
Description: This plugin enables Duo two-factor authentication for WordPress logins.
Version: 2.5.7
Author: Duo Security
Author URI: http://www.duosecurity.com
License: GPL2
*/
/*
Copyright 2014 Duo Security <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2, as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
require_once('duo_web/duo_web.php');
$GLOBALS['DuoAuthCookieName'] = 'duo_wordpress_auth_cookie';
$GLOBALS['DuoSecAuthCookieName'] = 'duo_secure_wordpress_auth_cookie';
$GLOBALS['DuoDebug'] = false;
$GLOBALS['DuoPing'] = '/auth/v2/ping';
function parameterize($key, $value) {
return sprintf('%s="%s"', $key, $value);
}
function duo_sign_request($user, $redirect) {
$ikey = duo_get_option('duo_ikey');
$skey = duo_get_option('duo_skey');
$host = duo_get_option('duo_host');
$akey = duo_get_akey();
$username = $user->user_login;
$duo_time = duo_get_time();
$request_sig = Duo::signRequest($ikey, $skey, $akey, $username, $duo_time);
duo_debug_log("Displaying iFrame. Username: $username cookie domain: " . COOKIE_DOMAIN . " redirect_to_url: $redirect ikey: $ikey host: $host duo_time: $duo_time");
duo_debug_log("Duo request signature: $request_sig");
$post_action = esc_url(site_url('wp-login.php', 'login_post'));
$iframe_attributes = array(
'id' => 'duo_iframe',
'data-host' => $host,
'data-sig-request' => $request_sig,
'data-post-action' => $post_action,
'frameborder' => '0',
);
$iframe_attributes = array_map(
"parameterize",
array_keys($iframe_attributes),
array_values($iframe_attributes)
);
$iframe_attributes = implode(" ", $iframe_attributes);
?>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<?php
global $wp_version;
if(version_compare($wp_version, "3.3", "<=")){
echo '<link rel="stylesheet" type="text/css" href="' . admin_url('css/login.css') . '" />';
}
else if(version_compare($wp_version, "3.7", "<=")){
echo '<link rel="stylesheet" type="text/css" href="' . admin_url('css/wp-admin.css') . '" />';
echo '<link rel="stylesheet" type="text/css" href="' . admin_url('css/colors-fresh.css') . '" />';
}
else if(version_compare($wp_version, "3.8", "<=")){
echo '<link rel="stylesheet" type="text/css" href="' . admin_url('css/wp-admin.css') . '" />';
echo '<link rel="stylesheet" type="text/css" href="' . admin_url('css/colors.css') . '" />';
}
else {
echo '<link rel="stylesheet" type="text/css" href="' . admin_url('css/login.min.css') . '" />';
}
?>
<style>
body {
background: #f1f1f1;
}
.centerHeader {
width: 100%;
padding-top: 8%;
}
#WPLogo {
width: 100%;
}
.iframe_div {
width: 90%;
max-width: 620px;
margin: 0 auto;
}
#duo_iframe {
height: 330px;
width: 100%;
min-width: 304px;
max-width: 620px;
}
div {
background: transparent;
}
</style>
</head>
<body class="login" >
<script src="<?php echo plugins_url('duo_web/Duo-Web-v2.min.js?v=2', __FILE__); ?>"></script>
<h1 class="centerHeader">
<a href="http://wordpress.org/" id="WPLogo" title="Powered by WordPress"><?php echo get_bloginfo('name'); ?></a>
</h1>
<div class="iframe_div">
<iframe <?php echo $iframe_attributes ?>></iframe>
</div>
<form method="POST" style="display:none;" id="duo_form">
<?php if (isset($_POST['rememberme'])) { ?>
<input type="hidden" name="rememberme" value="<?php echo esc_attr($_POST['rememberme'])?>"/>
<?php
}
if (isset($_REQUEST['interim-login'])){
echo '<input type="hidden" name="interim-login" value="1"/>';
}
else {
echo '<input type="hidden" name="redirect_to" value="' . esc_attr($redirect) . '"/>';
}
?>
</form>
</body>
</html>
<?php
}
function duo_get_roles(){
global $wp_roles;
// $wp_roles may not be initially set if wordpress < 3.3
$wp_roles = isset($wp_roles) ? $wp_roles : new WP_Roles();
return $wp_roles;
}
function duo_auth_enabled(){
if (defined('XMLRPC_REQUEST') && XMLRPC_REQUEST) {
duo_debug_log('Found an XMLRPC request. XMLRPC is allowed for this site. Skipping second factor');
return false; //allows the XML-RPC protocol for remote publishing
}
if (duo_get_option('duo_ikey', '') == '' || duo_get_option('duo_skey', '') == '' ||
duo_get_option('duo_host', '') == '') {
return false;
}
return true;
}
function duo_role_require_mfa($user){
$wp_roles = duo_get_roles();
$all_roles = array();
foreach ($wp_roles->get_names() as $k=>$r) {
$all_roles[$k] = $r;
}
$duo_roles = duo_get_option('duo_roles', $all_roles);
/*
* WordPress < 3.3 does not include the roles by default
* Create a User object to get roles info
* Don't use get_user_by()
*/
if (!isset($user->roles)){
$user = new WP_User(0, $user->user_login);
}
/*
* Mainly a workaround for multisite login:
* if a user logs in to a site different from the one
* they are a member of, login will work however
* it appears as if the user has no roles during authentication
* "fail closed" in this case and require duo auth
*/
if(empty($user->roles)) {
return true;
}
foreach ($user->roles as $role) {
if (array_key_exists($role, $duo_roles)) {
return true;
}
}
return false;
}
function duo_start_second_factor($user, $redirect_to=NULL){
if (!$redirect_to){
// Some custom themes do not provide the redirect_to value
// Admin page is a good default
$redirect_to = isset( $_POST['redirect_to'] ) ? $_POST['redirect_to'] : admin_url();
}
wp_logout();
duo_sign_request($user, $redirect_to);
exit();
}
function duo_authenticate_user($user="", $username="", $password="") {
// play nicely with other plugins if they have higher priority than us
if (is_a($user, 'WP_User')) {
return $user;
}
if (! duo_auth_enabled()){
duo_debug_log('Duo not enabled, skipping 2FA.');
return;
}
if (isset($_POST['sig_response'])) {
// secondary auth
remove_action('authenticate', 'wp_authenticate_username_password', 20);
$akey = duo_get_akey();
$duo_time = duo_get_time();
$username = Duo::verifyResponse(duo_get_option('duo_ikey'),
duo_get_option('duo_skey'),
$akey,
$_POST['sig_response'],
$duo_time);
if ($username) {
// Don't use get_user_by(). It doesn't return a WP_User object if wordpress version < 3.3
$user = new WP_User(0, $username);
duo_set_cookie($user);
duo_debug_log("Second factor successful for user: $username");
return $user;
} else {
$user = new WP_Error('Duo authentication_failed',
__('<strong>ERROR</strong>: Failed or expired two factor authentication'));
return $user;
}
}
if (strlen($username) > 0) {
// primary auth
// Don't use get_user_by(). It doesn't return a WP_User object if wordpress version < 3.3
$user = new WP_User(0, $username);
if (!$user) {
error_log("Failed to retrieve WP user $username");
return;
}
if(!duo_role_require_mfa($user)){
duo_debug_log("Skipping 2FA for user: $username with roles: " . print_r($user->roles, true));
return;
}
remove_action('authenticate', 'wp_authenticate_username_password', 20);
$user = wp_authenticate_username_password(NULL, $username, $password);
if (!is_a($user, 'WP_User')) {
// on error, return said error (and skip the remaining plugin chain)
return $user;
} else {
duo_debug_log("Primary auth succeeded, starting second factor for $username");
duo_start_second_factor($user);
}
}
duo_debug_log('Starting primary authentication');
}
function duo_settings_page() {
duo_debug_log('Displaying duo setting page');
?>
<div class="wrap">
<h2>Duo Two-Factor Authentication</h2>
<?php if(is_multisite()) { ?>
<form action="ms-options.php" method="post">
<?php } else { ?>
<form action="options.php" method="post">
<?php } ?>
<?php settings_fields('duo_settings'); ?>
<?php do_settings_sections('duo_settings'); ?>
<p class="submit">
<input name="Submit" type="submit" class="button primary-button" value="<?php esc_attr_e('Save Changes'); ?>" />
</p>
</form>
</div>
<?php
}
function duo_settings_ikey() {
$ikey = esc_attr(duo_get_option('duo_ikey'));
echo "<input id='duo_ikey' name='duo_ikey' size='40' type='text' value='$ikey' />";
}
function duo_settings_skey() {
$skey = esc_attr(duo_get_option('duo_skey'));
echo "<input id='duo_skey' name='duo_skey' size='40' type='password' value='$skey' autocomplete='off' />";
}
function duo_settings_host() {
$host = esc_attr(duo_get_option('duo_host'));
echo "<input id='duo_host' name='duo_host' size='40' type='text' value='$host' />";
}
function duo_settings_roles() {
$wp_roles = duo_get_roles();
$roles = $wp_roles->get_names();
$newroles = array();
foreach($roles as $key=>$role) {
$newroles[before_last_bar($key)] = before_last_bar($role);
}
$selected = duo_get_option('duo_roles', $newroles);
foreach ($wp_roles->get_names() as $key=>$role) {
//create checkbox for each role
?>
<input id="duo_roles" name='duo_roles[<?php echo $key; ?>]' type='checkbox' value='<?php echo $role; ?>' <?php if(in_array($role, $selected)) echo 'checked'; ?> /> <?php echo $role; ?> <br />
<?php
}
}
function duo_roles_validate($options) {
//return empty array
if (!is_array($options) || empty($options) || (false === $options)) {
return array();
}
$wp_roles = duo_get_roles();
$valid_roles = $wp_roles->get_names();
//otherwise validate each role and then return the array
foreach ($options as $opt) {
if (!in_array($opt, $valid_roles)) {
unset($options[$opt]);
}
}
return $options;
}
function duo_settings_text() {
echo "<p>See the <a target='_blank' href='https://www.duosecurity.com/docs/wordpress'>Duo for WordPress guide</a> to enable Duo two-factor authentication for your WordPress logins.</p>";
echo '<p>You can retrieve your integration key, secret key, and API hostname by logging in to the Duo administrative interface.</p>';
echo '<p>Note: After enabling the plugin, you will be immediately prompted for second factor authentication.</p>';
}
function duo_ikey_validate($ikey) {
if (strlen($ikey) != 20) {
add_settings_error('duo_ikey', '', 'Integration key is not valid');
return "";
} else {
return $ikey;
}
}
function duo_skey_validate($skey){
if (strlen($skey) != 40) {
add_settings_error('duo_skey', '', 'Secret key is not valid');
return "";
} else {
return $skey;
}
}
function duo_settings_xmlrpc() {
$val = '';
if(duo_get_option('duo_xmlrpc', 'off') == 'off') {
$val = "checked";
}
echo "<input id='duo_xmlrpc' name='duo_xmlrpc' type='checkbox' value='off' $val /> Yes<br />";
echo "Using XML-RPC bypasses two-factor authentication and makes your website less secure. We recommend only using the WordPress web interface for managing your WordPress website.";
}
function duo_xmlrpc_validate($option) {
if($option == 'off') {
return $option;
}
return 'on';
}
function duo_add_site_option($option, $value = '') {
// Add multisite option only if it doesn't exist already
// With Wordpress versions < 3.3, calling add_site_option will override old values
if (duo_get_option($option) === FALSE){
add_site_option($option, $value);
}
}
function duo_admin_init() {
if (is_multisite()) {
$wp_roles = duo_get_roles();
$roles = $wp_roles->get_names();
$allroles = array();
foreach($roles as $key=>$role) {
$allroles[before_last_bar($key)] = before_last_bar($role);
}
duo_add_site_option('duo_ikey', '');
duo_add_site_option('duo_skey', '');
duo_add_site_option('duo_host', '');
duo_add_site_option('duo_roles', $allroles);
duo_add_site_option('duo_xmlrpc', 'off');
}
else {
add_settings_section('duo_settings', 'Main Settings', 'duo_settings_text', 'duo_settings');
add_settings_field('duo_ikey', 'Integration key', 'duo_settings_ikey', 'duo_settings', 'duo_settings');
add_settings_field('duo_skey', 'Secret key', 'duo_settings_skey', 'duo_settings', 'duo_settings');
add_settings_field('duo_host', 'API hostname', 'duo_settings_host', 'duo_settings', 'duo_settings');
add_settings_field('duo_roles', 'Enable for roles:', 'duo_settings_roles', 'duo_settings', 'duo_settings');
add_settings_field('duo_xmlrpc', 'Disable XML-RPC (recommended)', 'duo_settings_xmlrpc', 'duo_settings', 'duo_settings');
register_setting('duo_settings', 'duo_ikey', 'duo_ikey_validate');
register_setting('duo_settings', 'duo_skey', 'duo_skey_validate');
register_setting('duo_settings', 'duo_host');
register_setting('duo_settings', 'duo_roles', 'duo_roles_validate');
register_setting('duo_settings', 'duo_xmlrpc', 'duo_xmlrpc_validate');
}
}
function duo_mu_options() {
?>
<h3>Duo Security</h3>
<table class="form-table">
<?php duo_settings_text();?></td></tr>
<tr><th>Integration key</th><td><?php duo_settings_ikey();?></td></tr>
<tr><th>Secret key</th><td><?php duo_settings_skey();?></td></tr>
<tr><th>API hostname</th><td><?php duo_settings_host();?></td></tr>
<tr><th>Roles</th><td><?php duo_settings_roles();?></td></tr>
<tr><th>Disable XML-RPC</th><td><?php duo_settings_xmlrpc();?></td></tr>
</table>
<?php
}
function duo_update_mu_options() {
if(isset($_POST['duo_ikey'])) {
$ikey = $_POST['duo_ikey'];
$result = update_site_option('duo_ikey', $ikey);
}
if(isset($_POST['duo_skey'])) {
$skey = $_POST['duo_skey'];
$result = update_site_option('duo_skey', $skey);
}
if(isset($_POST['duo_host'])) {
$host = $_POST['duo_host'];
$result = update_site_option('duo_host', $host);
}
if(isset($_POST['duo_roles'])) {
$roles = $_POST['duo_roles'];
$result = update_site_option('duo_roles', $roles);
}
else {
$result = update_site_option('duo_roles', []);
}
if(isset($_POST['duo_xmlrpc'])) {
$xmlrpc = $_POST['duo_xmlrpc'];
$result = update_site_option('duo_xmlrpc', $xmlrpc);
}
else {
$result = update_site_option('duo_xmlrpc', 'on');
}
}
function duo_add_page() {
if(! is_multisite()) {
add_options_page('Duo Two-Factor', 'Duo Two-Factor', 'manage_options', 'duo_wordpress', 'duo_settings_page');
}
}
function duo_add_link($links, $file) {
static $this_plugin;
if (!$this_plugin) $this_plugin = plugin_basename(__FILE__);
if ($file == $this_plugin) {
$settings_link = '<a href="options-general.php?page=duo_wordpress">'.__("Settings", "duo_wordpress").'</a>';
array_unshift($links, $settings_link);
}
return $links;
}
/*
* Returns current plugin version.
*
* @return string Plugin version
*/
function duo_get_plugin_version() {
if (!function_exists('get_plugin_data'))
require_once(ABSPATH . 'wp-admin/includes/plugin.php');
$plugin_data = get_plugin_data( __FILE__ );
return $plugin_data['Version'];
}
function duo_get_user_agent() {
global $wp_version;
$duo_wordpress_version = duo_get_plugin_version();
return $_SERVER['SERVER_SOFTWARE'] . " WordPress/$wp_version duo_wordpress/$duo_wordpress_version";
}
/*
* Get Duo's system time.
* If that fails then use server system time
*/
function duo_get_time() {
$time = NULL;
if (!extension_loaded('openssl')) {
//fall back to local time
error_log('SSL is disabled. Can\'t fetch Duo server time.');
}
else {
global $DuoPing;
$duo_host = duo_get_option('duo_host');
$headers = duo_sign_ping($duo_host);
$duo_url = 'https://' . $duo_host . $DuoPing;
$cert_file = dirname(__FILE__) . '/duo_web/ca_certs.pem';
if( ini_get('allow_url_fopen') ) {
$time = duo_get_time_fopen($duo_url, $cert_file, $headers);
}
else if(in_array('curl', get_loaded_extensions())){
$time = duo_get_time_curl($duo_url, $cert_file, $headers);
}
else{
$time = duo_get_time_WP_HTTP($duo_url, $headers);
}
}
//if all fails, use local time
$time = ($time != NULL ? $time : time());
return $time;
}
function duo_get_time_fopen($duo_url, $cert_file, $headers) {
$settings = array(
'http'=>array(
'method' => 'GET',
'header' => $headers,
'user_agent'=> duo_get_user_agent(),
),
'ssl'=>array(
'allow_self_signed'=>false,
'verify_peer'=>true,
'cafile'=>$cert_file,
)
);
if ( defined('WP_PROXY_HOST') && defined('WP_PROXY_PORT')) {
$settings['http']['proxy'] = 'tcp://' . WP_PROXY_HOST . ':' . WP_PROXY_PORT;
}
$context = stream_context_create($settings);
$response = json_decode(file_get_contents($duo_url, false, $context), true);
if (!$response){
return NULL;
}
$time = (int)$response['response']['time'];
return $time;
}
function duo_get_time_curl($duo_url, $cert_file, $headers) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $duo_url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CAINFO, $cert_file);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, duo_get_user_agent());
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
if ( defined('WP_PROXY_HOST') && defined('WP_PROXY_PORT')) {
curl_setopt( $ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP );
curl_setopt( $ch, CURLOPT_PROXY, WP_PROXY_HOST );
curl_setopt( $ch, CURLOPT_PROXYPORT, WP_PROXY_PORT );
}
$response =json_decode(curl_exec($ch), true);
curl_close ($ch);
if (!$response){
return NULL;
}
$time = (int)$response['response']['time'];
return $time;
}
// Uses Wordpress HTTP. We can't specify our SSL cert here.
// Servers with out of date root certs may fail.
function duo_get_time_WP_HTTP($duo_url, $headers) {
if(!class_exists('WP_Http')){
include_once(ABSPATH . WPINC . '/class-http.php');
}
$args = array(
'method' => 'GET',
'blocking' => true,
'sslverify' => true,
'user-agent' => duo_get_user_agent(),
'headers' => $headers,
);
$response = wp_remote_get($duo_url, $args);
if(is_wp_error($response)){
$error_message = $response->get_error_message();
error_log("Could not fetch Duo server time: $error_message");
return NULL;
}
else {
$body = json_decode(wp_remote_retrieve_body($response), true);
$time = (int)$body['response']['time'];
return $time;
}
}
function duo_set_cookie($user){
global $DuoAuthCookieName;
global $DuoSecAuthCookieName;
$ikey_b64 = base64_encode(duo_get_option('duo_ikey'));
$username_b64 = base64_encode($user->user_login);
$expire = strtotime('+48 hours');
//Create http cookie
$val = base64_encode(sprintf("%s|%s|%s|%s", $DuoAuthCookieName, $username_b64, $ikey_b64, $expire));
$sig = duo_hash_hmac($val);
$cookie = sprintf("%s|%s", $val, $sig);
setcookie($DuoAuthCookieName, $cookie, 0, COOKIEPATH, COOKIE_DOMAIN, false, true);
if (COOKIEPATH != SITECOOKIEPATH){
setcookie($DuoAuthCookieName, $cookie, 0, SITECOOKIEPATH, COOKIE_DOMAIN, false, true);
}
if (is_ssl()){
//Create https cookie
$sec_val = base64_encode(sprintf("%s|%s|%s|%s", $DuoSecAuthCookieName, $username_b64, $ikey_b64, $expire));
$sec_sig = duo_hash_hmac($sec_val);
$sec_cookie = sprintf("%s|%s", $sec_val, $sec_sig);
setcookie($DuoSecAuthCookieName, $sec_cookie, 0, COOKIEPATH, COOKIE_DOMAIN, true, true);
if (COOKIEPATH != SITECOOKIEPATH){
setcookie($DuoSecAuthCookieName, $sec_cookie, 0, SITECOOKIEPATH, COOKIE_DOMAIN, true, true);
}
}
duo_debug_log("Set Duo cookie for user: $user->user_login path: " . COOKIEPATH . " network path: " . SITECOOKIEPATH . " on domain: " . COOKIE_DOMAIN . " set SSL: " . is_ssl());
}
function duo_unset_cookie(){
global $DuoAuthCookieName;
global $DuoSecAuthCookieName;
setcookie($DuoAuthCookieName, '', strtotime('-1 day'), COOKIEPATH, COOKIE_DOMAIN);
setcookie($DuoAuthCookieName, '', strtotime('-1 day'), SITECOOKIEPATH, COOKIE_DOMAIN);
setcookie($DuoSecAuthCookieName, '', strtotime('-1 day'), COOKIEPATH, COOKIE_DOMAIN);
setcookie($DuoSecAuthCookieName, '', strtotime('-1 day'), SITECOOKIEPATH, COOKIE_DOMAIN);
duo_debug_log("Unset Duo cookie for path: " . COOKIEPATH . " network path: " . SITECOOKIEPATH . " on domain: " . COOKIE_DOMAIN);
}
if(!function_exists('hash_equals')) {
function hash_equals($str1, $str2) {
if(strlen($str1) != strlen($str2)) {
return false;
} else {
$res = $str1 ^ $str2;
$ret = 0;
for($i = strlen($res) - 1; $i >= 0; $i--) $ret |= ord($res[$i]);
return !$ret;
}
}
}
function duo_verify_sig($cookie, $u_sig){
$sig = duo_hash_hmac($cookie);
if (hash_equals(duo_hash_hmac($sig), duo_hash_hmac($u_sig))) {
return true;
}
return false;
}
function duo_verify_cookie($user){
/*
Return true if Duo cookie is valid, false otherwise
If using SSL, or secure cookie is set, only accept secure cookie
*/
global $DuoAuthCookieName;
global $DuoSecAuthCookieName;
if (is_ssl() || isset($_COOKIE[$DuoSecAuthCookieName])){
$duo_auth_cookie_name = $DuoSecAuthCookieName;
}
else {
$duo_auth_cookie_name = $DuoAuthCookieName;
}
if(!isset($_COOKIE[$duo_auth_cookie_name])){
error_log("Duo cookie with name: $duo_auth_cookie_name not found. Start two factor authentication. SSL: " . is_ssl());
return false;
}
$cookie_list = explode('|', $_COOKIE[$duo_auth_cookie_name]);
if (count($cookie_list) !== 2){
error_log('Invalid Duo cookie');
return false;
}
list($u_cookie_b64, $u_sig) = $cookie_list;
if (!duo_verify_sig($u_cookie_b64, $u_sig)){
error_log('Duo cookie signature mismatch');
return false;
}
$cookie_content = explode('|', base64_decode($u_cookie_b64));
if (count($cookie_content) !== 4){
error_log('Invalid field count in Duo cookie');
return false;
}
list($cookie_name, $cookie_username_b64, $cookie_ikey_b64, $expire) = $cookie_content;
// Check cookie values
if ($cookie_name !== $duo_auth_cookie_name ||
base64_decode($cookie_username_b64) !== $user->user_login ||
base64_decode($cookie_ikey_b64) !== duo_get_option('duo_ikey')){
error_log('Invalid Duo cookie content');
return false;
}
$expire = intval($expire);
if ($expire < strtotime('now')){
error_log('Duo cookie expired');
return false;
}
return true;
}
function duo_get_uri(){
// Workaround for IIS which may not set REQUEST_URI, or QUERY parameters
if (!isset($_SERVER['REQUEST_URI']) ||
(!empty($_SERVER['QUERY_STRING']) && !strpos($_SERVER['REQUEST_URI'], '?', 0))) {
$current_uri = substr($_SERVER['PHP_SELF'],1);
if (isset($_SERVER['QUERY_STRING']) AND $_SERVER['QUERY_STRING'] != '') {
$current_uri .= '?'.$_SERVER['QUERY_STRING'];
}
return $current_uri;
}
else {
return $_SERVER['REQUEST_URI'];
}
}
function duo_verify_auth(){
/*
Verify the user is authenticated with Duo. Start 2FA otherwise
*/
if (! duo_auth_enabled()){
if (is_multisite()) {
$site_info = get_current_site();
duo_debug_log("Duo not enabled on " . $site_info->site_name . ', skip cookie check.');
}
else {
duo_debug_log('Duo not enabled, skip cookie check.');
}
return;
}
if(is_user_logged_in()){
$user = wp_get_current_user();
duo_debug_log("Verifying second factor for user: $user->user_login URL: " . duo_get_uri() . ' path: ' . COOKIEPATH . ' network path: ' . SITECOOKIEPATH . 'cookie domain: ' . COOKIE_DOMAIN . ' is SSL: ' . is_ssl());
if (duo_role_require_mfa($user) and !duo_verify_cookie($user)){
duo_debug_log("Duo cookie invalid for user: $user->user_login");
duo_start_second_factor($user, duo_get_uri());
}
duo_debug_log("User $user->user_login allowed");
}
}
function duo_get_akey(){
// Get an application specific secret key.
// If wp_salt() is not long enough, append a random secret to it
$akey = duo_get_option('duo_akey', '');
$akey .= wp_salt();
if (strlen($akey) < 40) {
duo_debug_log('WordPress secret key is less than 40 chars. Creating new akey.');
$akey = wp_generate_password(40, true, true);
update_site_option('duo_akey', $akey);
$akey .= wp_salt();
}
return $akey;
}
function duo_debug_log($message) {
global $DuoDebug;
if ($DuoDebug) {
error_log('Duo debug: ' . $message);
}
}
function duo_hash_hmac($data){
return hash_hmac('sha1', $data, duo_get_akey());
}
function duo_sign_ping($host, $date=NULL) {
global $DuoPing;
if (! $date) {
$date = date('r');
}
$canon = array($date, 'GET', $host, $DuoPing, '');
$canon = implode("\n", $canon);
$sig = hash_hmac('sha1', $canon, duo_get_option('duo_skey'));
return array(
'Authorization: Basic ' . base64_encode(duo_get_option('duo_ikey') . ':' . $sig),
'Date: ' . $date,
'Host: ' . $host,
);
}
/*-------------XML-RPC Features-----------------*/
if(duo_get_option('duo_xmlrpc', 'off') == 'off') {
add_filter( 'xmlrpc_enabled', '__return_false' );
}
/*-------------Register WordPress Hooks-------------*/
if (!is_multisite()) {
add_filter('plugin_action_links', 'duo_add_link', 10, 2 );
}
add_action('init', 'duo_verify_auth', 10);
add_action('clear_auth_cookie', 'duo_unset_cookie', 10);
add_filter('authenticate', 'duo_authenticate_user', 10, 3);
//add single-site submenu option
add_action('admin_menu', 'duo_add_page');
// Custom fields in network settings
add_action('wpmu_options', 'duo_mu_options');
add_action('update_wpmu_options', 'duo_update_mu_options');
add_action('admin_init', 'duo_admin_init');
function duo_get_option($key, $default="") {
if (is_multisite()) {
return get_site_option($key, $default);
}
else {
return get_option($key, $default);
}
}
?>