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 $opts = ['accept_content' => 'application/activity+json, application/ld+json'];
332 $curlResult = self::fetchRaw($request, $uid, false, $opts);
334 if (empty($curlResult)) {
338 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
342 $content = json_decode($curlResult->getBody(), true);
343 if (empty($content) || !is_array($content)) {
351 * @brief Fetches raw data for a user
353 * @param string $request request url
354 * @param integer $uid User id of the requester
355 * @param boolean $binary TRUE if asked to return binary results (file download) (default is "false")
356 * @param array $opts (optional parameters) assoziative array with:
357 * 'accept_content' => supply Accept: header with 'accept_content' as the value
358 * 'timeout' => int Timeout in seconds, default system config value or 60 seconds
359 * 'http_auth' => username:password
360 * 'novalidate' => do not validate SSL certs, default is to validate using our CA list
361 * 'nobody' => only return the header
362 * 'cookiejar' => path to cookie jar file
364 * @return object CurlResult
365 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
367 public static function fetchRaw($request, $uid = 0, $binary = false, $opts = [])
370 $owner = User::getOwnerDataById($uid);
375 // Header data that is about to be signed.
376 $host = parse_url($request, PHP_URL_HOST);
377 $path = parse_url($request, PHP_URL_PATH);
378 $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP);
380 $headers = ['Date: ' . $date, 'Host: ' . $host];
382 $signed_data = "(request-target): get " . $path . "\ndate: ". $date . "\nhost: " . $host;
384 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
386 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) date host",signature="' . $signature . '"';
391 if (!empty($opts['accept_content'])) {
392 $headers[] = 'Accept: ' . $opts['accept_content'];
396 $curl_opts['header'] = $headers;
398 $curlResult = Network::curl($request, false, $redirects, $curl_opts);
399 $return_code = $curlResult->getReturnCode();
401 Logger::log('Fetched for user ' . $uid . ' from ' . $request . ' returned ' . $return_code, Logger::DEBUG);
407 * @brief Gets a signer from a given HTTP request
410 * @param $http_headers
412 * @return string Signer
413 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
415 public static function getSigner($content, $http_headers)
417 if (empty($http_headers['HTTP_SIGNATURE'])) {
421 if (!empty($content)) {
422 $object = json_decode($content, true);
423 if (empty($object)) {
427 $actor = JsonLD::fetchElement($object, 'actor', 'id');
433 $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . $http_headers['REQUEST_URI'];
435 // First take every header
436 foreach ($http_headers as $k => $v) {
437 $field = str_replace('_', '-', strtolower($k));
438 $headers[$field] = $v;
441 // Now add every http header
442 foreach ($http_headers as $k => $v) {
443 if (strpos($k, 'HTTP_') === 0) {
444 $field = str_replace('_', '-', strtolower(substr($k, 5)));
445 $headers[$field] = $v;
449 $sig_block = self::parseSigHeader($http_headers['HTTP_SIGNATURE']);
451 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
456 foreach ($sig_block['headers'] as $h) {
457 if (array_key_exists($h, $headers)) {
458 $signed_data .= $h . ': ' . $headers[$h] . "\n";
461 $signed_data = rtrim($signed_data, "\n");
463 if (empty($signed_data)) {
469 if ($sig_block['algorithm'] === 'rsa-sha256') {
470 $algorithm = 'sha256';
473 if ($sig_block['algorithm'] === 'rsa-sha512') {
474 $algorithm = 'sha512';
477 if (empty($algorithm)) {
481 $key = self::fetchKey($sig_block['keyId'], $actor);
487 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key['pubkey'], $algorithm)) {
491 $hasGoodSignedContent = false;
493 // Check the digest when it is part of the signed data
494 if (!empty($content) && in_array('digest', $sig_block['headers'])) {
495 $digest = explode('=', $headers['digest'], 2);
496 if ($digest[0] === 'SHA-256') {
499 if ($digest[0] === 'SHA-512') {
503 /// @todo add all hashes from the rfc
505 if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
509 $hasGoodSignedContent = true;
512 // Check if the signed date field is in an acceptable range
513 if (in_array('date', $sig_block['headers'])) {
514 $diff = abs(strtotime($headers['date']) - time());
516 Logger::log("Header date '" . $headers['date'] . "' is with " . $diff . " seconds out of the 300 second frame. The signature is invalid.");
519 $hasGoodSignedContent = true;
522 // Check the content-length when it is part of the signed data
523 if (in_array('content-length', $sig_block['headers'])) {
524 if (strlen($content) != $headers['content-length']) {
529 // Ensure that the authentication had been done with some content
530 // Without this check someone could authenticate with fakeable data
531 if (!$hasGoodSignedContent) {
539 * @brief fetches a key for a given id and actor
544 * @return array with actor url and public key
547 private static function fetchKey($id, $actor)
549 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
551 $profile = APContact::getByURL($url);
552 if (!empty($profile)) {
553 Logger::log('Taking key from id ' . $id, Logger::DEBUG);
554 return ['url' => $url, 'pubkey' => $profile['pubkey']];
555 } elseif ($url != $actor) {
556 $profile = APContact::getByURL($actor);
557 if (!empty($profile)) {
558 Logger::log('Taking key from actor ' . $actor, Logger::DEBUG);
559 return ['url' => $actor, 'pubkey' => $profile['pubkey']];