class.jetpack-signature.php 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. <?php
  2. // These constants can be set in wp-config.php to ensure sites behind proxies will still work.
  3. // Setting these constants, though, is *not* the preferred method. It's better to configure
  4. // the proxy to send the X-Forwarded-Port header.
  5. defined( 'JETPACK_SIGNATURE__HTTP_PORT' ) or define( 'JETPACK_SIGNATURE__HTTP_PORT' , 80 );
  6. defined( 'JETPACK_SIGNATURE__HTTPS_PORT' ) or define( 'JETPACK_SIGNATURE__HTTPS_PORT', 443 );
  7. class Jetpack_Signature {
  8. public $token;
  9. public $secret;
  10. function __construct( $access_token, $time_diff = 0 ) {
  11. $secret = explode( '.', $access_token );
  12. if ( 2 != count( $secret ) )
  13. return;
  14. $this->token = $secret[0];
  15. $this->secret = $secret[1];
  16. $this->time_diff = $time_diff;
  17. }
  18. function sign_current_request( $override = array() ) {
  19. if ( isset( $override['scheme'] ) ) {
  20. $scheme = $override['scheme'];
  21. if ( !in_array( $scheme, array( 'http', 'https' ) ) ) {
  22. return new Jetpack_Error( 'invalid_scheme', 'Invalid URL scheme' );
  23. }
  24. } else {
  25. if ( is_ssl() ) {
  26. $scheme = 'https';
  27. } else {
  28. $scheme = 'http';
  29. }
  30. }
  31. $host_port = isset( $_SERVER['HTTP_X_FORWARDED_PORT'] ) ? $_SERVER['HTTP_X_FORWARDED_PORT'] : $_SERVER['SERVER_PORT'];
  32. if ( is_ssl() ) {
  33. // 443: Standard Port
  34. // 80: Assume we're behind a proxy without X-Forwarded-Port. Hardcoding "80" here means most sites
  35. // with SSL termination proxies (self-served, Cloudflare, etc.) don't need to fiddle with
  36. // the JETPACK_SIGNATURE__HTTPS_PORT constant. The code also implies we can't talk to a
  37. // site at https://example.com:80/ (which would be a strange configuration).
  38. // JETPACK_SIGNATURE__HTTPS_PORT: Set this constant in wp-config.php to the back end webserver's port
  39. // if the site is behind a proxy running on port 443 without
  40. // X-Forwarded-Port and the back end's port is *not* 80. It's better,
  41. // though, to configure the proxy to send X-Forwarded-Port.
  42. $port = in_array( $host_port, array( 443, 80, JETPACK_SIGNATURE__HTTPS_PORT ) ) ? '' : $host_port;
  43. } else {
  44. // 80: Standard Port
  45. // JETPACK_SIGNATURE__HTTPS_PORT: Set this constant in wp-config.php to the back end webserver's port
  46. // if the site is behind a proxy running on port 80 without
  47. // X-Forwarded-Port. It's better, though, to configure the proxy to
  48. // send X-Forwarded-Port.
  49. $port = in_array( $host_port, array( 80, JETPACK_SIGNATURE__HTTP_PORT ) ) ? '' : $host_port;
  50. }
  51. $url = "{$scheme}://{$_SERVER['HTTP_HOST']}:{$port}" . stripslashes( $_SERVER['REQUEST_URI'] );
  52. if ( array_key_exists( 'body', $override ) && ! empty( $override['body'] ) ) {
  53. $body = $override['body'];
  54. } else if ( 'POST' == strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
  55. $body = isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ? $GLOBALS['HTTP_RAW_POST_DATA'] : null;
  56. // Convert the $_POST to the body, if the body was empty. This is how arrays are hashed
  57. // and encoded on the Jetpack side.
  58. if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
  59. if ( empty( $body ) && is_array( $_POST ) && count( $_POST ) > 0 ) {
  60. $body = $_POST;
  61. }
  62. }
  63. } else if ( 'PUT' == strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
  64. // This is a little strange-looking, but there doesn't seem to be another way to get the PUT body
  65. $raw_put_data = file_get_contents( 'php://input' );
  66. parse_str( $raw_put_data, $body );
  67. if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
  68. $put_data = json_decode( $raw_put_data, true );
  69. if ( is_array( $put_data ) && count( $put_data ) > 0 ) {
  70. $body = $put_data;
  71. }
  72. }
  73. } else {
  74. $body = null;
  75. }
  76. if ( empty( $body ) ) {
  77. $body = null;
  78. }
  79. $a = array();
  80. foreach ( array( 'token', 'timestamp', 'nonce', 'body-hash' ) as $parameter ) {
  81. if ( isset( $override[$parameter] ) ) {
  82. $a[$parameter] = $override[$parameter];
  83. } else {
  84. $a[$parameter] = isset( $_GET[$parameter] ) ? stripslashes( $_GET[$parameter] ) : '';
  85. }
  86. }
  87. $method = isset( $override['method'] ) ? $override['method'] : $_SERVER['REQUEST_METHOD'];
  88. return $this->sign_request( $a['token'], $a['timestamp'], $a['nonce'], $a['body-hash'], $method, $url, $body, true );
  89. }
  90. // body_hash v. body-hash is annoying. Refactor to accept an array?
  91. function sign_request( $token = '', $timestamp = 0, $nonce = '', $body_hash = '', $method = '', $url = '', $body = null, $verify_body_hash = true ) {
  92. if ( !$this->secret ) {
  93. return new Jetpack_Error( 'invalid_secret', 'Invalid secret' );
  94. }
  95. if ( !$this->token ) {
  96. return new Jetpack_Error( 'invalid_token', 'Invalid token' );
  97. }
  98. list( $token ) = explode( '.', $token );
  99. if ( 0 !== strpos( $token, "$this->token:" ) ) {
  100. return new Jetpack_Error( 'token_mismatch', 'Incorrect token' );
  101. }
  102. // If we got an array at this point, let's encode it, so we can see what it looks like as a string.
  103. if ( is_array( $body ) ) {
  104. if ( count( $body ) > 0 ) {
  105. $body = json_encode( $body );
  106. } else {
  107. $body = '';
  108. }
  109. }
  110. $required_parameters = array( 'token', 'timestamp', 'nonce', 'method', 'url' );
  111. if ( !is_null( $body ) ) {
  112. $required_parameters[] = 'body_hash';
  113. if ( !is_string( $body ) ) {
  114. return new Jetpack_Error( 'invalid_body', 'Body is malformed.' );
  115. }
  116. }
  117. foreach ( $required_parameters as $required ) {
  118. if ( !is_scalar( $$required ) ) {
  119. return new Jetpack_Error( 'invalid_signature', sprintf( 'The required "%s" parameter is malformed.', str_replace( '_', '-', $required ) ) );
  120. }
  121. if ( !strlen( $$required ) ) {
  122. return new Jetpack_Error( 'invalid_signature', sprintf( 'The required "%s" parameter is missing.', str_replace( '_', '-', $required ) ) );
  123. }
  124. }
  125. if ( empty( $body ) ) {
  126. if ( $body_hash ) {
  127. return new Jetpack_Error( 'invalid_body_hash', 'The body hash does not match.' );
  128. }
  129. } else {
  130. if ( $verify_body_hash && jetpack_sha1_base64( $body ) !== $body_hash ) {
  131. return new Jetpack_Error( 'invalid_body_hash', 'The body hash does not match.' );
  132. }
  133. }
  134. $parsed = parse_url( $url );
  135. if ( !isset( $parsed['host'] ) ) {
  136. return new Jetpack_Error( 'invalid_signature', sprintf( 'The required "%s" parameter is malformed.', 'url' ) );
  137. }
  138. if ( !empty( $parsed['port'] ) ) {
  139. $port = $parsed['port'];
  140. } else {
  141. if ( 'http' == $parsed['scheme'] ) {
  142. $port = 80;
  143. } else if ( 'https' == $parsed['scheme'] ) {
  144. $port = 443;
  145. } else {
  146. return new Jetpack_Error( 'unknown_scheme_port', "The scheme's port is unknown" );
  147. }
  148. }
  149. if ( !ctype_digit( "$timestamp" ) || 10 < strlen( $timestamp ) ) { // If Jetpack is around in 275 years, you can blame mdawaffe for the bug.
  150. return new Jetpack_Error( 'invalid_signature', sprintf( 'The required "%s" parameter is malformed.', 'timestamp' ) );
  151. }
  152. $local_time = $timestamp - $this->time_diff;
  153. if ( $local_time < time() - 600 || $local_time > time() + 300 ) {
  154. return new Jetpack_Error( 'invalid_signature', 'The timestamp is too old.' );
  155. }
  156. if ( 12 < strlen( $nonce ) || preg_match( '/[^a-zA-Z0-9]/', $nonce ) ) {
  157. return new Jetpack_Error( 'invalid_signature', sprintf( 'The required "%s" parameter is malformed.', 'nonce' ) );
  158. }
  159. $normalized_request_pieces = array(
  160. $token,
  161. $timestamp,
  162. $nonce,
  163. $body_hash,
  164. strtoupper( $method ),
  165. strtolower( $parsed['host'] ),
  166. $port,
  167. $parsed['path'],
  168. // Normalized Query String
  169. );
  170. $normalized_request_pieces = array_merge( $normalized_request_pieces, $this->normalized_query_parameters( isset( $parsed['query'] ) ? $parsed['query'] : '' ) );
  171. $flat_normalized_request_pieces = array();
  172. foreach ($normalized_request_pieces as $piece) {
  173. if ( is_array( $piece ) ) {
  174. foreach ( $piece as $subpiece ) {
  175. $flat_normalized_request_pieces[] = $subpiece;
  176. }
  177. } else {
  178. $flat_normalized_request_pieces[] = $piece;
  179. }
  180. }
  181. $normalized_request_pieces = $flat_normalized_request_pieces;
  182. $normalized_request_string = join( "\n", $normalized_request_pieces ) . "\n";
  183. return base64_encode( hash_hmac( 'sha1', $normalized_request_string, $this->secret, true ) );
  184. }
  185. function normalized_query_parameters( $query_string ) {
  186. parse_str( $query_string, $array );
  187. if ( get_magic_quotes_gpc() )
  188. $array = stripslashes_deep( $array );
  189. unset( $array['signature'] );
  190. $names = array_keys( $array );
  191. $values = array_values( $array );
  192. $names = array_map( array( $this, 'encode_3986' ), $names );
  193. $values = array_map( array( $this, 'encode_3986' ), $values );
  194. $pairs = array_map( array( $this, 'join_with_equal_sign' ), $names, $values );
  195. sort( $pairs );
  196. return $pairs;
  197. }
  198. function encode_3986( $string_or_array ) {
  199. if ( is_array( $string_or_array ) ) {
  200. return array_map( array( $this, 'encode_3986' ), $string_or_array );
  201. }
  202. $string_or_array = rawurlencode( $string_or_array );
  203. return str_replace( '%7E', '~', $string_or_array ); // prior to PHP 5.3, rawurlencode was RFC 1738
  204. }
  205. function join_with_equal_sign( $name, $value ) {
  206. if ( is_array( $value ) ) {
  207. $result = array();
  208. foreach ( $value as $array_key => $array_value ) {
  209. $result[] = $name . '[' . $array_key . ']' . '=' . $array_value;
  210. }
  211. return $result;
  212. }
  213. return "{$name}={$value}";
  214. }
  215. }
  216. function jetpack_sha1_base64( $text ) {
  217. return base64_encode( sha1( $text, true ) );
  218. }