PluginProbe
ActivityPub / 1.0.0
ActivityPub v1.0.0
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 +258 -347 8.3.01.0.0 View file →
@@ -1,20 +1,14 @@
1 1 <?php
2 -/**
3 - * Signature class file.
4 - *
5 - * @package Activitypub
6 - */
7 -
8 2 namespace Activitypub;
9 3
10 -use Activitypub\Collection\Actors;
11 -use Activitypub\Collection\Remote_Actors;
12 -use Activitypub\Signature\Http_Message_Signature;
13 -use Activitypub\Signature\Http_Signature_Draft;
4 +use WP_Error;
5 +use DateTime;
6 +use DateTimeZone;
7 +use Activitypub\Collection\Users;
14 8
15 9 /**
16 - * ActivityPub Signature Class.
10 + * ActivityPub Signature Class
17 11 *
18 12 * @author Matthias Pfefferle
19 13 * @author Django Doucet
20 14 */
@@ -20,266 +14,191 @@
20 14 */
21 15 class Signature {
22 16
23 17 /**
24 - * Initialize the class.
25 - */
26 - public static function init() {
27 - \add_filter( 'http_request_args', array( self::class, 'sign_request' ), 0, 2 ); // Ahead of all other filters, so signature is set.
28 - \add_filter( 'http_response', array( self::class, 'maybe_double_knock' ), 10, 3 );
29 - }
30 -
31 - /**
32 - * Sign an HTTP Request.
18 + * Return the public key for a given user.
33 19 *
34 - * @param array $args An array of HTTP request arguments.
35 - * @param string $url The request URL.
20 + * @param int $user_id The WordPress User ID.
21 + * @param bool $force Force the generation of a new key pair.
36 22 *
37 - * @return array Request arguments with signature headers.
23 + * @return mixed The public key.
38 24 */
39 - public static function sign_request( $args, $url ) {
40 - // Bail if there's nothing to sign with.
41 - if ( ! isset( $args['key_id'], $args['private_key'] ) ) {
42 - return $args;
25 + public static function get_public_key_for( $user_id, $force = false ) {
26 + if ( $force ) {
27 + self::generate_key_pair_for( $user_id );
43 28 }
44 29
45 - if ( '1' === \get_option( 'activitypub_rfc9421_signature' ) && self::could_support_rfc9421( $url ) ) {
46 - $signature = new Http_Message_Signature();
47 - } else {
48 - $signature = new Http_Signature_Draft();
49 - }
30 + $key_pair = self::get_keypair_for( $user_id );
50 31
51 - return $signature->sign( $args, $url );
32 + return $key_pair['public_key'];
52 33 }
53 34
54 35 /**
55 - * Verifies the http signatures
36 + * Return the private key for a given user.
56 37 *
57 - * @param \WP_REST_Request|array $request The request object or $_SERVER array.
38 + * @param int $user_id The WordPress User ID.
39 + * @param bool $force Force the generation of a new key pair.
58 40 *
59 - * @return bool|\WP_Error A boolean or WP_Error.
41 + * @return mixed The private key.
60 42 */
61 - public static function verify_http_signature( $request ) {
62 - if ( is_object( $request ) ) { // REST Request object.
63 - $body = $request->get_body();
64 - $headers = $request->get_headers();
65 - $headers['(request-target)'][0] = strtolower( $request->get_method() ) . ' ' . self::get_route( $request );
66 - } else {
67 - $headers = self::format_server_request( $request );
68 - $headers['(request-target)'][0] = strtolower( $headers['request_method'][0] ) . ' ' . $headers['request_uri'][0];
43 + public static function get_private_key_for( $user_id, $force = false ) {
44 + if ( $force ) {
45 + self::generate_key_pair_for( $user_id );
69 46 }
70 47
71 - $signature = isset( $headers['signature_input'] ) ? new Http_Message_Signature() : new Http_Signature_Draft();
48 + $key_pair = self::get_keypair_for( $user_id );
72 49
73 - return $signature->verify( $headers, $body ?? null );
50 + return $key_pair['private_key'];
74 51 }
75 52
76 53 /**
77 - * If a request with RFC-9421 signature fails, we try again with the Draft Cavage signature.
54 + * Return the key pair for a given user.
78 55 *
79 - * @param array $response HTTP response.
80 - * @param array $args HTTP request arguments.
81 - * @param string $url The request URL.
56 + * @param int $user_id The WordPress User ID.
82 57 *
83 - * @return array The HTTP response.
58 + * @return array The key pair.
84 59 */
85 - public static function maybe_double_knock( $response, $args, $url ) {
86 - // Bail if it didn't use an RFC-9421 signature or there's nothing to sign with.
87 - if ( ! isset( $args['key_id'], $args['private_key'], $args['headers']['Signature-Input'] ) ) {
88 - return $response;
89 - }
60 + public static function get_keypair_for( $user_id ) {
61 + $option_key = self::get_signature_options_key_for( $user_id );
62 + $key_pair = \get_option( $option_key );
90 63
91 - $response_code = \wp_remote_retrieve_response_code( $response );
92 -
93 - // Fall back to Draft Cavage signature for any 4xx responses.
94 - if ( $response_code >= 400 && $response_code < 500 ) {
95 - unset( $args['headers']['Signature'], $args['headers']['Signature-Input'], $args['headers']['Content-Digest'] );
96 - self::rfc9421_add_unsupported_host( $url );
97 -
98 - $args = ( new Http_Signature_Draft() )->sign( $args, $url );
99 - $response = \wp_safe_remote_request( $url, $args );
64 + if ( ! $key_pair ) {
65 + $key_pair = self::generate_key_pair_for( $user_id );
100 66 }
101 67
102 - return $response;
68 + return $key_pair;
103 69 }
104 70
105 71 /**
106 - * Formats the $_SERVER to resemble the WP_REST_REQUEST array,
107 - * for use with verify_http_signature().
72 + * Generates the pair keys
108 73 *
109 - * @param array $server The $_SERVER array.
74 + * @param int $user_id The WordPress User ID.
110 75 *
111 - * @return array $request The formatted request array.
76 + * @return array The key pair.
112 77 */
113 - public static function format_server_request( $server ) {
114 - $headers = array();
78 + protected static function generate_key_pair_for( $user_id ) {
79 + $option_key = self::get_signature_options_key_for( $user_id );
80 + $key_pair = self::check_legacy_key_pair_for( $user_id );
115 81
116 - foreach ( $server as $key => $value ) {
117 - $key = \str_replace( 'http_', '', \strtolower( $key ) );
118 - $headers[ $key ][] = \wp_unslash( $value );
82 + if ( $key_pair ) {
83 + \add_option( $option_key, $key_pair );
119 84
85 + return $key_pair;
120 86 }
121 87
122 - return $headers;
123 - }
88 + $config = array(
89 + 'digest_alg' => 'sha512',
90 + 'private_key_bits' => 2048,
91 + 'private_key_type' => \OPENSSL_KEYTYPE_RSA,
92 + );
124 93
125 - /**
126 - * Returns route.
127 - *
128 - * @param \WP_REST_Request $request The request object.
129 - *
130 - * @return string
131 - */
132 - private static function get_route( $request ) {
133 - // Check if the route starts with "index.php".
134 - if ( str_starts_with( $request->get_route(), '/index.php' ) || ! rest_get_url_prefix() ) {
135 - $route = $request->get_route();
136 - } else {
137 - $route = '/' . rest_get_url_prefix() . '/' . ltrim( $request->get_route(), '/' );
138 - }
94 + $key = \openssl_pkey_new( $config );
95 + $priv_key = null;
139 96
140 - // Fix route for subdirectory installations.
141 - $path = \wp_parse_url( \get_home_url(), PHP_URL_PATH );
97 + \openssl_pkey_export( $key, $priv_key );
142 98
143 - if ( \is_string( $path ) ) {
144 - $path = trim( $path, '/' );
145 - }
99 + $detail = \openssl_pkey_get_details( $key );
146 100
147 - if ( $path ) {
148 - $route = '/' . $path . $route;
101 + // check if keys are valid
102 + if (
103 + empty( $priv_key ) || ! is_string( $priv_key ) ||
104 + ! isset( $detail['key'] ) || ! is_string( $detail['key'] )
105 + ) {
106 + return array(
107 + 'private_key' => null,
108 + 'public_key' => null,
109 + );
149 110 }
150 111
151 - return $route;
152 - }
112 + $key_pair = array(
113 + 'private_key' => $priv_key,
114 + 'public_key' => $detail['key'],
115 + );
153 116
154 - /**
155 - * Check if RFC-9421 signature could be supported.
156 - *
157 - * @param string $url The URL to check.
158 - *
159 - * @return bool True, if RFC-9421 signature could be supported, false otherwise.
160 - */
161 - private static function could_support_rfc9421( $url ) {
162 - $host = \wp_parse_url( $url, \PHP_URL_HOST );
163 - $list = \get_option( 'activitypub_rfc9421_unsupported', array() );
117 + // persist keys
118 + \add_option( $option_key, $key_pair );
164 119
165 - if ( isset( $list[ $host ] ) ) {
166 - if ( $list[ $host ] > \time() ) {
167 - return false;
168 - }
169 -
170 - unset( $list[ $host ] );
171 - \update_option( 'activitypub_rfc9421_unsupported', $list );
172 - }
173 -
174 - return true;
120 + return $key_pair;
175 121 }
176 122
177 123 /**
178 - * Set RFC-9421 signature unsupported for a given host.
124 + * Return the option key for a given user.
179 125 *
180 - * @param string $url The URL to set.
181 - */
182 - private static function rfc9421_add_unsupported_host( $url ) {
183 - $list = \get_option( 'activitypub_rfc9421_unsupported', array() );
184 - $host = \wp_parse_url( $url, \PHP_URL_HOST );
185 -
186 - $list[ $host ] = \time() + MONTH_IN_SECONDS;
187 - \update_option( 'activitypub_rfc9421_unsupported', $list, false );
188 - }
189 -
190 - /**
191 - * Return the public key for a given user.
126 + * @param int $user_id The WordPress User ID.
192 127 *
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.
128 + * @return string The option key.
199 129 */
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' );
130 + protected static function get_signature_options_key_for( $user_id ) {
131 + $id = $user_id;
202 132
203 - return Actors::get_public_key( $user_id, $force );
204 - }
133 + if ( $user_id > 0 ) {
134 + $user = \get_userdata( $user_id );
135 + // sanatize username because it could include spaces and special chars
136 + $id = sanitize_title( $user->user_login );
137 + }
205 138
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 );
139 + return 'activitypub_keypair_for_' . $id;
220 140 }
221 141
222 142 /**
223 - * Return the key pair for a given user.
143 + * Check if there is a legacy key pair
224 144 *
225 - * @deprecated 7.0.0 Use {@see Actors::get_keypair()}.
226 - *
227 145 * @param int $user_id The WordPress User ID.
228 146 *
229 - * @return array The key pair.
147 + * @return array|bool The key pair or false.
230 148 */
231 - public static function get_keypair_for( $user_id ) {
232 - \_deprecated_function( __METHOD__, '7.0.0', 'Activitypub\Collection\Actors::get_keypair' );
149 + protected static function check_legacy_key_pair_for( $user_id ) {
150 + switch ( $user_id ) {
151 + case 0:
152 + $public_key = \get_option( 'activitypub_blog_user_public_key' );
153 + $private_key = \get_option( 'activitypub_blog_user_private_key' );
154 + break;
155 + case -1:
156 + $public_key = \get_option( 'activitypub_application_user_public_key' );
157 + $private_key = \get_option( 'activitypub_application_user_private_key' );
158 + break;
159 + default:
160 + $public_key = \get_user_meta( $user_id, 'magic_sig_public_key', true );
161 + $private_key = \get_user_meta( $user_id, 'magic_sig_private_key', true );
162 + break;
163 + }
233 164
234 - return Actors::get_keypair( $user_id );
235 - }
165 + if ( ! empty( $public_key ) && is_string( $public_key ) && ! empty( $private_key ) && is_string( $private_key ) ) {
166 + return array(
167 + 'private_key' => $private_key,
168 + 'public_key' => $public_key,
169 + );
170 + }
236 171
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 );
172 + return false;
250 173 }
251 174
252 175 /**
253 - * Generates the Signature for an HTTP Request.
176 + * Generates the Signature for a HTTP Request
254 177 *
255 - * @deprecated 7.0.0 Use {@see Signature::sign_request()}.
256 - *
257 178 * @param int $user_id The WordPress User ID.
258 179 * @param string $http_method The HTTP method.
259 180 * @param string $url The URL to send the request to.
260 181 * @param string $date The date the request is sent.
261 - * @param string $digest Optional. The digest of the request body. Default null.
182 + * @param string $digest The digest of the request body.
262 183 *
263 184 * @return string The signature.
264 185 */
265 186 public static function generate_signature( $user_id, $http_method, $url, $date, $digest = null ) {
266 - \_deprecated_function( __METHOD__, '7.0.0', self::class . '::sign_request()' );
187 + $user = Users::get_by_id( $user_id );
188 + $key = self::get_private_key_for( $user->get__id() );
267 189
268 - $user = Actors::get_by_id( $user_id );
269 - $key = Actors::get_private_key( $user_id );
270 -
271 190 $url_parts = \wp_parse_url( $url );
272 191
273 192 $host = $url_parts['host'];
274 193 $path = '/';
275 194
276 - // Add path.
195 + // add path
277 196 if ( ! empty( $url_parts['path'] ) ) {
278 197 $path = $url_parts['path'];
279 198 }
280 199
281 - // Add query.
200 + // add query
282 201 if ( ! empty( $url_parts['query'] ) ) {
283 202 $path .= '?' . $url_parts['query'];
284 203 }
285 204
@@ -292,11 +211,11 @@
292 211 }
293 212
294 213 $signature = null;
295 214 \openssl_sign( $signed_string, $signature, $key, \OPENSSL_ALGO_SHA256 );
296 - $signature = \base64_encode( $signature ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
215 + $signature = \base64_encode( $signature ); // phpcs:ignore
297 216
298 - $key_id = $user->get_id() . '#main-key';
217 + $key_id = $user->get_url() . '#main-key';
299 218
300 219 if ( ! empty( $digest ) ) {
301 220 return \sprintf( 'keyId="%s",algorithm="rsa-sha256",headers="(request-target) host date digest",signature="%s"', $key_id, $signature );
302 221 } else {
@@ -304,53 +223,145 @@
304 223 }
305 224 }
306 225
307 226 /**
308 - * Gets the signature algorithm from the signature header.
227 + * Verifies the http signatures
309 228 *
310 - * @deprecated 7.0.0 Use {@see Signature::verify()}.
229 + * @param WP_REQUEST|array $request The request object or $_SERVER array.
311 230 *
312 - * @param array $signature_block The signature block.
231 + * @return mixed A boolean or WP_Error.
232 + */
233 + public static function verify_http_signature( $request ) {
234 + if ( is_object( $request ) ) { // REST Request object
235 + // check if route starts with "index.php"
236 + if ( str_starts_with( $request->get_route(), '/index.php' ) || ! rest_get_url_prefix() ) {
237 + $route = $request->get_route();
238 + } else {
239 + $route = '/' . rest_get_url_prefix() . '/' . ltrim( $request->get_route(), '/' );
240 + }
241 + $headers = $request->get_headers();
242 + $headers['(request-target)'][0] = strtolower( $request->get_method() ) . ' ' . $route;
243 + } else {
244 + $request = self::format_server_request( $request );
245 + $headers = $request['headers']; // $_SERVER array
246 + $headers['(request-target)'][0] = strtolower( $headers['request_method'][0] ) . ' ' . $headers['request_uri'][0];
247 + }
248 +
249 + if ( ! isset( $headers['signature'] ) ) {
250 + return new WP_Error( 'activitypub_signature', 'Request not signed', array( 'status' => 403 ) );
251 + }
252 +
253 + if ( array_key_exists( 'signature', $headers ) ) {
254 + $signature_block = self::parse_signature_header( $headers['signature'][0] );
255 + } elseif ( array_key_exists( 'authorization', $headers ) ) {
256 + $signature_block = self::parse_signature_header( $headers['authorization'][0] );
257 + }
258 +
259 + if ( ! isset( $signature_block ) || ! $signature_block ) {
260 + return new WP_Error( 'activitypub_signature', 'Incompatible request signature. keyId and signature are required', array( 'status' => 403 ) );
261 + }
262 +
263 + $signed_headers = $signature_block['headers'];
264 + if ( ! $signed_headers ) {
265 + $signed_headers = array( 'date' );
266 + }
267 +
268 + $signed_data = self::get_signed_data( $signed_headers, $signature_block, $headers );
269 + if ( ! $signed_data ) {
270 + return new WP_Error( 'activitypub_signature', 'Signed request date outside acceptable time window', array( 'status' => 403 ) );
271 + }
272 +
273 + $algorithm = self::get_signature_algorithm( $signature_block );
274 + if ( ! $algorithm ) {
275 + return new WP_Error( 'activitypub_signature', 'Unsupported signature algorithm (only rsa-sha256 and hs2019 are supported)', array( 'status' => 403 ) );
276 + }
277 +
278 + if ( \in_array( 'digest', $signed_headers, true ) && isset( $body ) ) {
279 + if ( is_array( $headers['digest'] ) ) {
280 + $headers['digest'] = $headers['digest'][0];
281 + }
282 + $digest = explode( '=', $headers['digest'], 2 );
283 + if ( 'SHA-256' === $digest[0] ) {
284 + $hashalg = 'sha256';
285 + }
286 + if ( 'SHA-512' === $digest[0] ) {
287 + $hashalg = 'sha512';
288 + }
289 +
290 + if ( \base64_encode( \hash( $hashalg, $body, true ) ) !== $digest[1] ) { // phpcs:ignore
291 + return new WP_Error( 'activitypub_signature', 'Invalid Digest header', array( 'status' => 403 ) );
292 + }
293 + }
294 +
295 + $public_key = self::get_remote_key( $signature_block['keyId'] );
296 +
297 + if ( \is_wp_error( $public_key ) ) {
298 + return $public_key;
299 + }
300 +
301 + $verified = \openssl_verify( $signed_data, $signature_block['signature'], $public_key, $algorithm ) > 0;
302 +
303 + if ( ! $verified ) {
304 + return new WP_Error( 'activitypub_signature', 'Invalid signature', array( 'status' => 403 ) );
305 + }
306 + return $verified;
307 + }
308 +
309 + /**
310 + * Get public key from key_id
313 311 *
314 - * @return string|bool The signature algorithm or false if not found.
312 + * @param string $key_id The URL to the public key.
313 + *
314 + * @return WP_Error|string The public key.
315 315 */
316 - public static function get_signature_algorithm( $signature_block ) { // phpcs:ignore
317 - \_deprecated_function( __METHOD__, '7.0.0', self::class . '::verify' );
316 + public static function get_remote_key( $key_id ) { // phpcs:ignore
317 + $actor = get_remote_metadata_by_actor( strip_fragment_from_url( $key_id ) ); // phpcs:ignore
318 + if ( \is_wp_error( $actor ) ) {
319 + return $actor;
320 + }
321 + if ( isset( $actor['publicKey']['publicKeyPem'] ) ) {
322 + return \rtrim( $actor['publicKey']['publicKeyPem'] ); // phpcs:ignore
323 + }
324 + return new WP_Error( 'activitypub_no_remote_key_found', 'No Public-Key found' );
325 + }
318 326
319 - if ( ! empty( $signature_block['algorithm'] ) ) {
327 + /**
328 + * Gets the signature algorithm from the signature header
329 + *
330 + * @param array $signature_block
331 + *
332 + * @return string The signature algorithm.
333 + */
334 + public static function get_signature_algorithm( $signature_block ) {
335 + if ( $signature_block['algorithm'] ) {
320 336 switch ( $signature_block['algorithm'] ) {
321 337 case 'rsa-sha-512':
322 - return 'sha512'; // hs2019 https://datatracker.ietf.org/doc/html/draft-cavage-http-signatures-12.
338 + return 'sha512'; //hs2019 https://datatracker.ietf.org/doc/html/draft-cavage-http-signatures-12
323 339 default:
324 340 return 'sha256';
325 341 }
326 342 }
327 -
328 343 return false;
329 344 }
330 345
331 346 /**
332 - * Parses the Signature header.
347 + * Parses the Signature header
333 348 *
334 - * @deprecated 7.0.0 Use {@see Signature::verify()}.
335 - *
336 349 * @param string $signature The signature header.
337 350 *
338 - * @return array Signature parts.
351 + * @return array signature parts
339 352 */
340 - public static function parse_signature_header( $signature ) { // phpcs:ignore
341 - \_deprecated_function( __METHOD__, '7.0.0', self::class . '::verify' );
353 + public static function parse_signature_header( $signature ) {
354 + $parsed_header = array();
355 + $matches = array();
342 356
343 - $parsed_header = array();
344 - $matches = array();
345 -
346 357 if ( \preg_match( '/keyId="(.*?)"/ism', $signature, $matches ) ) {
347 358 $parsed_header['keyId'] = trim( $matches[1] );
348 359 }
349 - if ( \preg_match( '/created=["|\']*([0-9]*)["|\']*/ism', $signature, $matches ) ) {
360 + if ( \preg_match( '/created=([0-9]*)/ism', $signature, $matches ) ) {
350 361 $parsed_header['(created)'] = trim( $matches[1] );
351 362 }
352 - if ( \preg_match( '/expires=["|\']*([0-9]*)["|\']*/ism', $signature, $matches ) ) {
363 + if ( \preg_match( '/expires=([0-9]*)/ism', $signature, $matches ) ) {
353 364 $parsed_header['(expires)'] = trim( $matches[1] );
354 365 }
355 366 if ( \preg_match( '/algorithm="(.*?)"/ism', $signature, $matches ) ) {
356 367 $parsed_header['algorithm'] = trim( $matches[1] );
@@ -358,12 +369,12 @@
358 369 if ( \preg_match( '/headers="(.*?)"/ism', $signature, $matches ) ) {
359 370 $parsed_header['headers'] = \explode( ' ', trim( $matches[1] ) );
360 371 }
361 372 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
373 + $parsed_header['signature'] = \base64_decode( preg_replace( '/\s+/', '', trim( $matches[1] ) ) ); // phpcs:ignore
363 374 }
364 375
365 - if ( empty( $parsed_header['headers'] ) ) {
376 + if ( ( $parsed_header['signature'] ) && ( $parsed_header['algorithm'] ) && ( ! $parsed_header['headers'] ) ) {
366 377 $parsed_header['headers'] = array( 'date' );
367 378 }
368 379
369 380 return $parsed_header;
@@ -369,23 +380,18 @@
369 380 return $parsed_header;
370 381 }
371 382
372 383 /**
373 - * Gets the header data from the included pseudo headers.
384 + * Gets the header data from the included pseudo headers
374 385 *
375 - * @deprecated 7.0.0 Use {@see Signature::verify()}.
376 - *
377 386 * @param array $signed_headers The signed headers.
378 - * @param array $signature_block The signature block.
379 - * @param array $headers The HTTP headers.
387 + * @param array $signature_block (pseudo-headers)
388 + * @param array $headers (http headers)
380 389 *
381 390 * @return string signed headers for comparison
382 391 */
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 -
392 + public static function get_signed_data( $signed_headers, $signature_block, $headers ) {
386 393 $signed_data = '';
387 -
388 394 // This also verifies time-based values by returning false if any of these are out of range.
389 395 foreach ( $signed_headers as $header ) {
390 396 if ( 'host' === $header ) {
391 397 if ( isset( $headers['x_original_host'] ) ) {
@@ -402,166 +408,71 @@
402 408 continue;
403 409 }
404 410 if ( '(created)' === $header ) {
405 411 if ( ! empty( $signature_block['(created)'] ) && \intval( $signature_block['(created)'] ) > \time() ) {
406 - // Created in the future.
412 + // created in future
407 413 return false;
408 414 }
409 -
410 - if ( ! array_key_exists( '(created)', $headers ) ) {
411 - $signed_data .= $header . ': ' . $signature_block['(created)'] . "\n";
412 - continue;
413 - }
414 415 }
415 416 if ( '(expires)' === $header ) {
416 417 if ( ! empty( $signature_block['(expires)'] ) && \intval( $signature_block['(expires)'] ) < \time() ) {
417 - // Expired in the past.
418 + // expired in past
418 419 return false;
419 420 }
420 -
421 - if ( ! array_key_exists( '(expires)', $headers ) ) {
422 - $signed_data .= $header . ': ' . $signature_block['(expires)'] . "\n";
423 - continue;
424 - }
425 421 }
426 422 if ( 'date' === $header ) {
427 - // A signed `date` header with no value must fail closed, otherwise the time-window check is skipped.
428 - if ( empty( $headers[ $header ][0] ) ) {
429 - return false;
430 - }
423 + // allow a bit of leeway for misconfigured clocks.
424 + $d = new DateTime( $headers[ $header ][0] );
425 + $d->setTimeZone( new DateTimeZone( 'UTC' ) );
426 + $c = $d->format( 'U' );
431 427
432 - // date_create() returns false on malformed input; new DateTime() would instead throw.
433 - $d = \date_create( $headers[ $header ][0], new \DateTimeZone( 'UTC' ) );
434 - if ( false === $d ) {
435 - return false;
436 - }
437 - $d->setTimeZone( new \DateTimeZone( 'UTC' ) );
438 - $c = (int) $d->format( 'U' );
428 + $dplus = time() + ( 3 * HOUR_IN_SECONDS );
429 + $dminus = time() - ( 3 * HOUR_IN_SECONDS );
439 430
440 - // Match the past-skew of the maintained Http_Signature_Draft verifier (1 hour); use its 5-minute future allowance.
441 - $now = \time();
442 - $d_plus = $now + ( 5 * MINUTE_IN_SECONDS );
443 - $d_minus = $now - HOUR_IN_SECONDS;
444 -
445 - if ( $c > $d_plus || $c < $d_minus ) {
446 - // Time out of range.
431 + if ( $c > $dplus || $c < $dminus ) {
432 + // time out of range
447 433 return false;
448 434 }
449 435 }
450 -
451 - if ( ! empty( $headers[ $header ][0] ) ) {
452 - $signed_data .= $header . ': ' . $headers[ $header ][0] . "\n";
453 - }
436 + $signed_data .= $header . ': ' . $headers[ $header ][0] . "\n";
454 437 }
455 -
456 438 return \rtrim( $signed_data, "\n" );
457 439 }
458 440
459 441 /**
460 - * Generates the digest for an HTTP Request.
442 + * Generates the digest for a HTTP Request
461 443 *
462 - * @deprecated 7.0.0 Use {@see Signature::sign_request()}.
463 - *
464 444 * @param string $body The body of the request.
465 445 *
466 446 * @return string The digest.
467 447 */
468 448 public static function generate_digest( $body ) {
469 - \_deprecated_function( __METHOD__, '7.0.0', self::class . '::sign_request' );
470 -
471 - $digest = \base64_encode( \hash( 'sha256', $body, true ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
449 + $digest = \base64_encode( \hash( 'sha256', $body, true ) ); // phpcs:ignore
472 450 return "SHA-256=$digest";
473 451 }
474 452
475 453 /**
476 - * Compute the collection digest for a specific instance.
454 + * Formats the $_SERVER to resemble the WP_REST_REQUEST array,
455 + * for use with verify_http_signature()
477 456 *
478 - * Implements FEP-8fcf: Followers collection synchronization.
479 - * The digest is created by XORing together the individual SHA256 digests
480 - * of each follower's ID.
457 + * @param array $_SERVER The $_SERVER array.
481 458 *
482 - * @see https://codeberg.org/fediverse/fep/src/branch/main/fep/8fcf/fep-8fcf.md
483 - *
484 - * @param array $collection The user ID whose followers to compute.
485 - *
486 - * @return string|false The hex-encoded digest, or false if no followers.
459 + * @return array $request The formatted request array.
487 460 */
488 - public static function get_collection_digest( $collection ) {
489 - if ( empty( $collection ) || ! is_array( $collection ) ) {
490 - return false;
491 - }
492 -
493 - // Initialize with zeros (64 hex chars = 32 bytes = 256 bits).
494 - $digest = str_repeat( '0', 64 );
495 -
496 - foreach ( $collection as $item ) {
497 - // Compute SHA256 hash of the follower ID.
498 - $hash = hash( 'sha256', $item );
499 -
500 - // XOR the hash with the running digest.
501 - $digest = self::xor_hex_strings( $digest, $hash );
502 - }
503 -
504 - return $digest;
505 - }
506 -
507 - /**
508 - * XOR two hexadecimal strings.
509 - *
510 - * Used for FEP-8fcf digest computation.
511 - *
512 - * @param string $hex1 First hex string.
513 - * @param string $hex2 Second hex string.
514 - *
515 - * @return string The XORed result as a hex string.
516 - */
517 - public static function xor_hex_strings( $hex1, $hex2 ) {
518 - $result = '';
519 -
520 - // Ensure both strings are the same length (should be 64 chars for SHA256).
521 - $length = \max( \strlen( $hex1 ), \strlen( $hex2 ) );
522 - $hex1 = \str_pad( $hex1, $length, '0', STR_PAD_LEFT );
523 - $hex2 = \str_pad( $hex2, $length, '0', STR_PAD_LEFT );
524 -
525 - // XOR each pair of hex digits.
526 - for ( $i = 0; $i < $length; $i += 2 ) {
527 - $byte1 = \hexdec( \substr( $hex1, $i, 2 ) );
528 - $byte2 = \hexdec( \substr( $hex2, $i, 2 ) );
529 - $result .= \str_pad( \dechex( $byte1 ^ $byte2 ), 2, '0', STR_PAD_LEFT );
530 - }
531 -
532 - return $result;
533 - }
534 -
535 - /**
536 - * Parse a Collection-Synchronization header (FEP-8fcf).
537 - *
538 - * Parses the signature-style format used by the Collection-Synchronization header.
539 - *
540 - * @see https://codeberg.org/fediverse/fep/src/branch/main/fep/8fcf/fep-8fcf.md
541 - *
542 - * @param string $header The header value.
543 - *
544 - * @return array|false Array with parsed parameters (collectionId, url, digest), or false on failure.
545 - */
546 - public static function parse_collection_sync_header( $header ) {
547 - if ( empty( $header ) ) {
548 - return false;
549 - }
550 -
551 - // Parse the signature-style format: key="value", key="value".
552 - $params = array();
553 -
554 - if ( \preg_match_all( '/(\w+)="([^"]*)"/', $header, $matches, PREG_SET_ORDER ) ) {
555 - foreach ( $matches as $match ) {
556 - $params[ $match[1] ] = $match[2];
461 + public static function format_server_request( $server ) {
462 + $request = array();
463 + foreach ( $server as $param_key => $param_val ) {
464 + $req_param = strtolower( $param_key );
465 + if ( 'REQUEST_URI' === $req_param ) {
466 + $request['headers']['route'][] = $param_val;
467 + } else {
468 + $header_key = str_replace(
469 + 'http_',
470 + '',
471 + $req_param
472 + );
473 + $request['headers'][ $header_key ][] = \wp_unslash( $param_val );
557 474 }
558 475 }
559 -
560 - // Validate required fields for FEP-8fcf.
561 - if ( empty( $params['collectionId'] ) || empty( $params['url'] ) || empty( $params['digest'] ) ) {
562 - return false;
563 - }
564 -
565 - return $params;
476 + return $request;
566 477 }
567 478 }