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\Logger;
24 use Friendica\Core\Protocol;
25 use Friendica\Core\System;
26 use Friendica\Database\DBA;
27 use Friendica\Model\Contact;
28 use Friendica\Model\Group;
29 use Friendica\Model\User;
30 use Friendica\Network\Probe;
31 use Friendica\Protocol\Diaspora;
32 use Friendica\Protocol\ActivityPub;
33 use Friendica\Util\Crypto;
34 use Friendica\Util\DateTimeFormat;
35 use Friendica\Util\Network;
36 use Friendica\Util\Strings;
37 use Friendica\Util\XML;
39 require_once 'include/enotify.php';
40 require_once 'include/items.php';
42 function dfrn_confirm_post(App $a, $handsfree = null)
45 if (is_array($handsfree)) {
47 * We were called directly from dfrn_request due to automatic friend acceptance.
48 * Any $_POST parameters we may require are supplied in the $handsfree array.
51 $node = $handsfree['node'];
52 $a->interactive = false; // notice() becomes a no-op since nobody is there to see it
53 } elseif ($a->argc > 1) {
58 * Main entry point. Scenario 1. Our user received a friend request notification (perhaps
59 * from another site) and clicked 'Approve'.
60 * $POST['source_url'] is not set. If it is, it indicates Scenario 2.
62 * We may also have been called directly from dfrn_request ($handsfree != null) due to
63 * this being a page type which supports automatic friend acceptance. That is also Scenario 1
64 * since we are operating on behalf of our registered user to approve a friendship.
66 if (!x($_POST, 'source_url')) {
67 $uid = defaults($handsfree, 'uid', local_user());
69 notice(L10n::t('Permission denied.') . EOL);
73 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
74 if (!DBA::isResult($user)) {
75 notice(L10n::t('Profile not found.') . EOL);
79 // These data elements may come from either the friend request notification form or $handsfree array.
80 if (is_array($handsfree)) {
81 Logger::log('Confirm in handsfree mode');
82 $dfrn_id = $handsfree['dfrn_id'];
83 $intro_id = $handsfree['intro_id'];
84 $duplex = $handsfree['duplex'];
86 $hidden = intval(defaults($handsfree, 'hidden' , 0));
88 $dfrn_id = Strings::escapeTags(trim(defaults($_POST, 'dfrn_id' , '')));
89 $intro_id = intval(defaults($_POST, 'intro_id' , 0));
90 $duplex = intval(defaults($_POST, 'duplex' , 0));
91 $cid = intval(defaults($_POST, 'contact_id', 0));
92 $hidden = intval(defaults($_POST, 'hidden' , 0));
96 * Ensure that dfrn_id has precedence when we go to find the contact record.
97 * We only want to search based on contact id if there is no dfrn_id,
98 * e.g. for OStatus network followers.
100 if (strlen($dfrn_id)) {
104 Logger::log('Confirming request for dfrn_id (issued) ' . $dfrn_id);
106 Logger::log('Confirming follower with contact_id: ' . $cid);
110 * The other person will have been issued an ID when they first requested friendship.
111 * Locate their record. At this time, their record will have both pending and blocked set to 1.
112 * There won't be any dfrn_id if this is a network follower, so use the contact_id instead.
117 (`issued-id` != '' AND `issued-id` = '%s')
119 (`id` = %d AND `id` != 0)
124 DBA::escape($dfrn_id),
128 if (!DBA::isResult($r)) {
129 Logger::log('Contact not found in DB.');
130 notice(L10n::t('Contact not found.') . EOL);
131 notice(L10n::t('This may occasionally happen if contact was requested by both persons and it has already been approved.') . EOL);
137 $contact_id = $contact['id'];
138 $relation = $contact['rel'];
139 $site_pubkey = $contact['site-pubkey'];
140 $dfrn_confirm = $contact['confirm'];
141 $aes_allow = $contact['aes_allow'];
143 $network = ((strlen($contact['issued-id'])) ? Protocol::DFRN : Protocol::OSTATUS);
145 if ($contact['network']) {
146 $network = $contact['network'];
149 if ($network === Protocol::DFRN) {
151 * Generate a key pair for all further communications with this person.
152 * We have a keypair for every contact, and a site key for unknown people.
153 * This provides a means to carry on relationships with other people if
154 * any single key is compromised. It is a robust key. We're much more
155 * worried about key leakage than anybody cracking it.
157 $res = Crypto::newKeypair(4096);
159 $private_key = $res['prvkey'];
160 $public_key = $res['pubkey'];
162 // Save the private key. Send them the public key.
163 q("UPDATE `contact` SET `prvkey` = '%s' WHERE `id` = %d AND `uid` = %d",
164 DBA::escape($private_key),
172 * Per the DFRN protocol, we will verify both ends by encrypting the dfrn_id with our
173 * site private key (person on the other end can decrypt it with our site public key).
174 * Then encrypt our profile URL with the other person's site public key. They can decrypt
175 * it with their site private key. If the decryption on the other end fails for either
176 * item, it indicates tampering or key failure on at least one site and we will not be
177 * able to provide a secure communication pathway.
179 * If other site is willing to accept full encryption, (aes_allow is 1 AND we have php5.3
180 * or later) then we encrypt the personal public key we send them using AES-256-CBC and a
181 * random key which is encrypted with their site public key.
184 $src_aes_key = openssl_random_pseudo_bytes(64);
187 openssl_private_encrypt($dfrn_id, $result, $user['prvkey']);
189 $params['dfrn_id'] = bin2hex($result);
190 $params['public_key'] = $public_key;
192 $my_url = System::baseUrl() . '/profile/' . $user['nickname'];
194 openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey);
195 $params['source_url'] = bin2hex($params['source_url']);
197 if ($aes_allow && function_exists('openssl_encrypt')) {
198 openssl_public_encrypt($src_aes_key, $params['aes_key'], $site_pubkey);
199 $params['aes_key'] = bin2hex($params['aes_key']);
200 $params['public_key'] = bin2hex(openssl_encrypt($public_key, 'AES-256-CBC', $src_aes_key));
203 $params['dfrn_version'] = DFRN_PROTOCOL_VERSION;
205 $params['duplex'] = 1;
208 if ($user['page-flags'] == Contact::PAGE_COMMUNITY) {
212 if ($user['page-flags'] == Contact::PAGE_PRVGROUP) {
216 Logger::log('Confirm: posting data to ' . $dfrn_confirm . ': ' . print_r($params, true), Logger::DATA);
220 * POST all this stuff to the other site.
221 * Temporarily raise the network timeout to 120 seconds because the default 60
222 * doesn't always give the other side quite enough time to decrypt everything.
226 $res = Network::post($dfrn_confirm, $params, null, $redirects, 120)->getBody();
228 Logger::log(' Confirm: received data: ' . $res, Logger::DATA);
230 // Now figure out what they responded. Try to be robust if the remote site is
231 // having difficulty and throwing up errors of some kind.
233 $leading_junk = substr($res, 0, strpos($res, '<?xml'));
235 $res = substr($res, strpos($res, '<?xml'));
237 // No XML at all, this exchange is messed up really bad.
238 // We shouldn't proceed, because the xml parser might choke,
239 // and $status is going to be zero, which indicates success.
240 // We can hardly call this a success.
241 notice(L10n::t('Response from remote site was not understood.') . EOL);
245 if (strlen($leading_junk) && Config::get('system', 'debugging')) {
246 // This might be more common. Mixed error text and some XML.
247 // If we're configured for debugging, show the text. Proceed in either case.
248 notice(L10n::t('Unexpected response from remote site: ') . EOL . $leading_junk . EOL);
251 if (stristr($res, "<status") === false) {
252 // wrong xml! stop here!
253 Logger::log('Unexpected response posting to ' . $dfrn_confirm);
254 notice(L10n::t('Unexpected response from remote site: ') . EOL . htmlspecialchars($res) . EOL);
258 $xml = XML::parseString($res);
259 $status = (int) $xml->status;
260 $message = XML::unescape($xml->message); // human readable text of what may have gone wrong.
263 info(L10n::t("Confirmation completed successfully.") . EOL);
266 // birthday paradox - generate new dfrn-id and fall through.
267 $new_dfrn_id = Strings::getRandomHex();
268 q("UPDATE contact SET `issued-id` = '%s' WHERE `id` = %d AND `uid` = %d",
269 DBA::escape($new_dfrn_id),
275 notice(L10n::t("Temporary failure. Please wait and try again.") . EOL);
278 notice(L10n::t("Introduction failed or was revoked.") . EOL);
282 if (strlen($message)) {
283 notice(L10n::t('Remote site reported: ') . $message . EOL);
286 if (($status == 0) && $intro_id) {
287 $intro = DBA::selectFirst('intro', ['note'], ['id' => $intro_id]);
288 if (DBA::isResult($intro)) {
289 DBA::update('contact', ['reason' => $intro['note']], ['id' => $contact_id]);
292 // Success. Delete the notification.
293 DBA::delete('intro', ['id' => $intro_id]);
302 * We have now established a relationship with the other site.
303 * Let's make our own personal copy of their profile photo so we don't have
304 * to always load it from their site.
306 * We will also update the contact record with the nature and scope of the relationship.
308 Contact::updateAvatar($contact['photo'], $uid, $contact_id);
310 Logger::log('dfrn_confirm: confirm - imported photos');
312 if ($network === Protocol::DFRN) {
313 $new_relation = Contact::FOLLOWER;
315 if (($relation == Contact::SHARING) || ($duplex)) {
316 $new_relation = Contact::FRIEND;
319 if (($relation == Contact::SHARING) && ($duplex)) {
323 $r = q("UPDATE `contact` SET `rel` = %d,
330 `network` = '%s' WHERE `id` = %d
332 intval($new_relation),
333 DBA::escape(DateTimeFormat::utcNow()),
334 DBA::escape(DateTimeFormat::utcNow()),
337 DBA::escape(Protocol::DFRN),
341 if ($network == Protocol::ACTIVITYPUB) {
342 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $uid);
348 // $network !== Protocol::DFRN
349 $network = defaults($contact, 'network', Protocol::OSTATUS);
351 $arr = Probe::uri($contact['url'], $network);
353 $notify = defaults($contact, 'notify' , $arr['notify']);
354 $poll = defaults($contact, 'poll' , $arr['poll']);
356 $addr = $arr['addr'];
358 $new_relation = $contact['rel'];
359 $writable = $contact['writable'];
361 if (in_array($network, [Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
363 $new_relation = Contact::FRIEND;
365 $new_relation = Contact::FOLLOWER;
368 if ($new_relation != Contact::FOLLOWER) {
373 DBA::delete('intro', ['id' => $intro_id]);
375 $fields = ['name-date' => DateTimeFormat::utcNow(),
376 'uri-date' => DateTimeFormat::utcNow(), 'addr' => $addr,
377 'notify' => $notify, 'poll' => $poll, 'blocked' => false,
378 'pending' => $pending, 'network' => $network,
379 'writable' => $writable, 'hidden' => $hidden, 'rel' => $new_relation];
380 DBA::update('contact', $fields, ['id' => $contact_id]);
383 if (!DBA::isResult($r)) {
384 notice(L10n::t('Unable to set contact photo.') . EOL);
387 // reload contact info
388 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
389 if ((isset($new_relation) && $new_relation == Contact::FRIEND)) {
390 if (DBA::isResult($contact) && ($contact['network'] === Protocol::DIASPORA)) {
391 $ret = Diaspora::sendShare($user, $contact);
392 Logger::log('share returns: ' . $ret);
396 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact['id']);
398 if ($network == Protocol::ACTIVITYPUB && $duplex) {
399 ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid);
402 // Let's send our user to the contact editor in case they want to
403 // do anything special with this new friend.
404 if ($handsfree === null) {
405 $a->internalRedirect('contact/' . intval($contact_id));
413 * End of Scenario 1. [Local confirmation of remote friend request].
415 * Begin Scenario 2. This is the remote response to the above scenario.
416 * This will take place on the site that originally initiated the friend request.
417 * In the section above where the confirming party makes a POST and
418 * retrieves xml status information, they are communicating with the following code.
420 if (x($_POST, 'source_url')) {
421 // We are processing an external confirmation to an introduction created by our user.
422 $public_key = defaults($_POST, 'public_key', '');
423 $dfrn_id = hex2bin(defaults($_POST, 'dfrn_id' , ''));
424 $source_url = hex2bin(defaults($_POST, 'source_url', ''));
425 $aes_key = defaults($_POST, 'aes_key' , '');
426 $duplex = intval(defaults($_POST, 'duplex' , 0));
427 $page = intval(defaults($_POST, 'page' , 0));
429 $forum = (($page == 1) ? 1 : 0);
430 $prv = (($page == 2) ? 1 : 0);
432 Logger::log('dfrn_confirm: requestee contacted: ' . $node);
434 Logger::log('dfrn_confirm: request: POST=' . print_r($_POST, true), Logger::DATA);
436 // If $aes_key is set, both of these items require unpacking from the hex transport encoding.
439 $aes_key = hex2bin($aes_key);
440 $public_key = hex2bin($public_key);
443 // Find our user's account
444 $user = DBA::selectFirst('user', [], ['nickname' => $node]);
445 if (!DBA::isResult($user)) {
446 $message = L10n::t('No user record found for \'%s\' ', $node);
447 System::xmlExit(3, $message); // failure
451 $my_prvkey = $user['prvkey'];
452 $local_uid = $user['uid'];
455 if (!strstr($my_prvkey, 'PRIVATE KEY')) {
456 $message = L10n::t('Our site encryption key is apparently messed up.');
457 System::xmlExit(3, $message);
462 $decrypted_source_url = "";
463 openssl_private_decrypt($source_url, $decrypted_source_url, $my_prvkey);
466 if (!strlen($decrypted_source_url)) {
467 $message = L10n::t('Empty site URL was provided or URL could not be decrypted by us.');
468 System::xmlExit(3, $message);
472 $contact = DBA::selectFirst('contact', [], ['url' => $decrypted_source_url, 'uid' => $local_uid]);
473 if (!DBA::isResult($contact)) {
474 if (strstr($decrypted_source_url, 'http:')) {
475 $newurl = str_replace('http:', 'https:', $decrypted_source_url);
477 $newurl = str_replace('https:', 'http:', $decrypted_source_url);
480 $contact = DBA::selectFirst('contact', [], ['url' => $newurl, 'uid' => $local_uid]);
481 if (!DBA::isResult($contact)) {
482 // this is either a bogus confirmation (?) or we deleted the original introduction.
483 $message = L10n::t('Contact record was not found for you on our site.');
484 System::xmlExit(3, $message);
485 return; // NOTREACHED
489 $relation = $contact['rel'];
491 // Decrypt all this stuff we just received
493 $foreign_pubkey = $contact['site-pubkey'];
494 $dfrn_record = $contact['id'];
496 if (!$foreign_pubkey) {
497 $message = L10n::t('Site public key not available in contact record for URL %s.', $decrypted_source_url);
498 System::xmlExit(3, $message);
501 $decrypted_dfrn_id = "";
502 openssl_public_decrypt($dfrn_id, $decrypted_dfrn_id, $foreign_pubkey);
504 if (strlen($aes_key)) {
505 $decrypted_aes_key = "";
506 openssl_private_decrypt($aes_key, $decrypted_aes_key, $my_prvkey);
507 $dfrn_pubkey = openssl_decrypt($public_key, 'AES-256-CBC', $decrypted_aes_key);
509 $dfrn_pubkey = $public_key;
512 if (DBA::exists('contact', ['dfrn-id' => $decrypted_dfrn_id])) {
513 $message = L10n::t('The ID provided by your system is a duplicate on our system. It should work if you try again.');
514 System::xmlExit(1, $message); // Birthday paradox - duplicate dfrn-id
518 $r = q("UPDATE `contact` SET `dfrn-id` = '%s', `pubkey` = '%s' WHERE `id` = %d",
519 DBA::escape($decrypted_dfrn_id),
520 DBA::escape($dfrn_pubkey),
523 if (!DBA::isResult($r)) {
524 $message = L10n::t('Unable to set your contact credentials on our system.');
525 System::xmlExit(3, $message);
528 // It's possible that the other person also requested friendship.
529 // If it is a duplex relationship, ditch the issued-id if one exists.
532 q("UPDATE `contact` SET `issued-id` = '' WHERE `id` = %d",
537 // We're good but now we have to scrape the profile photo and send notifications.
538 $contact = DBA::selectFirst('contact', ['photo'], ['id' => $dfrn_record]);
539 if (DBA::isResult($contact)) {
540 $photo = $contact['photo'];
542 $photo = System::baseUrl() . '/images/person-300.jpg';
545 Contact::updateAvatar($photo, $local_uid, $dfrn_record);
547 Logger::log('dfrn_confirm: request - photos imported');
549 $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(Protocol::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::log('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() . '/contact/' . $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 $a->internalRedirect();