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\PConfig;
24 use Friendica\Core\System;
25 use Friendica\Core\Worker;
26 use Friendica\Database\DBM;
27 use Friendica\Model\Contact;
28 use Friendica\Model\Group;
29 use Friendica\Model\Item;
30 use Friendica\Model\User;
31 use Friendica\Network\Probe;
32 use Friendica\Protocol\Diaspora;
33 use Friendica\Util\Crypto;
34 use Friendica\Util\DateTimeFormat;
35 use Friendica\Util\Network;
36 use Friendica\Util\XML;
38 require_once 'include/enotify.php';
39 require_once 'include/items.php';
41 function dfrn_confirm_post(App $a, $handsfree = null)
44 if (is_array($handsfree)) {
46 * We were called directly from dfrn_request due to automatic friend acceptance.
47 * Any $_POST parameters we may require are supplied in the $handsfree array.
50 $node = $handsfree['node'];
51 $a->interactive = false; // notice() becomes a no-op since nobody is there to see it
52 } elseif ($a->argc > 1) {
57 * Main entry point. Scenario 1. Our user received a friend request notification (perhaps
58 * from another site) and clicked 'Approve'.
59 * $POST['source_url'] is not set. If it is, it indicates Scenario 2.
61 * We may also have been called directly from dfrn_request ($handsfree != null) due to
62 * this being a page type which supports automatic friend acceptance. That is also Scenario 1
63 * since we are operating on behalf of our registered user to approve a friendship.
65 if (!x($_POST, 'source_url')) {
66 $uid = defaults($handsfree, 'uid', local_user());
68 notice(L10n::t('Permission denied.') . EOL);
72 $user = dba::selectFirst('user', [], ['uid' => $uid]);
73 if (!DBM::is_result($user)) {
74 notice(L10n::t('Profile not found.') . EOL);
78 // These data elements may come from either the friend request notification form or $handsfree array.
79 if (is_array($handsfree)) {
80 logger('Confirm in handsfree mode');
81 $dfrn_id = $handsfree['dfrn_id'];
82 $intro_id = $handsfree['intro_id'];
83 $duplex = $handsfree['duplex'];
85 $hidden = intval(defaults($handsfree, 'hidden' , 0));
87 $dfrn_id = notags(trim(defaults($_POST, 'dfrn_id' , '')));
88 $intro_id = intval(defaults($_POST, 'intro_id' , 0));
89 $duplex = intval(defaults($_POST, 'duplex' , 0));
90 $cid = intval(defaults($_POST, 'contact_id', 0));
91 $hidden = intval(defaults($_POST, 'hidden' , 0));
95 * Ensure that dfrn_id has precedence when we go to find the contact record.
96 * We only want to search based on contact id if there is no dfrn_id,
97 * e.g. for OStatus network followers.
99 if (strlen($dfrn_id)) {
103 logger('Confirming request for dfrn_id (issued) ' . $dfrn_id);
105 logger('Confirming follower with contact_id: ' . $cid);
109 * The other person will have been issued an ID when they first requested friendship.
110 * Locate their record. At this time, their record will have both pending and blocked set to 1.
111 * There won't be any dfrn_id if this is a network follower, so use the contact_id instead.
116 (`issued-id` != '' AND `issued-id` = '%s')
118 (`id` = %d AND `id` != 0)
127 if (!DBM::is_result($r)) {
128 logger('Contact not found in DB.');
129 notice(L10n::t('Contact not found.') . EOL);
130 notice(L10n::t('This may occasionally happen if contact was requested by both persons and it has already been approved.') . EOL);
136 $contact_id = $contact['id'];
137 $relation = $contact['rel'];
138 $site_pubkey = $contact['site-pubkey'];
139 $dfrn_confirm = $contact['confirm'];
140 $aes_allow = $contact['aes_allow'];
142 $network = ((strlen($contact['issued-id'])) ? NETWORK_DFRN : NETWORK_OSTATUS);
144 if ($contact['network']) {
145 $network = $contact['network'];
148 if ($network === NETWORK_DFRN) {
150 * Generate a key pair for all further communications with this person.
151 * We have a keypair for every contact, and a site key for unknown people.
152 * This provides a means to carry on relationships with other people if
153 * any single key is compromised. It is a robust key. We're much more
154 * worried about key leakage than anybody cracking it.
156 $res = Crypto::newKeypair(4096);
158 $private_key = $res['prvkey'];
159 $public_key = $res['pubkey'];
161 // Save the private key. Send them the public key.
162 q("UPDATE `contact` SET `prvkey` = '%s' WHERE `id` = %d AND `uid` = %d",
171 * Per the DFRN protocol, we will verify both ends by encrypting the dfrn_id with our
172 * site private key (person on the other end can decrypt it with our site public key).
173 * Then encrypt our profile URL with the other person's site public key. They can decrypt
174 * it with their site private key. If the decryption on the other end fails for either
175 * item, it indicates tampering or key failure on at least one site and we will not be
176 * able to provide a secure communication pathway.
178 * If other site is willing to accept full encryption, (aes_allow is 1 AND we have php5.3
179 * or later) then we encrypt the personal public key we send them using AES-256-CBC and a
180 * random key which is encrypted with their site public key.
183 $src_aes_key = openssl_random_pseudo_bytes(64);
186 openssl_private_encrypt($dfrn_id, $result, $user['prvkey']);
188 $params['dfrn_id'] = bin2hex($result);
189 $params['public_key'] = $public_key;
191 $my_url = System::baseUrl() . '/profile/' . $user['nickname'];
193 openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey);
194 $params['source_url'] = bin2hex($params['source_url']);
196 if ($aes_allow && function_exists('openssl_encrypt')) {
197 openssl_public_encrypt($src_aes_key, $params['aes_key'], $site_pubkey);
198 $params['aes_key'] = bin2hex($params['aes_key']);
199 $params['public_key'] = bin2hex(openssl_encrypt($public_key, 'AES-256-CBC', $src_aes_key));
202 $params['dfrn_version'] = DFRN_PROTOCOL_VERSION;
204 $params['duplex'] = 1;
207 if ($user['page-flags'] == PAGE_COMMUNITY) {
211 if ($user['page-flags'] == PAGE_PRVGROUP) {
215 logger('Confirm: posting data to ' . $dfrn_confirm . ': ' . print_r($params, true), LOGGER_DATA);
219 * POST all this stuff to the other site.
220 * Temporarily raise the network timeout to 120 seconds because the default 60
221 * doesn't always give the other side quite enough time to decrypt everything.
225 $res = Network::post($dfrn_confirm, $params, null, $redirects, 120);
227 logger(' Confirm: received data: ' . $res, LOGGER_DATA);
229 // Now figure out what they responded. Try to be robust if the remote site is
230 // having difficulty and throwing up errors of some kind.
232 $leading_junk = substr($res, 0, strpos($res, '<?xml'));
234 $res = substr($res, strpos($res, '<?xml'));
236 // No XML at all, this exchange is messed up really bad.
237 // We shouldn't proceed, because the xml parser might choke,
238 // and $status is going to be zero, which indicates success.
239 // We can hardly call this a success.
240 notice(L10n::t('Response from remote site was not understood.') . EOL);
244 if (strlen($leading_junk) && Config::get('system', 'debugging')) {
245 // This might be more common. Mixed error text and some XML.
246 // If we're configured for debugging, show the text. Proceed in either case.
247 notice(L10n::t('Unexpected response from remote site: ') . EOL . $leading_junk . EOL);
250 if (stristr($res, "<status") === false) {
251 // wrong xml! stop here!
252 notice(L10n::t('Unexpected response from remote site: ') . EOL . htmlspecialchars($res) . EOL);
256 $xml = XML::parseString($res);
257 $status = (int) $xml->status;
258 $message = unxmlify($xml->message); // human readable text of what may have gone wrong.
261 info(L10n::t("Confirmation completed successfully.") . EOL);
264 // birthday paradox - generate new dfrn-id and fall through.
265 $new_dfrn_id = random_string();
266 q("UPDATE contact SET `issued-id` = '%s' WHERE `id` = %d AND `uid` = %d",
273 notice(L10n::t("Temporary failure. Please wait and try again.") . EOL);
276 notice(L10n::t("Introduction failed or was revoked.") . EOL);
280 if (strlen($message)) {
281 notice(L10n::t('Remote site reported: ') . $message . EOL);
284 if (($status == 0) && $intro_id) {
285 $intro = dba::selectFirst('intro', ['note'], ['id' => $intro_id]);
286 if (DBM::is_result($intro)) {
287 dba::update('contact', ['reason' => $intro['note']], ['id' => $contact_id]);
290 // Success. Delete the notification.
291 dba::delete('intro', ['id' => $intro_id]);
300 * We have now established a relationship with the other site.
301 * Let's make our own personal copy of their profile photo so we don't have
302 * to always load it from their site.
304 * We will also update the contact record with the nature and scope of the relationship.
306 Contact::updateAvatar($contact['photo'], $uid, $contact_id);
308 logger('dfrn_confirm: confirm - imported photos');
310 if ($network === NETWORK_DFRN) {
311 $new_relation = CONTACT_IS_FOLLOWER;
312 if (($relation == CONTACT_IS_SHARING) || ($duplex)) {
313 $new_relation = CONTACT_IS_FRIEND;
316 if (($relation == CONTACT_IS_SHARING) && ($duplex)) {
320 $r = q("UPDATE `contact` SET `rel` = %d,
327 `network` = '%s' WHERE `id` = %d
329 intval($new_relation),
330 dbesc(DateTimeFormat::utcNow()),
331 dbesc(DateTimeFormat::utcNow()),
338 // $network !== NETWORK_DFRN
339 $network = defaults($contact, 'network', NETWORK_OSTATUS);
341 $arr = Probe::uri($contact['url']);
343 $notify = defaults($contact, 'notify' , $arr['notify']);
344 $poll = defaults($contact, 'poll' , $arr['poll']);
346 $addr = $arr['addr'];
348 $new_relation = $contact['rel'];
349 $writable = $contact['writable'];
351 if ($network === NETWORK_DIASPORA) {
353 $new_relation = CONTACT_IS_FRIEND;
355 $new_relation = CONTACT_IS_FOLLOWER;
358 if ($new_relation != CONTACT_IS_FOLLOWER) {
363 dba::delete('intro', ['id' => $intro_id]);
365 $r = q("UPDATE `contact` SET `name-date` = '%s',
378 dbesc(DateTimeFormat::utcNow()),
379 dbesc(DateTimeFormat::utcNow()),
386 intval($new_relation),
391 if (!DBM::is_result($r)) {
392 notice(L10n::t('Unable to set contact photo.') . EOL);
395 // reload contact info
396 $contact = dba::selectFirst('contact', [], ['id' => $contact_id]);
397 if ((isset($new_relation) && $new_relation == CONTACT_IS_FRIEND)) {
398 if (DBM::is_result($contact) && ($contact['network'] === NETWORK_DIASPORA)) {
399 $ret = Diaspora::sendShare($user, $contact);
400 logger('share returns: ' . $ret);
404 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact['id']);
406 // Let's send our user to the contact editor in case they want to
407 // do anything special with this new friend.
408 if ($handsfree === null) {
409 goaway(System::baseUrl() . '/contacts/' . intval($contact_id));
417 * End of Scenario 1. [Local confirmation of remote friend request].
419 * Begin Scenario 2. This is the remote response to the above scenario.
420 * This will take place on the site that originally initiated the friend request.
421 * In the section above where the confirming party makes a POST and
422 * retrieves xml status information, they are communicating with the following code.
424 if (x($_POST, 'source_url')) {
425 // We are processing an external confirmation to an introduction created by our user.
426 $public_key = defaults($_POST, 'public_key', '');
427 $dfrn_id = hex2bin(defaults($_POST, 'dfrn_id' , ''));
428 $source_url = hex2bin(defaults($_POST, 'source_url', ''));
429 $aes_key = defaults($_POST, 'aes_key' , '');
430 $duplex = intval(defaults($_POST, 'duplex' , 0));
431 $page = intval(defaults($_POST, 'page' , 0));
433 $forum = (($page == 1) ? 1 : 0);
434 $prv = (($page == 2) ? 1 : 0);
436 logger('dfrn_confirm: requestee contacted: ' . $node);
438 logger('dfrn_confirm: request: POST=' . print_r($_POST, true), LOGGER_DATA);
440 // If $aes_key is set, both of these items require unpacking from the hex transport encoding.
443 $aes_key = hex2bin($aes_key);
444 $public_key = hex2bin($public_key);
447 // Find our user's account
448 $user = dba::selectFirst('user', [], ['nickname' => $node]);
449 if (!DBM::is_result($user)) {
450 $message = L10n::t('No user record found for \'%s\' ', $node);
451 System::xmlExit(3, $message); // failure
455 $my_prvkey = $user['prvkey'];
456 $local_uid = $user['uid'];
459 if (!strstr($my_prvkey, 'PRIVATE KEY')) {
460 $message = L10n::t('Our site encryption key is apparently messed up.');
461 System::xmlExit(3, $message);
466 $decrypted_source_url = "";
467 openssl_private_decrypt($source_url, $decrypted_source_url, $my_prvkey);
470 if (!strlen($decrypted_source_url)) {
471 $message = L10n::t('Empty site URL was provided or URL could not be decrypted by us.');
472 System::xmlExit(3, $message);
476 $contact = dba::selectFirst('contact', [], ['url' => $decrypted_source_url, 'uid' => $local_uid]);
477 if (!DBM::is_result($contact)) {
478 if (strstr($decrypted_source_url, 'http:')) {
479 $newurl = str_replace('http:', 'https:', $decrypted_source_url);
481 $newurl = str_replace('https:', 'http:', $decrypted_source_url);
484 $contact = dba::selectFirst('contact', [], ['url' => $newurl, 'uid' => $local_uid]);
485 if (!DBM::is_result($contact)) {
486 // this is either a bogus confirmation (?) or we deleted the original introduction.
487 $message = L10n::t('Contact record was not found for you on our site.');
488 System::xmlExit(3, $message);
489 return; // NOTREACHED
493 $relation = $contact['rel'];
495 // Decrypt all this stuff we just received
497 $foreign_pubkey = $contact['site-pubkey'];
498 $dfrn_record = $contact['id'];
500 if (!$foreign_pubkey) {
501 $message = L10n::t('Site public key not available in contact record for URL %s.', $decrypted_source_url);
502 System::xmlExit(3, $message);
505 $decrypted_dfrn_id = "";
506 openssl_public_decrypt($dfrn_id, $decrypted_dfrn_id, $foreign_pubkey);
508 if (strlen($aes_key)) {
509 $decrypted_aes_key = "";
510 openssl_private_decrypt($aes_key, $decrypted_aes_key, $my_prvkey);
511 $dfrn_pubkey = openssl_decrypt($public_key, 'AES-256-CBC', $decrypted_aes_key);
513 $dfrn_pubkey = $public_key;
516 if (dba::exists('contact', ['dfrn-id' => $decrypted_dfrn_id])) {
517 $message = L10n::t('The ID provided by your system is a duplicate on our system. It should work if you try again.');
518 System::xmlExit(1, $message); // Birthday paradox - duplicate dfrn-id
522 $r = q("UPDATE `contact` SET `dfrn-id` = '%s', `pubkey` = '%s' WHERE `id` = %d",
523 dbesc($decrypted_dfrn_id),
527 if (!DBM::is_result($r)) {
528 $message = L10n::t('Unable to set your contact credentials on our system.');
529 System::xmlExit(3, $message);
532 // It's possible that the other person also requested friendship.
533 // If it is a duplex relationship, ditch the issued-id if one exists.
536 q("UPDATE `contact` SET `issued-id` = '' WHERE `id` = %d",
541 // We're good but now we have to scrape the profile photo and send notifications.
542 $contact = dba::selectFirst('contact', ['photo'], ['id' => $dfrn_record]);
543 if (DBM::is_result($contact)) {
544 $photo = $contact['photo'];
546 $photo = System::baseUrl() . '/images/person-175.jpg';
549 Contact::updateAvatar($photo, $local_uid, $dfrn_record);
551 logger('dfrn_confirm: request - photos imported');
553 $new_relation = CONTACT_IS_SHARING;
554 if (($relation == CONTACT_IS_FOLLOWER) || ($duplex)) {
555 $new_relation = CONTACT_IS_FRIEND;
558 if (($relation == CONTACT_IS_FOLLOWER) && ($duplex)) {
562 $r = q("UPDATE `contact` SET
571 `network` = '%s' WHERE `id` = %d
573 intval($new_relation),
574 dbesc(DateTimeFormat::utcNow()),
575 dbesc(DateTimeFormat::utcNow()),
582 if (!DBM::is_result($r)) { // indicates schema is messed up or total db failure
583 $message = L10n::t('Unable to update your contact profile details on our system');
584 System::xmlExit(3, $message);
587 // Otherwise everything seems to have worked and we are almost done. Yay!
588 // Send an email notification
590 logger('dfrn_confirm: request: info updated');
593 $r = q("SELECT `contact`.*, `user`.*
595 LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
596 WHERE `contact`.`id` = %d
600 if (DBM::is_result($r)) {
603 if ($combined['notify-flags'] & NOTIFY_CONFIRM) {
604 $mutual = ($new_relation == CONTACT_IS_FRIEND);
606 'type' => NOTIFY_CONFIRM,
607 'notify_flags' => $combined['notify-flags'],
608 'language' => $combined['language'],
609 'to_name' => $combined['username'],
610 'to_email' => $combined['email'],
611 'uid' => $combined['uid'],
612 'link' => System::baseUrl() . '/contacts/' . $dfrn_record,
613 'source_name' => ((strlen(stripslashes($combined['name']))) ? stripslashes($combined['name']) : L10n::t('[Name Withheld]')),
614 'source_link' => $combined['url'],
615 'source_photo' => $combined['photo'],
616 'verb' => ($mutual?ACTIVITY_FRIEND:ACTIVITY_FOLLOW),
622 System::xmlExit(0); // Success
623 return; // NOTREACHED
624 ////////////////////// End of this scenario ///////////////////////////////////////////////
627 // somebody arrived here by mistake or they are fishing. Send them to the homepage.
628 goaway(System::baseUrl());