class-wc-api-authentication.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. /* translators: %s: parameter name */
  113. throw new Exception( sprintf( __( '%s parameter is missing', 'woocommerce' ), $param_name ), 404 );
  114. }
  115. }
  116. // Fetch WP user by consumer key
  117. $keys = $this->get_keys_by_consumer_key( $params['oauth_consumer_key'] );
  118. // Perform OAuth validation
  119. $this->check_oauth_signature( $keys, $params );
  120. $this->check_oauth_timestamp_and_nonce( $keys, $params['oauth_timestamp'], $params['oauth_nonce'] );
  121. // Authentication successful, return user
  122. return $keys;
  123. }
  124. /**
  125. * Return the keys for the given consumer key
  126. *
  127. * @since 2.4.0
  128. * @param string $consumer_key
  129. * @return array
  130. * @throws Exception
  131. */
  132. private function get_keys_by_consumer_key( $consumer_key ) {
  133. global $wpdb;
  134. $consumer_key = wc_api_hash( sanitize_text_field( $consumer_key ) );
  135. $keys = $wpdb->get_row( $wpdb->prepare( "
  136. SELECT key_id, user_id, permissions, consumer_key, consumer_secret, nonces
  137. FROM {$wpdb->prefix}woocommerce_api_keys
  138. WHERE consumer_key = '%s'
  139. ", $consumer_key ), ARRAY_A );
  140. if ( empty( $keys ) ) {
  141. throw new Exception( __( 'Consumer key is invalid.', 'woocommerce' ), 401 );
  142. }
  143. return $keys;
  144. }
  145. /**
  146. * Get user by ID
  147. *
  148. * @since 2.4.0
  149. * @param int $user_id
  150. * @return WP_User
  151. *
  152. * @throws Exception
  153. */
  154. private function get_user_by_id( $user_id ) {
  155. $user = get_user_by( 'id', $user_id );
  156. if ( ! $user ) {
  157. throw new Exception( __( 'API user is invalid', 'woocommerce' ), 401 );
  158. }
  159. return $user;
  160. }
  161. /**
  162. * Check if the consumer secret provided for the given user is valid
  163. *
  164. * @since 2.1
  165. * @param string $keys_consumer_secret
  166. * @param string $consumer_secret
  167. * @return bool
  168. */
  169. private function is_consumer_secret_valid( $keys_consumer_secret, $consumer_secret ) {
  170. return hash_equals( $keys_consumer_secret, $consumer_secret );
  171. }
  172. /**
  173. * Verify that the consumer-provided request signature matches our generated signature, this ensures the consumer
  174. * has a valid key/secret
  175. *
  176. * @param array $keys
  177. * @param array $params the request parameters
  178. * @throws Exception
  179. */
  180. private function check_oauth_signature( $keys, $params ) {
  181. $http_method = strtoupper( WC()->api->server->method );
  182. $base_request_uri = rawurlencode( untrailingslashit( get_woocommerce_api_url( '' ) ) . WC()->api->server->path );
  183. // Get the signature provided by the consumer and remove it from the parameters prior to checking the signature
  184. $consumer_signature = rawurldecode( str_replace( ' ', '+', $params['oauth_signature'] ) );
  185. unset( $params['oauth_signature'] );
  186. // Remove filters and convert them from array to strings to void normalize issues
  187. if ( isset( $params['filter'] ) ) {
  188. $filters = $params['filter'];
  189. unset( $params['filter'] );
  190. foreach ( $filters as $filter => $filter_value ) {
  191. $params[ 'filter[' . $filter . ']' ] = $filter_value;
  192. }
  193. }
  194. // Normalize parameter key/values
  195. $params = $this->normalize_parameters( $params );
  196. // Sort parameters
  197. if ( ! uksort( $params, 'strcmp' ) ) {
  198. throw new Exception( __( 'Invalid signature - failed to sort parameters.', 'woocommerce' ), 401 );
  199. }
  200. // Form query string
  201. $query_params = array();
  202. foreach ( $params as $param_key => $param_value ) {
  203. $query_params[] = $param_key . '%3D' . $param_value; // join with equals sign
  204. }
  205. $query_string = implode( '%26', $query_params ); // join with ampersand
  206. $string_to_sign = $http_method . '&' . $base_request_uri . '&' . $query_string;
  207. if ( 'HMAC-SHA1' !== $params['oauth_signature_method'] && 'HMAC-SHA256' !== $params['oauth_signature_method'] ) {
  208. throw new Exception( __( 'Invalid signature - signature method is invalid.', 'woocommerce' ), 401 );
  209. }
  210. $hash_algorithm = strtolower( str_replace( 'HMAC-', '', $params['oauth_signature_method'] ) );
  211. $signature = base64_encode( hash_hmac( $hash_algorithm, $string_to_sign, $keys['consumer_secret'], true ) );
  212. if ( ! hash_equals( $signature, $consumer_signature ) ) {
  213. throw new Exception( __( 'Invalid signature - provided signature does not match.', 'woocommerce' ), 401 );
  214. }
  215. }
  216. /**
  217. * Normalize each parameter by assuming each parameter may have already been
  218. * encoded, so attempt to decode, and then re-encode according to RFC 3986
  219. *
  220. * Note both the key and value is normalized so a filter param like:
  221. *
  222. * 'filter[period]' => 'week'
  223. *
  224. * is encoded to:
  225. *
  226. * 'filter%5Bperiod%5D' => 'week'
  227. *
  228. * This conforms to the OAuth 1.0a spec which indicates the entire query string
  229. * should be URL encoded
  230. *
  231. * @since 2.1
  232. * @see rawurlencode()
  233. * @param array $parameters un-normalized parameters
  234. * @return array normalized parameters
  235. */
  236. private function normalize_parameters( $parameters ) {
  237. $normalized_parameters = array();
  238. foreach ( $parameters as $key => $value ) {
  239. // Percent symbols (%) must be double-encoded
  240. $key = str_replace( '%', '%25', rawurlencode( rawurldecode( $key ) ) );
  241. $value = str_replace( '%', '%25', rawurlencode( rawurldecode( $value ) ) );
  242. $normalized_parameters[ $key ] = $value;
  243. }
  244. return $normalized_parameters;
  245. }
  246. /**
  247. * Verify that the timestamp and nonce provided with the request are valid. This prevents replay attacks where
  248. * an attacker could attempt to re-send an intercepted request at a later time.
  249. *
  250. * - A timestamp is valid if it is within 15 minutes of now
  251. * - A nonce is valid if it has not been used within the last 15 minutes
  252. *
  253. * @param array $keys
  254. * @param int $timestamp the unix timestamp for when the request was made
  255. * @param string $nonce a unique (for the given user) 32 alphanumeric string, consumer-generated
  256. * @throws Exception
  257. */
  258. private function check_oauth_timestamp_and_nonce( $keys, $timestamp, $nonce ) {
  259. global $wpdb;
  260. $valid_window = 15 * 60; // 15 minute window
  261. if ( ( $timestamp < time() - $valid_window ) || ( $timestamp > time() + $valid_window ) ) {
  262. throw new Exception( __( 'Invalid timestamp.', 'woocommerce' ) );
  263. }
  264. $used_nonces = maybe_unserialize( $keys['nonces'] );
  265. if ( empty( $used_nonces ) ) {
  266. $used_nonces = array();
  267. }
  268. if ( in_array( $nonce, $used_nonces ) ) {
  269. throw new Exception( __( 'Invalid nonce - nonce has already been used.', 'woocommerce' ), 401 );
  270. }
  271. $used_nonces[ $timestamp ] = $nonce;
  272. // Remove expired nonces
  273. foreach ( $used_nonces as $nonce_timestamp => $nonce ) {
  274. if ( $nonce_timestamp < ( time() - $valid_window ) ) {
  275. unset( $used_nonces[ $nonce_timestamp ] );
  276. }
  277. }
  278. $used_nonces = maybe_serialize( $used_nonces );
  279. $wpdb->update(
  280. $wpdb->prefix . 'woocommerce_api_keys',
  281. array( 'nonces' => $used_nonces ),
  282. array( 'key_id' => $keys['key_id'] ),
  283. array( '%s' ),
  284. array( '%d' )
  285. );
  286. }
  287. /**
  288. * Check that the API keys provided have the proper key-specific permissions to either read or write API resources
  289. *
  290. * @param string $key_permissions
  291. * @throws Exception if the permission check fails
  292. */
  293. public function check_api_key_permissions( $key_permissions ) {
  294. switch ( WC()->api->server->method ) {
  295. case 'HEAD':
  296. case 'GET':
  297. if ( 'read' !== $key_permissions && 'read_write' !== $key_permissions ) {
  298. throw new Exception( __( 'The API key provided does not have read permissions.', 'woocommerce' ), 401 );
  299. }
  300. break;
  301. case 'POST':
  302. case 'PUT':
  303. case 'PATCH':
  304. case 'DELETE':
  305. if ( 'write' !== $key_permissions && 'read_write' !== $key_permissions ) {
  306. throw new Exception( __( 'The API key provided does not have write permissions.', 'woocommerce' ), 401 );
  307. }
  308. break;
  309. }
  310. }
  311. /**
  312. * Updated API Key last access datetime
  313. *
  314. * @since 2.4.0
  315. *
  316. * @param int $key_id
  317. */
  318. private function update_api_key_last_access( $key_id ) {
  319. global $wpdb;
  320. $wpdb->update(
  321. $wpdb->prefix . 'woocommerce_api_keys',
  322. array( 'last_access' => current_time( 'mysql' ) ),
  323. array( 'key_id' => $key_id ),
  324. array( '%s' ),
  325. array( '%d' )
  326. );
  327. }
  328. }