Completed
Push — add/jetpack-start-reconnect-us... ( 7f1fbb )
by
unknown
10:36
created

class.jetpack-signature.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
// These constants can be set in wp-config.php to ensure sites behind proxies will still work.
4
// Setting these constants, though, is *not* the preferred method. It's better to configure
5
// the proxy to send the X-Forwarded-Port header.
6
defined( 'JETPACK_SIGNATURE__HTTP_PORT'  ) or define( 'JETPACK_SIGNATURE__HTTP_PORT' , 80  );
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

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