Completed
Pull Request — master (#11747)
by Claudio
11:46
created

check_authentication_error()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
eloc 5
nc 2
nop 1
1
<?php
2
/**
3
 * REST API Authentication
4
 *
5
 * @author   WooThemes
6
 * @category API
7
 * @package  WooCommerce/API
8
 * @since    2.6.0
9
 */
10
11
if ( ! defined( 'ABSPATH' ) ) {
12
	exit;
13
}
14
15
class WC_REST_Authentication {
16
17
	/**
18
	 * Initialize authentication actions.
19
	 */
20
	public function __construct() {
21
		add_filter( 'determine_current_user', array( $this, 'authenticate' ), 100 );
22
		add_filter( 'rest_authentication_errors', array( $this, 'check_authentication_error' ) );
23
		add_filter( 'rest_post_dispatch', array( $this, 'send_unauthorized_headers' ), 50 );
24
	}
25
26
	/**
27
	 * Check if is request to our REST API.
28
	 *
29
	 * @return bool
30
	 */
31
	protected function is_request_to_rest_api() {
32
		if ( empty( $_SERVER['REQUEST_URI'] ) ) {
33
			return false;
34
		}
35
36
		$rest_prefix = trailingslashit( rest_get_url_prefix() );
37
38
		// Check if our endpoint.
39
		$woocommerce = false !== strpos( $_SERVER['REQUEST_URI'], $rest_prefix . 'wc/' );
40
41
		// Allow third party plugins use our authentication methods.
42
		$third_party = false !== strpos( $_SERVER['REQUEST_URI'], $rest_prefix . 'wc-' );
43
44
		return apply_filters( 'woocommerce_rest_is_request_to_rest_api', $woocommerce || $third_party );
45
	}
46
47
	/**
48
	 * Authenticate user.
49
	 *
50
	 * @param int|false $user_id User ID if one has been determined, false otherwise.
51
	 * @return int|false
52
	 */
53
	public function authenticate( $user_id ) {
54
		// Do not authenticate twice and check if is a request to our endpoint in the WP REST API.
55
		if ( ! empty( $user_id ) || ! $this->is_request_to_rest_api() ) {
56
			return $user_id;
57
		}
58
59
		if ( is_ssl() ) {
60
			return $this->perform_basic_authentication();
61
		} else {
62
			return $this->perform_oauth_authentication();
63
		}
64
	}
65
66
	/**
67
	 * Check for authentication error.
68
	 *
69
	 * @param WP_Error|null|bool $error
70
	 * @return WP_Error|null|bool
71
	 */
72
	public function check_authentication_error( $error ) {
73
		global $wc_rest_authentication_error;
74
75
		// Passthrough other errors.
76
		if ( ! empty( $error ) ) {
77
			return $error;
78
		}
79
80
		return $wc_rest_authentication_error;
81
	}
82
83
	/**
84
	 * Basic Authentication.
85
	 *
86
	 * SSL-encrypted requests are not subject to sniffing or man-in-the-middle
87
	 * attacks, so the request can be authenticated by simply looking up the user
88
	 * associated with the given consumer key and confirming the consumer secret
89
	 * provided is valid.
90
	 *
91
	 * @return int|bool
92
	 */
93
	private function perform_basic_authentication() {
94
		global $wc_rest_authentication_error;
95
96
		$consumer_key    = '';
97
		$consumer_secret = '';
98
99
		// If the $_GET parameters are present, use those first.
100 View Code Duplication
		if ( ! empty( $_GET['consumer_key'] ) && ! empty( $_GET['consumer_secret'] ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
101
			$consumer_key    = $_GET['consumer_key'];
102
			$consumer_secret = $_GET['consumer_secret'];
103
		}
104
105
		// If the above is not present, we will do full basic auth.
106 View Code Duplication
		if ( ! $consumer_key && ! empty( $_SERVER['PHP_AUTH_USER'] ) && ! empty( $_SERVER['PHP_AUTH_PW'] ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
107
			$consumer_key    = $_SERVER['PHP_AUTH_USER'];
108
			$consumer_secret = $_SERVER['PHP_AUTH_PW'];
109
		}
110
111
		// Stop if don't have any key.
112
		if ( ! $consumer_key || ! $consumer_secret ) {
113
			return false;
114
		}
115
116
		// Get user data.
117
		$user = $this->get_user_data_by_consumer_key( $consumer_key );
118
		if ( empty( $user ) ) {
119
			return false;
120
		}
121
122
		// Validate user secret.
123
		if ( ! hash_equals( $user->consumer_secret, $consumer_secret ) ) {
124
			$wc_rest_authentication_error = new WP_Error( 'woocommerce_rest_authentication_error', __( 'Consumer Secret is invalid.', 'woocommerce' ), array( 'status' => 401 ) );
125
126
			return false;
127
		}
128
129
		// Check API Key permissions.
130
		if ( ! $this->check_permissions( $user->permissions ) ) {
131
			return false;
132
		}
133
134
		// Update last access.
135
		$this->update_last_access( $user->key_id );
136
137
		return $user->user_id;
138
	}
139
140
	/**
141
	 * Parse the Authorization header into parameters.
142
	 *
143
	 * @since 2.7.0
144
	 *
145
	 * @param string $header Authorization header value (not including "Authorization: " prefix).
146
	 *
147
	 * @return array Map of parameter values.
148
	 */
149
	public function parse_header( $header ) {
150
		if ( 'OAuth ' !== substr( $header, 0, 6 ) ) {
151
			return array();
152
		}
153
154
		// From OAuth PHP library, used under MIT license.
155
		$params = array();
156
		if ( preg_match_all( '/(oauth_[a-z_-]*)=(:?"([^"]*)"|([^,]*))/', $header, $matches ) ) {
157
			foreach ( $matches[ 1 ] as $i => $h ) {
158
				$params[ $h ] = urldecode( empty( $matches[3][ $i ] ) ? $matches[4][ $i ] : $matches[3][ $i ] );
159
			}
160
			if ( isset( $params['realm'] ) ) {
161
				unset( $params['realm'] );
162
			}
163
		}
164
165
		return $params;
166
	}
167
168
	/**
169
	 * Get the authorization header.
170
	 *
171
	 * On certain systems and configurations, the Authorization header will be
172
	 * stripped out by the server or PHP. Typically this is then used to
173
	 * generate `PHP_AUTH_USER`/`PHP_AUTH_PASS` but not passed on. We use
174
	 * `getallheaders` here to try and grab it out instead.
175
	 *
176
	 * @since 2.7.0
177
	 *
178
	 * @return string Authorization header if set.
179
	 */
180
	public function get_authorization_header() {
181
		if ( ! empty( $_SERVER['HTTP_AUTHORIZATION'] ) ) {
182
			return wp_unslash( $_SERVER['HTTP_AUTHORIZATION'] );
183
		}
184
185
		if ( function_exists( 'getallheaders' ) ) {
186
			$headers = getallheaders();
187
			// Check for the authoization header case-insensitively.
188
			foreach ( $headers as $key => $value ) {
189
				if ( 'authorization' === strtolower( $key ) ) {
190
					return $value;
191
				}
192
			}
193
		}
194
195
		return '';
196
	}
197
198
	/**
199
	 * Get oAuth parameters from $_GET, $_POST or request header.
200
	 *
201
	 * @since 2.7.0
202
	 *
203
	 * @return array|WP_Error
204
	 */
205
	public function get_oauth_parameters() {
206
		global $wc_rest_authentication_error;
207
208
		$params = array_merge( $_GET, $_POST );
209
		$params = wp_unslash( $params );
210
		$header = $this->get_authorization_header();
211
212
		if ( ! empty( $header ) ) {
213
			// Trim leading spaces.
214
			$header = trim( $header );
215
			$header_params = $this->parse_header( $header );
216
217
			if ( ! empty( $header_params ) ) {
218
				$params = array_merge( $params, $header_params );
219
			}
220
		}
221
222
		$param_names = array(
223
			'oauth_consumer_key',
224
			'oauth_timestamp',
225
			'oauth_nonce',
226
			'oauth_signature',
227
			'oauth_signature_method'
228
		);
229
230
		$errors   = array();
231
		$have_one = false;
232
233
		// Check for required OAuth parameters.
234
		foreach ( $param_names as $param_name ) {
235
			if ( empty( $params[ $param_name ] ) ) {
236
				$errors[] = $param_name;
237
			} else {
238
				$have_one = true;
239
			}
240
		}
241
242
		// All keys are missing, so we're probably not even trying to use OAuth.
243
		if ( ! $have_one ) {
244
			return array();
245
		}
246
247
		// If we have at least one supplied piece of data, and we have an error,
248
		// then it's a failed authentication.
249
		if ( ! empty( $errors ) ) {
250
			$message = sprintf(
251
				_n(
252
					__( 'Missing OAuth parameter %s', 'woocommerce' ),
253
					__( 'Missing OAuth parameters %s', 'woocommerce' ),
254
					count( $errors )
255
				),
256
				implode( ', ', $errors )
257
			);
258
259
			$wc_rest_authentication_error = new WP_Error( 'woocommerce_rest_authentication_missing_parameter', $message, array( 'status' => 401 ) );
260
261
			return array();
262
		}
263
264
		return $params;
265
	}
266
267
	/**
268
	 * Perform OAuth 1.0a "one-legged" (http://oauthbible.com/#oauth-10a-one-legged) authentication for non-SSL requests.
269
	 *
270
	 * This is required so API credentials cannot be sniffed or intercepted when making API requests over plain HTTP.
271
	 *
272
	 * This follows the spec for simple OAuth 1.0a authentication (RFC 5849) as closely as possible, with two exceptions:
273
	 *
274
	 * 1) There is no token associated with request/responses, only consumer keys/secrets are used.
275
	 *
276
	 * 2) The OAuth parameters are included as part of the request query string instead of part of the Authorization header,
277
	 *    This is because there is no cross-OS function within PHP to get the raw Authorization header.
278
	 *
279
	 * @link http://tools.ietf.org/html/rfc5849 for the full spec.
280
	 *
281
	 * @return int|bool
282
	 */
283
	private function perform_oauth_authentication() {
284
		global $wc_rest_authentication_error;
285
286
		$params = $this->get_oauth_parameters();
287
		if ( empty( $params ) ) {
288
			return false;
289
		}
290
291
		// Fetch WP user by consumer key.
292
		$user = $this->get_user_data_by_consumer_key( $params['oauth_consumer_key'] );
293
294
		if ( empty( $user ) ) {
295
			$wc_rest_authentication_error = new WP_Error( 'woocommerce_rest_authentication_error', __( 'Consumer Key is invalid.', 'woocommerce' ), array( 'status' => 401 ) );
296
297
			return false;
298
		}
299
300
		// Perform OAuth validation.
301
		$wc_rest_authentication_error = $this->check_oauth_signature( $user, $params );
302
		if ( is_wp_error( $wc_rest_authentication_error ) ) {
303
			return false;
304
		}
305
306
		$wc_rest_authentication_error = $this->check_oauth_timestamp_and_nonce( $user, $params['oauth_timestamp'], $params['oauth_nonce'] );
307
		if ( is_wp_error( $wc_rest_authentication_error ) ) {
308
			return false;
309
		}
310
311
		// Check API Key permissions.
312
		if ( ! $this->check_permissions( $user->permissions ) ) {
313
			return false;
314
		}
315
316
		// Update last access.
317
		$this->update_last_access( $user->key_id );
318
319
		return $user->user_id;
320
	}
321
322
	/**
323
	 * Verify that the consumer-provided request signature matches our generated signature,
324
	 * this ensures the consumer has a valid key/secret.
325
	 *
326
	 * @param stdClass $user
327
	 * @param array $params The request parameters.
328
	 * @return null|WP_Error
329
	 */
330
	private function check_oauth_signature( $user, $params ) {
331
		$http_method  = strtoupper( $_SERVER['REQUEST_METHOD'] );
332
		$request_path = parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH );
333
		$wp_base      = get_home_url( null, '/', 'relative' );
334
		if ( substr( $request_path, 0, strlen( $wp_base ) ) === $wp_base ) {
335
			$request_path = substr( $request_path, strlen( $wp_base ) );
336
		}
337
		$base_request_uri = rawurlencode( get_home_url( null, $request_path ) );
338
339
		// Get the signature provided by the consumer and remove it from the parameters prior to checking the signature.
340
		$consumer_signature = rawurldecode( $params['oauth_signature'] );
341
		unset( $params['oauth_signature'] );
342
343
		// Sort parameters.
344
		if ( ! uksort( $params, 'strcmp' ) ) {
345
			return new WP_Error( 'woocommerce_rest_authentication_error', __( 'Invalid Signature - failed to sort parameters.', 'woocommerce' ), array( 'status' => 401 ) );
346
		}
347
348
		// Normalize parameter key/values.
349
		$params           = $this->normalize_parameters( $params );
350
		$query_parameters = array();
351
		foreach ( $params as $param_key => $param_value ) {
352
			if ( is_array( $param_value ) ) {
353
				foreach ( $param_value as $param_key_inner => $param_value_inner ) {
354
					$query_parameters[] = $param_key . '%255B' . $param_key_inner . '%255D%3D' . $param_value_inner;
355
				}
356
			} else {
357
				$query_parameters[] = $param_key . '%3D' . $param_value; // Join with equals sign.
358
			}
359
		}
360
		$query_string   = implode( '%26', $query_parameters ); // Join with ampersand.
361
		$string_to_sign = $http_method . '&' . $base_request_uri . '&' . $query_string;
362
363
		if ( $params['oauth_signature_method'] !== 'HMAC-SHA1' && $params['oauth_signature_method'] !== 'HMAC-SHA256' ) {
364
			return new WP_Error( 'woocommerce_rest_authentication_error', __( 'Invalid Signature - signature method is invalid.', 'woocommerce' ), array( 'status' => 401 ) );
365
		}
366
367
		$hash_algorithm = strtolower( str_replace( 'HMAC-', '', $params['oauth_signature_method'] ) );
368
		$secret         = $user->consumer_secret . '&';
369
		$signature      = base64_encode( hash_hmac( $hash_algorithm, $string_to_sign, $secret, true ) );
370
371
		if ( ! hash_equals( $signature, $consumer_signature ) ) {
372
			return new WP_Error( 'woocommerce_rest_authentication_error', __( 'Invalid Signature - provided signature does not match.', 'woocommerce' ), array( 'status' => 401 ) );
373
		}
374
375
		return true;
376
	}
377
378
	/**
379
	 * Normalize each parameter by assuming each parameter may have already been
380
	 * encoded, so attempt to decode, and then re-encode according to RFC 3986.
381
	 *
382
	 * Note both the key and value is normalized so a filter param like:
383
	 *
384
	 * 'filter[period]' => 'week'
385
	 *
386
	 * is encoded to:
387
	 *
388
	 * 'filter%5Bperiod%5D' => 'week'
389
	 *
390
	 * This conforms to the OAuth 1.0a spec which indicates the entire query string
391
	 * should be URL encoded.
392
	 *
393
	 * @see rawurlencode()
394
	 * @param array $parameters Un-normalized pararmeters.
395
	 * @return array Normalized parameters.
396
	 */
397
	private function normalize_parameters( $parameters ) {
398
		$keys       = wc_rest_urlencode_rfc3986( array_keys( $parameters ) );
399
		$values     = wc_rest_urlencode_rfc3986( array_values( $parameters ) );
400
		$parameters = array_combine( $keys, $values );
401
402
		return $parameters;
403
	}
404
405
	/**
406
	 * Verify that the timestamp and nonce provided with the request are valid. This prevents replay attacks where
407
	 * an attacker could attempt to re-send an intercepted request at a later time.
408
	 *
409
	 * - A timestamp is valid if it is within 15 minutes of now.
410
	 * - A nonce is valid if it has not been used within the last 15 minutes.
411
	 *
412
	 * @param stdClass $user
413
	 * @param int $timestamp the unix timestamp for when the request was made
414
	 * @param string $nonce a unique (for the given user) 32 alphanumeric string, consumer-generated
415
	 * @return bool|WP_Error
416
	 */
417
	private function check_oauth_timestamp_and_nonce( $user, $timestamp, $nonce ) {
418
		global $wpdb;
419
420
		$valid_window = 15 * 60; // 15 minute window.
421
422 View Code Duplication
		if ( ( $timestamp < time() - $valid_window ) || ( $timestamp > time() + $valid_window ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
423
			return new WP_Error( 'woocommerce_rest_authentication_error', __( 'Invalid timestamp.', 'woocommerce' ), array( 'status' => 401 ) );
424
		}
425
426
		$used_nonces = maybe_unserialize( $user->nonces );
427
428
		if ( empty( $used_nonces ) ) {
429
			$used_nonces = array();
430
		}
431
432
		if ( in_array( $nonce, $used_nonces ) ) {
433
			return new WP_Error( 'woocommerce_rest_authentication_error', __( 'Invalid nonce - nonce has already been used.', 'woocommerce' ), array( 'status' => 401 ) );
434
		}
435
436
		$used_nonces[ $timestamp ] = $nonce;
437
438
		// Remove expired nonces.
439
		foreach ( $used_nonces as $nonce_timestamp => $nonce ) {
440
			if ( $nonce_timestamp < ( time() - $valid_window ) ) {
441
				unset( $used_nonces[ $nonce_timestamp ] );
442
			}
443
		}
444
445
		$used_nonces = maybe_serialize( $used_nonces );
446
447
		$wpdb->update(
448
			$wpdb->prefix . 'woocommerce_api_keys',
449
			array( 'nonces' => $used_nonces ),
450
			array( 'key_id' => $user->key_id ),
451
			array( '%s' ),
452
			array( '%d' )
453
		);
454
455
		return true;
456
	}
457
458
	/**
459
	 * Return the user data for the given consumer_key.
460
	 *
461
	 * @param string $consumer_key
462
	 * @return array
463
	 */
464
	private function get_user_data_by_consumer_key( $consumer_key ) {
465
		global $wpdb;
466
467
		$consumer_key = wc_api_hash( sanitize_text_field( $consumer_key ) );
468
		$user         = $wpdb->get_row( $wpdb->prepare( "
469
			SELECT key_id, user_id, permissions, consumer_key, consumer_secret, nonces
470
			FROM {$wpdb->prefix}woocommerce_api_keys
471
			WHERE consumer_key = %s
472
		", $consumer_key ) );
473
474
		return $user;
475
	}
476
477
	/**
478
	 * Check that the API keys provided have the proper key-specific permissions to either read or write API resources.
479
	 *
480
	 * @param string $permissions
481
	 * @return bool
482
	 */
483
	private function check_permissions( $permissions ) {
484
		global $wc_rest_authentication_error;
485
486
		$valid = true;
487
488
		if ( ! isset( $_SERVER['REQUEST_METHOD'] ) ) {
489
			return false;
490
		}
491
492
		switch ( $_SERVER['REQUEST_METHOD'] ) {
493
494
			case 'HEAD' :
495 View Code Duplication
			case 'GET' :
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
496
				if ( 'read' !== $permissions && 'read_write' !== $permissions ) {
497
					$wc_rest_authentication_error = new WP_Error( 'woocommerce_rest_authentication_error', __( 'The API key provided does not have read permissions.', 'woocommerce' ), array( 'status' => 401 ) );
498
					$valid = false;
499
				}
500
				break;
501
502
			case 'POST' :
503
			case 'PUT' :
504
			case 'PATCH' :
505 View Code Duplication
			case 'DELETE' :
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
506
				if ( 'write' !== $permissions && 'read_write' !== $permissions ) {
507
					$wc_rest_authentication_error = new WP_Error( 'woocommerce_rest_authentication_error', __( 'The API key provided does not have write permissions.', 'woocommerce' ), array( 'status' => 401 ) );
508
					$valid = false;
509
				}
510
				break;
511
		}
512
513
		return $valid;
514
	}
515
516
	/**
517
	 * Updated API Key last access datetime.
518
	 *
519
	 * @param int $key_id
520
	 */
521
	private function update_last_access( $key_id ) {
522
		global $wpdb;
523
524
		$wpdb->update(
525
			$wpdb->prefix . 'woocommerce_api_keys',
526
			array( 'last_access' => current_time( 'mysql' ) ),
527
			array( 'key_id' => $key_id ),
528
			array( '%s' ),
529
			array( '%d' )
530
		);
531
	}
532
533
	/**
534
	 * If the consumer_key and consumer_secret $_GET parameters are NOT provided
535
	 * and the Basic auth headers are either not present or the consumer secret does not match the consumer
536
	 * key provided, then return the correct Basic headers and an error message.
537
	 *
538
	 * @param WP_REST_Response $response Current response being served.
539
	 * @return WP_REST_Response
540
	 */
541
	public function send_unauthorized_headers( $response ) {
542
		global $wc_rest_authentication_error;
543
544
		if ( is_wp_error( $wc_rest_authentication_error ) && is_ssl() ) {
545
			$auth_message = __( 'WooCommerce API - Use a consumer key in the username field and a consumer secret in the password field.', 'woocommerce' );
546
			$response->header( 'WWW-Authenticate', 'Basic realm="' . $auth_message . '"', true );
547
		}
548
549
		return $response;
550
	}
551
}
552
553
new WC_REST_Authentication();
554