wordpress-activitypub/includes/class-signature.php

408 lines
12 KiB
PHP
Raw Normal View History

<?php
namespace Activitypub;
2023-05-09 11:51:53 +02:00
use WP_Error;
2023-04-02 07:59:49 +02:00
use DateTime;
use DateTimeZone;
2023-05-15 10:48:34 +02:00
use Activitypub\Model\User;
2023-07-03 11:20:44 +02:00
use Activitypub\Collection\Users;
2022-02-28 23:52:30 +01:00
2019-02-24 13:01:28 +01:00
/**
* ActivityPub Signature Class
*
* @author Matthias Pfefferle
2023-05-12 10:17:36 +02:00
* @author Django Doucet
2019-02-24 13:01:28 +01:00
*/
class Signature {
2018-12-08 00:02:18 +01:00
/**
2023-05-12 10:17:36 +02:00
* Return the public key for a given user.
*
2023-05-12 10:17:36 +02:00
* @param int $user_id The WordPress User ID.
* @param bool $force Force the generation of a new key pair.
*
* @return mixed The public key.
*/
public static function get_public_key( $user_id, $force = false ) {
if ( $force ) {
self::generate_key_pair( $user_id );
}
2023-05-15 10:48:34 +02:00
if ( User::APPLICATION_USER_ID === $user_id ) {
2023-05-09 11:32:26 +02:00
$key = \get_option( 'activitypub_magic_sig_public_key' );
} else {
2023-05-09 11:32:26 +02:00
$key = \get_user_meta( $user_id, 'magic_sig_public_key', true );
}
2023-05-09 12:12:05 +02:00
if ( ! $key ) {
2023-05-09 12:17:48 +02:00
return self::get_public_key( $user_id, true );
2023-05-09 12:12:05 +02:00
}
2023-05-09 11:32:26 +02:00
return $key;
}
/**
2023-05-12 10:17:36 +02:00
* Return the private key for a given user.
*
* @param int $user_id The WordPress User ID.
* @param bool $force Force the generation of a new key pair.
*
2023-05-12 10:17:36 +02:00
* @return mixed The private key.
*/
public static function get_private_key( $user_id, $force = false ) {
if ( $force ) {
self::generate_key_pair( $user_id );
}
2023-05-15 10:48:34 +02:00
if ( User::APPLICATION_USER_ID === $user_id ) {
2023-05-05 21:00:21 +02:00
$key = \get_option( 'activitypub_magic_sig_private_key' );
} else {
2023-05-09 11:32:26 +02:00
$key = \get_user_meta( $user_id, 'magic_sig_private_key', true );
}
2023-05-09 12:12:05 +02:00
if ( ! $key ) {
2023-05-09 12:17:48 +02:00
return self::get_private_key( $user_id, true );
2023-05-09 12:12:05 +02:00
}
2023-05-09 11:32:26 +02:00
return $key;
}
/**
* Generates the pair keys
*
2023-05-12 10:17:36 +02:00
* @param int $user_id The WordPress User ID.
*
* @return void
*/
2023-05-31 10:31:49 +02:00
public static function generate_key_pair() {
$config = array(
'digest_alg' => 'sha512',
'private_key_bits' => 2048,
'private_key_type' => \OPENSSL_KEYTYPE_RSA,
);
2019-09-27 10:12:59 +02:00
$key = \openssl_pkey_new( $config );
$priv_key = null;
2019-09-27 10:12:59 +02:00
\openssl_pkey_export( $key, $priv_key );
2023-05-31 10:31:49 +02:00
$detail = \openssl_pkey_get_details( $key );
2023-05-31 10:31:49 +02:00
return array(
'private_key' => $priv_key,
'public_key' => $detail['key'],
);
}
2023-05-12 10:17:36 +02:00
/**
* Generates the Signature for a HTTP Request
*
* @param int $user_id The WordPress User ID.
* @param string $http_method The HTTP method.
* @param string $url The URL to send the request to.
* @param string $date The date the request is sent.
* @param string $digest The digest of the request body.
*
* @return string The signature.
*/
public static function generate_signature( $user_id, $http_method, $url, $date, $digest = null ) {
2023-07-03 11:20:44 +02:00
$user = Users::get_by_id( $user_id );
$key = $user->get__private_key();
2019-09-27 10:12:59 +02:00
$url_parts = \wp_parse_url( $url );
$host = $url_parts['host'];
$path = '/';
// add path
if ( ! empty( $url_parts['path'] ) ) {
2018-12-08 00:02:18 +01:00
$path = $url_parts['path'];
}
// add query
if ( ! empty( $url_parts['query'] ) ) {
$path .= '?' . $url_parts['query'];
}
2023-06-01 09:49:40 +02:00
$http_method = \strtolower( $http_method );
2020-12-10 04:23:05 +01:00
if ( ! empty( $digest ) ) {
2023-06-01 09:49:40 +02:00
$signed_string = "(request-target): $http_method $path\nhost: $host\ndate: $date\ndigest: $digest";
2020-12-10 04:23:05 +01:00
} else {
$signed_string = "(request-target): $http_method $path\nhost: $host\ndate: $date";
2020-12-10 04:23:05 +01:00
}
$signature = null;
\openssl_sign( $signed_string, $signature, $key, \OPENSSL_ALGO_SHA256 );
2019-09-27 10:12:59 +02:00
$signature = \base64_encode( $signature ); // phpcs:ignore
2023-07-03 11:20:44 +02:00
$user = Users::get_by_id( $user_id );
2023-06-01 11:50:01 +02:00
$key_id = $user->get_url() . '#main-key';
2020-12-10 04:23:05 +01:00
if ( ! empty( $digest ) ) {
return \sprintf( 'keyId="%s",algorithm="rsa-sha256",headers="(request-target) host date digest",signature="%s"', $key_id, $signature );
} else {
return \sprintf( 'keyId="%s",algorithm="rsa-sha256",headers="(request-target) host date",signature="%s"', $key_id, $signature );
}
}
2023-04-21 23:27:02 +02:00
/**
* Verifies the http signatures
*
2023-05-12 10:17:36 +02:00
* @param WP_REQUEST|array $request The request object or $_SERVER array.
*
* @return mixed A boolean or WP_Error.
2023-04-21 23:27:02 +02:00
*/
public static function verify_http_signature( $request ) {
2023-05-05 21:00:21 +02:00
if ( is_object( $request ) ) { // REST Request object
2023-06-01 10:13:49 +02:00
// check if route starts with "index.php"
if ( str_starts_with( $request->get_route(), '/index.php' ) || ! rest_get_url_prefix() ) {
2023-06-01 10:13:49 +02:00
$route = $request->get_route();
} else {
2023-06-01 10:25:18 +02:00
$route = '/' . rest_get_url_prefix() . '/' . ltrim( $request->get_route(), '/' );
2023-06-01 10:13:49 +02:00
}
2023-05-05 21:00:21 +02:00
$headers = $request->get_headers();
$actor = isset( json_decode( $request->get_body() )->actor ) ? json_decode( $request->get_body() )->actor : '';
2023-06-01 10:13:49 +02:00
$headers['(request-target)'][0] = strtolower( $request->get_method() ) . ' ' . $route;
2023-05-05 21:00:21 +02:00
} else {
$request = self::format_server_request( $request );
$headers = $request['headers']; // $_SERVER array
$actor = null;
2023-05-05 21:00:21 +02:00
$headers['(request-target)'][0] = strtolower( $headers['request_method'][0] ) . ' ' . $headers['request_uri'][0];
}
2023-04-01 18:17:56 +02:00
2023-05-05 21:00:21 +02:00
if ( ! isset( $headers['signature'] ) ) {
2023-05-09 11:51:53 +02:00
return new WP_Error( 'activitypub_signature', 'Request not signed', array( 'status' => 403 ) );
2023-04-01 18:17:56 +02:00
}
2023-04-21 17:18:24 +02:00
2023-04-01 18:17:56 +02:00
if ( array_key_exists( 'signature', $headers ) ) {
$signature_block = self::parse_signature_header( $headers['signature'] );
} elseif ( array_key_exists( 'authorization', $headers ) ) {
$signature_block = self::parse_signature_header( $headers['authorization'] );
}
2023-04-15 07:53:43 +02:00
if ( ! isset( $signature_block ) || ! $signature_block ) {
2023-05-09 11:51:53 +02:00
return new WP_Error( 'activitypub_signature', 'Incompatible request signature. keyId and signature are required', array( 'status' => 403 ) );
2023-04-01 18:17:56 +02:00
}
$signed_headers = $signature_block['headers'];
if ( ! $signed_headers ) {
2023-04-02 07:59:49 +02:00
$signed_headers = array( 'date' );
2023-04-01 18:17:56 +02:00
}
$signed_data = self::get_signed_data( $signed_headers, $signature_block, $headers );
if ( ! $signed_data ) {
2023-05-09 11:51:53 +02:00
return new WP_Error( 'activitypub_signature', 'Signed request date outside acceptable time window', array( 'status' => 403 ) );
2023-04-01 18:17:56 +02:00
}
$algorithm = self::get_signature_algorithm( $signature_block );
if ( ! $algorithm ) {
2023-05-09 11:51:53 +02:00
return new WP_Error( 'activitypub_signature', 'Unsupported signature algorithm (only rsa-sha256 and hs2019 are supported)', array( 'status' => 403 ) );
2023-04-01 18:17:56 +02:00
}
2023-04-02 07:59:49 +02:00
if ( \in_array( 'digest', $signed_headers, true ) && isset( $body ) ) {
2023-04-15 07:53:43 +02:00
if ( is_array( $headers['digest'] ) ) {
$headers['digest'] = $headers['digest'][0];
}
2023-04-01 18:17:56 +02:00
$digest = explode( '=', $headers['digest'], 2 );
2023-04-02 07:59:49 +02:00
if ( 'SHA-256' === $digest[0] ) {
2023-04-01 18:17:56 +02:00
$hashalg = 'sha256';
}
2023-04-02 07:59:49 +02:00
if ( 'SHA-512' === $digest[0] ) {
2023-04-01 18:17:56 +02:00
$hashalg = 'sha512';
2022-02-28 23:52:30 +01:00
}
2022-03-01 03:32:26 +01:00
2023-04-02 07:59:49 +02:00
if ( \base64_encode( \hash( $hashalg, $body, true ) ) !== $digest[1] ) { // phpcs:ignore
2023-05-09 11:51:53 +02:00
return new WP_Error( 'activitypub_signature', 'Invalid Digest header', array( 'status' => 403 ) );
}
2023-04-01 18:17:56 +02:00
}
if ( $actor ) {
$public_key = self::get_remote_key( $actor );
} else {
$public_key = self::get_remote_key( $signature_block['keyId'] );
}
if ( \is_wp_error( $public_key ) ) {
return $public_key;
}
2023-06-01 09:49:40 +02:00
2023-04-22 00:16:52 +02:00
$verified = \openssl_verify( $signed_data, $signature_block['signature'], $public_key, $algorithm ) > 0;
2023-06-01 09:49:40 +02:00
2023-04-22 00:16:52 +02:00
if ( ! $verified ) {
2023-05-09 11:51:53 +02:00
return new WP_Error( 'activitypub_signature', 'Invalid signature', array( 'status' => 403 ) );
2023-04-22 00:16:52 +02:00
}
2023-05-05 21:00:21 +02:00
return $verified;
2023-04-01 18:17:56 +02:00
}
2023-05-06 07:54:29 +02:00
/**
* Get public key from key_id
*
2023-06-01 11:05:47 +02:00
* @param string $key_id The URL to the public key.
2023-05-12 10:17:36 +02:00
*
2023-06-01 11:05:47 +02:00
* @return string The public key.
2023-05-06 07:54:29 +02:00
*/
public static function get_remote_key( $key_id ) { // phpcs:ignore
$actor = get_remote_metadata_by_actor( strtok( strip_fragment_from_url( $key_id ), '?' ) ); // phpcs:ignore
2023-05-06 07:54:29 +02:00
if ( \is_wp_error( $actor ) ) {
return $actor;
}
if ( isset( $actor['publicKey']['publicKeyPem'] ) ) {
return \rtrim( $actor['publicKey']['publicKeyPem'] ); // phpcs:ignore
}
return null;
}
2023-04-21 23:27:02 +02:00
/**
* Gets the signature algorithm from the signature header
*
* @param array $signature_block
2023-05-12 10:17:36 +02:00
*
2023-06-01 11:05:47 +02:00
* @return string The signature algorithm.
2023-04-21 23:27:02 +02:00
*/
2023-04-01 18:17:56 +02:00
public static function get_signature_algorithm( $signature_block ) {
2023-04-21 17:36:17 +02:00
if ( $signature_block['algorithm'] ) {
switch ( $signature_block['algorithm'] ) {
case 'rsa-sha-512':
return 'sha512'; //hs2019 https://datatracker.ietf.org/doc/html/draft-cavage-http-signatures-12
default:
return 'sha256';
}
2023-04-01 18:17:56 +02:00
}
return false;
2022-02-28 23:52:30 +01:00
}
2023-04-21 23:27:02 +02:00
/**
* Parses the Signature header
*
2023-06-01 11:05:47 +02:00
* @param array $header The signature header.
2023-05-12 10:17:36 +02:00
*
2023-04-21 23:27:02 +02:00
* @return array signature parts
*/
2023-04-01 18:17:56 +02:00
public static function parse_signature_header( $header ) {
2023-06-01 11:05:47 +02:00
$parsed_header = array();
$matches = array();
$h_string = \implode( ',', (array) $header[0] );
2022-02-28 23:52:30 +01:00
2023-04-02 07:59:49 +02:00
if ( \preg_match( '/keyId="(.*?)"/ism', $h_string, $matches ) ) {
2023-06-01 11:05:47 +02:00
$parsed_header['keyId'] = $matches[1];
2023-04-01 18:17:56 +02:00
}
2023-04-02 07:59:49 +02:00
if ( \preg_match( '/created=([0-9]*)/ism', $h_string, $matches ) ) {
2023-06-01 11:05:47 +02:00
$parsed_header['(created)'] = $matches[1];
2023-04-01 18:17:56 +02:00
}
2023-04-02 07:59:49 +02:00
if ( \preg_match( '/expires=([0-9]*)/ism', $h_string, $matches ) ) {
2023-06-01 11:05:47 +02:00
$parsed_header['(expires)'] = $matches[1];
2023-04-01 18:17:56 +02:00
}
2023-04-02 07:59:49 +02:00
if ( \preg_match( '/algorithm="(.*?)"/ism', $h_string, $matches ) ) {
2023-06-01 11:05:47 +02:00
$parsed_header['algorithm'] = $matches[1];
2023-04-01 18:17:56 +02:00
}
2023-04-02 07:59:49 +02:00
if ( \preg_match( '/headers="(.*?)"/ism', $h_string, $matches ) ) {
2023-06-01 11:05:47 +02:00
$parsed_header['headers'] = \explode( ' ', $matches[1] );
2023-04-01 18:17:56 +02:00
}
2023-04-02 07:59:49 +02:00
if ( \preg_match( '/signature="(.*?)"/ism', $h_string, $matches ) ) {
2023-06-01 11:05:47 +02:00
$parsed_header['signature'] = \base64_decode( preg_replace( '/\s+/', '', $matches[1] ) ); // phpcs:ignore
2022-02-28 23:52:30 +01:00
}
2023-06-01 11:05:47 +02:00
if ( ( $parsed_header['signature'] ) && ( $parsed_header['algorithm'] ) && ( ! $parsed_header['headers'] ) ) {
$parsed_header['headers'] = array( 'date' );
2022-02-28 23:52:30 +01:00
}
2023-06-01 11:05:47 +02:00
return $parsed_header;
2023-04-01 18:17:56 +02:00
}
2023-04-21 23:27:02 +02:00
/**
* Gets the header data from the included pseudo headers
*
* @param array $signed_headers
* @param array $signature_block (pseudo-headers)
2023-05-12 10:17:36 +02:00
* @param array $headers (http headers)
*
2023-06-01 11:05:47 +02:00
* @return string signed headers for comparison
2023-04-21 23:27:02 +02:00
*/
2023-04-01 18:17:56 +02:00
public static function get_signed_data( $signed_headers, $signature_block, $headers ) {
$signed_data = '';
// This also verifies time-based values by returning false if any of these are out of range.
foreach ( $signed_headers as $header ) {
if ( 'host' === $header ) {
if ( isset( $headers['x_original_host'] ) ) {
$signed_data .= $header . ': ' . $headers['x_original_host'][0] . "\n";
continue;
2023-04-01 18:17:56 +02:00
}
}
if ( '(request-target)' === $header ) {
$signed_data .= $header . ': ' . $headers[ $header ][0] . "\n";
continue;
}
if ( str_contains( $header, '-' ) ) {
$signed_data .= $header . ': ' . $headers[ str_replace( '-', '_', $header ) ][0] . "\n";
continue;
}
2023-04-02 07:59:49 +02:00
if ( '(created)' === $header ) {
2023-04-02 08:30:17 +02:00
if ( ! empty( $signature_block['(created)'] ) && \intval( $signature_block['(created)'] ) > \time() ) {
2023-04-01 18:17:56 +02:00
// created in future
return false;
}
}
2023-04-02 07:59:49 +02:00
if ( '(expires)' === $header ) {
if ( ! empty( $signature_block['(expires)'] ) && \intval( $signature_block['(expires)'] ) < \time() ) {
2023-04-01 18:17:56 +02:00
// expired in past
return false;
}
2023-05-25 14:03:30 +02:00
}
2023-04-02 07:59:49 +02:00
if ( 'date' === $header ) {
2023-04-01 18:17:56 +02:00
// allow a bit of leeway for misconfigured clocks.
2023-04-02 07:59:49 +02:00
$d = new DateTime( $headers[ $header ][0] );
$d->setTimeZone( new DateTimeZone( 'UTC' ) );
$c = $d->format( 'U' );
2023-04-01 18:17:56 +02:00
2023-04-02 07:59:49 +02:00
$dplus = time() + ( 3 * HOUR_IN_SECONDS );
$dminus = time() - ( 3 * HOUR_IN_SECONDS );
2023-04-01 18:17:56 +02:00
if ( $c > $dplus || $c < $dminus ) {
// time out of range
return false;
}
}
$signed_data .= $header . ': ' . $headers[ $header ][0] . "\n";
2023-04-01 18:17:56 +02:00
}
2023-04-02 07:59:49 +02:00
return \rtrim( $signed_data, "\n" );
}
2020-12-10 04:23:05 +01:00
2023-06-01 11:05:47 +02:00
/**
* Generates the digest for a HTTP Request
*
* @param string $body The body of the request.
*
* @return string The digest.
*/
2020-12-10 04:23:05 +01:00
public static function generate_digest( $body ) {
2020-12-17 17:39:35 +01:00
$digest = \base64_encode( \hash( 'sha256', $body, true ) ); // phpcs:ignore
2023-06-01 09:49:40 +02:00
return "SHA-256=$digest";
2020-12-10 04:23:05 +01:00
}
2023-05-05 20:53:43 +02:00
/**
* Formats the $_SERVER to resemble the WP_REST_REQUEST array,
* for use with verify_http_signature()
*
2023-06-01 11:05:47 +02:00
* @param array $_SERVER The $_SERVER array.
2023-05-12 10:17:36 +02:00
*
2023-06-01 11:05:47 +02:00
* @return array $request The formatted request array.
2023-05-05 20:53:43 +02:00
*/
public static function format_server_request( $server ) {
$request = array();
foreach ( $server as $param_key => $param_val ) {
$req_param = strtolower( $param_key );
if ( 'REQUEST_URI' === $req_param ) {
$request['headers']['route'][] = $param_val;
} else {
$header_key = str_replace(
'http_',
'',
$req_param
);
$request['headers'][ $header_key ][] = \wp_unslash( $param_val );
}
}
return $request;
}
}