3 * @file mod/dfrn_confirm.php
4 * @brief Module: dfrn_confirm
5 * Purpose: Friendship acceptance for DFRN contacts
7 * There are two possible entry points and three scenarios.
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.
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.
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
21 use Friendica\Core\Config;
22 use Friendica\Core\L10n;
23 use Friendica\Core\System;
24 use Friendica\Database\DBA;
25 use Friendica\Model\Contact;
26 use Friendica\Model\Group;
27 use Friendica\Model\User;
28 use Friendica\Network\Probe;
29 use Friendica\Protocol\Diaspora;
30 use Friendica\Util\Crypto;
31 use Friendica\Util\DateTimeFormat;
32 use Friendica\Util\Network;
33 use Friendica\Util\XML;
35 require_once 'include/enotify.php';
36 require_once 'include/items.php';
38 function dfrn_confirm_post(App $a, $handsfree = null)
41 if (is_array($handsfree)) {
43 * We were called directly from dfrn_request due to automatic friend acceptance.
44 * Any $_POST parameters we may require are supplied in the $handsfree array.
47 $node = $handsfree['node'];
48 $a->interactive = false; // notice() becomes a no-op since nobody is there to see it
49 } elseif ($a->argc > 1) {
54 * Main entry point. Scenario 1. Our user received a friend request notification (perhaps
55 * from another site) and clicked 'Approve'.
56 * $POST['source_url'] is not set. If it is, it indicates Scenario 2.
58 * We may also have been called directly from dfrn_request ($handsfree != null) due to
59 * this being a page type which supports automatic friend acceptance. That is also Scenario 1
60 * since we are operating on behalf of our registered user to approve a friendship.
62 if (!x($_POST, 'source_url')) {
63 $uid = defaults($handsfree, 'uid', local_user());
65 notice(L10n::t('Permission denied.') . EOL);
69 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
70 if (!DBA::isResult($user)) {
71 notice(L10n::t('Profile not found.') . EOL);
75 // These data elements may come from either the friend request notification form or $handsfree array.
76 if (is_array($handsfree)) {
77 logger('Confirm in handsfree mode');
78 $dfrn_id = $handsfree['dfrn_id'];
79 $intro_id = $handsfree['intro_id'];
80 $duplex = $handsfree['duplex'];
82 $hidden = intval(defaults($handsfree, 'hidden' , 0));
84 $dfrn_id = notags(trim(defaults($_POST, 'dfrn_id' , '')));
85 $intro_id = intval(defaults($_POST, 'intro_id' , 0));
86 $duplex = intval(defaults($_POST, 'duplex' , 0));
87 $cid = intval(defaults($_POST, 'contact_id', 0));
88 $hidden = intval(defaults($_POST, 'hidden' , 0));
92 * Ensure that dfrn_id has precedence when we go to find the contact record.
93 * We only want to search based on contact id if there is no dfrn_id,
94 * e.g. for OStatus network followers.
96 if (strlen($dfrn_id)) {
100 logger('Confirming request for dfrn_id (issued) ' . $dfrn_id);
102 logger('Confirming follower with contact_id: ' . $cid);
106 * The other person will have been issued an ID when they first requested friendship.
107 * Locate their record. At this time, their record will have both pending and blocked set to 1.
108 * There won't be any dfrn_id if this is a network follower, so use the contact_id instead.
113 (`issued-id` != '' AND `issued-id` = '%s')
115 (`id` = %d AND `id` != 0)
120 DBA::escape($dfrn_id),
124 if (!DBA::isResult($r)) {
125 logger('Contact not found in DB.');
126 notice(L10n::t('Contact not found.') . EOL);
127 notice(L10n::t('This may occasionally happen if contact was requested by both persons and it has already been approved.') . EOL);
133 $contact_id = $contact['id'];
134 $relation = $contact['rel'];
135 $site_pubkey = $contact['site-pubkey'];
136 $dfrn_confirm = $contact['confirm'];
137 $aes_allow = $contact['aes_allow'];
139 $network = ((strlen($contact['issued-id'])) ? NETWORK_DFRN : NETWORK_OSTATUS);
141 if ($contact['network']) {
142 $network = $contact['network'];
145 if ($network === NETWORK_DFRN) {
147 * Generate a key pair for all further communications with this person.
148 * We have a keypair for every contact, and a site key for unknown people.
149 * This provides a means to carry on relationships with other people if
150 * any single key is compromised. It is a robust key. We're much more
151 * worried about key leakage than anybody cracking it.
153 $res = Crypto::newKeypair(4096);
155 $private_key = $res['prvkey'];
156 $public_key = $res['pubkey'];
158 // Save the private key. Send them the public key.
159 q("UPDATE `contact` SET `prvkey` = '%s' WHERE `id` = %d AND `uid` = %d",
160 DBA::escape($private_key),
168 * Per the DFRN protocol, we will verify both ends by encrypting the dfrn_id with our
169 * site private key (person on the other end can decrypt it with our site public key).
170 * Then encrypt our profile URL with the other person's site public key. They can decrypt
171 * it with their site private key. If the decryption on the other end fails for either
172 * item, it indicates tampering or key failure on at least one site and we will not be
173 * able to provide a secure communication pathway.
175 * If other site is willing to accept full encryption, (aes_allow is 1 AND we have php5.3
176 * or later) then we encrypt the personal public key we send them using AES-256-CBC and a
177 * random key which is encrypted with their site public key.
180 $src_aes_key = openssl_random_pseudo_bytes(64);
183 openssl_private_encrypt($dfrn_id, $result, $user['prvkey']);
185 $params['dfrn_id'] = bin2hex($result);
186 $params['public_key'] = $public_key;
188 $my_url = System::baseUrl() . '/profile/' . $user['nickname'];
190 openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey);
191 $params['source_url'] = bin2hex($params['source_url']);
193 if ($aes_allow && function_exists('openssl_encrypt')) {
194 openssl_public_encrypt($src_aes_key, $params['aes_key'], $site_pubkey);
195 $params['aes_key'] = bin2hex($params['aes_key']);
196 $params['public_key'] = bin2hex(openssl_encrypt($public_key, 'AES-256-CBC', $src_aes_key));
199 $params['dfrn_version'] = DFRN_PROTOCOL_VERSION;
201 $params['duplex'] = 1;
204 if ($user['page-flags'] == Contact::PAGE_COMMUNITY) {
208 if ($user['page-flags'] == Contact::PAGE_PRVGROUP) {
212 logger('Confirm: posting data to ' . $dfrn_confirm . ': ' . print_r($params, true), LOGGER_DATA);
216 * POST all this stuff to the other site.
217 * Temporarily raise the network timeout to 120 seconds because the default 60
218 * doesn't always give the other side quite enough time to decrypt everything.
222 $res = Network::post($dfrn_confirm, $params, null, $redirects, 120);
224 logger(' Confirm: received data: ' . $res, LOGGER_DATA);
226 // Now figure out what they responded. Try to be robust if the remote site is
227 // having difficulty and throwing up errors of some kind.
229 $leading_junk = substr($res, 0, strpos($res, '<?xml'));
231 $res = substr($res, strpos($res, '<?xml'));
233 // No XML at all, this exchange is messed up really bad.
234 // We shouldn't proceed, because the xml parser might choke,
235 // and $status is going to be zero, which indicates success.
236 // We can hardly call this a success.
237 notice(L10n::t('Response from remote site was not understood.') . EOL);
241 if (strlen($leading_junk) && Config::get('system', 'debugging')) {
242 // This might be more common. Mixed error text and some XML.
243 // If we're configured for debugging, show the text. Proceed in either case.
244 notice(L10n::t('Unexpected response from remote site: ') . EOL . $leading_junk . EOL);
247 if (stristr($res, "<status") === false) {
248 // wrong xml! stop here!
249 notice(L10n::t('Unexpected response from remote site: ') . EOL . htmlspecialchars($res) . EOL);
253 $xml = XML::parseString($res);
254 $status = (int) $xml->status;
255 $message = unxmlify($xml->message); // human readable text of what may have gone wrong.
258 info(L10n::t("Confirmation completed successfully.") . EOL);
261 // birthday paradox - generate new dfrn-id and fall through.
262 $new_dfrn_id = random_string();
263 q("UPDATE contact SET `issued-id` = '%s' WHERE `id` = %d AND `uid` = %d",
264 DBA::escape($new_dfrn_id),
270 notice(L10n::t("Temporary failure. Please wait and try again.") . EOL);
273 notice(L10n::t("Introduction failed or was revoked.") . EOL);
277 if (strlen($message)) {
278 notice(L10n::t('Remote site reported: ') . $message . EOL);
281 if (($status == 0) && $intro_id) {
282 $intro = DBA::selectFirst('intro', ['note'], ['id' => $intro_id]);
283 if (DBA::isResult($intro)) {
284 DBA::update('contact', ['reason' => $intro['note']], ['id' => $contact_id]);
287 // Success. Delete the notification.
288 DBA::delete('intro', ['id' => $intro_id]);
297 * We have now established a relationship with the other site.
298 * Let's make our own personal copy of their profile photo so we don't have
299 * to always load it from their site.
301 * We will also update the contact record with the nature and scope of the relationship.
303 Contact::updateAvatar($contact['photo'], $uid, $contact_id);
305 logger('dfrn_confirm: confirm - imported photos');
307 if ($network === NETWORK_DFRN) {
308 $new_relation = Contact::FOLLOWER;
309 if (($relation == Contact::SHARING) || ($duplex)) {
310 $new_relation = Contact::FRIEND;
313 if (($relation == Contact::SHARING) && ($duplex)) {
317 $r = q("UPDATE `contact` SET `rel` = %d,
324 `network` = '%s' WHERE `id` = %d
326 intval($new_relation),
327 DBA::escape(DateTimeFormat::utcNow()),
328 DBA::escape(DateTimeFormat::utcNow()),
331 DBA::escape(NETWORK_DFRN),
335 // $network !== NETWORK_DFRN
336 $network = defaults($contact, 'network', NETWORK_OSTATUS);
338 $arr = Probe::uri($contact['url']);
340 $notify = defaults($contact, 'notify' , $arr['notify']);
341 $poll = defaults($contact, 'poll' , $arr['poll']);
343 $addr = $arr['addr'];
345 $new_relation = $contact['rel'];
346 $writable = $contact['writable'];
348 if ($network === NETWORK_DIASPORA) {
350 $new_relation = Contact::FRIEND;
352 $new_relation = Contact::FOLLOWER;
355 if ($new_relation != Contact::FOLLOWER) {
360 DBA::delete('intro', ['id' => $intro_id]);
362 $r = q("UPDATE `contact` SET `name-date` = '%s',
375 DBA::escape(DateTimeFormat::utcNow()),
376 DBA::escape(DateTimeFormat::utcNow()),
378 DBA::escape($notify),
380 DBA::escape($network),
383 intval($new_relation),
388 if (!DBA::isResult($r)) {
389 notice(L10n::t('Unable to set contact photo.') . EOL);
392 // reload contact info
393 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
394 if ((isset($new_relation) && $new_relation == Contact::FRIEND)) {
395 if (DBA::isResult($contact) && ($contact['network'] === NETWORK_DIASPORA)) {
396 $ret = Diaspora::sendShare($user, $contact);
397 logger('share returns: ' . $ret);
401 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact['id']);
403 // Let's send our user to the contact editor in case they want to
404 // do anything special with this new friend.
405 if ($handsfree === null) {
406 goaway(System::baseUrl() . '/contacts/' . intval($contact_id));
414 * End of Scenario 1. [Local confirmation of remote friend request].
416 * Begin Scenario 2. This is the remote response to the above scenario.
417 * This will take place on the site that originally initiated the friend request.
418 * In the section above where the confirming party makes a POST and
419 * retrieves xml status information, they are communicating with the following code.
421 if (x($_POST, 'source_url')) {
422 // We are processing an external confirmation to an introduction created by our user.
423 $public_key = defaults($_POST, 'public_key', '');
424 $dfrn_id = hex2bin(defaults($_POST, 'dfrn_id' , ''));
425 $source_url = hex2bin(defaults($_POST, 'source_url', ''));
426 $aes_key = defaults($_POST, 'aes_key' , '');
427 $duplex = intval(defaults($_POST, 'duplex' , 0));
428 $page = intval(defaults($_POST, 'page' , 0));
430 $forum = (($page == 1) ? 1 : 0);
431 $prv = (($page == 2) ? 1 : 0);
433 logger('dfrn_confirm: requestee contacted: ' . $node);
435 logger('dfrn_confirm: request: POST=' . print_r($_POST, true), LOGGER_DATA);
437 // If $aes_key is set, both of these items require unpacking from the hex transport encoding.
440 $aes_key = hex2bin($aes_key);
441 $public_key = hex2bin($public_key);
444 // Find our user's account
445 $user = DBA::selectFirst('user', [], ['nickname' => $node]);
446 if (!DBA::isResult($user)) {
447 $message = L10n::t('No user record found for \'%s\' ', $node);
448 System::xmlExit(3, $message); // failure
452 $my_prvkey = $user['prvkey'];
453 $local_uid = $user['uid'];
456 if (!strstr($my_prvkey, 'PRIVATE KEY')) {
457 $message = L10n::t('Our site encryption key is apparently messed up.');
458 System::xmlExit(3, $message);
463 $decrypted_source_url = "";
464 openssl_private_decrypt($source_url, $decrypted_source_url, $my_prvkey);
467 if (!strlen($decrypted_source_url)) {
468 $message = L10n::t('Empty site URL was provided or URL could not be decrypted by us.');
469 System::xmlExit(3, $message);
473 $contact = DBA::selectFirst('contact', [], ['url' => $decrypted_source_url, 'uid' => $local_uid]);
474 if (!DBA::isResult($contact)) {
475 if (strstr($decrypted_source_url, 'http:')) {
476 $newurl = str_replace('http:', 'https:', $decrypted_source_url);
478 $newurl = str_replace('https:', 'http:', $decrypted_source_url);
481 $contact = DBA::selectFirst('contact', [], ['url' => $newurl, 'uid' => $local_uid]);
482 if (!DBA::isResult($contact)) {
483 // this is either a bogus confirmation (?) or we deleted the original introduction.
484 $message = L10n::t('Contact record was not found for you on our site.');
485 System::xmlExit(3, $message);
486 return; // NOTREACHED
490 $relation = $contact['rel'];
492 // Decrypt all this stuff we just received
494 $foreign_pubkey = $contact['site-pubkey'];
495 $dfrn_record = $contact['id'];
497 if (!$foreign_pubkey) {
498 $message = L10n::t('Site public key not available in contact record for URL %s.', $decrypted_source_url);
499 System::xmlExit(3, $message);
502 $decrypted_dfrn_id = "";
503 openssl_public_decrypt($dfrn_id, $decrypted_dfrn_id, $foreign_pubkey);
505 if (strlen($aes_key)) {
506 $decrypted_aes_key = "";
507 openssl_private_decrypt($aes_key, $decrypted_aes_key, $my_prvkey);
508 $dfrn_pubkey = openssl_decrypt($public_key, 'AES-256-CBC', $decrypted_aes_key);
510 $dfrn_pubkey = $public_key;
513 if (DBA::exists('contact', ['dfrn-id' => $decrypted_dfrn_id])) {
514 $message = L10n::t('The ID provided by your system is a duplicate on our system. It should work if you try again.');
515 System::xmlExit(1, $message); // Birthday paradox - duplicate dfrn-id
519 $r = q("UPDATE `contact` SET `dfrn-id` = '%s', `pubkey` = '%s' WHERE `id` = %d",
520 DBA::escape($decrypted_dfrn_id),
521 DBA::escape($dfrn_pubkey),
524 if (!DBA::isResult($r)) {
525 $message = L10n::t('Unable to set your contact credentials on our system.');
526 System::xmlExit(3, $message);
529 // It's possible that the other person also requested friendship.
530 // If it is a duplex relationship, ditch the issued-id if one exists.
533 q("UPDATE `contact` SET `issued-id` = '' WHERE `id` = %d",
538 // We're good but now we have to scrape the profile photo and send notifications.
539 $contact = DBA::selectFirst('contact', ['photo'], ['id' => $dfrn_record]);
540 if (DBA::isResult($contact)) {
541 $photo = $contact['photo'];
543 $photo = System::baseUrl() . '/images/person-175.jpg';
546 Contact::updateAvatar($photo, $local_uid, $dfrn_record);
548 logger('dfrn_confirm: request - photos imported');
550 $new_relation = Contact::SHARING;
551 if (($relation == Contact::FOLLOWER) || ($duplex)) {
552 $new_relation = Contact::FRIEND;
555 if (($relation == Contact::FOLLOWER) && ($duplex)) {
559 $r = q("UPDATE `contact` SET
568 `network` = '%s' WHERE `id` = %d
570 intval($new_relation),
571 DBA::escape(DateTimeFormat::utcNow()),
572 DBA::escape(DateTimeFormat::utcNow()),
576 DBA::escape(NETWORK_DFRN),
579 if (!DBA::isResult($r)) { // indicates schema is messed up or total db failure
580 $message = L10n::t('Unable to update your contact profile details on our system');
581 System::xmlExit(3, $message);
584 // Otherwise everything seems to have worked and we are almost done. Yay!
585 // Send an email notification
587 logger('dfrn_confirm: request: info updated');
590 $r = q("SELECT `contact`.*, `user`.*
592 LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
593 WHERE `contact`.`id` = %d
597 if (DBA::isResult($r)) {
600 if ($combined['notify-flags'] & NOTIFY_CONFIRM) {
601 $mutual = ($new_relation == Contact::FRIEND);
603 'type' => NOTIFY_CONFIRM,
604 'notify_flags' => $combined['notify-flags'],
605 'language' => $combined['language'],
606 'to_name' => $combined['username'],
607 'to_email' => $combined['email'],
608 'uid' => $combined['uid'],
609 'link' => System::baseUrl() . '/contacts/' . $dfrn_record,
610 'source_name' => ((strlen(stripslashes($combined['name']))) ? stripslashes($combined['name']) : L10n::t('[Name Withheld]')),
611 'source_link' => $combined['url'],
612 'source_photo' => $combined['photo'],
613 'verb' => ($mutual?ACTIVITY_FRIEND:ACTIVITY_FOLLOW),
619 System::xmlExit(0); // Success
620 return; // NOTREACHED
621 ////////////////////// End of this scenario ///////////////////////////////////////////////
624 // somebody arrived here by mistake or they are fishing. Send them to the homepage.
625 goaway(System::baseUrl());