Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

625 lines
16 KiB

3 years ago
3 years ago
3 years ago
  1. <?php
  2. /**
  3. * @file src/Util/HTTPSignature.php
  4. */
  5. namespace Friendica\Util;
  6. use Friendica\Database\DBA;
  7. use Friendica\Core\Config;
  8. use Friendica\Core\Logger;
  9. use Friendica\Model\User;
  10. use Friendica\Model\APContact;
  11. /**
  12. * @brief Implements HTTP Signatures per draft-cavage-http-signatures-07.
  13. *
  14. * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/Zotlabs/Web/HTTPSig.php
  15. *
  16. * Other parts of the code for HTTP signing are taken from the Osada project.
  17. * https://framagit.org/macgirvin/osada
  18. *
  19. * @see https://tools.ietf.org/html/draft-cavage-http-signatures-07
  20. */
  21. class HTTPSignature
  22. {
  23. // See draft-cavage-http-signatures-08
  24. /**
  25. * @brief Verifies a magic request
  26. *
  27. * @param $key
  28. *
  29. * @return array with verification data
  30. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  31. */
  32. public static function verifyMagic($key)
  33. {
  34. $headers = null;
  35. $spoofable = false;
  36. $result = [
  37. 'signer' => '',
  38. 'header_signed' => false,
  39. 'header_valid' => false
  40. ];
  41. // Decide if $data arrived via controller submission or curl.
  42. $headers = [];
  43. $headers['(request-target)'] = strtolower($_SERVER['REQUEST_METHOD']).' '.$_SERVER['REQUEST_URI'];
  44. foreach ($_SERVER as $k => $v) {
  45. if (strpos($k, 'HTTP_') === 0) {
  46. $field = str_replace('_', '-', strtolower(substr($k, 5)));
  47. $headers[$field] = $v;
  48. }
  49. }
  50. $sig_block = null;
  51. $sig_block = self::parseSigheader($headers['authorization']);
  52. if (!$sig_block) {
  53. Logger::log('no signature provided.');
  54. return $result;
  55. }
  56. $result['header_signed'] = true;
  57. $signed_headers = $sig_block['headers'];
  58. if (!$signed_headers) {
  59. $signed_headers = ['date'];
  60. }
  61. $signed_data = '';
  62. foreach ($signed_headers as $h) {
  63. if (array_key_exists($h, $headers)) {
  64. $signed_data .= $h . ': ' . $headers[$h] . "\n";
  65. }
  66. if (strpos($h, '.')) {
  67. $spoofable = true;
  68. }
  69. }
  70. $signed_data = rtrim($signed_data, "\n");
  71. $algorithm = 'sha512';
  72. if ($key && function_exists($key)) {
  73. $result['signer'] = $sig_block['keyId'];
  74. $key = $key($sig_block['keyId']);
  75. }
  76. Logger::log('Got keyID ' . $sig_block['keyId'], Logger::DEBUG);
  77. if (!$key) {
  78. return $result;
  79. }
  80. $x = Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm);
  81. Logger::log('verified: ' . $x, Logger::DEBUG);
  82. if (!$x) {
  83. return $result;
  84. }
  85. if (!$spoofable) {
  86. $result['header_valid'] = true;
  87. }
  88. return $result;
  89. }
  90. /**
  91. * @brief
  92. *
  93. * @param array $head
  94. * @param string $prvkey
  95. * @param string $keyid (optional, default 'Key')
  96. *
  97. * @return array
  98. */
  99. public static function createSig($head, $prvkey, $keyid = 'Key')
  100. {
  101. $return_headers = [];
  102. $alg = 'sha512';
  103. $algorithm = 'rsa-sha512';
  104. $x = self::sign($head, $prvkey, $alg);
  105. $headerval = 'keyId="' . $keyid . '",algorithm="' . $algorithm
  106. . '",headers="' . $x['headers'] . '",signature="' . $x['signature'] . '"';
  107. $sighead = 'Authorization: Signature ' . $headerval;
  108. if ($head) {
  109. foreach ($head as $k => $v) {
  110. $return_headers[] = $k . ': ' . $v;
  111. }
  112. }
  113. $return_headers[] = $sighead;
  114. return $return_headers;
  115. }
  116. /**
  117. * @brief
  118. *
  119. * @param array $head
  120. * @param string $prvkey
  121. * @param string $alg (optional) default 'sha256'
  122. *
  123. * @return array
  124. */
  125. private static function sign($head, $prvkey, $alg = 'sha256')
  126. {
  127. $ret = [];
  128. $headers = '';
  129. $fields = '';
  130. foreach ($head as $k => $v) {
  131. $headers .= strtolower($k) . ': ' . trim($v) . "\n";
  132. if ($fields) {
  133. $fields .= ' ';
  134. }
  135. $fields .= strtolower($k);
  136. }
  137. // strip the trailing linefeed
  138. $headers = rtrim($headers, "\n");
  139. $sig = base64_encode(Crypto::rsaSign($headers, $prvkey, $alg));
  140. $ret['headers'] = $fields;
  141. $ret['signature'] = $sig;
  142. return $ret;
  143. }
  144. /**
  145. * @brief
  146. *
  147. * @param string $header
  148. * @return array associate array with
  149. * - \e string \b keyID
  150. * - \e string \b algorithm
  151. * - \e array \b headers
  152. * - \e string \b signature
  153. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  154. */
  155. public static function parseSigheader($header)
  156. {
  157. $ret = [];
  158. $matches = [];
  159. // if the header is encrypted, decrypt with (default) site private key and continue
  160. if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
  161. $header = self::decryptSigheader($header);
  162. }
  163. if (preg_match('/keyId="(.*?)"/ism', $header, $matches)) {
  164. $ret['keyId'] = $matches[1];
  165. }
  166. if (preg_match('/algorithm="(.*?)"/ism', $header, $matches)) {
  167. $ret['algorithm'] = $matches[1];
  168. } else {
  169. $ret['algorithm'] = 'rsa-sha256';
  170. }
  171. if (preg_match('/headers="(.*?)"/ism', $header, $matches)) {
  172. $ret['headers'] = explode(' ', $matches[1]);
  173. }
  174. if (preg_match('/signature="(.*?)"/ism', $header, $matches)) {
  175. $ret['signature'] = base64_decode(preg_replace('/\s+/', '', $matches[1]));
  176. }
  177. if (!empty($ret['signature']) && !empty($ret['algorithm']) && empty($ret['headers'])) {
  178. $ret['headers'] = ['date'];
  179. }
  180. return $ret;
  181. }
  182. /**
  183. * @brief
  184. *
  185. * @param string $header
  186. * @param string $prvkey (optional), if not set use site private key
  187. *
  188. * @return array|string associative array, empty string if failue
  189. * - \e string \b iv
  190. * - \e string \b key
  191. * - \e string \b alg
  192. * - \e string \b data
  193. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  194. */
  195. private static function decryptSigheader($header, $prvkey = null)
  196. {
  197. $iv = $key = $alg = $data = null;
  198. if (!$prvkey) {
  199. $prvkey = Config::get('system', 'prvkey');
  200. }
  201. $matches = [];
  202. if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
  203. $iv = $matches[1];
  204. }
  205. if (preg_match('/key="(.*?)"/ism', $header, $matches)) {
  206. $key = $matches[1];
  207. }
  208. if (preg_match('/alg="(.*?)"/ism', $header, $matches)) {
  209. $alg = $matches[1];
  210. }
  211. if (preg_match('/data="(.*?)"/ism', $header, $matches)) {
  212. $data = $matches[1];
  213. }
  214. if ($iv && $key && $alg && $data) {
  215. return Crypto::unencapsulate(['iv' => $iv, 'key' => $key, 'alg' => $alg, 'data' => $data], $prvkey);
  216. }
  217. return '';
  218. }
  219. /*
  220. * Functions for ActivityPub
  221. */
  222. /**
  223. * @brief Transmit given data to a target for a user
  224. *
  225. * @param array $data Data that is about to be send
  226. * @param string $target The URL of the inbox
  227. * @param integer $uid User id of the sender
  228. *
  229. * @return boolean Was the transmission successful?
  230. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  231. */
  232. public static function transmit($data, $target, $uid)
  233. {
  234. $owner = User::getOwnerDataById($uid);
  235. if (!$owner) {
  236. return;
  237. }
  238. $content = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
  239. // Header data that is about to be signed.
  240. $host = parse_url($target, PHP_URL_HOST);
  241. $path = parse_url($target, PHP_URL_PATH);
  242. $digest = 'SHA-256=' . base64_encode(hash('sha256', $content, true));
  243. $content_length = strlen($content);
  244. $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP);
  245. $headers = ['Date: ' . $date, 'Content-Length: ' . $content_length, 'Digest: ' . $digest, 'Host: ' . $host];
  246. $signed_data = "(request-target): post " . $path . "\ndate: ". $date . "\ncontent-length: " . $content_length . "\ndigest: " . $digest . "\nhost: " . $host;
  247. $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
  248. $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) date content-length digest host",signature="' . $signature . '"';
  249. $headers[] = 'Content-Type: application/activity+json';
  250. $postResult = Network::post($target, $content, $headers);
  251. $return_code = $postResult->getReturnCode();
  252. Logger::log('Transmit to ' . $target . ' returned ' . $return_code, Logger::DEBUG);
  253. $success = ($return_code >= 200) && ($return_code <= 299);
  254. self::setInboxStatus($target, $success);
  255. return $success;
  256. }
  257. /**
  258. * @brief Set the delivery status for a given inbox
  259. *
  260. * @param string $url The URL of the inbox
  261. * @param boolean $success Transmission status
  262. */
  263. static private function setInboxStatus($url, $success)
  264. {
  265. $now = DateTimeFormat::utcNow();
  266. $status = DBA::selectFirst('inbox-status', [], ['url' => $url]);
  267. if (!DBA::isResult($status)) {
  268. DBA::insert('inbox-status', ['url' => $url, 'created' => $now]);
  269. $status = DBA::selectFirst('inbox-status', [], ['url' => $url]);
  270. }
  271. if ($success) {
  272. $fields = ['success' => $now];
  273. } else {
  274. $fields = ['failure' => $now];
  275. }
  276. if ($status['failure'] > DBA::NULL_DATETIME) {
  277. $new_previous_stamp = strtotime($status['failure']);
  278. $old_previous_stamp = strtotime($status['previous']);
  279. // Only set "previous" with at least one day difference.
  280. // We use this to assure to not accidentally archive too soon.
  281. if (($new_previous_stamp - $old_previous_stamp) >= 86400) {
  282. $fields['previous'] = $status['failure'];
  283. }
  284. }
  285. if (!$success) {
  286. if ($status['success'] <= DBA::NULL_DATETIME) {
  287. $stamp1 = strtotime($status['created']);
  288. } else {
  289. $stamp1 = strtotime($status['success']);
  290. }
  291. $stamp2 = strtotime($now);
  292. $previous_stamp = strtotime($status['previous']);
  293. // Archive the inbox when there had been failures for five days.
  294. // Additionally ensure that at least one previous attempt has to be in between.
  295. if ((($stamp2 - $stamp1) >= 86400 * 5) && ($previous_stamp > $stamp1)) {
  296. $fields['archive'] = true;
  297. }
  298. } else {
  299. $fields['archive'] = false;
  300. }
  301. DBA::update('inbox-status', $fields, ['url' => $url]);
  302. }
  303. /**
  304. * @brief Fetches JSON data for a user
  305. *
  306. * @param string $request request url
  307. * @param integer $uid User id of the requester
  308. *
  309. * @return array JSON array
  310. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  311. */
  312. public static function fetch($request, $uid)
  313. {
  314. $opts = ['accept_content' => 'application/activity+json, application/ld+json'];
  315. $curlResult = self::fetchRaw($request, $uid, false, $opts);
  316. if (empty($curlResult)) {
  317. return false;
  318. }
  319. if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
  320. return false;
  321. }
  322. $content = json_decode($curlResult->getBody(), true);
  323. if (empty($content) || !is_array($content)) {
  324. return false;
  325. }
  326. return $content;
  327. }
  328. /**
  329. * @brief Fetches raw data for a user
  330. *
  331. * @param string $request request url
  332. * @param integer $uid User id of the requester
  333. * @param boolean $binary TRUE if asked to return binary results (file download) (default is "false")
  334. * @param array $opts (optional parameters) assoziative array with:
  335. * 'accept_content' => supply Accept: header with 'accept_content' as the value
  336. * 'timeout' => int Timeout in seconds, default system config value or 60 seconds
  337. * 'http_auth' => username:password
  338. * 'novalidate' => do not validate SSL certs, default is to validate using our CA list
  339. * 'nobody' => only return the header
  340. * 'cookiejar' => path to cookie jar file
  341. *
  342. * @return object CurlResult
  343. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  344. */
  345. public static function fetchRaw($request, $uid = 0, $binary = false, $opts = [])
  346. {
  347. if (!empty($uid)) {
  348. $owner = User::getOwnerDataById($uid);
  349. if (!$owner) {
  350. return;
  351. }
  352. // Header data that is about to be signed.
  353. $host = parse_url($request, PHP_URL_HOST);
  354. $path = parse_url($request, PHP_URL_PATH);
  355. $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP);
  356. $headers = ['Date: ' . $date, 'Host: ' . $host];
  357. $signed_data = "(request-target): get " . $path . "\ndate: ". $date . "\nhost: " . $host;
  358. $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
  359. $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) date host",signature="' . $signature . '"';
  360. } else {
  361. $headers = [];
  362. }
  363. if (!empty($opts['accept_content'])) {
  364. $headers[] = 'Accept: ' . $opts['accept_content'];
  365. }
  366. $curl_opts = $opts;
  367. $curl_opts['header'] = $headers;
  368. $curlResult = Network::curl($request, false, $curl_opts);
  369. $return_code = $curlResult->getReturnCode();
  370. Logger::log('Fetched for user ' . $uid . ' from ' . $request . ' returned ' . $return_code, Logger::DEBUG);
  371. return $curlResult;
  372. }
  373. /**
  374. * @brief Gets a signer from a given HTTP request
  375. *
  376. * @param $content
  377. * @param $http_headers
  378. *
  379. * @return string Signer
  380. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  381. */
  382. public static function getSigner($content, $http_headers)
  383. {
  384. if (empty($http_headers['HTTP_SIGNATURE'])) {
  385. return false;
  386. }
  387. if (!empty($content)) {
  388. $object = json_decode($content, true);
  389. if (empty($object)) {
  390. return false;
  391. }
  392. $actor = JsonLD::fetchElement($object, 'actor', 'id');
  393. } else {
  394. $actor = '';
  395. }
  396. $headers = [];
  397. $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . $http_headers['REQUEST_URI'];
  398. // First take every header
  399. foreach ($http_headers as $k => $v) {
  400. $field = str_replace('_', '-', strtolower($k));
  401. $headers[$field] = $v;
  402. }
  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;
  408. }
  409. }
  410. $sig_block = self::parseSigHeader($http_headers['HTTP_SIGNATURE']);
  411. if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
  412. return false;
  413. }
  414. $signed_data = '';
  415. foreach ($sig_block['headers'] as $h) {
  416. if (array_key_exists($h, $headers)) {
  417. $signed_data .= $h . ': ' . $headers[$h] . "\n";
  418. }
  419. }
  420. $signed_data = rtrim($signed_data, "\n");
  421. if (empty($signed_data)) {
  422. return false;
  423. }
  424. $algorithm = null;
  425. if ($sig_block['algorithm'] === 'rsa-sha256') {
  426. $algorithm = 'sha256';
  427. }
  428. if ($sig_block['algorithm'] === 'rsa-sha512') {
  429. $algorithm = 'sha512';
  430. }
  431. if (empty($algorithm)) {
  432. return false;
  433. }
  434. $key = self::fetchKey($sig_block['keyId'], $actor);
  435. if (empty($key)) {
  436. return false;
  437. }
  438. if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key['pubkey'], $algorithm)) {
  439. return false;
  440. }
  441. $hasGoodSignedContent = false;
  442. // Check the digest when it is part of the signed data
  443. if (!empty($content) && in_array('digest', $sig_block['headers'])) {
  444. $digest = explode('=', $headers['digest'], 2);
  445. if ($digest[0] === 'SHA-256') {
  446. $hashalg = 'sha256';
  447. }
  448. if ($digest[0] === 'SHA-512') {
  449. $hashalg = 'sha512';
  450. }
  451. /// @todo add all hashes from the rfc
  452. if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
  453. return false;
  454. }
  455. $hasGoodSignedContent = true;
  456. }
  457. // Check if the signed date field is in an acceptable range
  458. if (in_array('date', $sig_block['headers'])) {
  459. $diff = abs(strtotime($headers['date']) - time());
  460. if ($diff > 300) {
  461. Logger::log("Header date '" . $headers['date'] . "' is with " . $diff . " seconds out of the 300 second frame. The signature is invalid.");
  462. return false;
  463. }
  464. $hasGoodSignedContent = true;
  465. }
  466. // Check the content-length when it is part of the signed data
  467. if (in_array('content-length', $sig_block['headers'])) {
  468. if (strlen($content) != $headers['content-length']) {
  469. return false;
  470. }
  471. }
  472. // Ensure that the authentication had been done with some content
  473. // Without this check someone could authenticate with fakeable data
  474. if (!$hasGoodSignedContent) {
  475. return false;
  476. }
  477. return $key['url'];
  478. }
  479. /**
  480. * @brief fetches a key for a given id and actor
  481. *
  482. * @param $id
  483. * @param $actor
  484. *
  485. * @return array with actor url and public key
  486. * @throws \Exception
  487. */
  488. private static function fetchKey($id, $actor)
  489. {
  490. $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
  491. $profile = APContact::getByURL($url);
  492. if (!empty($profile)) {
  493. Logger::log('Taking key from id ' . $id, Logger::DEBUG);
  494. return ['url' => $url, 'pubkey' => $profile['pubkey']];
  495. } elseif ($url != $actor) {
  496. $profile = APContact::getByURL($actor);
  497. if (!empty($profile)) {
  498. Logger::log('Taking key from actor ' . $actor, Logger::DEBUG);
  499. return ['url' => $actor, 'pubkey' => $profile['pubkey']];
  500. }
  501. }
  502. return false;
  503. }
  504. }