Merge pull request #299 from mediaformat/signature_verification

Signature verification
This commit is contained in:
Matthias Pfefferle 2023-06-01 11:21:33 +02:00 committed by GitHub
commit bfe5381d99
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
10 changed files with 602 additions and 105 deletions

View file

@ -27,6 +27,7 @@ function init() {
\defined( 'ACTIVITYPUB_HASHTAGS_REGEXP' ) || \define( 'ACTIVITYPUB_HASHTAGS_REGEXP', '(?:(?<=\s)|(?<=<p>)|(?<=<br>)|^)#([A-Za-z0-9_]+)(?:(?=\s|[[:punct:]]|$))' ); \defined( 'ACTIVITYPUB_HASHTAGS_REGEXP' ) || \define( 'ACTIVITYPUB_HASHTAGS_REGEXP', '(?:(?<=\s)|(?<=<p>)|(?<=<br>)|^)#([A-Za-z0-9_]+)(?:(?=\s|[[:punct:]]|$))' );
\defined( 'ACTIVITYPUB_USERNAME_REGEXP' ) || \define( 'ACTIVITYPUB_USERNAME_REGEXP', '(?:([A-Za-z0-9_-]+)@((?:[A-Za-z0-9_-]+\.)+[A-Za-z]+))' ); \defined( 'ACTIVITYPUB_USERNAME_REGEXP' ) || \define( 'ACTIVITYPUB_USERNAME_REGEXP', '(?:([A-Za-z0-9_-]+)@((?:[A-Za-z0-9_-]+\.)+[A-Za-z]+))' );
\defined( 'ACTIVITYPUB_CUSTOM_POST_CONTENT' ) || \define( 'ACTIVITYPUB_CUSTOM_POST_CONTENT', "<strong>[ap_title]</strong>\n\n[ap_content]\n\n[ap_hashtags]\n\n[ap_shortlink]" ); \defined( 'ACTIVITYPUB_CUSTOM_POST_CONTENT' ) || \define( 'ACTIVITYPUB_CUSTOM_POST_CONTENT', "<strong>[ap_title]</strong>\n\n[ap_content]\n\n[ap_hashtags]\n\n[ap_shortlink]" );
\defined( 'ACTIVITYPUB_SECURE_MODE' ) || \define( 'ACTIVITYPUB_SECURE_MODE', apply_filters( 'activitypub_secure_mode', $value = false ) );
\define( 'ACTIVITYPUB_PLUGIN_DIR', plugin_dir_path( __FILE__ ) ); \define( 'ACTIVITYPUB_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
\define( 'ACTIVITYPUB_PLUGIN_BASENAME', plugin_basename( __FILE__ ) ); \define( 'ACTIVITYPUB_PLUGIN_BASENAME', plugin_basename( __FILE__ ) );
@ -43,6 +44,7 @@ function init() {
Rest\Followers::init(); Rest\Followers::init();
Rest\Following::init(); Rest\Following::init();
Rest\Webfinger::init(); Rest\Webfinger::init();
Rest\Server::init();
Admin::init(); Admin::init();
Hashtag::init(); Hashtag::init();

View file

@ -1,6 +1,8 @@
<?php <?php
namespace Activitypub; namespace Activitypub;
use Activitypub\Signature;
/** /**
* ActivityPub Class * ActivityPub Class
* *
@ -87,34 +89,14 @@ class Activitypub {
$json_template = ACTIVITYPUB_PLUGIN_DIR . '/templates/blog-json.php'; $json_template = ACTIVITYPUB_PLUGIN_DIR . '/templates/blog-json.php';
} }
global $wp_query; if ( is_activitypub_request() ) {
if ( ACTIVITYPUB_SECURE_MODE ) {
if ( isset( $wp_query->query_vars['activitypub'] ) ) { $verification = Signature::verify_http_signature( $_SERVER );
return $json_template; if ( \is_wp_error( $verification ) ) {
} // fallback as template_loader can't return http headers
return $template;
if ( ! isset( $_SERVER['HTTP_ACCEPT'] ) ) { }
return $template; }
}
$accept_header = $_SERVER['HTTP_ACCEPT'];
if (
\stristr( $accept_header, 'application/activity+json' ) ||
\stristr( $accept_header, 'application/ld+json' )
) {
return $json_template;
}
// Accept header as an array.
$accept = \explode( ',', \trim( $accept_header ) );
if (
\in_array( 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"', $accept, true ) ||
\in_array( 'application/activity+json', $accept, true ) ||
\in_array( 'application/ld+json', $accept, true ) ||
\in_array( 'application/json', $accept, true )
) {
return $json_template; return $json_template;
} }

View file

@ -2,6 +2,7 @@
namespace Activitypub; namespace Activitypub;
use WP_Error; use WP_Error;
use Activitypub\Model\User;
/** /**
* ActivityPub HTTP Class * ActivityPub HTTP Class
@ -33,7 +34,7 @@ class Http {
'headers' => array( 'headers' => array(
'Accept' => 'application/activity+json', 'Accept' => 'application/activity+json',
'Content-Type' => 'application/activity+json', 'Content-Type' => 'application/activity+json',
'Digest' => "SHA-256=$digest", 'Digest' => $digest,
'Signature' => $signature, 'Signature' => $signature,
'Date' => $date, 'Date' => $date,
), ),
@ -60,9 +61,9 @@ class Http {
* *
* @return array|WP_Error The GET Response or an WP_ERROR * @return array|WP_Error The GET Response or an WP_ERROR
*/ */
public static function get( $url, $user_id ) { public static function get( $url ) {
$date = \gmdate( 'D, d M Y H:i:s T' ); $date = \gmdate( 'D, d M Y H:i:s T' );
$signature = Signature::generate_signature( $user_id, 'get', $url, $date ); $signature = Signature::generate_signature( User::APPLICATION_USER_ID, 'get', $url, $date );
$wp_version = \get_bloginfo( 'version' ); $wp_version = \get_bloginfo( 'version' );
$user_agent = \apply_filters( 'http_headers_useragent', 'WordPress/' . $wp_version . '; ' . \get_bloginfo( 'url' ) ); $user_agent = \apply_filters( 'http_headers_useragent', 'WordPress/' . $wp_version . '; ' . \get_bloginfo( 'url' ) );
@ -86,7 +87,7 @@ class Http {
$response = new WP_Error( $code, __( 'Failed HTTP Request', 'activitypub' ) ); $response = new WP_Error( $code, __( 'Failed HTTP Request', 'activitypub' ) );
} }
\do_action( 'activitypub_safe_remote_get_response', $response, $url, $user_id ); \do_action( 'activitypub_safe_remote_get_response', $response, $url );
return $response; return $response;
} }

View file

@ -1,53 +1,77 @@
<?php <?php
namespace Activitypub; namespace Activitypub;
use WP_Error;
use DateTime;
use DateTimeZone;
use Activitypub\Model\User;
/** /**
* ActivityPub Signature Class * ActivityPub Signature Class
* *
* @author Matthias Pfefferle * @author Matthias Pfefferle
* @author Django Doucet
*/ */
class Signature { class Signature {
/** /**
* @param int $user_id * Return the public key for a given user.
* *
* @return mixed * @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 ) { public static function get_public_key( $user_id, $force = false ) {
$key = \get_user_meta( $user_id, 'magic_sig_public_key' ); if ( $force ) {
self::generate_key_pair( $user_id );
if ( $key && ! $force ) {
return $key[0];
} }
self::generate_key_pair( $user_id ); if ( User::APPLICATION_USER_ID === $user_id ) {
$key = \get_user_meta( $user_id, 'magic_sig_public_key' ); $key = \get_option( 'activitypub_magic_sig_public_key' );
} else {
$key = \get_user_meta( $user_id, 'magic_sig_public_key', true );
}
return $key[0]; if ( ! $key ) {
return self::get_public_key( $user_id, true );
}
return $key;
} }
/** /**
* @param int $user_id * Return the private key for a given user.
* *
* @return mixed * @param int $user_id The WordPress User ID.
* @param bool $force Force the generation of a new key pair.
*
* @return mixed The private key.
*/ */
public static function get_private_key( $user_id, $force = false ) { public static function get_private_key( $user_id, $force = false ) {
$key = \get_user_meta( $user_id, 'magic_sig_private_key' ); if ( $force ) {
self::generate_key_pair( $user_id );
if ( $key && ! $force ) {
return $key[0];
} }
self::generate_key_pair( $user_id ); if ( User::APPLICATION_USER_ID === $user_id ) {
$key = \get_user_meta( $user_id, 'magic_sig_private_key' ); $key = \get_option( 'activitypub_magic_sig_private_key' );
} else {
$key = \get_user_meta( $user_id, 'magic_sig_private_key', true );
}
return $key[0]; if ( ! $key ) {
return self::get_private_key( $user_id, true );
}
return $key;
} }
/** /**
* Generates the pair keys * Generates the pair keys
* *
* @param int $user_id * @param int $user_id The WordPress User ID.
*
* @return void
*/ */
public static function generate_key_pair( $user_id ) { public static function generate_key_pair( $user_id ) {
$config = array( $config = array(
@ -60,16 +84,35 @@ class Signature {
$priv_key = null; $priv_key = null;
\openssl_pkey_export( $key, $priv_key ); \openssl_pkey_export( $key, $priv_key );
// private key
\update_user_meta( $user_id, 'magic_sig_private_key', $priv_key );
$detail = \openssl_pkey_get_details( $key ); $detail = \openssl_pkey_get_details( $key );
// public key if ( User::APPLICATION_USER_ID === $user_id ) {
\update_user_meta( $user_id, 'magic_sig_public_key', $detail['key'] ); // private key
\update_option( 'activitypub_magic_sig_private_key', $priv_key );
// public key
\update_option( 'activitypub_magic_sig_public_key', $detail['key'] );
} else {
// private key
\update_user_meta( $user_id, 'magic_sig_private_key', $priv_key );
// public key
\update_user_meta( $user_id, 'magic_sig_public_key', $detail['key'] );
}
} }
/**
* 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 ) { public static function generate_signature( $user_id, $http_method, $url, $date, $digest = null ) {
$key = self::get_private_key( $user_id ); $key = self::get_private_key( $user_id );
@ -88,8 +131,10 @@ class Signature {
$path .= '?' . $url_parts['query']; $path .= '?' . $url_parts['query'];
} }
$http_method = \strtolower( $http_method );
if ( ! empty( $digest ) ) { if ( ! empty( $digest ) ) {
$signed_string = "(request-target): $http_method $path\nhost: $host\ndate: $date\ndigest: SHA-256=$digest"; $signed_string = "(request-target): $http_method $path\nhost: $host\ndate: $date\ndigest: $digest";
} else { } else {
$signed_string = "(request-target): $http_method $path\nhost: $host\ndate: $date"; $signed_string = "(request-target): $http_method $path\nhost: $host\ndate: $date";
} }
@ -98,7 +143,11 @@ class Signature {
\openssl_sign( $signed_string, $signature, $key, \OPENSSL_ALGO_SHA256 ); \openssl_sign( $signed_string, $signature, $key, \OPENSSL_ALGO_SHA256 );
$signature = \base64_encode( $signature ); // phpcs:ignore $signature = \base64_encode( $signature ); // phpcs:ignore
$key_id = \get_author_posts_url( $user_id ) . '#main-key'; if ( User::APPLICATION_USER_ID === $user_id ) {
$key_id = \get_rest_url( null, 'activitypub/1.0/application#main-key' );
} else {
$key_id = \get_author_posts_url( $user_id ) . '#main-key';
}
if ( ! empty( $digest ) ) { if ( ! empty( $digest ) ) {
return \sprintf( 'keyId="%s",algorithm="rsa-sha256",headers="(request-target) host date digest",signature="%s"', $key_id, $signature ); return \sprintf( 'keyId="%s",algorithm="rsa-sha256",headers="(request-target) host date digest",signature="%s"', $key_id, $signature );
@ -107,12 +156,262 @@ class Signature {
} }
} }
public static function verify_signature( $headers, $signature ) { /**
* Verifies the http signatures
*
* @param WP_REQUEST|array $request The request object or $_SERVER array.
*
* @return mixed A boolean or WP_Error.
*/
public static function verify_http_signature( $request ) {
if ( is_object( $request ) ) { // REST Request object
// check if route starts with "index.php"
if ( str_starts_with( $request->get_route(), '/index.php' ) ) {
$route = $request->get_route();
} else {
$route = '/' . rest_get_url_prefix() . '/' . ltrim( $request->get_route(), '/' );
}
$headers = $request->get_headers();
$actor = isset( json_decode( $request->get_body() )->actor ) ? json_decode( $request->get_body() )->actor : '';
$headers['(request-target)'][0] = strtolower( $request->get_method() ) . ' ' . $route;
} else {
$request = self::format_server_request( $request );
$headers = $request['headers']; // $_SERVER array
$actor = null;
$headers['(request-target)'][0] = strtolower( $headers['request_method'][0] ) . ' ' . $headers['request_uri'][0];
}
if ( ! isset( $headers['signature'] ) ) {
return new WP_Error( 'activitypub_signature', 'Request not signed', array( 'status' => 403 ) );
}
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'] );
}
if ( ! isset( $signature_block ) || ! $signature_block ) {
return new WP_Error( 'activitypub_signature', 'Incompatible request signature. keyId and signature are required', array( 'status' => 403 ) );
}
$signed_headers = $signature_block['headers'];
if ( ! $signed_headers ) {
$signed_headers = array( 'date' );
}
$signed_data = self::get_signed_data( $signed_headers, $signature_block, $headers );
if ( ! $signed_data ) {
return new WP_Error( 'activitypub_signature', 'Signed request date outside acceptable time window', array( 'status' => 403 ) );
}
$algorithm = self::get_signature_algorithm( $signature_block );
if ( ! $algorithm ) {
return new WP_Error( 'activitypub_signature', 'Unsupported signature algorithm (only rsa-sha256 and hs2019 are supported)', array( 'status' => 403 ) );
}
if ( \in_array( 'digest', $signed_headers, true ) && isset( $body ) ) {
if ( is_array( $headers['digest'] ) ) {
$headers['digest'] = $headers['digest'][0];
}
$digest = explode( '=', $headers['digest'], 2 );
if ( 'SHA-256' === $digest[0] ) {
$hashalg = 'sha256';
}
if ( 'SHA-512' === $digest[0] ) {
$hashalg = 'sha512';
}
if ( \base64_encode( \hash( $hashalg, $body, true ) ) !== $digest[1] ) { // phpcs:ignore
return new WP_Error( 'activitypub_signature', 'Invalid Digest header', array( 'status' => 403 ) );
}
}
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;
}
$verified = \openssl_verify( $signed_data, $signature_block['signature'], $public_key, $algorithm ) > 0;
if ( ! $verified ) {
return new WP_Error( 'activitypub_signature', 'Invalid signature', array( 'status' => 403 ) );
}
return $verified;
} }
/**
* Get public key from key_id
*
* @param string $key_id The URL to the public key.
*
* @return string The public key.
*/
public static function get_remote_key( $key_id ) { // phpcs:ignore
$actor = \Activitypub\get_remote_metadata_by_actor( strtok( strip_fragment_from_url( $key_id ), '?' ) ); // phpcs:ignore
if ( \is_wp_error( $actor ) ) {
return $actor;
}
if ( isset( $actor['publicKey']['publicKeyPem'] ) ) {
return \rtrim( $actor['publicKey']['publicKeyPem'] ); // phpcs:ignore
}
return null;
}
/**
* Gets the signature algorithm from the signature header
*
* @param array $signature_block
*
* @return string The signature algorithm.
*/
public static function get_signature_algorithm( $signature_block ) {
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';
}
}
return false;
}
/**
* Parses the Signature header
*
* @param array $header The signature header.
*
* @return array signature parts
*/
public static function parse_signature_header( $header ) {
$parsed_header = array();
$matches = array();
$h_string = \implode( ',', (array) $header[0] );
if ( \preg_match( '/keyId="(.*?)"/ism', $h_string, $matches ) ) {
$parsed_header['keyId'] = $matches[1];
}
if ( \preg_match( '/created=([0-9]*)/ism', $h_string, $matches ) ) {
$parsed_header['(created)'] = $matches[1];
}
if ( \preg_match( '/expires=([0-9]*)/ism', $h_string, $matches ) ) {
$parsed_header['(expires)'] = $matches[1];
}
if ( \preg_match( '/algorithm="(.*?)"/ism', $h_string, $matches ) ) {
$parsed_header['algorithm'] = $matches[1];
}
if ( \preg_match( '/headers="(.*?)"/ism', $h_string, $matches ) ) {
$parsed_header['headers'] = \explode( ' ', $matches[1] );
}
if ( \preg_match( '/signature="(.*?)"/ism', $h_string, $matches ) ) {
$parsed_header['signature'] = \base64_decode( preg_replace( '/\s+/', '', $matches[1] ) ); // phpcs:ignore
}
if ( ( $parsed_header['signature'] ) && ( $parsed_header['algorithm'] ) && ( ! $parsed_header['headers'] ) ) {
$parsed_header['headers'] = array( 'date' );
}
return $parsed_header;
}
/**
* Gets the header data from the included pseudo headers
*
* @param array $signed_headers
* @param array $signature_block (pseudo-headers)
* @param array $headers (http headers)
*
* @return string signed headers for comparison
*/
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;
}
}
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;
}
if ( '(created)' === $header ) {
if ( ! empty( $signature_block['(created)'] ) && \intval( $signature_block['(created)'] ) > \time() ) {
// created in future
return false;
}
}
if ( '(expires)' === $header ) {
if ( ! empty( $signature_block['(expires)'] ) && \intval( $signature_block['(expires)'] ) < \time() ) {
// expired in past
return false;
}
}
if ( 'date' === $header ) {
// allow a bit of leeway for misconfigured clocks.
$d = new DateTime( $headers[ $header ][0] );
$d->setTimeZone( new DateTimeZone( 'UTC' ) );
$c = $d->format( 'U' );
$dplus = time() + ( 3 * HOUR_IN_SECONDS );
$dminus = time() - ( 3 * HOUR_IN_SECONDS );
if ( $c > $dplus || $c < $dminus ) {
// time out of range
return false;
}
}
$signed_data .= $header . ': ' . $headers[ $header ][0] . "\n";
}
return \rtrim( $signed_data, "\n" );
}
/**
* Generates the digest for a HTTP Request
*
* @param string $body The body of the request.
*
* @return string The digest.
*/
public static function generate_digest( $body ) { public static function generate_digest( $body ) {
$digest = \base64_encode( \hash( 'sha256', $body, true ) ); // phpcs:ignore $digest = \base64_encode( \hash( 'sha256', $body, true ) ); // phpcs:ignore
return "$digest"; return "SHA-256=$digest";
}
/**
* Formats the $_SERVER to resemble the WP_REST_REQUEST array,
* for use with verify_http_signature()
*
* @param array $_SERVER The $_SERVER array.
*
* @return array $request The formatted request array.
*/
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;
} }
} }

