PluginProbe
ActivityPub / 8.0.2
ActivityPub v8.0.2
9.3.1 9.3.0 9.2.2 9.2.1 9.2.0 9.1.0 9.0.2 9.0.1 9.0.0 8.3.0 8.2.1 8.2.0 8.1.1 1.0.5 1.0.6 1.0.7 1.0.8 1.0.9 1.1.0 1.2.0 1.3.0 2.0.0 2.0.1 2.1.0 2.1.1 All 160 releases
← All changes | includes/class-signature.php +292 -154 9.2.0 → 8.0.2 View file →
@@ -6,8 +6,10 @@
6 6 */
7 7
8 8 namespace Activitypub;
9 9
10 +use Activitypub\Collection\Actors;
11 +use Activitypub\Collection\Remote_Actors;
10 12 use Activitypub\Signature\Http_Message_Signature;
11 13 use Activitypub\Signature\Http_Signature_Draft;
12 14
13 15 /**
@@ -26,83 +28,8 @@
26 28 \add_filter( 'http_response', array( self::class, 'maybe_double_knock' ), 10, 3 );
27 29 }
28 30
29 31 /**
30 - * Generate a new RSA key pair for signing HTTP requests.
31 - *
32 - * Does not persist anything — callers are responsible for storing the keys.
33 - *
34 - * @since 9.1.0
35 - *
36 - * @return array The key pair with 'private_key' and 'public_key', both null on failure.
37 - */
38 - public static function generate_key_pair() {
39 - $config = array(
40 - 'digest_alg' => 'sha512',
41 - 'private_key_bits' => 2048,
42 - 'private_key_type' => \OPENSSL_KEYTYPE_RSA,
43 - );
44 -
45 - $key = \openssl_pkey_new( $config );
46 - $private_key = null;
47 - $detail = array();
48 - if ( $key ) {
49 - \openssl_pkey_export( $key, $private_key );
50 - $detail = \openssl_pkey_get_details( $key );
51 - }
52 -
53 - // Check if keys are valid.
54 - if (
55 - empty( $private_key ) || ! \is_string( $private_key ) ||
56 - ! isset( $detail['key'] ) || ! \is_string( $detail['key'] )
57 - ) {
58 - return array(
59 - 'private_key' => null,
60 - 'public_key' => null,
61 - );
62 - }
63 -
64 - return array(
65 - 'private_key' => $private_key,
66 - 'public_key' => $detail['key'],
67 - );
68 - }
69 -
70 - /**
71 - * Get the key pair stored in an option, migrating a legacy pair or generating a new one on first use.
72 - *
73 - * @since 9.1.0
74 - *
75 - * @param string $option_key The option name the key pair is stored in.
76 - * @param callable|null $legacy_callback Optional. Callback that returns a legacy key pair to migrate, or false. Default null.
77 - *
78 - * @return array The key pair with 'private_key' and 'public_key'.
79 - */
80 - public static function get_key_pair( $option_key, $legacy_callback = null ) {
81 - $key_pair = \get_option( $option_key );
82 -
83 - if ( $key_pair ) {
84 - return $key_pair;
85 - }
86 -
87 - $key_pair = $legacy_callback ? $legacy_callback() : false;
88 -
89 - if ( ! $key_pair ) {
90 - $key_pair = self::generate_key_pair();
91 -
92 - // Only persist valid keys.
93 - if ( empty( $key_pair['private_key'] ) ) {
94 - return $key_pair;
95 - }
96 - }
97 -
98 - // `update_option()` also overwrites a corrupted-but-present row, which `add_option()` would silently skip.
99 - \update_option( $option_key, $key_pair );
100 -
101 - return $key_pair;
102 - }
103 -
104 - /**
105 32 * Sign an HTTP Request.
106 33 *
107 34 * @param array $args An array of HTTP request arguments.
108 35 * @param string $url The request URL.
@@ -126,26 +53,20 @@
126 53
127 54 /**
128 55 * Verifies the http signatures
129 56 *
130 - * On success the verified keyId is returned (a truthy string), so callers can bind it to
131 - * the activity actor without re-parsing headers, which cannot tell which signature label
132 - * actually validated. Pass/fail callers should branch on {@see is_wp_error()} as before.
133 - *
134 - * @since 9.0.0 Returns the verified keyId on success instead of `true`.
135 - *
136 57 * @param \WP_REST_Request|array $request The request object or $_SERVER array.
137 58 *
138 - * @return string|\WP_Error The verified keyId on success, WP_Error on failure.
59 + * @return bool|\WP_Error A boolean or WP_Error.
139 60 */
140 61 public static function verify_http_signature( $request ) {
141 - if ( \is_object( $request ) ) { // REST Request object.
62 + if ( is_object( $request ) ) { // REST Request object.
142 63 $body = $request->get_body();
143 64 $headers = $request->get_headers();
144 - $headers['(request-target)'][0] = \strtolower( $request->get_method() ) . ' ' . self::get_route( $request );
65 + $headers['(request-target)'][0] = strtolower( $request->get_method() ) . ' ' . self::get_route( $request );
145 66 } else {
146 67 $headers = self::format_server_request( $request );
147 - $headers['(request-target)'][0] = \strtolower( $headers['request_method'][0] ) . ' ' . $headers['request_uri'][0];
68 + $headers['(request-target)'][0] = strtolower( $headers['request_method'][0] ) . ' ' . $headers['request_uri'][0];
148 69 }
149 70
150 71 $signature = isset( $headers['signature_input'] ) ? new Http_Message_Signature() : new Http_Signature_Draft();
151 72
@@ -152,56 +73,8 @@
152 73 return $signature->verify( $headers, $body ?? null );
153 74 }
154 75
155 76 /**
156 - * Extract the signing keyId that {@see Signature::verify_http_signature()} would verify against.
157 - *
158 - * The returned keyId is only trustworthy if it identifies the key the signature is
159 - * actually checked with, so this mirrors the verifier's header choice rather than
160 - * scanning headers in an arbitrary order:
161 - *
162 - * - When a `Signature-Input` header is present the RFC 9421 verifier is used, so the
163 - * keyId is taken from there and a draft `Signature` header (which the verifier ignores)
164 - * is not consulted. The RFC 9421 verifier accepts whichever of several signature labels
165 - * validates, so a `Signature-Input` carrying more than one keyId is ambiguous: we cannot
166 - * know in advance which key will verify and must not guess, so `null` is returned.
167 - * - Otherwise the draft HTTP Signatures form is used, taking the first `keyId` from the
168 - * `Signature` header or, failing that, the `Authorization` header — matching the draft
169 - * verifier, which reads `signature ?? authorization`.
170 - *
171 - * @since 9.0.0
172 - *
173 - * @param \WP_REST_Request $request The request object.
174 - *
175 - * @return string|null The keyId, or null when none is present or the choice is ambiguous.
176 - */
177 - public static function get_key_id( $request ) {
178 - $signature_input = $request->get_header( 'signature-input' );
179 - if ( $signature_input ) {
180 - /*
181 - * keyid is a `;`-delimited parameter whose value may be quoted or unquoted.
182 - * Anchoring on `;` (or string start) avoids matching a `keyid=` substring inside
183 - * another parameter's value. Count every label's keyId: more than one is ambiguous.
184 - */
185 - $count = \preg_match_all( '/(?:^|;)\s*keyid="?([^";,\s]+)/i', $signature_input, $matches );
186 -
187 - return 1 === $count ? $matches[1][0] : null;
188 - }
189 -
190 - // A draft signature may arrive in the Signature header or, less commonly, Authorization.
191 - $signature = $request->get_header( 'signature' );
192 - if ( ! $signature ) {
193 - $signature = $request->get_header( 'authorization' );
194 - }
195 -
196 - if ( $signature && \preg_match( '/keyId="([^"]+)"/i', $signature, $matches ) ) {
197 - return $matches[1];
198 - }
199 -
200 - return null;
201 - }
202 -
203 - /**
204 77 * If a request with RFC-9421 signature fails, we try again with the Draft Cavage signature.
205 78 *
206 79 * @param array $response HTTP response.
207 80 * @param array $args HTTP request arguments.
@@ -222,9 +95,9 @@
222 95 unset( $args['headers']['Signature'], $args['headers']['Signature-Input'], $args['headers']['Content-Digest'] );
223 96 self::rfc9421_add_unsupported_host( $url );
224 97
225 98 $args = ( new Http_Signature_Draft() )->sign( $args, $url );
226 - $response = \wp_safe_remote_request( $url, $args );
99 + $response = \wp_remote_request( $url, $args );
227 100 }
228 101
229 102 return $response;
230 103 }
@@ -257,12 +130,12 @@
257 130 * @return string
258 131 */
259 132 private static function get_route( $request ) {
260 133 // Check if the route starts with "index.php".
261 - if ( \str_starts_with( $request->get_route(), '/index.php' ) || ! \rest_get_url_prefix() ) {
134 + if ( str_starts_with( $request->get_route(), '/index.php' ) || ! rest_get_url_prefix() ) {
262 135 $route = $request->get_route();
263 136 } else {
264 - $route = '/' . \rest_get_url_prefix() . '/' . \ltrim( $request->get_route(), '/' );
137 + $route = '/' . rest_get_url_prefix() . '/' . ltrim( $request->get_route(), '/' );
265 138 }
266 139
267 140 // Fix route for subdirectory installations.
268 141 $path = \wp_parse_url( \get_home_url(), PHP_URL_PATH );
@@ -267,9 +140,9 @@
267 140 // Fix route for subdirectory installations.
268 141 $path = \wp_parse_url( \get_home_url(), PHP_URL_PATH );
269 142
270 143 if ( \is_string( $path ) ) {
271 - $path = \trim( $path, '/' );
144 + $path = trim( $path, '/' );
272 145 }
273 146
274 147 if ( $path ) {
275 148 $route = '/' . $path . $route;
@@ -274,22 +147,8 @@
274 147 if ( $path ) {
275 148 $route = '/' . $path . $route;
276 149 }
277 150
278 - /*
279 - * Append the query string. Peers sign the full request-target including
280 - * the query (see Http_Signature_Draft::sign()), so the reconstructed
281 - * value has to match byte-for-byte. Use the raw REQUEST_URI instead of
282 - * re-encoding the parsed query params, re-encoding could change the
283 - * percent-encoding or parameter order and break the signature.
284 - */
285 - // phpcs:ignore WordPress.Security.ValidatedSanitizedInput
286 - $query = (string) \wp_parse_url( $_SERVER['REQUEST_URI'] ?? '', \PHP_URL_QUERY );
287 -
288 - if ( '' !== $query ) {
289 - $route .= '?' . $query;
290 - }
291 -
292 151 return $route;
293 152 }
294 153
295 154 /**
@@ -328,8 +187,287 @@
328 187 \update_option( 'activitypub_rfc9421_unsupported', $list, false );
329 188 }
330 189
331 190 /**
191 + * Return the public key for a given user.
192 + *
193 + * @deprecated 7.0.0 Use {@see Actors::get_public_key()}.
194 + *
195 + * @param int $user_id The WordPress User ID.
196 + * @param bool $force Optional. Force the generation of a new key pair. Default false.
197 + *
198 + * @return string The public key.
199 + */
200 + public static function get_public_key_for( $user_id, $force = false ) {
201 + \_deprecated_function( __METHOD__, '7.0.0', 'Activitypub\Collection\Actors::get_public_key' );
202 +
203 + return Actors::get_public_key( $user_id, $force );
204 + }
205 +
206 + /**
207 + * Return the private key for a given user.
208 + *
209 + * @deprecated 7.0.0 Use {@see Actors::get_private_key()}.
210 + *
211 + * @param int $user_id The WordPress User ID.
212 + * @param bool $force Optional. Force the generation of a new key pair. Default false.
213 + *
214 + * @return string The private key.
215 + */
216 + public static function get_private_key_for( $user_id, $force = false ) {
217 + \_deprecated_function( __METHOD__, '7.0.0', 'Activitypub\Collection\Actors::get_private_key' );
218 +
219 + return Actors::get_private_key( $user_id, $force );
220 + }
221 +
222 + /**
223 + * Return the key pair for a given user.
224 + *
225 + * @deprecated 7.0.0 Use {@see Actors::get_keypair()}.
226 + *
227 + * @param int $user_id The WordPress User ID.
228 + *
229 + * @return array The key pair.
230 + */
231 + public static function get_keypair_for( $user_id ) {
232 + \_deprecated_function( __METHOD__, '7.0.0', 'Activitypub\Collection\Actors::get_keypair' );
233 +
234 + return Actors::get_keypair( $user_id );
235 + }
236 +
237 + /**
238 + * Get public key from key_id.
239 + *
240 + * @deprecated 7.4.0 Use {@see Remote_Actors::get_public_key()}.
241 + *
242 + * @param string $key_id The URL to the public key.
243 + *
244 + * @return resource|\WP_Error The public key resource or WP_Error.
245 + */
246 + public static function get_remote_key( $key_id ) {
247 + \_deprecated_function( __METHOD__, '7.4.0', 'Activitypub\Collection\Remote_Actors::get_public_key()' );
248 +
249 + return Remote_Actors::get_public_key( $key_id );
250 + }
251 +
252 + /**
253 + * Generates the Signature for an HTTP Request.
254 + *
255 + * @deprecated 7.0.0 Use {@see Signature::sign_request()}.
256 + *
257 + * @param int $user_id The WordPress User ID.
258 + * @param string $http_method The HTTP method.
259 + * @param string $url The URL to send the request to.
260 + * @param string $date The date the request is sent.
261 + * @param string $digest Optional. The digest of the request body. Default null.
262 + *
263 + * @return string The signature.
264 + */
265 + public static function generate_signature( $user_id, $http_method, $url, $date, $digest = null ) {
266 + \_deprecated_function( __METHOD__, '7.0.0', self::class . '::sign_request()' );
267 +
268 + $user = Actors::get_by_id( $user_id );
269 + $key = Actors::get_private_key( $user_id );
270 +
271 + $url_parts = \wp_parse_url( $url );
272 +
273 + $host = $url_parts['host'];
274 + $path = '/';
275 +
276 + // Add path.
277 + if ( ! empty( $url_parts['path'] ) ) {
278 + $path = $url_parts['path'];
279 + }
280 +
281 + // Add query.
282 + if ( ! empty( $url_parts['query'] ) ) {
283 + $path .= '?' . $url_parts['query'];
284 + }
285 +
286 + $http_method = \strtolower( $http_method );
287 +
288 + if ( ! empty( $digest ) ) {
289 + $signed_string = "(request-target): $http_method $path\nhost: $host\ndate: $date\ndigest: $digest";
290 + } else {
291 + $signed_string = "(request-target): $http_method $path\nhost: $host\ndate: $date";
292 + }
293 +
294 + $signature = null;
295 + \openssl_sign( $signed_string, $signature, $key, \OPENSSL_ALGO_SHA256 );
296 + $signature = \base64_encode( $signature ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
297 +
298 + $key_id = $user->get_id() . '#main-key';
299 +
300 + if ( ! empty( $digest ) ) {
301 + return \sprintf( 'keyId="%s",algorithm="rsa-sha256",headers="(request-target) host date digest",signature="%s"', $key_id, $signature );
302 + } else {
303 + return \sprintf( 'keyId="%s",algorithm="rsa-sha256",headers="(request-target) host date",signature="%s"', $key_id, $signature );
304 + }
305 + }
306 +
307 + /**
308 + * Gets the signature algorithm from the signature header.
309 + *
310 + * @deprecated 7.0.0 Use {@see Signature::verify()}.
311 + *
312 + * @param array $signature_block The signature block.
313 + *
314 + * @return string|bool The signature algorithm or false if not found.
315 + */
316 + public static function get_signature_algorithm( $signature_block ) { // phpcs:ignore
317 + \_deprecated_function( __METHOD__, '7.0.0', self::class . '::verify' );
318 +
319 + if ( ! empty( $signature_block['algorithm'] ) ) {
320 + switch ( $signature_block['algorithm'] ) {
321 + case 'rsa-sha-512':
322 + return 'sha512'; // hs2019 https://datatracker.ietf.org/doc/html/draft-cavage-http-signatures-12.
323 + default:
324 + return 'sha256';
325 + }
326 + }
327 +
328 + return false;
329 + }
330 +
331 + /**
332 + * Parses the Signature header.
333 + *
334 + * @deprecated 7.0.0 Use {@see Signature::verify()}.
335 + *
336 + * @param string $signature The signature header.
337 + *
338 + * @return array Signature parts.
339 + */
340 + public static function parse_signature_header( $signature ) { // phpcs:ignore
341 + \_deprecated_function( __METHOD__, '7.0.0', self::class . '::verify' );
342 +
343 + $parsed_header = array();
344 + $matches = array();
345 +
346 + if ( \preg_match( '/keyId="(.*?)"/ism', $signature, $matches ) ) {
347 + $parsed_header['keyId'] = trim( $matches[1] );
348 + }
349 + if ( \preg_match( '/created=["|\']*([0-9]*)["|\']*/ism', $signature, $matches ) ) {
350 + $parsed_header['(created)'] = trim( $matches[1] );
351 + }
352 + if ( \preg_match( '/expires=["|\']*([0-9]*)["|\']*/ism', $signature, $matches ) ) {
353 + $parsed_header['(expires)'] = trim( $matches[1] );
354 + }
355 + if ( \preg_match( '/algorithm="(.*?)"/ism', $signature, $matches ) ) {
356 + $parsed_header['algorithm'] = trim( $matches[1] );
357 + }
358 + if ( \preg_match( '/headers="(.*?)"/ism', $signature, $matches ) ) {
359 + $parsed_header['headers'] = \explode( ' ', trim( $matches[1] ) );
360 + }
361 + if ( \preg_match( '/signature="(.*?)"/ism', $signature, $matches ) ) {
362 + $parsed_header['signature'] = \base64_decode( preg_replace( '/\s+/', '', trim( $matches[1] ) ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
363 + }
364 +
365 + if ( empty( $parsed_header['headers'] ) ) {
366 + $parsed_header['headers'] = array( 'date' );
367 + }
368 +
369 + return $parsed_header;
370 + }
371 +
372 + /**
373 + * Gets the header data from the included pseudo headers.
374 + *
375 + * @deprecated 7.0.0 Use {@see Signature::verify()}.
376 + *
377 + * @param array $signed_headers The signed headers.
378 + * @param array $signature_block The signature block.
379 + * @param array $headers The HTTP headers.
380 + *
381 + * @return string signed headers for comparison
382 + */
383 + public static function get_signed_data( $signed_headers, $signature_block, $headers ) { // phpcs:ignore
384 + \_deprecated_function( __METHOD__, '7.0.0', self::class . '::verify' );
385 +
386 + $signed_data = '';
387 +
388 + // This also verifies time-based values by returning false if any of these are out of range.
389 + foreach ( $signed_headers as $header ) {
390 + if ( 'host' === $header ) {
391 + if ( isset( $headers['x_original_host'] ) ) {
392 + $signed_data .= $header . ': ' . $headers['x_original_host'][0] . "\n";
393 + continue;
394 + }
395 + }
396 + if ( '(request-target)' === $header ) {
397 + $signed_data .= $header . ': ' . $headers[ $header ][0] . "\n";
398 + continue;
399 + }
400 + if ( str_contains( $header, '-' ) ) {
401 + $signed_data .= $header . ': ' . $headers[ str_replace( '-', '_', $header ) ][0] . "\n";
402 + continue;
403 + }
404 + if ( '(created)' === $header ) {
405 + if ( ! empty( $signature_block['(created)'] ) && \intval( $signature_block['(created)'] ) > \time() ) {
406 + // Created in the future.
407 + return false;
408 + }
409 +
410 + if ( ! array_key_exists( '(created)', $headers ) ) {
411 + $signed_data .= $header . ': ' . $signature_block['(created)'] . "\n";
412 + continue;
413 + }
414 + }
415 + if ( '(expires)' === $header ) {
416 + if ( ! empty( $signature_block['(expires)'] ) && \intval( $signature_block['(expires)'] ) < \time() ) {
417 + // Expired in the past.
418 + return false;
419 + }
420 +
421 + if ( ! array_key_exists( '(expires)', $headers ) ) {
422 + $signed_data .= $header . ': ' . $signature_block['(expires)'] . "\n";
423 + continue;
424 + }
425 + }
426 + if ( 'date' === $header ) {
427 + if ( empty( $headers[ $header ][0] ) ) {
428 + continue;
429 + }
430 +
431 + // Allow a bit of leeway for misconfigured clocks.
432 + $d = new \DateTime( $headers[ $header ][0] );
433 + $d->setTimeZone( new \DateTimeZone( 'UTC' ) );
434 + $c = $d->format( 'U' );
435 +
436 + $d_plus = time() + ( 3 * HOUR_IN_SECONDS );
437 + $d_minus = time() - ( 3 * HOUR_IN_SECONDS );
438 +
439 + if ( $c > $d_plus || $c < $d_minus ) {
440 + // Time out of range.
441 + return false;
442 + }
443 + }
444 +
445 + if ( ! empty( $headers[ $header ][0] ) ) {
446 + $signed_data .= $header . ': ' . $headers[ $header ][0] . "\n";
447 + }
448 + }
449 +
450 + return \rtrim( $signed_data, "\n" );
451 + }
452 +
453 + /**
454 + * Generates the digest for an HTTP Request.
455 + *
456 + * @deprecated 7.0.0 Use {@see Signature::sign_request()}.
457 + *
458 + * @param string $body The body of the request.
459 + *
460 + * @return string The digest.
461 + */
462 + public static function generate_digest( $body ) {
463 + \_deprecated_function( __METHOD__, '7.0.0', self::class . '::sign_request' );
464 +
465 + $digest = \base64_encode( \hash( 'sha256', $body, true ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
466 + return "SHA-256=$digest";
467 + }
468 +
469 + /**
332 470 * Compute the collection digest for a specific instance.
333 471 *
334 472 * Implements FEP-8fcf: Followers collection synchronization.
335 473 * The digest is created by XORing together the individual SHA256 digests
@@ -341,18 +479,18 @@
341 479 *
342 480 * @return string|false The hex-encoded digest, or false if no followers.
343 481 */
344 482 public static function get_collection_digest( $collection ) {
345 - if ( empty( $collection ) || ! \is_array( $collection ) ) {
483 + if ( empty( $collection ) || ! is_array( $collection ) ) {
346 484 return false;
347 485 }
348 486
349 487 // Initialize with zeros (64 hex chars = 32 bytes = 256 bits).
350 - $digest = \str_repeat( '0', 64 );
488 + $digest = str_repeat( '0', 64 );
351 489
352 490 foreach ( $collection as $item ) {
353 491 // Compute SHA256 hash of the follower ID.
354 - $hash = \hash( 'sha256', $item );
492 + $hash = hash( 'sha256', $item );
355 493
356 494 // XOR the hash with the running digest.
357 495 $digest = self::xor_hex_strings( $digest, $hash );
358 496 }