class-wc-api-authentication.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. <?php
  2. /**
  3. * WooCommerce API Authentication Class
  4. *
  5. * @author WooThemes
  6. * @category API
  7. * @package WooCommerce/API
  8. * @since 2.1.0
  9. * @version 2.4.0
  10. */
  11. if ( ! defined( 'ABSPATH' ) ) {
  12. exit; // Exit if accessed directly
  13. }
  14. class WC_API_Authentication {
  15. /**
  16. * Setup class
  17. *
  18. * @since 2.1
  19. */
  20. public function __construct() {
  21. // To disable authentication, hook into this filter at a later priority and return a valid WP_User
  22. add_filter( 'woocommerce_api_check_authentication', array( $this, 'authenticate' ), 0 );
  23. }
  24. /**
  25. * Authenticate the request. The authentication method varies based on whether the request was made over SSL or not.
  26. *
  27. * @since 2.1
  28. * @param WP_User $user
  29. * @return null|WP_Error|WP_User
  30. */
  31. public function authenticate( $user ) {
  32. // Allow access to the index by default
  33. if ( '/' === WC()->api->server->path ) {
  34. return new WP_User( 0 );
  35. }
  36. try {
  37. if ( is_ssl() ) {
  38. $keys = $this->perform_ssl_authentication();
  39. } else {
  40. $keys = $this->perform_oauth_authentication();
  41. }
  42. // Check API key-specific permission
  43. $this->check_api_key_permissions( $keys['permissions'] );
  44. $user = $this->get_user_by_id( $keys['user_id'] );
  45. $this->update_api_key_last_access( $keys['key_id'] );
  46. } catch ( Exception $e ) {
  47. $user = new WP_Error( 'woocommerce_api_authentication_error', $e->getMessage(), array( 'status' => $e->getCode() ) );
  48. }
  49. return $user;
  50. }
  51. /**
  52. * SSL-encrypted requests are not subject to sniffing or man-in-the-middle
  53. * attacks, so the request can be authenticated by simply looking up the user
  54. * associated with the given consumer key and confirming the consumer secret
  55. * provided is valid
  56. *
  57. * @since 2.1
  58. * @return array
  59. * @throws Exception
  60. */
  61. private function perform_ssl_authentication() {
  62. $params = WC()->api->server->params['GET'];
  63. // Get consumer key
  64. if ( ! empty( $_SERVER['PHP_AUTH_USER'] ) ) {
  65. // Should be in HTTP Auth header by default
  66. $consumer_key = $_SERVER['PHP_AUTH_USER'];
  67. } elseif ( ! empty( $params['consumer_key'] ) ) {
  68. // Allow a query string parameter as a fallback
  69. $consumer_key = $params['consumer_key'];
  70. } else {
  71. throw new Exception( __( 'Consumer key is missing.', 'woocommerce' ), 404 );
  72. }
  73. // Get consumer secret
  74. if ( ! empty( $_SERVER['PHP_AUTH_PW'] ) ) {
  75. // Should be in HTTP Auth header by default
  76. $consumer_secret = $_SERVER['PHP_AUTH_PW'];
  77. } elseif ( ! empty( $params['consumer_secret'] ) ) {
  78. // Allow a query string parameter as a fallback
  79. $consumer_secret = $params['consumer_secret'];
  80. } else {
  81. throw new Exception( __( 'Consumer secret is missing.', 'woocommerce' ), 404 );
  82. }
  83. $keys = $this->get_keys_by_consumer_key( $consumer_key );
  84. if ( ! $this->is_consumer_secret_valid( $keys['consumer_secret'], $consumer_secret ) ) {
  85. throw new Exception( __( 'Consumer secret is invalid.', 'woocommerce' ), 401 );
  86. }
  87. return $keys;
  88. }
  89. /**
  90. * Perform OAuth 1.0a "one-legged" (http://oauthbible.com/#oauth-10a-one-legged) authentication for non-SSL requests
  91. *
  92. * This is required so API credentials cannot be sniffed or intercepted when making API requests over plain HTTP
  93. *
  94. * This follows the spec for simple OAuth 1.0a authentication (RFC 5849) as closely as possible, with two exceptions:
  95. *
  96. * 1) There is no token associated with request/responses, only consumer keys/secrets are used
  97. *
  98. * 2) The OAuth parameters are included as part of the request query string instead of part of the Authorization header,
  99. * This is because there is no cross-OS function within PHP to get the raw Authorization header
  100. *
  101. * @link http://tools.ietf.org/html/rfc5849 for the full spec
  102. * @since 2.1
  103. * @return array
  104. * @throws Exception
  105. */
  106. private function perform_oauth_authentication() {
  107. $params = WC()->api->server->params['GET'];
  108. $param_names = array( 'oauth_consumer_key', 'oauth_timestamp', 'oauth_nonce', 'oauth_signature', 'oauth_signature_method' );
  109. // Check for required OAuth parameters
  110. foreach ( $param_names as $param_name ) {
  111. if ( empty( $params[ $param_name ] ) ) {
  112. throw new Exception( sprintf( __( '%s parameter is missing', 'woocommerce' ), $param_name ), 404 );
  113. }
  114. }
  115. // Fetch WP user by consumer key
  116. $keys = $this->get_keys_by_consumer_key( $params['oauth_consumer_key'] );
  117. // Perform OAuth validation
  118. $this->check_oauth_signature( $keys, $params );
  119. $this->check_oauth_timestamp_and_nonce( $keys, $params['oauth_timestamp'], $params['oauth_nonce'] );
  120. // Authentication successful, return user
  121. return $keys;
  122. }
  123. /**
  124. * Return the keys for the given consumer key
  125. *
  126. * @since 2.4.0
  127. * @param string $consumer_key
  128. * @return array
  129. * @throws Exception
  130. */
  131. private function get_keys_by_consumer_key( $consumer_key ) {
  132. global $wpdb;
  133. $consumer_key = wc_api_hash( sanitize_text_field( $consumer_key ) );
  134. $keys = $wpdb->get_row( $wpdb->prepare( "
  135. SELECT key_id, user_id, permissions, consumer_key, consumer_secret, nonces
  136. FROM {$wpdb->prefix}woocommerce_api_keys
  137. WHERE consumer_key = '%s'
  138. ", $consumer_key ), ARRAY_A );
  139. if ( empty( $keys ) ) {
  140. throw new Exception( __( 'Consumer key is invalid.', 'woocommerce' ), 401 );
  141. }
  142. return $keys;
  143. }
  144. /**
  145. * Get user by ID
  146. *
  147. * @since 2.4.0
  148. * @param int $user_id
  149. * @return WP_User
  150. * @throws Exception
  151. */
  152. private function get_user_by_id( $user_id ) {
  153. $user = get_user_by( 'id', $user_id );
  154. if ( ! $user ) {
  155. throw new Exception( __( 'API user is invalid', 'woocommerce' ), 401 );
  156. }
  157. return $user;
  158. }
  159. /**
  160. * Check if the consumer secret provided for the given user is valid
  161. *
  162. * @since 2.1
  163. * @param string $keys_consumer_secret
  164. * @param string $consumer_secret
  165. * @return bool
  166. */
  167. private function is_consumer_secret_valid( $keys_consumer_secret, $consumer_secret ) {
  168. return hash_equals( $keys_consumer_secret, $consumer_secret );
  169. }
  170. /**
  171. * Verify that the consumer-provided request signature matches our generated signature, this ensures the consumer
  172. * has a valid key/secret
  173. *
  174. * @param array $keys
  175. * @param array $params the request parameters
  176. * @throws Exception
  177. */
  178. private function check_oauth_signature( $keys, $params ) {
  179. $http_method = strtoupper( WC()->api->server->method );
  180. $base_request_uri = rawurlencode( untrailingslashit( get_woocommerce_api_url( '' ) ) . WC()->api->server->path );
  181. // Get the signature provided by the consumer and remove it from the parameters prior to checking the signature
  182. $consumer_signature = rawurldecode( str_replace( ' ', '+', $params['oauth_signature'] ) );
  183. unset( $params['oauth_signature'] );
  184. // Remove filters and convert them from array to strings to void normalize issues
  185. if ( isset( $params['filter'] ) ) {
  186. $filters = $params['filter'];
  187. unset( $params['filter'] );
  188. foreach ( $filters as $filter => $filter_value ) {
  189. $params[ 'filter[' . $filter . ']' ] = $filter_value;
  190. }
  191. }
  192. // Normalize parameter key/values
  193. $params = $this->normalize_parameters( $params );
  194. // Sort parameters
  195. if ( ! uksort( $params, 'strcmp' ) ) {
  196. throw new Exception( __( 'Invalid signature - failed to sort parameters.', 'woocommerce' ), 401 );
  197. }
  198. // Form query string
  199. $query_params = array();
  200. foreach ( $params as $param_key => $param_value ) {
  201. $query_params[] = $param_key . '%3D' . $param_value; // join with equals sign
  202. }
  203. $query_string = implode( '%26', $query_params ); // join with ampersand
  204. $string_to_sign = $http_method . '&' . $base_request_uri . '&' . $query_string;
  205. if ( 'HMAC-SHA1' !== $params['oauth_signature_method'] && 'HMAC-SHA256' !== $params['oauth_signature_method'] ) {
  206. throw new Exception( __( 'Invalid signature - signature method is invalid.', 'woocommerce' ), 401 );
  207. }
  208. $hash_algorithm = strtolower( str_replace( 'HMAC-', '', $params['oauth_signature_method'] ) );
  209. $signature = base64_encode( hash_hmac( $hash_algorithm, $string_to_sign, $keys['consumer_secret'], true ) );
  210. if ( ! hash_equals( $signature, $consumer_signature ) ) {
  211. throw new Exception( __( 'Invalid signature - provided signature does not match.', 'woocommerce' ), 401 );
  212. }
  213. }
  214. /**
  215. * Normalize each parameter by assuming each parameter may have already been
  216. * encoded, so attempt to decode, and then re-encode according to RFC 3986
  217. *
  218. * Note both the key and value is normalized so a filter param like:
  219. *
  220. * 'filter[period]' => 'week'
  221. *
  222. * is encoded to:
  223. *
  224. * 'filter%5Bperiod%5D' => 'week'
  225. *
  226. * This conforms to the OAuth 1.0a spec which indicates the entire query string
  227. * should be URL encoded
  228. *
  229. * @since 2.1
  230. * @see rawurlencode()
  231. * @param array $parameters un-normalized parameters
  232. * @return array normalized parameters
  233. */
  234. private function normalize_parameters( $parameters ) {
  235. $normalized_parameters = array();
  236. foreach ( $parameters as $key => $value ) {
  237. // Percent symbols (%) must be double-encoded
  238. $key = str_replace( '%', '%25', rawurlencode( rawurldecode( $key ) ) );
  239. $value = str_replace( '%', '%25', rawurlencode( rawurldecode( $value ) ) );
  240. $normalized_parameters[ $key ] = $value;
  241. }
  242. return $normalized_parameters;
  243. }
  244. /**
  245. * Verify that the timestamp and nonce provided with the request are valid. This prevents replay attacks where
  246. * an attacker could attempt to re-send an intercepted request at a later time.
  247. *
  248. * - A timestamp is valid if it is within 15 minutes of now
  249. * - A nonce is valid if it has not been used within the last 15 minutes
  250. *
  251. * @param array $keys
  252. * @param int $timestamp the unix timestamp for when the request was made
  253. * @param string $nonce a unique (for the given user) 32 alphanumeric string, consumer-generated
  254. * @throws Exception
  255. */
  256. private function check_oauth_timestamp_and_nonce( $keys, $timestamp, $nonce ) {
  257. global $wpdb;
  258. $valid_window = 15 * 60; // 15 minute window
  259. if ( ( $timestamp < time() - $valid_window ) || ( $timestamp > time() + $valid_window ) ) {
  260. throw new Exception( __( 'Invalid timestamp.', 'woocommerce' ), 401 );
  261. }
  262. $used_nonces = maybe_unserialize( $keys['nonces'] );
  263. if ( empty( $used_nonces ) ) {
  264. $used_nonces = array();
  265. }
  266. if ( in_array( $nonce, $used_nonces ) ) {
  267. throw new Exception( __( 'Invalid nonce - nonce has already been used.', 'woocommerce' ), 401 );
  268. }
  269. $used_nonces[ $timestamp ] = $nonce;
  270. // Remove expired nonces
  271. foreach ( $used_nonces as $nonce_timestamp => $nonce ) {
  272. if ( $nonce_timestamp < ( time() - $valid_window ) ) {
  273. unset( $used_nonces[ $nonce_timestamp ] );
  274. }
  275. }
  276. $used_nonces = maybe_serialize( $used_nonces );
  277. $wpdb->update(
  278. $wpdb->prefix . 'woocommerce_api_keys',
  279. array( 'nonces' => $used_nonces ),
  280. array( 'key_id' => $keys['key_id'] ),
  281. array( '%s' ),
  282. array( '%d' )
  283. );
  284. }
  285. /**
  286. * Check that the API keys provided have the proper key-specific permissions to either read or write API resources
  287. *
  288. * @param string $key_permissions
  289. * @throws Exception if the permission check fails
  290. */
  291. public function check_api_key_permissions( $key_permissions ) {
  292. switch ( WC()->api->server->method ) {
  293. case 'HEAD':
  294. case 'GET':
  295. if ( 'read' !== $key_permissions && 'read_write' !== $key_permissions ) {
  296. throw new Exception( __( 'The API key provided does not have read permissions.', 'woocommerce' ), 401 );
  297. }
  298. break;
  299. case 'POST':
  300. case 'PUT':
  301. case 'PATCH':
  302. case 'DELETE':
  303. if ( 'write' !== $key_permissions && 'read_write' !== $key_permissions ) {
  304. throw new Exception( __( 'The API key provided does not have write permissions.', 'woocommerce' ), 401 );
  305. }
  306. break;
  307. }
  308. }
  309. /**
  310. * Updated API Key last access datetime
  311. *
  312. * @since 2.4.0
  313. *
  314. * @param int $key_id
  315. */
  316. private function update_api_key_last_access( $key_id ) {
  317. global $wpdb;
  318. $wpdb->update(
  319. $wpdb->prefix . 'woocommerce_api_keys',
  320. array( 'last_access' => current_time( 'mysql' ) ),
  321. array( 'key_id' => $key_id ),
  322. array( '%s' ),
  323. array( '%d' )
  324. );
  325. }
  326. }