View file

@ -36,8 +36,8 @@ function safe_remote_post( $url, $body, $user_id ) {
return \Activitypub\Http::post( $url, $body, $user_id ); return \Activitypub\Http::post( $url, $body, $user_id );
} }
function safe_remote_get( $url, $user_id ) { function safe_remote_get( $url ) {
return \Activitypub\Http::get( $url, $user_id ); return \Activitypub\Http::get( $url );
} }
/** /**
@ -92,21 +92,11 @@ function get_remote_metadata_by_actor( $actor, $cached = true ) {
return $metadata; return $metadata;
} }
$user = \get_users(
array(
'number' => 1,
'capability__in' => array( 'publish_posts' ),
'fields' => 'ID',
)
);
// we just need any user to generate a request signature
$user_id = \reset( $user );
$short_timeout = function() { $short_timeout = function() {
return 3; return 3;
}; };
add_filter( 'activitypub_remote_get_timeout', $short_timeout ); add_filter( 'activitypub_remote_get_timeout', $short_timeout );
$response = Http::get( $actor, $user_id ); $response = Http::get( $actor );
remove_filter( 'activitypub_remote_get_timeout', $short_timeout ); remove_filter( 'activitypub_remote_get_timeout', $short_timeout );
if ( \is_wp_error( $response ) ) { if ( \is_wp_error( $response ) ) {
\set_transient( $transient_key, $response, HOUR_IN_SECONDS ); // Cache the error for a shorter period. \set_transient( $transient_key, $response, HOUR_IN_SECONDS ); // Cache the error for a shorter period.

View file

@ -0,0 +1,23 @@
<?php
namespace Activitypub\Model;
/**
* ActivityPub User Class
*
* @author Matthias Pfefferle
*/
class User {
/**
* The ID of the Blog User
*
* @var int
*/
const BLOG_USER_ID = 0;
/**
* The ID of the Application User
*
* @var int
*/
const APPLICATION_USER_ID = -1;
}

