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
20KB

  1. <?php
  2. /**
  3. * @file mod/dfrn_confirm.php
  4. * @brief Module: dfrn_confirm
  5. * Purpose: Friendship acceptance for DFRN contacts
  6. *
  7. * There are two possible entry points and three scenarios.
  8. *
  9. * 1. A form was submitted by our user approving a friendship that originated elsewhere.
  10. * This may also be called from dfrn_request to automatically approve a friendship.
  11. *
  12. * 2. We may be the target or other side of the conversation to scenario 1, and will
  13. * interact with that process on our own user's behalf.
  14. *
  15. * @see PDF with dfrn specs: https://github.com/friendica/friendica/blob/master/spec/dfrn2.pdf
  16. * You also find a graphic which describes the confirmation process at
  17. * https://github.com/friendica/friendica/blob/master/spec/dfrn2_contact_confirmation.png
  18. */
  19. use Friendica\App;
  20. use Friendica\Core\Config;
  21. use Friendica\Core\L10n;
  22. use Friendica\Core\Logger;
  23. use Friendica\Core\Protocol;
  24. use Friendica\Core\System;
  25. use Friendica\Database\DBA;
  26. use Friendica\Model\Contact;
  27. use Friendica\Model\Group;
  28. use Friendica\Model\User;
  29. use Friendica\Network\Probe;
  30. use Friendica\Protocol\Diaspora;
  31. use Friendica\Protocol\ActivityPub;
  32. use Friendica\Util\Crypto;
  33. use Friendica\Util\DateTimeFormat;
  34. use Friendica\Util\Network;
  35. use Friendica\Util\Strings;
  36. use Friendica\Util\XML;
  37. function dfrn_confirm_post(App $a, $handsfree = null)
  38. {
  39. $node = null;
  40. if (is_array($handsfree)) {
  41. /*
  42. * We were called directly from dfrn_request due to automatic friend acceptance.
  43. * Any $_POST parameters we may require are supplied in the $handsfree array.
  44. *
  45. */
  46. $node = $handsfree['node'];
  47. $a->interactive = false; // notice() becomes a no-op since nobody is there to see it
  48. } elseif ($a->argc > 1) {
  49. $node = $a->argv[1];
  50. }
  51. /*
  52. * Main entry point. Scenario 1. Our user received a friend request notification (perhaps
  53. * from another site) and clicked 'Approve'.
  54. * $POST['source_url'] is not set. If it is, it indicates Scenario 2.
  55. *
  56. * We may also have been called directly from dfrn_request ($handsfree != null) due to
  57. * this being a page type which supports automatic friend acceptance. That is also Scenario 1
  58. * since we are operating on behalf of our registered user to approve a friendship.
  59. */
  60. if (empty($_POST['source_url'])) {
  61. $uid = defaults($handsfree, 'uid', local_user());
  62. if (!$uid) {
  63. notice(L10n::t('Permission denied.') . EOL);
  64. return;
  65. }
  66. $user = DBA::selectFirst('user', [], ['uid' => $uid]);
  67. if (!DBA::isResult($user)) {
  68. notice(L10n::t('Profile not found.') . EOL);
  69. return;
  70. }
  71. // These data elements may come from either the friend request notification form or $handsfree array.
  72. if (is_array($handsfree)) {
  73. Logger::log('Confirm in handsfree mode');
  74. $dfrn_id = $handsfree['dfrn_id'];
  75. $intro_id = $handsfree['intro_id'];
  76. $duplex = $handsfree['duplex'];
  77. $cid = 0;
  78. $hidden = intval(defaults($handsfree, 'hidden' , 0));
  79. } else {
  80. $dfrn_id = Strings::escapeTags(trim(defaults($_POST, 'dfrn_id' , '')));
  81. $intro_id = intval(defaults($_POST, 'intro_id' , 0));
  82. $duplex = intval(defaults($_POST, 'duplex' , 0));
  83. $cid = intval(defaults($_POST, 'contact_id', 0));
  84. $hidden = intval(defaults($_POST, 'hidden' , 0));
  85. }
  86. /*
  87. * Ensure that dfrn_id has precedence when we go to find the contact record.
  88. * We only want to search based on contact id if there is no dfrn_id,
  89. * e.g. for OStatus network followers.
  90. */
  91. if (strlen($dfrn_id)) {
  92. $cid = 0;
  93. }
  94. Logger::log('Confirming request for dfrn_id (issued) ' . $dfrn_id);
  95. if ($cid) {
  96. Logger::log('Confirming follower with contact_id: ' . $cid);
  97. }
  98. /*
  99. * The other person will have been issued an ID when they first requested friendship.
  100. * Locate their record. At this time, their record will have both pending and blocked set to 1.
  101. * There won't be any dfrn_id if this is a network follower, so use the contact_id instead.
  102. */
  103. $r = q("SELECT *
  104. FROM `contact`
  105. WHERE (
  106. (`issued-id` != '' AND `issued-id` = '%s')
  107. OR
  108. (`id` = %d AND `id` != 0)
  109. )
  110. AND `uid` = %d
  111. AND `duplex` = 0
  112. LIMIT 1",
  113. DBA::escape($dfrn_id),
  114. intval($cid),
  115. intval($uid)
  116. );
  117. if (!DBA::isResult($r)) {
  118. Logger::log('Contact not found in DB.');
  119. notice(L10n::t('Contact not found.') . EOL);
  120. notice(L10n::t('This may occasionally happen if contact was requested by both persons and it has already been approved.') . EOL);
  121. return;
  122. }
  123. $contact = $r[0];
  124. $contact_id = $contact['id'];
  125. $relation = $contact['rel'];
  126. $site_pubkey = $contact['site-pubkey'];
  127. $dfrn_confirm = $contact['confirm'];
  128. $aes_allow = $contact['aes_allow'];
  129. $network = ((strlen($contact['issued-id'])) ? Protocol::DFRN : Protocol::OSTATUS);
  130. if ($contact['network']) {
  131. $network = $contact['network'];
  132. }
  133. if ($network === Protocol::DFRN) {
  134. /*
  135. * Generate a key pair for all further communications with this person.
  136. * We have a keypair for every contact, and a site key for unknown people.
  137. * This provides a means to carry on relationships with other people if
  138. * any single key is compromised. It is a robust key. We're much more
  139. * worried about key leakage than anybody cracking it.
  140. */
  141. $res = Crypto::newKeypair(4096);
  142. $private_key = $res['prvkey'];
  143. $public_key = $res['pubkey'];
  144. // Save the private key. Send them the public key.
  145. q("UPDATE `contact` SET `prvkey` = '%s' WHERE `id` = %d AND `uid` = %d",
  146. DBA::escape($private_key),
  147. intval($contact_id),
  148. intval($uid)
  149. );
  150. $params = [];
  151. /*
  152. * Per the DFRN protocol, we will verify both ends by encrypting the dfrn_id with our
  153. * site private key (person on the other end can decrypt it with our site public key).
  154. * Then encrypt our profile URL with the other person's site public key. They can decrypt
  155. * it with their site private key. If the decryption on the other end fails for either
  156. * item, it indicates tampering or key failure on at least one site and we will not be
  157. * able to provide a secure communication pathway.
  158. *
  159. * If other site is willing to accept full encryption, (aes_allow is 1 AND we have php5.3
  160. * or later) then we encrypt the personal public key we send them using AES-256-CBC and a
  161. * random key which is encrypted with their site public key.
  162. */
  163. $src_aes_key = openssl_random_pseudo_bytes(64);
  164. $result = '';
  165. openssl_private_encrypt($dfrn_id, $result, $user['prvkey']);
  166. $params['dfrn_id'] = bin2hex($result);
  167. $params['public_key'] = $public_key;
  168. $my_url = System::baseUrl() . '/profile/' . $user['nickname'];
  169. openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey);
  170. $params['source_url'] = bin2hex($params['source_url']);
  171. if ($aes_allow && function_exists('openssl_encrypt')) {
  172. openssl_public_encrypt($src_aes_key, $params['aes_key'], $site_pubkey);
  173. $params['aes_key'] = bin2hex($params['aes_key']);
  174. $params['public_key'] = bin2hex(openssl_encrypt($public_key, 'AES-256-CBC', $src_aes_key));
  175. }
  176. $params['dfrn_version'] = DFRN_PROTOCOL_VERSION;
  177. if ($duplex == 1) {
  178. $params['duplex'] = 1;
  179. }
  180. if ($user['page-flags'] == Contact::PAGE_COMMUNITY) {
  181. $params['page'] = 1;
  182. }
  183. if ($user['page-flags'] == Contact::PAGE_PRVGROUP) {
  184. $params['page'] = 2;
  185. }
  186. Logger::log('Confirm: posting data to ' . $dfrn_confirm . ': ' . print_r($params, true), Logger::DATA);
  187. /*
  188. *
  189. * POST all this stuff to the other site.
  190. * Temporarily raise the network timeout to 120 seconds because the default 60
  191. * doesn't always give the other side quite enough time to decrypt everything.
  192. *
  193. */
  194. $res = Network::post($dfrn_confirm, $params, null, $redirects, 120)->getBody();
  195. Logger::log(' Confirm: received data: ' . $res, Logger::DATA);
  196. // Now figure out what they responded. Try to be robust if the remote site is
  197. // having difficulty and throwing up errors of some kind.
  198. $leading_junk = substr($res, 0, strpos($res, '<?xml'));
  199. $res = substr($res, strpos($res, '<?xml'));
  200. if (!strlen($res)) {
  201. // No XML at all, this exchange is messed up really bad.
  202. // We shouldn't proceed, because the xml parser might choke,
  203. // and $status is going to be zero, which indicates success.
  204. // We can hardly call this a success.
  205. notice(L10n::t('Response from remote site was not understood.') . EOL);
  206. return;
  207. }
  208. if (strlen($leading_junk) && Config::get('system', 'debugging')) {
  209. // This might be more common. Mixed error text and some XML.
  210. // If we're configured for debugging, show the text. Proceed in either case.
  211. notice(L10n::t('Unexpected response from remote site: ') . EOL . $leading_junk . EOL);
  212. }
  213. if (stristr($res, "<status") === false) {
  214. // wrong xml! stop here!
  215. Logger::log('Unexpected response posting to ' . $dfrn_confirm);
  216. notice(L10n::t('Unexpected response from remote site: ') . EOL . htmlspecialchars($res) . EOL);
  217. return;
  218. }
  219. $xml = XML::parseString($res);
  220. $status = (int) $xml->status;
  221. $message = XML::unescape($xml->message); // human readable text of what may have gone wrong.
  222. switch ($status) {
  223. case 0:
  224. info(L10n::t("Confirmation completed successfully.") . EOL);
  225. break;
  226. case 1:
  227. // birthday paradox - generate new dfrn-id and fall through.
  228. $new_dfrn_id = Strings::getRandomHex();
  229. q("UPDATE contact SET `issued-id` = '%s' WHERE `id` = %d AND `uid` = %d",
  230. DBA::escape($new_dfrn_id),
  231. intval($contact_id),
  232. intval($uid)
  233. );
  234. case 2:
  235. notice(L10n::t("Temporary failure. Please wait and try again.") . EOL);
  236. break;
  237. case 3:
  238. notice(L10n::t("Introduction failed or was revoked.") . EOL);
  239. break;
  240. }
  241. if (strlen($message)) {
  242. notice(L10n::t('Remote site reported: ') . $message . EOL);
  243. }
  244. if (($status == 0) && $intro_id) {
  245. $intro = DBA::selectFirst('intro', ['note'], ['id' => $intro_id]);
  246. if (DBA::isResult($intro)) {
  247. DBA::update('contact', ['reason' => $intro['note']], ['id' => $contact_id]);
  248. }
  249. // Success. Delete the notification.
  250. DBA::delete('intro', ['id' => $intro_id]);
  251. }
  252. if ($status != 0) {
  253. return;
  254. }
  255. }
  256. /*
  257. * We have now established a relationship with the other site.
  258. * Let's make our own personal copy of their profile photo so we don't have
  259. * to always load it from their site.
  260. *
  261. * We will also update the contact record with the nature and scope of the relationship.
  262. */
  263. Contact::updateAvatar($contact['photo'], $uid, $contact_id);
  264. Logger::log('dfrn_confirm: confirm - imported photos');
  265. if ($network === Protocol::DFRN) {
  266. $new_relation = Contact::FOLLOWER;
  267. if (($relation == Contact::SHARING) || ($duplex)) {
  268. $new_relation = Contact::FRIEND;
  269. }
  270. if (($relation == Contact::SHARING) && ($duplex)) {
  271. $duplex = 0;
  272. }
  273. $r = q("UPDATE `contact` SET `rel` = %d,
  274. `name-date` = '%s',
  275. `uri-date` = '%s',
  276. `blocked` = 0,
  277. `pending` = 0,
  278. `duplex` = %d,
  279. `hidden` = %d,
  280. `network` = '%s' WHERE `id` = %d
  281. ",
  282. intval($new_relation),
  283. DBA::escape(DateTimeFormat::utcNow()),
  284. DBA::escape(DateTimeFormat::utcNow()),
  285. intval($duplex),
  286. intval($hidden),
  287. DBA::escape(Protocol::DFRN),
  288. intval($contact_id)
  289. );
  290. } else {
  291. if ($network == Protocol::ACTIVITYPUB) {
  292. ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $uid);
  293. $pending = true;
  294. } else {
  295. $pending = false;
  296. }
  297. // $network !== Protocol::DFRN
  298. $network = defaults($contact, 'network', Protocol::OSTATUS);
  299. $arr = Probe::uri($contact['url'], $network);
  300. $notify = defaults($contact, 'notify' , $arr['notify']);
  301. $poll = defaults($contact, 'poll' , $arr['poll']);
  302. $addr = $arr['addr'];
  303. $new_relation = $contact['rel'];
  304. $writable = $contact['writable'];
  305. if (in_array($network, [Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
  306. if ($duplex) {
  307. $new_relation = Contact::FRIEND;
  308. } else {
  309. $new_relation = Contact::FOLLOWER;
  310. }
  311. if ($new_relation != Contact::FOLLOWER) {
  312. $writable = 1;
  313. }
  314. }
  315. DBA::delete('intro', ['id' => $intro_id]);
  316. $fields = ['name-date' => DateTimeFormat::utcNow(),
  317. 'uri-date' => DateTimeFormat::utcNow(), 'addr' => $addr,
  318. 'notify' => $notify, 'poll' => $poll, 'blocked' => false,
  319. 'pending' => $pending, 'network' => $network,
  320. 'writable' => $writable, 'hidden' => $hidden, 'rel' => $new_relation];
  321. DBA::update('contact', $fields, ['id' => $contact_id]);
  322. }
  323. if (!DBA::isResult($r)) {
  324. notice(L10n::t('Unable to set contact photo.') . EOL);
  325. }
  326. // reload contact info
  327. $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
  328. if ((isset($new_relation) && $new_relation == Contact::FRIEND)) {
  329. if (DBA::isResult($contact) && ($contact['network'] === Protocol::DIASPORA)) {
  330. $ret = Diaspora::sendShare($user, $contact);
  331. Logger::log('share returns: ' . $ret);
  332. }
  333. }
  334. Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact['id']);
  335. if ($network == Protocol::ACTIVITYPUB && $duplex) {
  336. ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid);
  337. }
  338. // Let's send our user to the contact editor in case they want to
  339. // do anything special with this new friend.
  340. if ($handsfree === null) {
  341. $a->internalRedirect('contact/' . intval($contact_id));
  342. } else {
  343. return;
  344. }
  345. //NOTREACHED
  346. }
  347. /*
  348. * End of Scenario 1. [Local confirmation of remote friend request].
  349. *
  350. * Begin Scenario 2. This is the remote response to the above scenario.
  351. * This will take place on the site that originally initiated the friend request.
  352. * In the section above where the confirming party makes a POST and
  353. * retrieves xml status information, they are communicating with the following code.
  354. */
  355. if (!empty($_POST['source_url'])) {
  356. // We are processing an external confirmation to an introduction created by our user.
  357. $public_key = defaults($_POST, 'public_key', '');
  358. $dfrn_id = hex2bin(defaults($_POST, 'dfrn_id' , ''));
  359. $source_url = hex2bin(defaults($_POST, 'source_url', ''));
  360. $aes_key = defaults($_POST, 'aes_key' , '');
  361. $duplex = intval(defaults($_POST, 'duplex' , 0));
  362. $page = intval(defaults($_POST, 'page' , 0));
  363. $forum = (($page == 1) ? 1 : 0);
  364. $prv = (($page == 2) ? 1 : 0);
  365. Logger::log('dfrn_confirm: requestee contacted: ' . $node);
  366. Logger::log('dfrn_confirm: request: POST=' . print_r($_POST, true), Logger::DATA);
  367. // If $aes_key is set, both of these items require unpacking from the hex transport encoding.
  368. if (!empty($aes_key)) {
  369. $aes_key = hex2bin($aes_key);
  370. $public_key = hex2bin($public_key);
  371. }
  372. // Find our user's account
  373. $user = DBA::selectFirst('user', [], ['nickname' => $node]);
  374. if (!DBA::isResult($user)) {
  375. $message = L10n::t('No user record found for \'%s\' ', $node);
  376. System::xmlExit(3, $message); // failure
  377. // NOTREACHED
  378. }
  379. $my_prvkey = $user['prvkey'];
  380. $local_uid = $user['uid'];
  381. if (!strstr($my_prvkey, 'PRIVATE KEY')) {
  382. $message = L10n::t('Our site encryption key is apparently messed up.');
  383. System::xmlExit(3, $message);
  384. }
  385. // verify everything
  386. $decrypted_source_url = "";
  387. openssl_private_decrypt($source_url, $decrypted_source_url, $my_prvkey);
  388. if (!strlen($decrypted_source_url)) {
  389. $message = L10n::t('Empty site URL was provided or URL could not be decrypted by us.');
  390. System::xmlExit(3, $message);
  391. // NOTREACHED
  392. }
  393. $contact = DBA::selectFirst('contact', [], ['url' => $decrypted_source_url, 'uid' => $local_uid]);
  394. if (!DBA::isResult($contact)) {
  395. if (strstr($decrypted_source_url, 'http:')) {
  396. $newurl = str_replace('http:', 'https:', $decrypted_source_url);
  397. } else {
  398. $newurl = str_replace('https:', 'http:', $decrypted_source_url);
  399. }
  400. $contact = DBA::selectFirst('contact', [], ['url' => $newurl, 'uid' => $local_uid]);
  401. if (!DBA::isResult($contact)) {
  402. // this is either a bogus confirmation (?) or we deleted the original introduction.
  403. $message = L10n::t('Contact record was not found for you on our site.');
  404. System::xmlExit(3, $message);
  405. return; // NOTREACHED
  406. }
  407. }
  408. $relation = $contact['rel'];
  409. // Decrypt all this stuff we just received
  410. $foreign_pubkey = $contact['site-pubkey'];
  411. $dfrn_record = $contact['id'];
  412. if (!$foreign_pubkey) {
  413. $message = L10n::t('Site public key not available in contact record for URL %s.', $decrypted_source_url);
  414. System::xmlExit(3, $message);
  415. }
  416. $decrypted_dfrn_id = "";
  417. openssl_public_decrypt($dfrn_id, $decrypted_dfrn_id, $foreign_pubkey);
  418. if (strlen($aes_key)) {
  419. $decrypted_aes_key = "";
  420. openssl_private_decrypt($aes_key, $decrypted_aes_key, $my_prvkey);
  421. $dfrn_pubkey = openssl_decrypt($public_key, 'AES-256-CBC', $decrypted_aes_key);
  422. } else {
  423. $dfrn_pubkey = $public_key;
  424. }
  425. if (DBA::exists('contact', ['dfrn-id' => $decrypted_dfrn_id])) {
  426. $message = L10n::t('The ID provided by your system is a duplicate on our system. It should work if you try again.');
  427. System::xmlExit(1, $message); // Birthday paradox - duplicate dfrn-id
  428. // NOTREACHED
  429. }
  430. $r = q("UPDATE `contact` SET `dfrn-id` = '%s', `pubkey` = '%s' WHERE `id` = %d",
  431. DBA::escape($decrypted_dfrn_id),
  432. DBA::escape($dfrn_pubkey),
  433. intval($dfrn_record)
  434. );
  435. if (!DBA::isResult($r)) {
  436. $message = L10n::t('Unable to set your contact credentials on our system.');
  437. System::xmlExit(3, $message);
  438. }
  439. // It's possible that the other person also requested friendship.
  440. // If it is a duplex relationship, ditch the issued-id if one exists.
  441. if ($duplex) {
  442. q("UPDATE `contact` SET `issued-id` = '' WHERE `id` = %d",
  443. intval($dfrn_record)
  444. );
  445. }
  446. // We're good but now we have to scrape the profile photo and send notifications.
  447. $contact = DBA::selectFirst('contact', ['photo'], ['id' => $dfrn_record]);
  448. if (DBA::isResult($contact)) {
  449. $photo = $contact['photo'];
  450. } else {
  451. $photo = System::baseUrl() . '/images/person-300.jpg';
  452. }
  453. Contact::updateAvatar($photo, $local_uid, $dfrn_record);
  454. Logger::log('dfrn_confirm: request - photos imported');
  455. $new_relation = Contact::SHARING;
  456. if (($relation == Contact::FOLLOWER) || ($duplex)) {
  457. $new_relation = Contact::FRIEND;
  458. }
  459. if (($relation == Contact::FOLLOWER) && ($duplex)) {
  460. $duplex = 0;
  461. }
  462. $r = q("UPDATE `contact` SET
  463. `rel` = %d,
  464. `name-date` = '%s',
  465. `uri-date` = '%s',
  466. `blocked` = 0,
  467. `pending` = 0,
  468. `duplex` = %d,
  469. `forum` = %d,
  470. `prv` = %d,
  471. `network` = '%s' WHERE `id` = %d
  472. ",
  473. intval($new_relation),
  474. DBA::escape(DateTimeFormat::utcNow()),
  475. DBA::escape(DateTimeFormat::utcNow()),
  476. intval($duplex),
  477. intval($forum),
  478. intval($prv),
  479. DBA::escape(Protocol::DFRN),
  480. intval($dfrn_record)
  481. );
  482. if (!DBA::isResult($r)) { // indicates schema is messed up or total db failure
  483. $message = L10n::t('Unable to update your contact profile details on our system');
  484. System::xmlExit(3, $message);
  485. }
  486. // Otherwise everything seems to have worked and we are almost done. Yay!
  487. // Send an email notification
  488. Logger::log('dfrn_confirm: request: info updated');
  489. $combined = null;
  490. $r = q("SELECT `contact`.*, `user`.*
  491. FROM `contact`
  492. LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
  493. WHERE `contact`.`id` = %d
  494. LIMIT 1",
  495. intval($dfrn_record)
  496. );
  497. if (DBA::isResult($r)) {
  498. $combined = $r[0];
  499. if ($combined['notify-flags'] & NOTIFY_CONFIRM) {
  500. $mutual = ($new_relation == Contact::FRIEND);
  501. notification([
  502. 'type' => NOTIFY_CONFIRM,
  503. 'notify_flags' => $combined['notify-flags'],
  504. 'language' => $combined['language'],
  505. 'to_name' => $combined['username'],
  506. 'to_email' => $combined['email'],
  507. 'uid' => $combined['uid'],
  508. 'link' => System::baseUrl() . '/contact/' . $dfrn_record,
  509. 'source_name' => ((strlen(stripslashes($combined['name']))) ? stripslashes($combined['name']) : L10n::t('[Name Withheld]')),
  510. 'source_link' => $combined['url'],
  511. 'source_photo' => $combined['photo'],
  512. 'verb' => ($mutual?ACTIVITY_FRIEND:ACTIVITY_FOLLOW),
  513. 'otype' => 'intro'
  514. ]);
  515. }
  516. }
  517. System::xmlExit(0); // Success
  518. return; // NOTREACHED
  519. ////////////////////// End of this scenario ///////////////////////////////////////////////
  520. }
  521. // somebody arrived here by mistake or they are fishing. Send them to the homepage.
  522. $a->internalRedirect();
  523. // NOTREACHED
  524. }