4 * @file src/Util/HTTPSignature.php
6 namespace Friendica\Util;
8 use Friendica\BaseObject;
9 use Friendica\Core\Config;
10 use Friendica\Database\DBA;
11 use Friendica\Model\User;
12 use Friendica\Model\APContact;
13 use Friendica\Protocol\ActivityPub;
16 * @brief Implements HTTP Signatures per draft-cavage-http-signatures-07.
18 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/Zotlabs/Web/HTTPSig.php
20 * Other parts of the code for HTTP signing are taken from the Osada project.
21 * https://framagit.org/macgirvin/osada
23 * @see https://tools.ietf.org/html/draft-cavage-http-signatures-07
28 // See draft-cavage-http-signatures-08
30 * @brief Verifies a magic request
34 * @return array with verification data
36 public static function verifyMagic($key)
42 'header_signed' => false,
43 'header_valid' => false
46 // Decide if $data arrived via controller submission or curl.
48 $headers['(request-target)'] = strtolower($_SERVER['REQUEST_METHOD']).' '.$_SERVER['REQUEST_URI'];
50 foreach ($_SERVER as $k => $v) {
51 if (strpos($k, 'HTTP_') === 0) {
52 $field = str_replace('_', '-', strtolower(substr($k, 5)));
53 $headers[$field] = $v;
59 $sig_block = self::parseSigheader($headers['authorization']);
62 logger('no signature provided.');
66 $result['header_signed'] = true;
68 $signed_headers = $sig_block['headers'];
69 if (!$signed_headers) {
70 $signed_headers = ['date'];
74 foreach ($signed_headers as $h) {
75 if (array_key_exists($h, $headers)) {
76 $signed_data .= $h . ': ' . $headers[$h] . "\n";
78 if (strpos($h, '.')) {
83 $signed_data = rtrim($signed_data, "\n");
85 $algorithm = 'sha512';
87 if ($key && function_exists($key)) {
88 $result['signer'] = $sig_block['keyId'];
89 $key = $key($sig_block['keyId']);
92 logger('Got keyID ' . $sig_block['keyId']);
98 $x = Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm);
100 logger('verified: ' . $x, LOGGER_DEBUG);
107 $result['header_valid'] = true;
117 * @param string $prvkey
118 * @param string $keyid (optional, default 'Key')
122 public static function createSig($head, $prvkey, $keyid = 'Key')
124 $return_headers = [];
127 $algorithm = 'rsa-sha512';
129 $x = self::sign($head, $prvkey, $alg);
131 $headerval = 'keyId="' . $keyid . '",algorithm="' . $algorithm
132 . '",headers="' . $x['headers'] . '",signature="' . $x['signature'] . '"';
134 $sighead = 'Authorization: Signature ' . $headerval;
137 foreach ($head as $k => $v) {
138 $return_headers[] = $k . ': ' . $v;
142 $return_headers[] = $sighead;
144 return $return_headers;
151 * @param string $prvkey
152 * @param string $alg (optional) default 'sha256'
156 private static function sign($head, $prvkey, $alg = 'sha256')
162 foreach ($head as $k => $v) {
163 $headers .= strtolower($k) . ': ' . trim($v) . "\n";
167 $fields .= strtolower($k);
169 // strip the trailing linefeed
170 $headers = rtrim($headers, "\n");
172 $sig = base64_encode(Crypto::rsaSign($headers, $prvkey, $alg));
174 $ret['headers'] = $fields;
175 $ret['signature'] = $sig;
183 * @param string $header
184 * @return array associate array with
185 * - \e string \b keyID
186 * - \e string \b algorithm
187 * - \e array \b headers
188 * - \e string \b signature
190 public static function parseSigheader($header)
195 // if the header is encrypted, decrypt with (default) site private key and continue
196 if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
197 $header = self::decryptSigheader($header);
200 if (preg_match('/keyId="(.*?)"/ism', $header, $matches)) {
201 $ret['keyId'] = $matches[1];
204 if (preg_match('/algorithm="(.*?)"/ism', $header, $matches)) {
205 $ret['algorithm'] = $matches[1];
208 if (preg_match('/headers="(.*?)"/ism', $header, $matches)) {
209 $ret['headers'] = explode(' ', $matches[1]);
212 if (preg_match('/signature="(.*?)"/ism', $header, $matches)) {
213 $ret['signature'] = base64_decode(preg_replace('/\s+/', '', $matches[1]));
216 if (($ret['signature']) && ($ret['algorithm']) && (!$ret['headers'])) {
217 $ret['headers'] = ['date'];
226 * @param string $header
227 * @param string $prvkey (optional), if not set use site private key
229 * @return array|string associative array, empty string if failue
233 * - \e string \b data
235 private static function decryptSigheader($header, $prvkey = null)
237 $iv = $key = $alg = $data = null;
240 $prvkey = Config::get('system', 'prvkey');
245 if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
249 if (preg_match('/key="(.*?)"/ism', $header, $matches)) {
253 if (preg_match('/alg="(.*?)"/ism', $header, $matches)) {
257 if (preg_match('/data="(.*?)"/ism', $header, $matches)) {
261 if ($iv && $key && $alg && $data) {
262 return Crypto::unencapsulate(['iv' => $iv, 'key' => $key, 'alg' => $alg, 'data' => $data], $prvkey);
269 * Functions for ActivityPub
273 * @brief Transmit given data to a target for a user
279 public static function transmit($data, $target, $uid)
281 $owner = User::getOwnerDataById($uid);
287 $content = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
289 // Header data that is about to be signed.
290 $host = parse_url($target, PHP_URL_HOST);
291 $path = parse_url($target, PHP_URL_PATH);
292 $digest = 'SHA-256=' . base64_encode(hash('sha256', $content, true));
293 $content_length = strlen($content);
295 $headers = ['Content-Length: ' . $content_length, 'Digest: ' . $digest, 'Host: ' . $host];
297 $signed_data = "(request-target): post " . $path . "\ncontent-length: " . $content_length . "\ndigest: " . $digest . "\nhost: " . $host;
299 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
301 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) content-length digest host",signature="' . $signature . '"';
303 $headers[] = 'Content-Type: application/activity+json';
305 Network::post($target, $content, $headers);
306 $return_code = BaseObject::getApp()->get_curl_code();
308 logger('Transmit to ' . $target . ' returned ' . $return_code);
312 * @brief Gets a signer from a given HTTP request
315 * @param $http_headers
317 * @return signer string
319 public static function getSigner($content, $http_headers)
321 $object = json_decode($content, true);
323 if (empty($object)) {
327 $actor = JsonLD::fetchElement($object, 'actor', 'id');
330 $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . $http_headers['REQUEST_URI'];
332 // First take every header
333 foreach ($http_headers as $k => $v) {
334 $field = str_replace('_', '-', strtolower($k));
335 $headers[$field] = $v;
338 // Now add every http header
339 foreach ($http_headers as $k => $v) {
340 if (strpos($k, 'HTTP_') === 0) {
341 $field = str_replace('_', '-', strtolower(substr($k, 5)));
342 $headers[$field] = $v;
346 $sig_block = self::parseSigHeader($http_headers['HTTP_SIGNATURE']);
348 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
353 foreach ($sig_block['headers'] as $h) {
354 if (array_key_exists($h, $headers)) {
355 $signed_data .= $h . ': ' . $headers[$h] . "\n";
358 $signed_data = rtrim($signed_data, "\n");
360 if (empty($signed_data)) {
366 if ($sig_block['algorithm'] === 'rsa-sha256') {
367 $algorithm = 'sha256';
370 if ($sig_block['algorithm'] === 'rsa-sha512') {
371 $algorithm = 'sha512';
374 if (empty($algorithm)) {
378 $key = self::fetchKey($sig_block['keyId'], $actor);
384 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key['pubkey'], $algorithm)) {
388 // Check the digest when it is part of the signed data
389 if (in_array('digest', $sig_block['headers'])) {
390 $digest = explode('=', $headers['digest'], 2);
391 if ($digest[0] === 'SHA-256') {
394 if ($digest[0] === 'SHA-512') {
398 /// @todo add all hashes from the rfc
400 if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
405 // Check the content-length when it is part of the signed data
406 if (in_array('content-length', $sig_block['headers'])) {
407 if (strlen($content) != $headers['content-length']) {
416 * @brief fetches a key for a given id and actor
421 * @return array with actor url and public key
423 private static function fetchKey($id, $actor)
425 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
427 $profile = APContact::getByURL($url);
428 if (!empty($profile)) {
429 logger('Taking key from id ' . $id, LOGGER_DEBUG);
430 return ['url' => $url, 'pubkey' => $profile['pubkey']];
431 } elseif ($url != $actor) {
432 $profile = APContact::getByURL($actor);
433 if (!empty($profile)) {
434 logger('Taking key from actor ' . $actor, LOGGER_DEBUG);
435 return ['url' => $actor, 'pubkey' => $profile['pubkey']];