View file

@ -4,6 +4,7 @@ namespace Activitypub\Rest;
use WP_Error; use WP_Error;
use WP_REST_Server; use WP_REST_Server;
use WP_REST_Response; use WP_REST_Response;
use Activitypub\Signature;
use Activitypub\Model\Activity; use Activitypub\Model\Activity;
use function Activitypub\get_context; use function Activitypub\get_context;
@ -24,7 +25,6 @@ class Inbox {
*/ */
public static function init() { public static function init() {
\add_action( 'rest_api_init', array( self::class, 'register_routes' ) ); \add_action( 'rest_api_init', array( self::class, 'register_routes' ) );
\add_filter( 'rest_pre_serve_request', array( self::class, 'serve_request' ), 11, 4 );
\add_action( 'activitypub_inbox_create', array( self::class, 'handle_create' ), 10, 2 ); \add_action( 'activitypub_inbox_create', array( self::class, 'handle_create' ), 10, 2 );
} }
@ -66,35 +66,6 @@ class Inbox {
); );
} }
/**
* Hooks into the REST API request to verify the signature.
*
* @param bool $served Whether the request has already been served.
* @param WP_HTTP_ResponseInterface $result Result to send to the client. Usually a WP_REST_Response.
* @param WP_REST_Request $request Request used to generate the response.
* @param WP_REST_Server $server Server instance.
*
* @return true
*/
public static function serve_request( $served, $result, $request, $server ) {
if ( '/activitypub' !== \substr( $request->get_route(), 0, 12 ) ) {
return $served;
}
$signature = $request->get_header( 'signature' );
if ( ! $signature ) {
return $served;
}
$headers = $request->get_headers();
// verify signature
//\Activitypub\Signature::verify_signature( $headers, $key );
return $served;
}
/** /**
* Renders the user-inbox * Renders the user-inbox
* *
@ -147,6 +118,7 @@ class Inbox {
* @return WP_REST_Response * @return WP_REST_Response
*/ */
public static function user_inbox_post( $request ) { public static function user_inbox_post( $request ) {
$user_id = $request->get_param( 'user_id' ); $user_id = $request->get_param( 'user_id' );
$data = $request->get_params(); $data = $request->get_params();
@ -167,6 +139,7 @@ class Inbox {
* @return WP_REST_Response * @return WP_REST_Response
*/ */
public static function shared_inbox_post( $request ) { public static function shared_inbox_post( $request ) {
$data = $request->get_params(); $data = $request->get_params();
$type = $request->get_param( 'type' ); $type = $request->get_param( 'type' );
$users = self::extract_recipients( $data ); $users = self::extract_recipients( $data );

View file

@ -0,0 +1,117 @@
<?php
namespace Activitypub\Rest;
use stdClass;
use WP_REST_Response;
use Activitypub\Signature;
use Activitypub\Model\User;
use function Activitypub\get_context;
use function Activitypub\get_rest_url_by_path;
/**
* ActivityPub Server REST-Class
*
* @author Django Doucet
*
* @see https://www.w3.org/TR/activitypub/#security-verification
*/
class Server {
/**
* Initialize the class, registering WordPress hooks
*/
public static function init() {
\add_action( 'rest_api_init', array( self::class, 'register_routes' ) );
\add_filter( 'rest_request_before_callbacks', array( self::class, 'authorize_activitypub_requests' ), 10, 3 );
}
/**
* Register routes
*/
public static function register_routes() {
\register_rest_route(
ACTIVITYPUB_REST_NAMESPACE,
'/application',
array(
array(
'methods' => \WP_REST_Server::READABLE,
'callback' => array( self::class, 'application_actor' ),
'permission_callback' => '__return_true',
),
)
);
}
/**
* Render Application actor profile
*
* @return WP_REST_Response The JSON profile of the Application Actor.
*/
public static function application_actor() {
$json = new stdClass();
$json->{'@context'} = get_context();
$json->id = get_rest_url_by_path( 'application' );
$json->type = 'Application';
$json->preferredUsername = str_replace( array( '.' ), '-', wp_parse_url( get_site_url(), PHP_URL_HOST ) ); // phpcs:ignore WordPress.NamingConventions
$json->name = get_bloginfo( 'name' );
$json->summary = __( 'WordPress-ActivityPub application actor', 'activitypub' );
$json->manuallyApprovesFollowers = true; // phpcs:ignore WordPress.NamingConventions
$json->icon = array( get_site_icon_url() ); // phpcs:ignore WordPress.NamingConventions short array syntax
$json->publicKey = array( // phpcs:ignore WordPress.NamingConventions
'id' => get_rest_url_by_path( 'application#main-key' ),
'owner' => get_rest_url_by_path( 'application' ),
'publicKeyPem' => Signature::get_public_key( User::APPLICATION_USER_ID ), // phpcs:ignore WordPress.NamingConventions
);
$response = new WP_REST_Response( $json, 200 );
$response->header( 'Content-Type', 'application/activity+json' );
return $response;
}
/**
* Callback function to authorize each api requests
*
* @see WP_REST_Request
*
* @param WP_REST_Response|WP_HTTP_Response|WP_Error|mixed $response Result to send to the client.
* Usually a WP_REST_Response or WP_Error.
* @param array $handler Route handler used for the request.
* @param WP_REST_Request $request Request used to generate the response.
*
* @return mixed|WP_Error The response, error, or modified response.
*/
public static function authorize_activitypub_requests( $response, $handler, $request ) {
$route = $request->get_route();
// check if it is an activitypub request and exclude webfinger and nodeinfo endpoints
if (
! str_starts_with( $route, '/' . ACTIVITYPUB_REST_NAMESPACE ) ||
str_starts_with( $route, '/' . \trailingslashit( ACTIVITYPUB_REST_NAMESPACE ) . 'webfinger' ) ||
str_starts_with( $route, '/' . \trailingslashit( ACTIVITYPUB_REST_NAMESPACE ) . 'nodeinfo' )
) {
return $response;
}
// POST-Requets are always signed
if ( 'POST' === $request->get_method() ) {
$verified_request = Signature::verify_http_signature( $request );
if ( \is_wp_error( $verified_request ) ) {
return $verified_request;
}
} elseif ( 'GET' === $request->get_method() ) { // GET-Requests are only signed in secure mode
if ( ACTIVITYPUB_SECURE_MODE ) {
$verified_request = Signature::verify_http_signature( $request );
if ( \is_wp_error( $verified_request ) ) {
return $verified_request;
}
}
}
return $response;
}
}

View file

@ -22,7 +22,7 @@ class Test_Activitypub_Activity extends WP_UnitTestCase {
$activitypub_activity = new \Activitypub\Model\Activity( 'Create' ); $activitypub_activity = new \Activitypub\Model\Activity( 'Create' );
$activitypub_activity->from_post( $activitypub_post ); $activitypub_activity->from_post( $activitypub_post );
$this->assertContains( \Activitypub\get_rest_url_by_path( 'users/1/followers' ), $activitypub_activity->get_to() ); $this->assertContains( \Activitypub\get_rest_url_by_path( 'users/1/followers' ), $activitypub_activity->get_to() );
$this->assertContains( 'https://example.com/alex', $activitypub_activity->get_cc() ); $this->assertContains( 'https://example.com/alex', $activitypub_activity->get_cc() );
remove_all_filters( 'activitypub_extract_mentions' ); remove_all_filters( 'activitypub_extract_mentions' );

View file

@ -0,0 +1,110 @@
<?php
class Test_Activitypub_Signature_Verification extends WP_UnitTestCase {
public function test_activity_signature() {
// Activity for generate_digest
$post = \wp_insert_post(
array(
'post_author' => 1,
'post_content' => 'hello world',
)
);
$remote_actor = \get_author_posts_url( 2 );
$activitypub_post = new \Activitypub\Model\Post( $post );
$activitypub_activity = new Activitypub\Model\Activity( 'Create' );
$activitypub_activity->from_post( $activitypub_post );
$activitypub_activity->add_cc( $remote_actor );
$activity = $activitypub_activity->to_json();
// generate_digest & generate_signature
$digest = Activitypub\Signature::generate_digest( $activity );
$date = gmdate( 'D, d M Y H:i:s T' );
$signature = Activitypub\Signature::generate_signature( 1, 'POST', $remote_actor, $date, $digest );
$this->assertRegExp( '/keyId="http:\/\/example\.org\/\?author=1#main-key",algorithm="rsa-sha256",headers="\(request-target\) host date digest",signature="[^"]*"/', $signature );
// Signed headers
$url_parts = wp_parse_url( $remote_actor );
$route = $url_parts['path'] . '?' . $url_parts['query'];
$host = $url_parts['host'];
$headers = array(
'digest' => array( $digest ),
'signature' => array( $signature ),
'date' => array( $date ),
'host' => array( $host ),
'(request-target)' => array( 'post ' . $route ),
);
// Start verification
// parse_signature_header, get_signed_data, get_public_key
$signature_block = Activitypub\Signature::parse_signature_header( $headers['signature'] );
$signed_headers = $signature_block['headers'];
$signed_data = Activitypub\Signature::get_signed_data( $signed_headers, $signature_block, $headers );
$public_key = Activitypub\Signature::get_public_key( 1 );
// signature_verification
$verified = \openssl_verify( $signed_data, $signature_block['signature'], $public_key, 'rsa-sha256' ) > 0;
$this->assertTrue( $verified );
}
public function test_rest_activity_signature() {
add_filter(
'pre_get_remote_metadata_by_actor',
function( $json, $actor ) {
// return ActivityPub Profile with signature
return array(
'id' => $actor,
'type' => 'Person',
'publicKey' => array(
'id' => $actor . '#main-key',
'owner' => $actor,
'publicKeyPem' => \Activitypub\Signature::get_public_key( 1 ),
),
);
},
10,
2
);
// Activity Object
$post = \wp_insert_post(
array(
'post_author' => 1,
'post_content' => 'hello world',
)
);
$remote_actor = \get_author_posts_url( 2 );
$remote_actor_inbox = Activitypub\get_rest_url_by_path( '/inbox' );
$activitypub_post = new \Activitypub\Model\Post( $post );
$activitypub_activity = new Activitypub\Model\Activity( 'Create' );
$activitypub_activity->from_post( $activitypub_post );
$activitypub_activity->add_cc( $remote_actor_inbox );
$activity = $activitypub_activity->to_json();
// generate_digest & generate_signature
$digest = Activitypub\Signature::generate_digest( $activity );
$date = gmdate( 'D, d M Y H:i:s T' );
$signature = Activitypub\Signature::generate_signature( 1, 'POST', $remote_actor_inbox, $date, $digest );
// Signed headers
$url_parts = wp_parse_url( $remote_actor_inbox );
$route = $url_parts['path'] . '?' . $url_parts['query'];
$host = $url_parts['host'];
$request = new WP_REST_Request( 'POST', $route );
$request->set_header( 'content-type', 'application/activity+json' );
$request->set_header( 'digest', $digest );
$request->set_header( 'signature', $signature );
$request->set_header( 'date', $date );
$request->set_header( 'host', $host );
$request->set_body( $activity );
// Start verification
$verified = \Activitypub\Signature::verify_http_signature( $request );
$this->assertTrue( $verified );
remove_filter( 'pre_get_remote_metadata_by_actor', array( get_called_class(), 'pre_get_remote_key' ), 10, 2 );
}
}