4 * @file src/Util/HTTPSignature.php
6 namespace Friendica\Util;
8 use Friendica\BaseObject;
9 use Friendica\Core\Config;
10 use Friendica\Core\Logger;
11 use Friendica\Database\DBA;
12 use Friendica\Model\User;
13 use Friendica\Model\APContact;
14 use Friendica\Protocol\ActivityPub;
15 use Friendica\Util\DateTimeFormat;
18 * @brief Implements HTTP Signatures per draft-cavage-http-signatures-07.
20 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/Zotlabs/Web/HTTPSig.php
22 * Other parts of the code for HTTP signing are taken from the Osada project.
23 * https://framagit.org/macgirvin/osada
25 * @see https://tools.ietf.org/html/draft-cavage-http-signatures-07
30 // See draft-cavage-http-signatures-08
32 * @brief Verifies a magic request
36 * @return array with verification data
38 public static function verifyMagic($key)
44 'header_signed' => false,
45 'header_valid' => false
48 // Decide if $data arrived via controller submission or curl.
50 $headers['(request-target)'] = strtolower($_SERVER['REQUEST_METHOD']).' '.$_SERVER['REQUEST_URI'];
52 foreach ($_SERVER as $k => $v) {
53 if (strpos($k, 'HTTP_') === 0) {
54 $field = str_replace('_', '-', strtolower(substr($k, 5)));
55 $headers[$field] = $v;
61 $sig_block = self::parseSigheader($headers['authorization']);
64 Logger::log('no signature provided.');
68 $result['header_signed'] = true;
70 $signed_headers = $sig_block['headers'];
71 if (!$signed_headers) {
72 $signed_headers = ['date'];
76 foreach ($signed_headers as $h) {
77 if (array_key_exists($h, $headers)) {
78 $signed_data .= $h . ': ' . $headers[$h] . "\n";
80 if (strpos($h, '.')) {
85 $signed_data = rtrim($signed_data, "\n");
87 $algorithm = 'sha512';
89 if ($key && function_exists($key)) {
90 $result['signer'] = $sig_block['keyId'];
91 $key = $key($sig_block['keyId']);
94 Logger::log('Got keyID ' . $sig_block['keyId'], Logger::DEBUG);
100 $x = Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm);
102 Logger::log('verified: ' . $x, Logger::DEBUG);
109 $result['header_valid'] = true;
119 * @param string $prvkey
120 * @param string $keyid (optional, default 'Key')
124 public static function createSig($head, $prvkey, $keyid = 'Key')
126 $return_headers = [];
129 $algorithm = 'rsa-sha512';
131 $x = self::sign($head, $prvkey, $alg);
133 $headerval = 'keyId="' . $keyid . '",algorithm="' . $algorithm
134 . '",headers="' . $x['headers'] . '",signature="' . $x['signature'] . '"';
136 $sighead = 'Authorization: Signature ' . $headerval;
139 foreach ($head as $k => $v) {
140 $return_headers[] = $k . ': ' . $v;
144 $return_headers[] = $sighead;
146 return $return_headers;
153 * @param string $prvkey
154 * @param string $alg (optional) default 'sha256'
158 private static function sign($head, $prvkey, $alg = 'sha256')
164 foreach ($head as $k => $v) {
165 $headers .= strtolower($k) . ': ' . trim($v) . "\n";
169 $fields .= strtolower($k);
171 // strip the trailing linefeed
172 $headers = rtrim($headers, "\n");
174 $sig = base64_encode(Crypto::rsaSign($headers, $prvkey, $alg));
176 $ret['headers'] = $fields;
177 $ret['signature'] = $sig;
185 * @param string $header
186 * @return array associate array with
187 * - \e string \b keyID
188 * - \e string \b algorithm
189 * - \e array \b headers
190 * - \e string \b signature
192 public static function parseSigheader($header)
197 // if the header is encrypted, decrypt with (default) site private key and continue
198 if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
199 $header = self::decryptSigheader($header);
202 if (preg_match('/keyId="(.*?)"/ism', $header, $matches)) {
203 $ret['keyId'] = $matches[1];
206 if (preg_match('/algorithm="(.*?)"/ism', $header, $matches)) {
207 $ret['algorithm'] = $matches[1];
209 $ret['algorithm'] = 'rsa-sha256';
212 if (preg_match('/headers="(.*?)"/ism', $header, $matches)) {
213 $ret['headers'] = explode(' ', $matches[1]);
216 if (preg_match('/signature="(.*?)"/ism', $header, $matches)) {
217 $ret['signature'] = base64_decode(preg_replace('/\s+/', '', $matches[1]));
220 if (!empty($ret['signature']) && !empty($ret['algorithm']) && empty($ret['headers'])) {
221 $ret['headers'] = ['date'];
230 * @param string $header
231 * @param string $prvkey (optional), if not set use site private key
233 * @return array|string associative array, empty string if failue
237 * - \e string \b data
239 private static function decryptSigheader($header, $prvkey = null)
241 $iv = $key = $alg = $data = null;
244 $prvkey = Config::get('system', 'prvkey');
249 if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
253 if (preg_match('/key="(.*?)"/ism', $header, $matches)) {
257 if (preg_match('/alg="(.*?)"/ism', $header, $matches)) {
261 if (preg_match('/data="(.*?)"/ism', $header, $matches)) {
265 if ($iv && $key && $alg && $data) {
266 return Crypto::unencapsulate(['iv' => $iv, 'key' => $key, 'alg' => $alg, 'data' => $data], $prvkey);
273 * Functions for ActivityPub
277 * @brief Transmit given data to a target for a user
279 * @param array $data Data that is about to be send
280 * @param string $target The URL of the inbox
281 * @param integer $uid User id of the sender
283 * @return boolean Was the transmission successful?
285 public static function transmit($data, $target, $uid)
287 $owner = User::getOwnerDataById($uid);
293 $content = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
295 // Header data that is about to be signed.
296 $host = parse_url($target, PHP_URL_HOST);
297 $path = parse_url($target, PHP_URL_PATH);
298 $digest = 'SHA-256=' . base64_encode(hash('sha256', $content, true));
299 $content_length = strlen($content);
300 $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP);
302 $headers = ['Date: ' . $date, 'Content-Length: ' . $content_length, 'Digest: ' . $digest, 'Host: ' . $host];
304 $signed_data = "(request-target): post " . $path . "\ndate: ". $date . "\ncontent-length: " . $content_length . "\ndigest: " . $digest . "\nhost: " . $host;
306 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
308 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) date content-length digest host",signature="' . $signature . '"';
310 $headers[] = 'Content-Type: application/activity+json';
312 $postResult = Network::post($target, $content, $headers);
313 $return_code = $postResult->getReturnCode();
315 Logger::log('Transmit to ' . $target . ' returned ' . $return_code, Logger::DEBUG);
317 return ($return_code >= 200) && ($return_code <= 299);
321 * @brief Fetches JSON data for a user
323 * @param string $request request url
324 * @param integer $uid User id of the requester
326 * @return array JSON array
328 public static function fetch($request, $uid)
330 $owner = User::getOwnerDataById($uid);
336 // Header data that is about to be signed.
337 $host = parse_url($request, PHP_URL_HOST);
338 $path = parse_url($request, PHP_URL_PATH);
339 $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP);
341 $headers = ['Date: ' . $date, 'Host: ' . $host];
343 $signed_data = "(request-target): get " . $path . "\ndate: ". $date . "\nhost: " . $host;
345 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
347 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) date host",signature="' . $signature . '"';
349 $headers[] = 'Accept: application/activity+json, application/ld+json';
351 $curlResult = Network::curl($request, false, $redirects, ['header' => $headers]);
352 $return_code = $curlResult->getReturnCode();
354 Logger::log('Fetched for user ' . $uid . ' from ' . $request . ' returned ' . $return_code, Logger::DEBUG);
356 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
360 $content = json_decode($curlResult->getBody(), true);
362 if (empty($content) || !is_array($content)) {
370 * @brief Gets a signer from a given HTTP request
373 * @param $http_headers
375 * @return signer string
377 public static function getSigner($content, $http_headers)
379 if (empty($http_headers['HTTP_SIGNATURE'])) {
383 if (!empty($content)) {
384 $object = json_decode($content, true);
385 if (empty($object)) {
389 $actor = JsonLD::fetchElement($object, 'actor', 'id');
395 $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . $http_headers['REQUEST_URI'];
397 // First take every header
398 foreach ($http_headers as $k => $v) {
399 $field = str_replace('_', '-', strtolower($k));
400 $headers[$field] = $v;
403 // Now add every http header
404 foreach ($http_headers as $k => $v) {
405 if (strpos($k, 'HTTP_') === 0) {
406 $field = str_replace('_', '-', strtolower(substr($k, 5)));
407 $headers[$field] = $v;
411 $sig_block = self::parseSigHeader($http_headers['HTTP_SIGNATURE']);
413 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
418 foreach ($sig_block['headers'] as $h) {
419 if (array_key_exists($h, $headers)) {
420 $signed_data .= $h . ': ' . $headers[$h] . "\n";
423 $signed_data = rtrim($signed_data, "\n");
425 if (empty($signed_data)) {
431 if ($sig_block['algorithm'] === 'rsa-sha256') {
432 $algorithm = 'sha256';
435 if ($sig_block['algorithm'] === 'rsa-sha512') {
436 $algorithm = 'sha512';
439 if (empty($algorithm)) {
443 $key = self::fetchKey($sig_block['keyId'], $actor);
449 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key['pubkey'], $algorithm)) {
453 // Check the digest when it is part of the signed data
454 if (in_array('digest', $sig_block['headers'])) {
455 $digest = explode('=', $headers['digest'], 2);
456 if ($digest[0] === 'SHA-256') {
459 if ($digest[0] === 'SHA-512') {
463 /// @todo add all hashes from the rfc
465 if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
470 // Check if the signed date field is in an acceptable range
471 if (in_array('date', $sig_block['headers'])) {
472 $diff = abs(strtotime($headers['date']) - time());
474 Logger::log("Header date '" . $headers['date'] . "' is with " . $diff . " seconds out of the 300 second frame. The signature is invalid.");
479 // Check the content-length when it is part of the signed data
480 if (in_array('content-length', $sig_block['headers'])) {
481 if (strlen($content) != $headers['content-length']) {
490 * @brief fetches a key for a given id and actor
495 * @return array with actor url and public key
497 private static function fetchKey($id, $actor)
499 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
501 $profile = APContact::getByURL($url);
502 if (!empty($profile)) {
503 Logger::log('Taking key from id ' . $id, Logger::DEBUG);
504 return ['url' => $url, 'pubkey' => $profile['pubkey']];
505 } elseif ($url != $actor) {
506 $profile = APContact::getByURL($actor);
507 if (!empty($profile)) {
508 Logger::log('Taking key from actor ' . $actor, Logger::DEBUG);
509 return ['url' => $actor, 'pubkey' => $profile['pubkey']];