Fix signature parse verification

This commit is contained in:
Django Doucet 2023-04-01 10:17:56 -06:00
parent 8f80a70ee5
commit 0c7cec3eba
2 changed files with 172 additions and 125 deletions

View file

@ -1,7 +1,8 @@
<?php <?php
namespace Activitypub; namespace Activitypub;
use phpseclib3\Crypt\RSA; // use DateTime;
// use DateTimeZone;
/** /**
* ActivityPub Signature Class * ActivityPub Signature Class
@ -10,16 +11,13 @@ use phpseclib3\Crypt\RSA;
*/ */
class Signature { class Signature {
const SIGNATURE_PATTERN = '/^ /**
keyId="(?P<keyId> * How much leeway to provide on the date header in seconds.
(https?:\/\/[\w\-\.]+[\w]+) * Not everybody uses NTP.
(:[\d]+)? */
([\w\-\.#\/@]+) const MAX_TIME_OFFSET = 10800;
)",
(algorithm="(?P<algorithm>[\w\s-]+)",)? const DEFAULT_SIGNING_ALGORITHM = 'sha256';
(headers="(?P<headers>[\(\)\w\s-]+)",)?
signature="(?P<signature>[\w+\/]+={0,2})"
/x';
/** /**
* @param int $user_id * @param int $user_id
@ -120,136 +118,176 @@ class Signature {
} }
} }
public static function verify_signature( $request ) { public static function verify_signature( $request = null ) {
$headers = $request->get_headers();
$headers["(request-target)"][0] = strtolower( $request->get_method() ) . ' /wp-json' . $request->get_route();
// https://github.com/landrok/activitypub/blob/master/src/ActivityPhp/Server/Http/HttpSignature.php if ( !$headers ) {
$header_data = $request->get_headers(); $headers = self::default_server_headers();
$body = $request->get_body(); }
if ( !$header_data['signature'][0] ) { if ( array_key_exists( 'signature', $headers ) ) {
return false; $signature_block = self::parse_signature_header( $headers['signature'] );
} } elseif ( array_key_exists( 'authorization', $headers ) ) {
$signature_block = self::parse_signature_header( $headers['authorization'] );
}
// Split signature into its parts if ( !$signature_block ) {
$signature_parts = self::splitSignature( $header_data['signature'][0] ); return false;
if ( !count( $signature_parts ) ) { }
return false;
}
extract( $signature_parts );// $keyId, $algorithm, $headers, $signature
// Fetch the public key linked from keyId $signed_headers = $signature_block['headers'];
$actor = \strip_fragment_from_url( $keyId ); if ( ! $signed_headers ) {
$publicKeyPem = \Activitypub\get_publickey_by_actor( $actor, $keyId ); $signed_headers = ['date'];
}
if ( !is_wp_error( $publicKeyPem ) ) { $signed_data = self::get_signed_data( $signed_headers, $signature_block, $headers );
// Probably overkill since we already have a seemingly weelformed PEM if ( ! $signed_data ) {
$pkey = \openssl_pkey_get_details( \openssl_pkey_get_public( $publicKeyPem ) ); return false;
}
// Verify Digest $algorithm = self::get_signature_algorithm( $signature_block );
$digest_gen = 'SHA-256=' . \base64_encode( \hash( 'sha256', $body, true ) ); if ( ! $algorithm ) {
if ( ! isset( $header_data['digest'][0] ) || ( $digest_gen !== $header_data['digest'][0] ) ) { return false;
}
if ( in_array( 'digest', $signed_headers ) && isset( $body ) ) {
$digest = explode( '=', $headers['digest'], 2 );
if ( $digest[0] === 'SHA-256' ) {
$hashalg = 'sha256';
}
if ( $digest[0] === 'SHA-512' ) {
$hashalg = 'sha512';
}
// TODO Test
if ( base64_encode( hash( $hashalg, $body, true ) ) !== $digest[1] ) {
return false; return false;
} }
}
// Create a comparison string from the plaintext headers we got $public_key = $key?? self::get_key( $signature_block['keyId'] );
// in the same order as was given in the signature header,
$signing_headers = self::getPlainText(
explode(' ', trim( $headers ) ),
$request
);
// 2 methods because neither works ¯\_(ツ)_/¯ return \openssl_verify( $signed_data,$signature_block['signature'], $public_key, $algorithm ) > 0;
// phpseclib method
$rsa = RSA::createKey() }
->loadPublicKey( $pkey['key'])
->withHash('sha256'); public static function default_server_headers() {
$verified = $rsa->verify( $signing_headers, \base64_decode( $signature ) ); $headers = array(
if ( $verified > 0 ) { '(request-target)' => strtolower( $_SERVER['REQUEST_METHOD'] ) . ' ' . $_SERVER['REQUEST_URI'],
\error_log( '$rsa->verify: //return true;' ); 'content-type' => $_SERVER['CONTENT_TYPE'],
return true; 'content-length' => $_SERVER['CONTENT_LENGTH'],
} else { );
while ( $ossl_error = openssl_error_string() ) { foreach ( $_SERVER as $k => $v ) {
\error_log( '$rsa->verify(): ' . $ossl_error ); if ( strpos( $k, 'HTTP_' ) === 0 ) {
} $field = str_replace( '_', '-', strtolower( substr( $k, 5 ) ) );
$activity = \json_decode( $body ); $headers[$field] = $v;
\error_log( 'activity->type: ' . print_r( $activity->type, true ) );
//return false;
} }
}
return $headers;
}
// openssl method public static function get_signature_algorithm( $signature_block ) {
$verified = \openssl_verify( $signing_headers, switch ( $signature_block['algorithm'] ) {
\base64_decode( \normalize_whitespace( $signature ) ), case 'rsa-sha256':
$pkey['key'], return 'sha256';
\OPENSSL_ALGO_SHA256 case 'rsa-sha-512':
); return 'sha512';
if ( $verified > 0 ) { case 'hs2019':
\error_log( 'openssl_verify: //return true;' ); return self::DEFAULT_SIGNING_ALGORITHM;
return true;
} else {
while ( $ossl_error = openssl_error_string() ) {
\error_log( 'openssl_error_string(): ' . $ossl_error );
}
//return false;
}
} }
return false; return false;
} }
/** public static function parse_signature_header( $header ) {
* Split HTTP signature into its parts (keyId, headers and signature) $ret = [];
*/ $matches = [];
public static function splitSignature( $signature ) { $h_string = implode( ',', (array) $header[0] );
$allowedKeys = [ if ( preg_match( '/keyId="(.*?)"/ism', $h_string, $matches ) ) {
'keyId', $ret['keyId'] = $matches[1];
'algorithm', // optional }
'headers', // optional if ( preg_match( '/created=([0-9]*)/ism', $h_string, $matches ) ) {
'signature', $ret['(created)'] = $matches[1];
]; }
if ( preg_match( '/expires=([0-9]*)/ism', $h_string, $matches ) ) {
if (!preg_match(self::SIGNATURE_PATTERN, $signature, $matches)) { $ret['(expires)'] = $matches[1];
return []; }
} if ( preg_match( '/algorithm="(.*?)"/ism', $h_string, $matches ) ) {
$ret['algorithm'] = $matches[1];
// Headers are optional }
if (!isset($matches['headers']) || $matches['headers'] == '') { if ( preg_match( '/headers="(.*?)"/ism', $h_string, $matches ) ) {
$matches['headers'] = 'date'; $ret['headers'] = explode( ' ', $matches[1] );
} }
if ( preg_match( '/signature="(.*?)"/ism', $h_string, $matches ) ) {
return array_filter($matches, function($key) use ($allowedKeys) { $ret['signature'] = base64_decode( preg_replace( '/\s+/', '', $matches[1] ) );
return !is_int($key) && in_array($key, $allowedKeys);
}, ARRAY_FILTER_USE_KEY );
}
/**
* Get plain text that has been originally signed
*
* @param array $headers HTTP header keys
* @param \Symfony\Component\HttpFoundation\Request $request
*/
public static function getPlainText( $headers, $request ) {
$url_params = $request->get_url_params();
if ( isset( $url_params ) && isset( $url_params['user_id'] ) ) {
$url_params = '';
} }
$strings = []; if ( ( $ret['signature'] ) && ( $ret['algorithm'] ) && ( !$ret['headers'] ) ) {
$request_target = sprintf( $ret['headers'] = ['date'];
'%s %s%s', }
strtolower($request->get_method()),
$request->get_route(),
$url_params
);
foreach ($headers as $value) { return $ret;
if ( $value == '(request-target)' ) { }
$strings[] = "$value: " . $request_target;
} else { public static function get_key( $keyId ) {
$strings[] = "$value: " . $request->get_header($value); // If there was no key passed to verify, it will find the keyId and call this
// function to fetch the public key from stored data or a network fetch.
$actor = \strip_fragment_from_url( $keyId );
$publicKeyPem = \Activitypub\get_publickey_by_actor( $actor, $keyId );
return rtrim( $publicKeyPem );
}
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 ( array_key_exists($header, $headers ) ) {
if ( $header === 'host' ) {
if ( isset( $headers['x_original_host'] ) ) {
$signed_data .= 'host: ' . $headers['x_original_host'][0] . "\n";
} else {
$signed_data .= $header . ': ' . $headers[$header][0] . "\n";
}
} else {
$signed_data .= $header . ': ' . $headers[$header][0] . "\n";
}
}
if ( $header === '(created)' ) {
if ( !empty( $signature_block['(created)'] ) && intval( $signature_block['(created)'] ) > time() ) {
// created in future
return false;
}
$signed_data .= '(created): ' . $signature_block['(created)'] . "\n";
}
if ( $header === '(expires)' ) {
if ( !empty( $signature_block['(expires)'] ) && intval( $signature_block['(expires)'] ) < time() ) {
// expired in past
return false;
}
$signed_data .= '(expires): ' . $signature_block['(expires)'] . "\n";
}
if ( $header === 'content-type' ) {
$signed_data .= $header . ': ' . $headers['content_type'][0] . "\n";
}
if ( $header === 'date' ) {
// allow a bit of leeway for misconfigured clocks.
$d = new DateTime( $headers[$header][0] );
$d->setTimeZone( new DateTimeZone('UTC') );
$dplus = time() + self::MAX_TIME_OFFSET;
$dminus = time() - self::MAX_TIME_OFFSET;
$c = wp_date( 'U' );
if ( $c > $dplus || $c < $dminus ) {
// time out of range
return false;
}
} }
} }
// error_log( '$signed_data: ' . print_r( rtrim( $signed_data, "\n" ), true ) );
return implode("\n", $strings); return rtrim($signed_data, "\n");
} }
public static function generate_digest( $body ) { public static function generate_digest( $body ) {

View file

@ -84,7 +84,6 @@ class Inbox {
// verify signature // verify signature
\Activitypub\Signature::verify_signature( $request ); \Activitypub\Signature::verify_signature( $request );
//\Activitypub\Signature::verify_signature( $headers, $key );
return $served; return $served;
} }
@ -340,6 +339,16 @@ class Inbox {
}, },
); );
$params['validated'] = array(
'sanitize_callback' => function( $param, $request, $key ) {
if ( \is_string( $param ) ) {
$param = array( $param );
}
return $param;
},
);
return $params; return $params;
} }