3 * @file mod/dfrn_confirm.php
6 * Purpose: Friendship acceptance for DFRN contacts
8 * There are two possible entry points and three scenarios.
10 * 1. A form was submitted by our user approving a friendship that originated elsewhere.
11 * This may also be called from dfrn_request to automatically approve a friendship.
13 * 2. We may be the target or other side of the conversation to scenario 1, and will
14 * interact with that process on our own user's behalf.
16 * @see PDF with dfrn specs: https://github.com/friendica/friendica/blob/master/spec/dfrn2.pdf
17 * You also find a graphic which describes the confirmation process at
18 * https://github.com/friendica/friendica/blob/master/spec/dfrn2_contact_confirmation.png
22 use Friendica\Core\Config;
23 use Friendica\Core\Logger;
24 use Friendica\Core\Protocol;
25 use Friendica\Core\System;
26 use Friendica\Database\DBA;
28 use Friendica\Model\Contact;
29 use Friendica\Model\Group;
30 use Friendica\Model\User;
31 use Friendica\Protocol\Activity;
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;
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 (empty($_POST['source_url'])) {
63 $uid = ($handsfree['uid'] ?? 0) ?: local_user();
65 notice(DI::l10n()->t('Permission denied.') . EOL);
69 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
70 if (!DBA::isResult($user)) {
71 notice(DI::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::log('Confirm in handsfree mode');
78 $dfrn_id = $handsfree['dfrn_id'];
79 $intro_id = $handsfree['intro_id'];
80 $duplex = $handsfree['duplex'];
82 $hidden = intval($handsfree['hidden'] ?? 0);
84 $dfrn_id = Strings::escapeTags(trim($_POST['dfrn_id'] ?? ''));
85 $intro_id = intval($_POST['intro_id'] ?? 0);
86 $duplex = intval($_POST['duplex'] ?? 0);
87 $cid = intval($_POST['contact_id'] ?? 0);
88 $hidden = intval($_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::log('Confirming request for dfrn_id (issued) ' . $dfrn_id);
102 Logger::log('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::log('Contact not found in DB.');
126 notice(DI::l10n()->t('Contact not found.') . EOL);
127 notice(DI::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'];
138 $protocol = $contact['network'];
141 * Generate a key pair for all further communications with this person.
142 * We have a keypair for every contact, and a site key for unknown people.
143 * This provides a means to carry on relationships with other people if
144 * any single key is compromised. It is a robust key. We're much more
145 * worried about key leakage than anybody cracking it.
147 $res = Crypto::newKeypair(4096);
149 $private_key = $res['prvkey'];
150 $public_key = $res['pubkey'];
152 // Save the private key. Send them the public key.
153 $fields = ['prvkey' => $private_key, 'protocol' => Protocol::DFRN];
154 DBA::update('contact', $fields, ['id' => $contact_id]);
159 * Per the DFRN protocol, we will verify both ends by encrypting the dfrn_id with our
160 * site private key (person on the other end can decrypt it with our site public key).
161 * Then encrypt our profile URL with the other person's site public key. They can decrypt
162 * it with their site private key. If the decryption on the other end fails for either
163 * item, it indicates tampering or key failure on at least one site and we will not be
164 * able to provide a secure communication pathway.
166 * If other site is willing to accept full encryption, (aes_allow is 1 AND we have php5.3
167 * or later) then we encrypt the personal public key we send them using AES-256-CBC and a
168 * random key which is encrypted with their site public key.
171 $src_aes_key = openssl_random_pseudo_bytes(64);
174 openssl_private_encrypt($dfrn_id, $result, $user['prvkey']);
176 $params['dfrn_id'] = bin2hex($result);
177 $params['public_key'] = $public_key;
179 $my_url = DI::baseUrl() . '/profile/' . $user['nickname'];
181 openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey);
182 $params['source_url'] = bin2hex($params['source_url']);
184 if ($aes_allow && function_exists('openssl_encrypt')) {
185 openssl_public_encrypt($src_aes_key, $params['aes_key'], $site_pubkey);
186 $params['aes_key'] = bin2hex($params['aes_key']);
187 $params['public_key'] = bin2hex(openssl_encrypt($public_key, 'AES-256-CBC', $src_aes_key));
190 $params['dfrn_version'] = DFRN_PROTOCOL_VERSION;
192 $params['duplex'] = 1;
195 if ($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY) {
199 if ($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
203 Logger::log('Confirm: posting data to ' . $dfrn_confirm . ': ' . print_r($params, true), Logger::DATA);
207 * POST all this stuff to the other site.
208 * Temporarily raise the network timeout to 120 seconds because the default 60
209 * doesn't always give the other side quite enough time to decrypt everything.
213 $res = Network::post($dfrn_confirm, $params, [], 120)->getBody();
215 Logger::log(' Confirm: received data: ' . $res, Logger::DATA);
217 // Now figure out what they responded. Try to be robust if the remote site is
218 // having difficulty and throwing up errors of some kind.
220 $leading_junk = substr($res, 0, strpos($res, '<?xml'));
222 $res = substr($res, strpos($res, '<?xml'));
224 // No XML at all, this exchange is messed up really bad.
225 // We shouldn't proceed, because the xml parser might choke,
226 // and $status is going to be zero, which indicates success.
227 // We can hardly call this a success.
228 notice(DI::l10n()->t('Response from remote site was not understood.') . EOL);
232 if (strlen($leading_junk) && Config::get('system', 'debugging')) {
233 // This might be more common. Mixed error text and some XML.
234 // If we're configured for debugging, show the text. Proceed in either case.
235 notice(DI::l10n()->t('Unexpected response from remote site: ') . EOL . $leading_junk . EOL);
238 if (stristr($res, "<status") === false) {
239 // wrong xml! stop here!
240 Logger::log('Unexpected response posting to ' . $dfrn_confirm);
241 notice(DI::l10n()->t('Unexpected response from remote site: ') . EOL . htmlspecialchars($res) . EOL);
245 $xml = XML::parseString($res);
246 $status = (int) $xml->status;
247 $message = XML::unescape($xml->message); // human readable text of what may have gone wrong.
250 info(DI::l10n()->t("Confirmation completed successfully.") . EOL);
253 // birthday paradox - generate new dfrn-id and fall through.
254 $new_dfrn_id = Strings::getRandomHex();
255 q("UPDATE contact SET `issued-id` = '%s' WHERE `id` = %d AND `uid` = %d",
256 DBA::escape($new_dfrn_id),
262 notice(DI::l10n()->t("Temporary failure. Please wait and try again.") . EOL);
265 notice(DI::l10n()->t("Introduction failed or was revoked.") . EOL);
269 if (strlen($message)) {
270 notice(DI::l10n()->t('Remote site reported: ') . $message . EOL);
273 if (($status == 0) && $intro_id) {
274 $intro = DBA::selectFirst('intro', ['note'], ['id' => $intro_id]);
275 if (DBA::isResult($intro)) {
276 DBA::update('contact', ['reason' => $intro['note']], ['id' => $contact_id]);
279 // Success. Delete the notification.
280 DBA::delete('intro', ['id' => $intro_id]);
288 * We have now established a relationship with the other site.
289 * Let's make our own personal copy of their profile photo so we don't have
290 * to always load it from their site.
292 * We will also update the contact record with the nature and scope of the relationship.
294 Contact::updateAvatar($contact['photo'], $uid, $contact_id);
296 Logger::log('dfrn_confirm: confirm - imported photos');
298 $new_relation = Contact::FOLLOWER;
300 if (($relation == Contact::SHARING) || ($duplex)) {
301 $new_relation = Contact::FRIEND;
304 if (($relation == Contact::SHARING) && ($duplex)) {
308 $r = q("UPDATE `contact` SET `rel` = %d,
315 `network` = '%s' WHERE `id` = %d
317 intval($new_relation),
318 DBA::escape(DateTimeFormat::utcNow()),
319 DBA::escape(DateTimeFormat::utcNow()),
322 DBA::escape(Protocol::DFRN),
326 // reload contact info
327 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
329 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact['id']);
331 // Let's send our user to the contact editor in case they want to
332 // do anything special with this new friend.
333 if ($handsfree === null) {
334 DI::baseUrl()->redirect('contact/' . intval($contact_id));
342 * End of Scenario 1. [Local confirmation of remote friend request].
344 * Begin Scenario 2. This is the remote response to the above scenario.
345 * This will take place on the site that originally initiated the friend request.
346 * In the section above where the confirming party makes a POST and
347 * retrieves xml status information, they are communicating with the following code.
349 if (!empty($_POST['source_url'])) {
350 // We are processing an external confirmation to an introduction created by our user.
351 $public_key = $_POST['public_key'] ?? '';
352 $dfrn_id = hex2bin($_POST['dfrn_id'] ?? '');
353 $source_url = hex2bin($_POST['source_url'] ?? '');
354 $aes_key = $_POST['aes_key'] ?? '';
355 $duplex = intval($_POST['duplex'] ?? 0);
356 $page = intval($_POST['page'] ?? 0);
358 $forum = (($page == 1) ? 1 : 0);
359 $prv = (($page == 2) ? 1 : 0);
361 Logger::log('dfrn_confirm: requestee contacted: ' . $node);
363 Logger::log('dfrn_confirm: request: POST=' . print_r($_POST, true), Logger::DATA);
365 // If $aes_key is set, both of these items require unpacking from the hex transport encoding.
367 if (!empty($aes_key)) {
368 $aes_key = hex2bin($aes_key);
369 $public_key = hex2bin($public_key);
372 // Find our user's account
373 $user = DBA::selectFirst('user', [], ['nickname' => $node]);
374 if (!DBA::isResult($user)) {
375 $message = DI::l10n()->t('No user record found for \'%s\' ', $node);
376 System::xmlExit(3, $message); // failure
380 $my_prvkey = $user['prvkey'];
381 $local_uid = $user['uid'];
384 if (!strstr($my_prvkey, 'PRIVATE KEY')) {
385 $message = DI::l10n()->t('Our site encryption key is apparently messed up.');
386 System::xmlExit(3, $message);
391 $decrypted_source_url = "";
392 openssl_private_decrypt($source_url, $decrypted_source_url, $my_prvkey);
395 if (!strlen($decrypted_source_url)) {
396 $message = DI::l10n()->t('Empty site URL was provided or URL could not be decrypted by us.');
397 System::xmlExit(3, $message);
401 $contact = DBA::selectFirst('contact', [], ['url' => $decrypted_source_url, 'uid' => $local_uid]);
402 if (!DBA::isResult($contact)) {
403 if (strstr($decrypted_source_url, 'http:')) {
404 $newurl = str_replace('http:', 'https:', $decrypted_source_url);
406 $newurl = str_replace('https:', 'http:', $decrypted_source_url);
409 $contact = DBA::selectFirst('contact', [], ['url' => $newurl, 'uid' => $local_uid]);
410 if (!DBA::isResult($contact)) {
411 // this is either a bogus confirmation (?) or we deleted the original introduction.
412 $message = DI::l10n()->t('Contact record was not found for you on our site.');
413 System::xmlExit(3, $message);
414 return; // NOTREACHED
418 $relation = $contact['rel'];
420 // Decrypt all this stuff we just received
422 $foreign_pubkey = $contact['site-pubkey'];
423 $dfrn_record = $contact['id'];
425 if (!$foreign_pubkey) {
426 $message = DI::l10n()->t('Site public key not available in contact record for URL %s.', $decrypted_source_url);
427 System::xmlExit(3, $message);
430 $decrypted_dfrn_id = "";
431 openssl_public_decrypt($dfrn_id, $decrypted_dfrn_id, $foreign_pubkey);
433 if (strlen($aes_key)) {
434 $decrypted_aes_key = "";
435 openssl_private_decrypt($aes_key, $decrypted_aes_key, $my_prvkey);
436 $dfrn_pubkey = openssl_decrypt($public_key, 'AES-256-CBC', $decrypted_aes_key);
438 $dfrn_pubkey = $public_key;
441 if (DBA::exists('contact', ['dfrn-id' => $decrypted_dfrn_id])) {
442 $message = DI::l10n()->t('The ID provided by your system is a duplicate on our system. It should work if you try again.');
443 System::xmlExit(1, $message); // Birthday paradox - duplicate dfrn-id
447 $r = q("UPDATE `contact` SET `dfrn-id` = '%s', `pubkey` = '%s' WHERE `id` = %d",
448 DBA::escape($decrypted_dfrn_id),
449 DBA::escape($dfrn_pubkey),
452 if (!DBA::isResult($r)) {
453 $message = DI::l10n()->t('Unable to set your contact credentials on our system.');
454 System::xmlExit(3, $message);
457 // It's possible that the other person also requested friendship.
458 // If it is a duplex relationship, ditch the issued-id if one exists.
461 q("UPDATE `contact` SET `issued-id` = '' WHERE `id` = %d",
466 // We're good but now we have to scrape the profile photo and send notifications.
467 $contact = DBA::selectFirst('contact', ['photo'], ['id' => $dfrn_record]);
468 if (DBA::isResult($contact)) {
469 $photo = $contact['photo'];
471 $photo = DI::baseUrl() . '/images/person-300.jpg';
474 Contact::updateAvatar($photo, $local_uid, $dfrn_record);
476 Logger::log('dfrn_confirm: request - photos imported');
478 $new_relation = Contact::SHARING;
480 if (($relation == Contact::FOLLOWER) || ($duplex)) {
481 $new_relation = Contact::FRIEND;
484 if (($relation == Contact::FOLLOWER) && ($duplex)) {
488 $r = q("UPDATE `contact` SET
497 `network` = '%s' WHERE `id` = %d
499 intval($new_relation),
500 DBA::escape(DateTimeFormat::utcNow()),
501 DBA::escape(DateTimeFormat::utcNow()),
505 DBA::escape(Protocol::DFRN),
508 if (!DBA::isResult($r)) { // indicates schema is messed up or total db failure
509 $message = DI::l10n()->t('Unable to update your contact profile details on our system');
510 System::xmlExit(3, $message);
513 // Otherwise everything seems to have worked and we are almost done. Yay!
514 // Send an email notification
516 Logger::log('dfrn_confirm: request: info updated');
519 $r = q("SELECT `contact`.*, `user`.*
521 LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
522 WHERE `contact`.`id` = %d
526 if (DBA::isResult($r)) {
529 if ($combined['notify-flags'] & NOTIFY_CONFIRM) {
530 $mutual = ($new_relation == Contact::FRIEND);
532 'type' => NOTIFY_CONFIRM,
533 'notify_flags' => $combined['notify-flags'],
534 'language' => $combined['language'],
535 'to_name' => $combined['username'],
536 'to_email' => $combined['email'],
537 'uid' => $combined['uid'],
538 'link' => DI::baseUrl() . '/contact/' . $dfrn_record,
539 'source_name' => ((strlen(stripslashes($combined['name']))) ? stripslashes($combined['name']) : DI::l10n()->t('[Name Withheld]')),
540 'source_link' => $combined['url'],
541 'source_photo' => $combined['photo'],
542 'verb' => ($mutual ? Activity::FRIEND : Activity::FOLLOW),
548 System::xmlExit(0); // Success
549 return; // NOTREACHED
550 ////////////////////// End of this scenario ///////////////////////////////////////////////
553 // somebody arrived here by mistake or they are fishing. Send them to the homepage.
554 DI::baseUrl()->redirect();