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\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\Util\Crypto;
32 use Friendica\Util\DateTimeFormat;
33 use Friendica\Util\Network;
34 use Friendica\Util\XML;
36 require_once 'include/enotify.php';
37 require_once 'include/items.php';
39 function dfrn_confirm_post(App $a, $handsfree = null)
42 if (is_array($handsfree)) {
44 * We were called directly from dfrn_request due to automatic friend acceptance.
45 * Any $_POST parameters we may require are supplied in the $handsfree array.
48 $node = $handsfree['node'];
49 $a->interactive = false; // notice() becomes a no-op since nobody is there to see it
50 } elseif ($a->argc > 1) {
55 * Main entry point. Scenario 1. Our user received a friend request notification (perhaps
56 * from another site) and clicked 'Approve'.
57 * $POST['source_url'] is not set. If it is, it indicates Scenario 2.
59 * We may also have been called directly from dfrn_request ($handsfree != null) due to
60 * this being a page type which supports automatic friend acceptance. That is also Scenario 1
61 * since we are operating on behalf of our registered user to approve a friendship.
63 if (!x($_POST, 'source_url')) {
64 $uid = defaults($handsfree, 'uid', local_user());
66 notice(L10n::t('Permission denied.') . EOL);
70 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
71 if (!DBA::isResult($user)) {
72 notice(L10n::t('Profile not found.') . EOL);
76 // These data elements may come from either the friend request notification form or $handsfree array.
77 if (is_array($handsfree)) {
78 logger('Confirm in handsfree mode');
79 $dfrn_id = $handsfree['dfrn_id'];
80 $intro_id = $handsfree['intro_id'];
81 $duplex = $handsfree['duplex'];
83 $hidden = intval(defaults($handsfree, 'hidden' , 0));
85 $dfrn_id = notags(trim(defaults($_POST, 'dfrn_id' , '')));
86 $intro_id = intval(defaults($_POST, 'intro_id' , 0));
87 $duplex = intval(defaults($_POST, 'duplex' , 0));
88 $cid = intval(defaults($_POST, 'contact_id', 0));
89 $hidden = intval(defaults($_POST, 'hidden' , 0));
93 * Ensure that dfrn_id has precedence when we go to find the contact record.
94 * We only want to search based on contact id if there is no dfrn_id,
95 * e.g. for OStatus network followers.
97 if (strlen($dfrn_id)) {
101 logger('Confirming request for dfrn_id (issued) ' . $dfrn_id);
103 logger('Confirming follower with contact_id: ' . $cid);
107 * The other person will have been issued an ID when they first requested friendship.
108 * Locate their record. At this time, their record will have both pending and blocked set to 1.
109 * There won't be any dfrn_id if this is a network follower, so use the contact_id instead.
114 (`issued-id` != '' AND `issued-id` = '%s')
116 (`id` = %d AND `id` != 0)
121 DBA::escape($dfrn_id),
125 if (!DBA::isResult($r)) {
126 logger('Contact not found in DB.');
127 notice(L10n::t('Contact not found.') . EOL);
128 notice(L10n::t('This may occasionally happen if contact was requested by both persons and it has already been approved.') . EOL);
134 $contact_id = $contact['id'];
135 $relation = $contact['rel'];
136 $site_pubkey = $contact['site-pubkey'];
137 $dfrn_confirm = $contact['confirm'];
138 $aes_allow = $contact['aes_allow'];
140 $network = ((strlen($contact['issued-id'])) ? Protocol::DFRN : Protocol::OSTATUS);
142 if ($contact['network']) {
143 $network = $contact['network'];
146 if ($network === Protocol::DFRN) {
148 * Generate a key pair for all further communications with this person.
149 * We have a keypair for every contact, and a site key for unknown people.
150 * This provides a means to carry on relationships with other people if
151 * any single key is compromised. It is a robust key. We're much more
152 * worried about key leakage than anybody cracking it.
154 $res = Crypto::newKeypair(4096);
156 $private_key = $res['prvkey'];
157 $public_key = $res['pubkey'];
159 // Save the private key. Send them the public key.
160 q("UPDATE `contact` SET `prvkey` = '%s' WHERE `id` = %d AND `uid` = %d",
161 DBA::escape($private_key),
169 * Per the DFRN protocol, we will verify both ends by encrypting the dfrn_id with our
170 * site private key (person on the other end can decrypt it with our site public key).
171 * Then encrypt our profile URL with the other person's site public key. They can decrypt
172 * it with their site private key. If the decryption on the other end fails for either
173 * item, it indicates tampering or key failure on at least one site and we will not be
174 * able to provide a secure communication pathway.
176 * If other site is willing to accept full encryption, (aes_allow is 1 AND we have php5.3
177 * or later) then we encrypt the personal public key we send them using AES-256-CBC and a
178 * random key which is encrypted with their site public key.
181 $src_aes_key = openssl_random_pseudo_bytes(64);
184 openssl_private_encrypt($dfrn_id, $result, $user['prvkey']);
186 $params['dfrn_id'] = bin2hex($result);
187 $params['public_key'] = $public_key;
189 $my_url = System::baseUrl() . '/profile/' . $user['nickname'];
191 openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey);
192 $params['source_url'] = bin2hex($params['source_url']);
194 if ($aes_allow && function_exists('openssl_encrypt')) {
195 openssl_public_encrypt($src_aes_key, $params['aes_key'], $site_pubkey);
196 $params['aes_key'] = bin2hex($params['aes_key']);
197 $params['public_key'] = bin2hex(openssl_encrypt($public_key, 'AES-256-CBC', $src_aes_key));
200 $params['dfrn_version'] = DFRN_PROTOCOL_VERSION;
202 $params['duplex'] = 1;
205 if ($user['page-flags'] == Contact::PAGE_COMMUNITY) {
209 if ($user['page-flags'] == Contact::PAGE_PRVGROUP) {
213 logger('Confirm: posting data to ' . $dfrn_confirm . ': ' . print_r($params, true), LOGGER_DATA);
217 * POST all this stuff to the other site.
218 * Temporarily raise the network timeout to 120 seconds because the default 60
219 * doesn't always give the other side quite enough time to decrypt everything.
223 $res = Network::post($dfrn_confirm, $params, null, $redirects, 120);
225 logger(' Confirm: received data: ' . $res, LOGGER_DATA);
227 // Now figure out what they responded. Try to be robust if the remote site is
228 // having difficulty and throwing up errors of some kind.
230 $leading_junk = substr($res, 0, strpos($res, '<?xml'));
232 $res = substr($res, strpos($res, '<?xml'));
234 // No XML at all, this exchange is messed up really bad.
235 // We shouldn't proceed, because the xml parser might choke,
236 // and $status is going to be zero, which indicates success.
237 // We can hardly call this a success.
238 notice(L10n::t('Response from remote site was not understood.') . EOL);
242 if (strlen($leading_junk) && Config::get('system', 'debugging')) {
243 // This might be more common. Mixed error text and some XML.
244 // If we're configured for debugging, show the text. Proceed in either case.
245 notice(L10n::t('Unexpected response from remote site: ') . EOL . $leading_junk . EOL);
248 if (stristr($res, "<status") === false) {
249 // wrong xml! stop here!
250 logger('Unexpected response posting to ' . $dfrn_confirm);
251 notice(L10n::t('Unexpected response from remote site: ') . EOL . htmlspecialchars($res) . EOL);
255 $xml = XML::parseString($res);
256 $status = (int) $xml->status;
257 $message = unxmlify($xml->message); // human readable text of what may have gone wrong.
260 info(L10n::t("Confirmation completed successfully.") . EOL);
263 // birthday paradox - generate new dfrn-id and fall through.
264 $new_dfrn_id = random_string();
265 q("UPDATE contact SET `issued-id` = '%s' WHERE `id` = %d AND `uid` = %d",
266 DBA::escape($new_dfrn_id),
272 notice(L10n::t("Temporary failure. Please wait and try again.") . EOL);
275 notice(L10n::t("Introduction failed or was revoked.") . EOL);
279 if (strlen($message)) {
280 notice(L10n::t('Remote site reported: ') . $message . EOL);
283 if (($status == 0) && $intro_id) {
284 $intro = DBA::selectFirst('intro', ['note'], ['id' => $intro_id]);
285 if (DBA::isResult($intro)) {
286 DBA::update('contact', ['reason' => $intro['note']], ['id' => $contact_id]);
289 // Success. Delete the notification.
290 DBA::delete('intro', ['id' => $intro_id]);
299 * We have now established a relationship with the other site.
300 * Let's make our own personal copy of their profile photo so we don't have
301 * to always load it from their site.
303 * We will also update the contact record with the nature and scope of the relationship.
305 Contact::updateAvatar($contact['photo'], $uid, $contact_id);
307 logger('dfrn_confirm: confirm - imported photos');
309 if ($network === Protocol::DFRN) {
310 $new_relation = Contact::FOLLOWER;
311 if (($relation == Contact::SHARING) || ($duplex)) {
312 $new_relation = Contact::FRIEND;
315 if (($relation == Contact::SHARING) && ($duplex)) {
319 $r = q("UPDATE `contact` SET `rel` = %d,
326 `network` = '%s' WHERE `id` = %d
328 intval($new_relation),
329 DBA::escape(DateTimeFormat::utcNow()),
330 DBA::escape(DateTimeFormat::utcNow()),
333 DBA::escape(Protocol::DFRN),
337 // $network !== Protocol::DFRN
338 $network = defaults($contact, 'network', Protocol::OSTATUS);
340 $arr = Probe::uri($contact['url']);
342 $notify = defaults($contact, 'notify' , $arr['notify']);
343 $poll = defaults($contact, 'poll' , $arr['poll']);
345 $addr = $arr['addr'];
347 $new_relation = $contact['rel'];
348 $writable = $contact['writable'];
350 if ($network === Protocol::DIASPORA) {
352 $new_relation = Contact::FRIEND;
354 $new_relation = Contact::FOLLOWER;
357 if ($new_relation != Contact::FOLLOWER) {
362 DBA::delete('intro', ['id' => $intro_id]);
364 $r = q("UPDATE `contact` SET `name-date` = '%s',
377 DBA::escape(DateTimeFormat::utcNow()),
378 DBA::escape(DateTimeFormat::utcNow()),
380 DBA::escape($notify),
382 DBA::escape($network),
385 intval($new_relation),
390 if (!DBA::isResult($r)) {
391 notice(L10n::t('Unable to set contact photo.') . EOL);
394 // reload contact info
395 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
396 if ((isset($new_relation) && $new_relation == Contact::FRIEND)) {
397 if (DBA::isResult($contact) && ($contact['network'] === Protocol::DIASPORA)) {
398 $ret = Diaspora::sendShare($user, $contact);
399 logger('share returns: ' . $ret);
403 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact['id']);
405 // Let's send our user to the contact editor in case they want to
406 // do anything special with this new friend.
407 if ($handsfree === null) {
408 goaway(System::baseUrl() . '/contacts/' . intval($contact_id));
416 * End of Scenario 1. [Local confirmation of remote friend request].
418 * Begin Scenario 2. This is the remote response to the above scenario.
419 * This will take place on the site that originally initiated the friend request.
420 * In the section above where the confirming party makes a POST and
421 * retrieves xml status information, they are communicating with the following code.
423 if (x($_POST, 'source_url')) {
424 // We are processing an external confirmation to an introduction created by our user.
425 $public_key = defaults($_POST, 'public_key', '');
426 $dfrn_id = hex2bin(defaults($_POST, 'dfrn_id' , ''));
427 $source_url = hex2bin(defaults($_POST, 'source_url', ''));
428 $aes_key = defaults($_POST, 'aes_key' , '');
429 $duplex = intval(defaults($_POST, 'duplex' , 0));
430 $page = intval(defaults($_POST, 'page' , 0));
432 $forum = (($page == 1) ? 1 : 0);
433 $prv = (($page == 2) ? 1 : 0);
435 logger('dfrn_confirm: requestee contacted: ' . $node);
437 logger('dfrn_confirm: request: POST=' . print_r($_POST, true), LOGGER_DATA);
439 // If $aes_key is set, both of these items require unpacking from the hex transport encoding.
442 $aes_key = hex2bin($aes_key);
443 $public_key = hex2bin($public_key);
446 // Find our user's account
447 $user = DBA::selectFirst('user', [], ['nickname' => $node]);
448 if (!DBA::isResult($user)) {
449 $message = L10n::t('No user record found for \'%s\' ', $node);
450 System::xmlExit(3, $message); // failure
454 $my_prvkey = $user['prvkey'];
455 $local_uid = $user['uid'];
458 if (!strstr($my_prvkey, 'PRIVATE KEY')) {
459 $message = L10n::t('Our site encryption key is apparently messed up.');
460 System::xmlExit(3, $message);
465 $decrypted_source_url = "";
466 openssl_private_decrypt($source_url, $decrypted_source_url, $my_prvkey);
469 if (!strlen($decrypted_source_url)) {
470 $message = L10n::t('Empty site URL was provided or URL could not be decrypted by us.');
471 System::xmlExit(3, $message);
475 $contact = DBA::selectFirst('contact', [], ['url' => $decrypted_source_url, 'uid' => $local_uid]);
476 if (!DBA::isResult($contact)) {
477 if (strstr($decrypted_source_url, 'http:')) {
478 $newurl = str_replace('http:', 'https:', $decrypted_source_url);
480 $newurl = str_replace('https:', 'http:', $decrypted_source_url);
483 $contact = DBA::selectFirst('contact', [], ['url' => $newurl, 'uid' => $local_uid]);
484 if (!DBA::isResult($contact)) {
485 // this is either a bogus confirmation (?) or we deleted the original introduction.
486 $message = L10n::t('Contact record was not found for you on our site.');
487 System::xmlExit(3, $message);
488 return; // NOTREACHED
492 $relation = $contact['rel'];
494 // Decrypt all this stuff we just received
496 $foreign_pubkey = $contact['site-pubkey'];
497 $dfrn_record = $contact['id'];
499 if (!$foreign_pubkey) {
500 $message = L10n::t('Site public key not available in contact record for URL %s.', $decrypted_source_url);
501 System::xmlExit(3, $message);
504 $decrypted_dfrn_id = "";
505 openssl_public_decrypt($dfrn_id, $decrypted_dfrn_id, $foreign_pubkey);
507 if (strlen($aes_key)) {
508 $decrypted_aes_key = "";
509 openssl_private_decrypt($aes_key, $decrypted_aes_key, $my_prvkey);
510 $dfrn_pubkey = openssl_decrypt($public_key, 'AES-256-CBC', $decrypted_aes_key);
512 $dfrn_pubkey = $public_key;
515 if (DBA::exists('contact', ['dfrn-id' => $decrypted_dfrn_id])) {
516 $message = L10n::t('The ID provided by your system is a duplicate on our system. It should work if you try again.');
517 System::xmlExit(1, $message); // Birthday paradox - duplicate dfrn-id
521 $r = q("UPDATE `contact` SET `dfrn-id` = '%s', `pubkey` = '%s' WHERE `id` = %d",
522 DBA::escape($decrypted_dfrn_id),
523 DBA::escape($dfrn_pubkey),
526 if (!DBA::isResult($r)) {
527 $message = L10n::t('Unable to set your contact credentials on our system.');
528 System::xmlExit(3, $message);
531 // It's possible that the other person also requested friendship.
532 // If it is a duplex relationship, ditch the issued-id if one exists.
535 q("UPDATE `contact` SET `issued-id` = '' WHERE `id` = %d",
540 // We're good but now we have to scrape the profile photo and send notifications.
541 $contact = DBA::selectFirst('contact', ['photo'], ['id' => $dfrn_record]);
542 if (DBA::isResult($contact)) {
543 $photo = $contact['photo'];
545 $photo = System::baseUrl() . '/images/person-175.jpg';
548 Contact::updateAvatar($photo, $local_uid, $dfrn_record);
550 logger('dfrn_confirm: request - photos imported');
552 $new_relation = Contact::SHARING;
553 if (($relation == Contact::FOLLOWER) || ($duplex)) {
554 $new_relation = Contact::FRIEND;
557 if (($relation == Contact::FOLLOWER) && ($duplex)) {
561 $r = q("UPDATE `contact` SET
570 `network` = '%s' WHERE `id` = %d
572 intval($new_relation),
573 DBA::escape(DateTimeFormat::utcNow()),
574 DBA::escape(DateTimeFormat::utcNow()),
578 DBA::escape(Protocol::DFRN),
581 if (!DBA::isResult($r)) { // indicates schema is messed up or total db failure
582 $message = L10n::t('Unable to update your contact profile details on our system');
583 System::xmlExit(3, $message);
586 // Otherwise everything seems to have worked and we are almost done. Yay!
587 // Send an email notification
589 logger('dfrn_confirm: request: info updated');
592 $r = q("SELECT `contact`.*, `user`.*
594 LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
595 WHERE `contact`.`id` = %d
599 if (DBA::isResult($r)) {
602 if ($combined['notify-flags'] & NOTIFY_CONFIRM) {
603 $mutual = ($new_relation == Contact::FRIEND);
605 'type' => NOTIFY_CONFIRM,
606 'notify_flags' => $combined['notify-flags'],
607 'language' => $combined['language'],
608 'to_name' => $combined['username'],
609 'to_email' => $combined['email'],
610 'uid' => $combined['uid'],
611 'link' => System::baseUrl() . '/contacts/' . $dfrn_record,
612 'source_name' => ((strlen(stripslashes($combined['name']))) ? stripslashes($combined['name']) : L10n::t('[Name Withheld]')),
613 'source_link' => $combined['url'],
614 'source_photo' => $combined['photo'],
615 'verb' => ($mutual?ACTIVITY_FRIEND:ACTIVITY_FOLLOW),
621 System::xmlExit(0); // Success
622 return; // NOTREACHED
623 ////////////////////// End of this scenario ///////////////////////////////////////////////
626 // somebody arrived here by mistake or they are fishing. Send them to the homepage.
627 goaway(System::baseUrl());