4 * @file src/Util/HTTPSignature.php
6 namespace Friendica\Util;
8 use Friendica\Core\Config;
9 use Friendica\Core\Logger;
10 use Friendica\Model\User;
11 use Friendica\Model\APContact;
14 * @brief Implements HTTP Signatures per draft-cavage-http-signatures-07.
16 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/Zotlabs/Web/HTTPSig.php
18 * Other parts of the code for HTTP signing are taken from the Osada project.
19 * https://framagit.org/macgirvin/osada
21 * @see https://tools.ietf.org/html/draft-cavage-http-signatures-07
26 // See draft-cavage-http-signatures-08
28 * @brief Verifies a magic request
32 * @return array with verification data
33 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
35 public static function verifyMagic($key)
41 'header_signed' => false,
42 'header_valid' => false
45 // Decide if $data arrived via controller submission or curl.
47 $headers['(request-target)'] = strtolower($_SERVER['REQUEST_METHOD']).' '.$_SERVER['REQUEST_URI'];
49 foreach ($_SERVER as $k => $v) {
50 if (strpos($k, 'HTTP_') === 0) {
51 $field = str_replace('_', '-', strtolower(substr($k, 5)));
52 $headers[$field] = $v;
58 $sig_block = self::parseSigheader($headers['authorization']);
61 Logger::log('no signature provided.');
65 $result['header_signed'] = true;
67 $signed_headers = $sig_block['headers'];
68 if (!$signed_headers) {
69 $signed_headers = ['date'];
73 foreach ($signed_headers as $h) {
74 if (array_key_exists($h, $headers)) {
75 $signed_data .= $h . ': ' . $headers[$h] . "\n";
77 if (strpos($h, '.')) {
82 $signed_data = rtrim($signed_data, "\n");
84 $algorithm = 'sha512';
86 if ($key && function_exists($key)) {
87 $result['signer'] = $sig_block['keyId'];
88 $key = $key($sig_block['keyId']);
91 Logger::log('Got keyID ' . $sig_block['keyId'], Logger::DEBUG);
97 $x = Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm);
99 Logger::log('verified: ' . $x, Logger::DEBUG);
106 $result['header_valid'] = true;
116 * @param string $prvkey
117 * @param string $keyid (optional, default 'Key')
121 public static function createSig($head, $prvkey, $keyid = 'Key')
123 $return_headers = [];
126 $algorithm = 'rsa-sha512';
128 $x = self::sign($head, $prvkey, $alg);
130 $headerval = 'keyId="' . $keyid . '",algorithm="' . $algorithm
131 . '",headers="' . $x['headers'] . '",signature="' . $x['signature'] . '"';
133 $sighead = 'Authorization: Signature ' . $headerval;
136 foreach ($head as $k => $v) {
137 $return_headers[] = $k . ': ' . $v;
141 $return_headers[] = $sighead;
143 return $return_headers;
150 * @param string $prvkey
151 * @param string $alg (optional) default 'sha256'
155 private static function sign($head, $prvkey, $alg = 'sha256')
161 foreach ($head as $k => $v) {
162 $headers .= strtolower($k) . ': ' . trim($v) . "\n";
166 $fields .= strtolower($k);
168 // strip the trailing linefeed
169 $headers = rtrim($headers, "\n");
171 $sig = base64_encode(Crypto::rsaSign($headers, $prvkey, $alg));
173 $ret['headers'] = $fields;
174 $ret['signature'] = $sig;
182 * @param string $header
183 * @return array associate array with
184 * - \e string \b keyID
185 * - \e string \b algorithm
186 * - \e array \b headers
187 * - \e string \b signature
188 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
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];
207 $ret['algorithm'] = 'rsa-sha256';
210 if (preg_match('/headers="(.*?)"/ism', $header, $matches)) {
211 $ret['headers'] = explode(' ', $matches[1]);
214 if (preg_match('/signature="(.*?)"/ism', $header, $matches)) {
215 $ret['signature'] = base64_decode(preg_replace('/\s+/', '', $matches[1]));
218 if (!empty($ret['signature']) && !empty($ret['algorithm']) && empty($ret['headers'])) {
219 $ret['headers'] = ['date'];
228 * @param string $header
229 * @param string $prvkey (optional), if not set use site private key
231 * @return array|string associative array, empty string if failue
235 * - \e string \b data
236 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
238 private static function decryptSigheader($header, $prvkey = null)
240 $iv = $key = $alg = $data = null;
243 $prvkey = Config::get('system', 'prvkey');
248 if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
252 if (preg_match('/key="(.*?)"/ism', $header, $matches)) {
256 if (preg_match('/alg="(.*?)"/ism', $header, $matches)) {
260 if (preg_match('/data="(.*?)"/ism', $header, $matches)) {
264 if ($iv && $key && $alg && $data) {
265 return Crypto::unencapsulate(['iv' => $iv, 'key' => $key, 'alg' => $alg, 'data' => $data], $prvkey);
272 * Functions for ActivityPub
276 * @brief Transmit given data to a target for a user
278 * @param array $data Data that is about to be send
279 * @param string $target The URL of the inbox
280 * @param integer $uid User id of the sender
282 * @return boolean Was the transmission successful?
283 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
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
327 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
329 public static function fetch($request, $uid)
331 $owner = User::getOwnerDataById($uid);
337 // Header data that is about to be signed.
338 $host = parse_url($request, PHP_URL_HOST);
339 $path = parse_url($request, PHP_URL_PATH);
340 $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP);
342 $headers = ['Date: ' . $date, 'Host: ' . $host];
344 $signed_data = "(request-target): get " . $path . "\ndate: ". $date . "\nhost: " . $host;
346 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
348 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) date host",signature="' . $signature . '"';
350 $headers[] = 'Accept: application/activity+json, application/ld+json';
352 $curlResult = Network::curl($request, false, $redirects, ['header' => $headers]);
353 $return_code = $curlResult->getReturnCode();
355 Logger::log('Fetched for user ' . $uid . ' from ' . $request . ' returned ' . $return_code, Logger::DEBUG);
357 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
361 $content = json_decode($curlResult->getBody(), true);
363 if (empty($content) || !is_array($content)) {
371 * @brief Gets a signer from a given HTTP request
374 * @param $http_headers
376 * @return string Signer
377 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
379 public static function getSigner($content, $http_headers)
381 if (empty($http_headers['HTTP_SIGNATURE'])) {
385 if (!empty($content)) {
386 $object = json_decode($content, true);
387 if (empty($object)) {
391 $actor = JsonLD::fetchElement($object, 'actor', 'id');
397 $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . $http_headers['REQUEST_URI'];
399 // First take every header
400 foreach ($http_headers as $k => $v) {
401 $field = str_replace('_', '-', strtolower($k));
402 $headers[$field] = $v;
405 // Now add every http header
406 foreach ($http_headers as $k => $v) {
407 if (strpos($k, 'HTTP_') === 0) {
408 $field = str_replace('_', '-', strtolower(substr($k, 5)));
409 $headers[$field] = $v;
413 $sig_block = self::parseSigHeader($http_headers['HTTP_SIGNATURE']);
415 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
420 foreach ($sig_block['headers'] as $h) {
421 if (array_key_exists($h, $headers)) {
422 $signed_data .= $h . ': ' . $headers[$h] . "\n";
425 $signed_data = rtrim($signed_data, "\n");
427 if (empty($signed_data)) {
433 if ($sig_block['algorithm'] === 'rsa-sha256') {
434 $algorithm = 'sha256';
437 if ($sig_block['algorithm'] === 'rsa-sha512') {
438 $algorithm = 'sha512';
441 if (empty($algorithm)) {
445 $key = self::fetchKey($sig_block['keyId'], $actor);
451 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key['pubkey'], $algorithm)) {
455 // Check the digest when it is part of the signed data
456 if (in_array('digest', $sig_block['headers'])) {
457 $digest = explode('=', $headers['digest'], 2);
458 if ($digest[0] === 'SHA-256') {
461 if ($digest[0] === 'SHA-512') {
465 /// @todo add all hashes from the rfc
467 if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
472 // Check if the signed date field is in an acceptable range
473 if (in_array('date', $sig_block['headers'])) {
474 $diff = abs(strtotime($headers['date']) - time());
476 Logger::log("Header date '" . $headers['date'] . "' is with " . $diff . " seconds out of the 300 second frame. The signature is invalid.");
481 // Check the content-length when it is part of the signed data
482 if (in_array('content-length', $sig_block['headers'])) {
483 if (strlen($content) != $headers['content-length']) {
492 * @brief fetches a key for a given id and actor
497 * @return array with actor url and public key
500 private static function fetchKey($id, $actor)
502 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
504 $profile = APContact::getByURL($url);
505 if (!empty($profile)) {
506 Logger::log('Taking key from id ' . $id, Logger::DEBUG);
507 return ['url' => $url, 'pubkey' => $profile['pubkey']];
508 } elseif ($url != $actor) {
509 $profile = APContact::getByURL($actor);
510 if (!empty($profile)) {
511 Logger::log('Taking key from actor ' . $actor, Logger::DEBUG);
512 return ['url' => $actor, 'pubkey' => $profile['pubkey']];