Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
75.17% covered (warning)
75.17%
112 / 149
77.78% covered (warning)
77.78%
7 / 9
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_Signature
75.17% covered (warning)
75.17%
112 / 149
77.78% covered (warning)
77.78%
7 / 9
181.47
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 sign_current_request
51.52% covered (warning)
51.52%
17 / 33
0.00% covered (danger)
0.00%
0 / 1
89.65
 sign_request
69.57% covered (warning)
69.57%
48 / 69
0.00% covered (danger)
0.00%
0 / 1
52.71
 normalized_query_parameters
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
1
 encode_3986
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 join_with_equal_sign
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 join_array_with_equal_sign
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
5
 get_current_request_port
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
9
 sanitize_host_post
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
7
1<?php
2/**
3 * The Jetpack Connection signature class file.
4 *
5 * @package automattic/jetpack-connection
6 */
7
8use Automattic\Jetpack\Connection\Manager as Connection_Manager;
9
10/**
11 * The Jetpack Connection signature class that is used to sign requests.
12 */
13class Jetpack_Signature {
14    /**
15     * Token part of the access token.
16     *
17     * @access public
18     * @var string
19     */
20    public $token;
21
22    /**
23     * Access token secret.
24     *
25     * @access public
26     * @var string
27     */
28    public $secret;
29
30    /**
31     * Timezone difference (in seconds).
32     *
33     * @access public
34     * @var int
35     */
36    public $time_diff;
37
38    /**
39     * The current request URL.
40     *
41     * @access public
42     * @var string
43     */
44    public $current_request_url;
45
46    /**
47     * Constructor.
48     *
49     * @param string $access_token Access token.
50     * @param int    $time_diff    Timezone difference (in seconds).
51     */
52    public function __construct( $access_token, $time_diff = 0 ) {
53        $secret = explode( '.', $access_token );
54        if ( 2 !== count( $secret ) ) {
55            return;
56        }
57
58        $this->token     = $secret[0];
59        $this->secret    = $secret[1];
60        $this->time_diff = $time_diff;
61    }
62
63    /**
64     * Sign the current request.
65     *
66     * @todo Implement a proper nonce verification.
67     *
68     * @param array $override Optional arguments to override the ones from the current request.
69     * @return string|WP_Error Request signature, or a WP_Error on failure.
70     */
71    public function sign_current_request( $override = array() ) {
72        if ( isset( $override['scheme'] ) ) {
73            $scheme = $override['scheme'];
74            if ( ! in_array( $scheme, array( 'http', 'https' ), true ) ) {
75                return new WP_Error( 'invalid_scheme', 'Invalid URL scheme' );
76            }
77        } elseif ( is_ssl() ) {
78            $scheme = 'https';
79        } else {
80            $scheme = 'http';
81        }
82
83        $port = $this->get_current_request_port();
84
85        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidatedNotSanitized -- Sniff misses the esc_url_raw wrapper.
86        $this->current_request_url = esc_url_raw( wp_unslash( "{$scheme}://{$_SERVER['HTTP_HOST']}:{$port}" . ( $_SERVER['REQUEST_URI'] ?? '' ) ) );
87
88        if ( array_key_exists( 'body', $override ) && ! empty( $override['body'] ) ) {
89            $body = $override['body'];
90        } elseif ( isset( $_SERVER['REQUEST_METHOD'] ) && 'POST' === strtoupper( $_SERVER['REQUEST_METHOD'] ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput -- This is validating.
91            $body = $GLOBALS['HTTP_RAW_POST_DATA'] ?? null;
92
93            // Convert the $_POST to the body, if the body was empty. This is how arrays are hashed
94            // and encoded on the Jetpack side.
95            if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
96                // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Used to generate a cryptographic signature of the post data. Not actually using any of it here.
97                if ( empty( $body ) && is_array( $_POST ) && $_POST !== array() ) {
98                    $body = $_POST; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- We need all of $_POST in order to generate a cryptographic signature of the post data.
99                }
100            }
101        } elseif ( isset( $_SERVER['REQUEST_METHOD'] ) && 'PUT' === strtoupper( $_SERVER['REQUEST_METHOD'] ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput -- This is validating.
102            // This is a little strange-looking, but there doesn't seem to be another way to get the PUT body.
103            $raw_put_data = file_get_contents( 'php://input' );
104            parse_str( $raw_put_data, $body );
105
106            if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
107                $put_data = json_decode( $raw_put_data, true );
108                if ( is_array( $put_data ) && $put_data !== array() ) {
109                    $body = $put_data;
110                }
111            }
112        } else {
113            $body = null;
114        }
115
116        if ( empty( $body ) ) {
117            $body = null;
118        }
119
120        $a = array();
121        foreach ( array( 'token', 'timestamp', 'nonce', 'body-hash' ) as $parameter ) {
122            if ( isset( $override[ $parameter ] ) ) {
123                $a[ $parameter ] = $override[ $parameter ];
124            } else {
125                // phpcs:ignore WordPress.Security.NonceVerification.Recommended
126                $a[ $parameter ] = isset( $_GET[ $parameter ] ) ? filter_var( wp_unslash( $_GET[ $parameter ] ) ) : '';
127            }
128        }
129
130        $method = $override['method'] ?? ( isset( $_SERVER['REQUEST_METHOD'] ) ? filter_var( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) : null );
131        return $this->sign_request( $a['token'], $a['timestamp'], $a['nonce'], $a['body-hash'], $method, $this->current_request_url, $body, true );
132    }
133
134    /**
135     * Sign a specified request.
136     *
137     * @todo Having body_hash v. body-hash is annoying. Refactor to accept an array?
138     * @todo Use wp_json_encode() instead of json_encode()?
139     *
140     * @param string $token            Request token.
141     * @param int    $timestamp        Timestamp of the request.
142     * @param string $nonce            Request nonce.
143     * @param string $body_hash        Request body hash.
144     * @param string $method           Request method.
145     * @param string $url              Request URL.
146     * @param mixed  $body             Request body.
147     * @param bool   $verify_body_hash Whether to verify the body hash against the body.
148     * @return string|WP_Error Request signature, or a WP_Error on failure.
149     */
150    public function sign_request( $token = '', $timestamp = 0, $nonce = '', $body_hash = '', $method = '', $url = '', $body = null, $verify_body_hash = true ) {
151        if ( ! $this->secret ) {
152            return new WP_Error( 'invalid_secret', 'Invalid secret' );
153        }
154
155        if ( ! $this->token ) {
156            return new WP_Error( 'invalid_token', 'Invalid token' );
157        }
158
159        list( $token ) = explode( '.', $token );
160
161        $signature_details = compact( 'token', 'timestamp', 'nonce', 'body_hash', 'method', 'url' );
162
163        // This path currently can't ever be true. Every caller (Client::build_signed_request,
164        // Manager::internal_verify_xml_rpc_signature, Authorize_Json_Api, Server_Sandbox)
165        // derives the token_key param from the same $token->secret used to construct the Jetpack_Signature object
166        // â€” so $this->token and the passed $token key can never actually differ in practice.
167        if ( ! str_starts_with( $token, "$this->token:" ) ) {
168            return new WP_Error( 'token_mismatch', 'Incorrect token', compact( 'signature_details' ) );
169        }
170
171        // If we got an array at this point, let's encode it, so we can see what it looks like as a string.
172        if ( is_array( $body ) ) {
173            if ( $body !== array() ) {
174                // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode
175                $body = json_encode(
176                    $body,
177                    0 // phpcs:ignore Jetpack.Functions.JsonEncodeFlags.ZeroFound -- No `json_encode()` flags because this needs to match whatever is calculating the hash on the other end.
178                );
179
180            } else {
181                $body = '';
182            }
183        }
184
185        $required_parameters = array( 'token', 'timestamp', 'nonce', 'method', 'url' );
186        if ( $body !== null ) {
187            $required_parameters[] = 'body_hash';
188            if ( ! is_string( $body ) ) {
189                return new WP_Error( 'invalid_body', 'Body is malformed.', compact( 'signature_details' ) );
190            }
191        }
192
193        foreach ( $required_parameters as $required ) {
194            if ( ! is_scalar( $$required ) ) {
195                return new WP_Error( 'invalid_signature', sprintf( 'The required "%s" parameter is malformed.', str_replace( '_', '-', $required ) ), compact( 'signature_details' ) );
196            }
197
198            if ( ! strlen( $$required ) ) {
199                return new WP_Error( 'invalid_signature', sprintf( 'The required "%s" parameter is missing.', str_replace( '_', '-', $required ) ), compact( 'signature_details' ) );
200            }
201        }
202
203        if ( empty( $body ) ) {
204            if ( $body_hash ) {
205                return new WP_Error( 'invalid_body_hash', 'Invalid body hash for empty body.', compact( 'signature_details' ) );
206            }
207        } else {
208            $connection = new Connection_Manager();
209            if ( $verify_body_hash && $connection->sha1_base64( $body ) !== $body_hash ) {
210                return new WP_Error( 'invalid_body_hash', 'The body hash does not match.', compact( 'signature_details' ) );
211            }
212        }
213
214        $parsed = wp_parse_url( $url );
215        if ( ! isset( $parsed['host'] ) ) {
216            return new WP_Error( 'invalid_signature', sprintf( 'The required "%s" parameter is malformed.', 'url' ), compact( 'signature_details' ) );
217        }
218
219        if ( ! empty( $parsed['port'] ) ) {
220            $port = $parsed['port'];
221        } elseif ( 'http' === $parsed['scheme'] ) {
222            $port = 80;
223        } elseif ( 'https' === $parsed['scheme'] ) {
224            $port = 443;
225        } else {
226            return new WP_Error( 'unknown_scheme_port', "The scheme's port is unknown", compact( 'signature_details' ) );
227        }
228
229        if ( ! ctype_digit( "$timestamp" ) || 10 < strlen( (string) $timestamp ) ) { // If Jetpack is around in 275 years, you can blame mdawaffe for the bug.
230            return new WP_Error( 'invalid_signature', sprintf( 'The required "%s" parameter is malformed.', 'timestamp' ), compact( 'signature_details' ) );
231        }
232
233        $local_time = $timestamp - $this->time_diff;
234        if ( $local_time < time() - 600 || $local_time > time() + 300 ) {
235            return new WP_Error( 'invalid_signature', 'The timestamp is too old.', compact( 'signature_details' ) );
236        }
237
238        if ( 12 < strlen( $nonce ) || preg_match( '/[^a-zA-Z0-9]/', $nonce ) ) {
239            return new WP_Error( 'invalid_signature', sprintf( 'The required "%s" parameter is malformed.', 'nonce' ), compact( 'signature_details' ) );
240        }
241
242        $normalized_request_pieces = array(
243            $token,
244            $timestamp,
245            $nonce,
246            $body_hash,
247            strtoupper( $method ),
248            strtolower( $parsed['host'] ),
249            $port,
250            empty( $parsed['path'] ) ? '' : $parsed['path'],
251            // Normalized Query String.
252        );
253
254        $normalized_request_pieces      = array_merge( $normalized_request_pieces, $this->normalized_query_parameters( $parsed['query'] ?? '' ) );
255        $flat_normalized_request_pieces = array();
256        foreach ( $normalized_request_pieces as $piece ) {
257            if ( is_array( $piece ) ) {
258                foreach ( $piece as $subpiece ) {
259                    $flat_normalized_request_pieces[] = $subpiece;
260                }
261            } else {
262                $flat_normalized_request_pieces[] = $piece;
263            }
264        }
265        $normalized_request_pieces = $flat_normalized_request_pieces;
266
267        $normalized_request_string = implode( "\n", $normalized_request_pieces ) . "\n";
268
269        // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
270        return base64_encode( hash_hmac( 'sha1', $normalized_request_string, $this->secret, true ) );
271    }
272
273    /**
274     * Retrieve and normalize the parameters from a query string.
275     *
276     * @param string $query_string Query string.
277     * @return array Normalized query string parameters.
278     */
279    public function normalized_query_parameters( $query_string ) {
280        parse_str( $query_string, $array );
281
282        unset( $array['signature'] );
283
284        $names  = array_keys( $array );
285        $values = array_values( $array );
286
287        $names  = array_map( array( $this, 'encode_3986' ), $names );
288        $values = array_map( array( $this, 'encode_3986' ), $values );
289
290        $pairs = array_map( array( $this, 'join_with_equal_sign' ), $names, $values );
291
292        sort( $pairs );
293
294        return $pairs;
295    }
296
297    /**
298     * Encodes a string or array of strings according to RFC 3986.
299     *
300     * @param string|array $string_or_array String or array to encode.
301     * @return string|array URL-encoded string or array.
302     */
303    public function encode_3986( $string_or_array ) {
304        if ( is_array( $string_or_array ) ) {
305            return array_map( array( $this, 'encode_3986' ), $string_or_array );
306        }
307
308        return rawurlencode( $string_or_array );
309    }
310
311    /**
312     * Concatenates a parameter name and a parameter value with an equals sign between them.
313     *
314     * @param string       $name  Parameter name.
315     * @param string|array $value Parameter value.
316     * @return string|array A string pair (e.g. `name=value`) or an array of string pairs.
317     */
318    public function join_with_equal_sign( $name, $value ) {
319        if ( is_array( $value ) ) {
320            return $this->join_array_with_equal_sign( $name, $value );
321        }
322        return "{$name}={$value}";
323    }
324
325    /**
326     * Helper function for join_with_equal_sign for handling arrayed values.
327     * Explicitly supports nested arrays.
328     *
329     * @param string $name  Parameter name.
330     * @param array  $value Parameter value.
331     * @return array An array of string pairs (e.g. `[ name[example]=value ]`).
332     */
333    private function join_array_with_equal_sign( $name, $value ) {
334        $result = array();
335        foreach ( $value as $value_key => $value_value ) {
336            $joined_value = $this->join_with_equal_sign( $name . '[' . $value_key . ']', $value_value );
337            if ( is_array( $joined_value ) ) {
338                foreach ( array_values( $joined_value ) as $individual_joined_value ) {
339                    $result[] = $individual_joined_value;
340                }
341            } elseif ( is_string( $joined_value ) ) {
342                $result[] = $joined_value;
343            }
344        }
345
346        sort( $result );
347        return $result;
348    }
349
350    /**
351     * Gets the port that should be considered to sign the current request.
352     *
353     * It will analyze the current request, as well as some Jetpack constants, to return the string
354     * to be concatenated in the URL representing the port of the current request.
355     *
356     * @since 1.8.4
357     *
358     * @return string The port to be used in the signature
359     */
360    public function get_current_request_port() {
361        $host_port = isset( $_SERVER['HTTP_X_FORWARDED_PORT'] ) ? $this->sanitize_host_post( $_SERVER['HTTP_X_FORWARDED_PORT'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput -- This is validating.
362        if ( '' === $host_port && isset( $_SERVER['SERVER_PORT'] ) ) {
363            $host_port = $this->sanitize_host_post( $_SERVER['SERVER_PORT'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput -- This is validating.
364        }
365
366        /**
367         * Note: This port logic is tested in the Jetpack_Cxn_Tests->test__server_port_value() test.
368         * Please update the test if any changes are made in this logic.
369         */
370        if ( is_ssl() ) {
371            // 443: Standard Port
372            // 80: Assume we're behind a proxy without X-Forwarded-Port. Hardcoding "80" here means most sites
373            // with SSL termination proxies (self-served, Cloudflare, etc.) don't need to fiddle with
374            // the JETPACK_SIGNATURE__HTTPS_PORT constant. The code also implies we can't talk to a
375            // site at https://example.com:80/ (which would be a strange configuration).
376            // JETPACK_SIGNATURE__HTTPS_PORT: Set this constant in wp-config.php to the back end webserver's port
377            // if the site is behind a proxy running on port 443 without
378            // X-Forwarded-Port and the back end's port is *not* 80. It's better,
379            // though, to configure the proxy to send X-Forwarded-Port.
380            $https_port = defined( 'JETPACK_SIGNATURE__HTTPS_PORT' ) ? $this->sanitize_host_post( JETPACK_SIGNATURE__HTTPS_PORT ) : '443';
381            $port       = in_array( $host_port, array( '443', '80', $https_port ), true ) ? '' : $host_port;
382        } else {
383            // 80: Standard Port
384            // JETPACK_SIGNATURE__HTTPS_PORT: Set this constant in wp-config.php to the back end webserver's port
385            // if the site is behind a proxy running on port 80 without
386            // X-Forwarded-Port. It's better, though, to configure the proxy to
387            // send X-Forwarded-Port.
388            $http_port = defined( 'JETPACK_SIGNATURE__HTTP_PORT' ) ? $this->sanitize_host_post( JETPACK_SIGNATURE__HTTP_PORT ) : '80';
389            $port      = in_array( $host_port, array( '80', $http_port ), true ) ? '' : $host_port;
390        }
391        return (string) $port;
392    }
393
394    /**
395     * Sanitizes a variable checking if it's a valid port number, which can be an integer or a numeric string
396     *
397     * @since 1.8.4
398     *
399     * @param mixed $port_number Variable representing a port number.
400     * @return string Always a string with a valid port number, or an empty string if input is invalid
401     */
402    public function sanitize_host_post( $port_number ) {
403
404        if ( ! is_int( $port_number ) && ! is_string( $port_number ) ) {
405            return '';
406        }
407        if ( is_string( $port_number ) && ! ctype_digit( $port_number ) ) {
408            return '';
409        }
410
411        if ( 0 >= (int) $port_number || 65535 < $port_number ) {
412            return '';
413        }
414        return (string) $port_number;
415    }
416}