Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
74.50% covered (warning)
74.50%
111 / 149
77.78% covered (warning)
77.78%
7 / 9
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_Signature
74.50% covered (warning)
74.50%
111 / 149
77.78% covered (warning)
77.78%
7 / 9
189.83
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
68.12% covered (warning)
68.12%
47 / 69
0.00% covered (danger)
0.00%
0 / 1
56.26
 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        if ( ! str_starts_with( $token, "$this->token:" ) ) {
164            return new WP_Error( 'token_mismatch', 'Incorrect token', compact( 'signature_details' ) );
165        }
166
167        // If we got an array at this point, let's encode it, so we can see what it looks like as a string.
168        if ( is_array( $body ) ) {
169            if ( $body !== array() ) {
170                // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode
171                $body = json_encode(
172                    $body,
173                    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.
174                );
175
176            } else {
177                $body = '';
178            }
179        }
180
181        $required_parameters = array( 'token', 'timestamp', 'nonce', 'method', 'url' );
182        if ( $body !== null ) {
183            $required_parameters[] = 'body_hash';
184            if ( ! is_string( $body ) ) {
185                return new WP_Error( 'invalid_body', 'Body is malformed.', compact( 'signature_details' ) );
186            }
187        }
188
189        foreach ( $required_parameters as $required ) {
190            if ( ! is_scalar( $$required ) ) {
191                return new WP_Error( 'invalid_signature', sprintf( 'The required "%s" parameter is malformed.', str_replace( '_', '-', $required ) ), compact( 'signature_details' ) );
192            }
193
194            if ( ! strlen( $$required ) ) {
195                return new WP_Error( 'invalid_signature', sprintf( 'The required "%s" parameter is missing.', str_replace( '_', '-', $required ) ), compact( 'signature_details' ) );
196            }
197        }
198
199        if ( empty( $body ) ) {
200            if ( $body_hash ) {
201                return new WP_Error( 'invalid_body_hash', 'Invalid body hash for empty body.', compact( 'signature_details' ) );
202            }
203        } else {
204            $connection = new Connection_Manager();
205            if ( $verify_body_hash && $connection->sha1_base64( $body ) !== $body_hash ) {
206                return new WP_Error( 'invalid_body_hash', 'The body hash does not match.', compact( 'signature_details' ) );
207            }
208        }
209
210        $parsed = wp_parse_url( $url );
211        if ( ! isset( $parsed['host'] ) ) {
212            return new WP_Error( 'invalid_signature', sprintf( 'The required "%s" parameter is malformed.', 'url' ), compact( 'signature_details' ) );
213        }
214
215        if ( ! empty( $parsed['port'] ) ) {
216            $port = $parsed['port'];
217        } elseif ( 'http' === $parsed['scheme'] ) {
218            $port = 80;
219        } elseif ( 'https' === $parsed['scheme'] ) {
220            $port = 443;
221        } else {
222            return new WP_Error( 'unknown_scheme_port', "The scheme's port is unknown", compact( 'signature_details' ) );
223        }
224
225        if ( ! ctype_digit( "$timestamp" ) || 10 < strlen( (string) $timestamp ) ) { // If Jetpack is around in 275 years, you can blame mdawaffe for the bug.
226            return new WP_Error( 'invalid_signature', sprintf( 'The required "%s" parameter is malformed.', 'timestamp' ), compact( 'signature_details' ) );
227        }
228
229        $local_time = $timestamp - $this->time_diff;
230        if ( $local_time < time() - 600 || $local_time > time() + 300 ) {
231            return new WP_Error( 'invalid_signature', 'The timestamp is too old.', compact( 'signature_details' ) );
232        }
233
234        if ( 12 < strlen( $nonce ) || preg_match( '/[^a-zA-Z0-9]/', $nonce ) ) {
235            return new WP_Error( 'invalid_signature', sprintf( 'The required "%s" parameter is malformed.', 'nonce' ), compact( 'signature_details' ) );
236        }
237
238        $normalized_request_pieces = array(
239            $token,
240            $timestamp,
241            $nonce,
242            $body_hash,
243            strtoupper( $method ),
244            strtolower( $parsed['host'] ),
245            $port,
246            empty( $parsed['path'] ) ? '' : $parsed['path'],
247            // Normalized Query String.
248        );
249
250        $normalized_request_pieces      = array_merge( $normalized_request_pieces, $this->normalized_query_parameters( $parsed['query'] ?? '' ) );
251        $flat_normalized_request_pieces = array();
252        foreach ( $normalized_request_pieces as $piece ) {
253            if ( is_array( $piece ) ) {
254                foreach ( $piece as $subpiece ) {
255                    $flat_normalized_request_pieces[] = $subpiece;
256                }
257            } else {
258                $flat_normalized_request_pieces[] = $piece;
259            }
260        }
261        $normalized_request_pieces = $flat_normalized_request_pieces;
262
263        $normalized_request_string = implode( "\n", $normalized_request_pieces ) . "\n";
264
265        // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
266        return base64_encode( hash_hmac( 'sha1', $normalized_request_string, $this->secret, true ) );
267    }
268
269    /**
270     * Retrieve and normalize the parameters from a query string.
271     *
272     * @param string $query_string Query string.
273     * @return array Normalized query string parameters.
274     */
275    public function normalized_query_parameters( $query_string ) {
276        parse_str( $query_string, $array );
277
278        unset( $array['signature'] );
279
280        $names  = array_keys( $array );
281        $values = array_values( $array );
282
283        $names  = array_map( array( $this, 'encode_3986' ), $names );
284        $values = array_map( array( $this, 'encode_3986' ), $values );
285
286        $pairs = array_map( array( $this, 'join_with_equal_sign' ), $names, $values );
287
288        sort( $pairs );
289
290        return $pairs;
291    }
292
293    /**
294     * Encodes a string or array of strings according to RFC 3986.
295     *
296     * @param string|array $string_or_array String or array to encode.
297     * @return string|array URL-encoded string or array.
298     */
299    public function encode_3986( $string_or_array ) {
300        if ( is_array( $string_or_array ) ) {
301            return array_map( array( $this, 'encode_3986' ), $string_or_array );
302        }
303
304        return rawurlencode( $string_or_array );
305    }
306
307    /**
308     * Concatenates a parameter name and a parameter value with an equals sign between them.
309     *
310     * @param string       $name  Parameter name.
311     * @param string|array $value Parameter value.
312     * @return string|array A string pair (e.g. `name=value`) or an array of string pairs.
313     */
314    public function join_with_equal_sign( $name, $value ) {
315        if ( is_array( $value ) ) {
316            return $this->join_array_with_equal_sign( $name, $value );
317        }
318        return "{$name}={$value}";
319    }
320
321    /**
322     * Helper function for join_with_equal_sign for handling arrayed values.
323     * Explicitly supports nested arrays.
324     *
325     * @param string $name  Parameter name.
326     * @param array  $value Parameter value.
327     * @return array An array of string pairs (e.g. `[ name[example]=value ]`).
328     */
329    private function join_array_with_equal_sign( $name, $value ) {
330        $result = array();
331        foreach ( $value as $value_key => $value_value ) {
332            $joined_value = $this->join_with_equal_sign( $name . '[' . $value_key . ']', $value_value );
333            if ( is_array( $joined_value ) ) {
334                foreach ( array_values( $joined_value ) as $individual_joined_value ) {
335                    $result[] = $individual_joined_value;
336                }
337            } elseif ( is_string( $joined_value ) ) {
338                $result[] = $joined_value;
339            }
340        }
341
342        sort( $result );
343        return $result;
344    }
345
346    /**
347     * Gets the port that should be considered to sign the current request.
348     *
349     * It will analyze the current request, as well as some Jetpack constants, to return the string
350     * to be concatenated in the URL representing the port of the current request.
351     *
352     * @since 1.8.4
353     *
354     * @return string The port to be used in the signature
355     */
356    public function get_current_request_port() {
357        $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.
358        if ( '' === $host_port && isset( $_SERVER['SERVER_PORT'] ) ) {
359            $host_port = $this->sanitize_host_post( $_SERVER['SERVER_PORT'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput -- This is validating.
360        }
361
362        /**
363         * Note: This port logic is tested in the Jetpack_Cxn_Tests->test__server_port_value() test.
364         * Please update the test if any changes are made in this logic.
365         */
366        if ( is_ssl() ) {
367            // 443: Standard Port
368            // 80: Assume we're behind a proxy without X-Forwarded-Port. Hardcoding "80" here means most sites
369            // with SSL termination proxies (self-served, Cloudflare, etc.) don't need to fiddle with
370            // the JETPACK_SIGNATURE__HTTPS_PORT constant. The code also implies we can't talk to a
371            // site at https://example.com:80/ (which would be a strange configuration).
372            // JETPACK_SIGNATURE__HTTPS_PORT: Set this constant in wp-config.php to the back end webserver's port
373            // if the site is behind a proxy running on port 443 without
374            // X-Forwarded-Port and the back end's port is *not* 80. It's better,
375            // though, to configure the proxy to send X-Forwarded-Port.
376            $https_port = defined( 'JETPACK_SIGNATURE__HTTPS_PORT' ) ? $this->sanitize_host_post( JETPACK_SIGNATURE__HTTPS_PORT ) : '443';
377            $port       = in_array( $host_port, array( '443', '80', $https_port ), true ) ? '' : $host_port;
378        } else {
379            // 80: Standard Port
380            // JETPACK_SIGNATURE__HTTPS_PORT: Set this constant in wp-config.php to the back end webserver's port
381            // if the site is behind a proxy running on port 80 without
382            // X-Forwarded-Port. It's better, though, to configure the proxy to
383            // send X-Forwarded-Port.
384            $http_port = defined( 'JETPACK_SIGNATURE__HTTP_PORT' ) ? $this->sanitize_host_post( JETPACK_SIGNATURE__HTTP_PORT ) : '80';
385            $port      = in_array( $host_port, array( '80', $http_port ), true ) ? '' : $host_port;
386        }
387        return (string) $port;
388    }
389
390    /**
391     * Sanitizes a variable checking if it's a valid port number, which can be an integer or a numeric string
392     *
393     * @since 1.8.4
394     *
395     * @param mixed $port_number Variable representing a port number.
396     * @return string Always a string with a valid port number, or an empty string if input is invalid
397     */
398    public function sanitize_host_post( $port_number ) {
399
400        if ( ! is_int( $port_number ) && ! is_string( $port_number ) ) {
401            return '';
402        }
403        if ( is_string( $port_number ) && ! ctype_digit( $port_number ) ) {
404            return '';
405        }
406
407        if ( 0 >= (int) $port_number || 65535 < $port_number ) {
408            return '';
409        }
410        return (string) $port_number;
411    }
412}