-
Notifications
You must be signed in to change notification settings - Fork 2
/
class-duouniversal-wordpressplugin.php
290 lines (251 loc) · 10.1 KB
/
class-duouniversal-wordpressplugin.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
<?php
/**
* Authentication flow handler
*
* Provides a class for handling user authentication including
* during login as well as tracking login state.
*
* @link https://duo.com/docs/wordpress
*
* @package Duo Universal
* @since 1.0.0
*/
namespace Duo\DuoUniversalWordpress;
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
require_once plugin_dir_path( __FILE__ ) . 'class-duouniversal-settings.php';
require_once plugin_dir_path( __FILE__ ) . 'class-duouniversal-utilities.php';
require_once plugin_dir_path( __FILE__ ) . 'vendor/autoload.php';
use Duo\DuoUniversal\Client;
class DuoUniversal_WordpressPlugin {
private $duo_client;
public $duo_utils;
public function __construct(
$duo_utils,
$duo_client
) {
$this->duo_client = $duo_client;
$this->duo_utils = $duo_utils;
}
/**
* Sets a user's auth state
* user: username of the user to update
* status: whether or not an authentication is in progress or is completed ("in-progress" or "authenticated")
**/
function update_user_auth_status( $user_id, $status, $redirect_url = '', $oidc_state = null ) {
\update_user_meta( $user_id, 'duo_auth_status', $status );
if ( $redirect_url ) {
\update_user_meta( $user_id, 'duo_auth_redirect_url', $redirect_url );
}
if ( $oidc_state ) {
// we need to track the state in two places so we can clean up later.
\update_user_meta( $user_id, 'duo_auth_oidc_state', $oidc_state );
// site_option will fallback to a standard option if this isn't multisite
\update_site_option( "duo_auth_state_$oidc_state", $user_id );
}
}
function duo_debug_log( $str ) {
return $this->duo_utils->duo_debug_log( $str );
}
function get_user_auth_status( $user_id ) {
return \get_user_meta( $user_id, 'duo_auth_status' , true);
}
function duo_verify_auth_status( $user_id ) {
return ( $this->get_user_auth_status( $user_id ) === 'authenticated' );
}
function get_user_from_oidc_state( $oidc_state ) {
$user_id = \get_site_option( "duo_auth_state_$oidc_state" );
return get_user_by('ID', $user_id);
}
function get_redirect_url( $user_id ) {
return \get_user_meta( $user_id, 'duo_auth_redirect_url' , true);
}
function clear_user_auth( $user_id ) {
try {
$oidc_state = \get_user_meta( $user_id, 'duo_auth_oidc_state' , true);
\delete_user_meta( $user_id, 'duo_auth_status' );
\delete_user_meta( $user_id, 'duo_auth_oidc_state' );
\delete_user_meta( $user_id, 'duo_auth_redirect_url' );
\delete_site_option( "duo_auth_state_$oidc_state" );
} catch ( \Exception $e ) {
// there's not much we can do but we shouldn't fail the logout because of this.
$this->duo_debug_log( $e->getMessage() );
}
}
function clear_current_user_auth() {
$user = \wp_get_current_user();
$this->clear_user_auth( $user->ID );
}
function get_page_url() {
// Per PHP documentation, HTTPS will be set to a non-empty value when
// the script was queried through HTTPS. However, IIS will set the
// value to 'off' HTTPS was not used, so we have to check that special
// case.
$https_used = ( ! empty( $_SERVER['HTTPS'] ) && strtolower( \sanitize_text_field( wp_unslash( $_SERVER['HTTPS'] ) ) ) !== 'off' );
if ( ! isset( $_SERVER['SERVER_PORT'] ) ) {
throw new Exception( 'Could not determine server port' );
}
$port = isset( $_SERVER['SERVER_PORT'] ) ? absint( $_SERVER['SERVER_PORT'] ) : null;
$protocol = ( $https_used || 443 === $port ) ? 'https://' : 'http://';
if ( ! isset( $_SERVER['HTTP_HOST'] ) ) {
throw new Exception( 'Could not determine host' );
}
$host = ! empty( $_SERVER['HTTP_HOST'] ) ? \sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) ) : null;
return \sanitize_url( $protocol . $host . $this->duo_utils->duo_get_uri(), array( 'http', 'https' ) );
}
function exit() {
exit();
}
function error_log( $str, int $type = 0, $destination = null, $headers = null ) {
error_log( $str, $type, $destination, $headers );
}
function duo_start_second_factor( $user ) {
// Clear any existing user state to purge old DB rows
$this->clear_user_auth( $user->ID );
$this->duo_client->healthCheck();
$oidc_state = $this->duo_client->generateState();
$redirect_url = $this->get_page_url();
$this->duo_client->redirect_url = $redirect_url;
$this->update_user_auth_status( $user->ID, 'in-progress', $redirect_url, $oidc_state );
$prompt_uri = $this->duo_client->createAuthUrl( $user->user_login, $oidc_state );
\wp_redirect( $prompt_uri );
$this->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 ( ! $this->duo_utils->duo_auth_enabled() ) {
$this->duo_debug_log( 'Duo not enabled, skipping 2FA.' );
return;
}
if ( isset( $_GET['duo_code'] ) ) {
// doing secondary auth.
if ( isset( $_GET['error'] ) ) {
$error = $this->duo_utils->new_WP_Error(
'Duo authentication failed',
\__( 'ERROR: Error during login; please contact your system administrator.' )
);
$error_msg = \sanitize_text_field( wp_unslash( $_GET['error'] ) );
if ( isset( $_GET['error_description'] ) ) {
$error_msg .= ': ' . \sanitize_text_field( wp_unslash( $_GET['error_description'] ) );
}
$this->duo_debug_log( $error_msg );
return $error;
}
if ( ! isset( $_GET['state'] ) ) {
$error = $this->duo_utils->new_WP_Error(
'Duo authentication failed',
\__( 'ERROR: Missing state; Please login again' )
);
$this->duo_debug_log( $error->get_error_message() );
return $error;
}
$this->duo_debug_log( 'Doing secondary auth' );
// Get authorization token to trade for 2FA.
$code = \sanitize_text_field( wp_unslash( $_GET['duo_code'] ) );
// Get state to verify consistency and originality.
$state = \sanitize_text_field( wp_unslash( $_GET['state'] ) );
// Retrieve the previously stored state and username from the session.
$associated_user = $this->get_user_from_oidc_state( $state );
// Immediately cleanup state after reading to reduce chance of an orphaned value
\delete_site_option( "duo_auth_state_$state" );
if ( empty( $associated_user ) ) {
$error = $this->duo_utils->new_WP_Error(
'Duo authentication failed',
\__( 'ERROR: No saved state please login again' )
);
$this->duo_debug_log( $error->get_error_message() );
return $error;
}
try {
// Update redirect URL to be one associated with initial authentication.
$this->duo_client->redirect_url = $this->get_redirect_url( $associated_user->ID );
$decoded_token = $this->duo_client->exchangeAuthorizationCodeFor2FAResult( $code, $associated_user->user_login );
} catch ( \Duo\DuoUniversal\DuoException $e ) {
$this->duo_debug_log( $e->getMessage() );
$error = $this->duo_utils->new_WP_Error(
'Duo authentication failed',
\__( 'ERROR: Error decoding Duo result. Confirm device clock is correct.' )
);
$this->duo_debug_log( $error->get_error_message() );
return $error;
}
$this->duo_debug_log( "Completed secondary auth for $associated_user->user_login" );
$this->update_user_auth_status( $associated_user->ID, 'authenticated' );
$user = $this->duo_utils->new_WP_user( 0, $associated_user->user_login );
return $user;
}
if ( strlen( $username ) > 0 ) {
// primary auth.
$this->duo_debug_log( 'Doing primary authentication' );
\remove_action( 'authenticate', 'wp_authenticate_username_password', 20 );
\remove_action( 'authenticate', 'wp_authenticate_email_password', 20 );
$user = \wp_authenticate_username_password( null, $username, $password );
if ( ! is_a( $user, 'WP_User' ) ) {
// maybe we got an email?
$user = \wp_authenticate_email_password( null, $username, $password );
if ( ! is_a( $user, 'WP_User' ) ) {
// on error, return said error (and skip the remaining plugin chain).
return $user;
}
}
$this->duo_debug_log( "Primary auth succeeded, starting second factor for $username" );
if ( ! $this->duo_utils->duo_role_require_mfa( $user ) ) {
$this->duo_debug_log( "Skipping 2FA for user: $username with roles: " . print_r( $user->roles, true ) );
$this->update_user_auth_status( $user->ID, 'authenticated' );
return $user;
}
$this->update_user_auth_status( $user->ID, 'in-progress' );
try {
// logging out clears cookies and user_metadata so it should be done _before_ updating
// the auth status.
\wp_logout();
$this->duo_start_second_factor( $user );
} catch ( \Duo\DuoUniversal\DuoException $e ) {
$this->duo_debug_log( $e->getMessage() );
if ( $this->duo_utils->duo_get_option( 'duoup_failmode' ) === 'open' ) {
// If we're failing open, errors in 2FA still allow for success.
$this->duo_debug_log( "Login 'Successful', but 2FA Not Performed. Confirm Duo client/secret/host values are correct" );
$this->update_user_auth_status( $user->ID, 'authenticated' );
return $user;
} else {
$error = $this->duo_utils->new_WP_Error(
'Duo authentication failed',
\__( 'Error: 2FA Unavailable. Confirm Duo client/secret/host values are correct' )
);
$this->duo_debug_log( $error->get_error_message() );
$this->clear_user_auth( $user->ID );
return $error;
}
}
}
$this->duo_debug_log( 'Starting primary authentication' );
}
/**
* Verify the user is authenticated with Duo. Start 2FA otherwise
*/
function duo_verify_auth() {
if ( ! $this->duo_utils->duo_auth_enabled() ) {
if ( \is_multisite() ) {
$site_info = \get_current_site();
$this->duo_debug_log( 'Duo not enabled on ' . $site_info->site_name );
} else {
$this->duo_debug_log( 'Duo not enabled, skip auth check.' );
}
return;
}
if ( \is_user_logged_in() ) {
$user = \wp_get_current_user();
$this->duo_debug_log( "Verifying auth state for user: $user->user_login" );
if ( $this->duo_utils->duo_role_require_mfa( $user ) && ! $this->duo_verify_auth_status( $user->ID ) ) {
\wp_logout();
wp_redirect( wp_login_url() );
$this->exit();
}
$this->duo_debug_log( "User $user->user_login allowed" );
}
}
}