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\L10n;
24 use Friendica\Core\Logger;
25 use Friendica\Core\Protocol;
26 use Friendica\Core\System;
27 use Friendica\Database\DBA;
29 use Friendica\Model\Contact;
30 use Friendica\Model\Group;
31 use Friendica\Model\User;
32 use Friendica\Network\Probe;
33 use Friendica\Protocol\Activity;
34 use Friendica\Util\Crypto;
35 use Friendica\Util\DateTimeFormat;
36 use Friendica\Util\Network;
37 use Friendica\Util\Strings;
38 use Friendica\Util\XML;
40 function dfrn_confirm_post(App $a, $handsfree = null)
43 if (is_array($handsfree)) {
45 * We were called directly from dfrn_request due to automatic friend acceptance.
46 * Any $_POST parameters we may require are supplied in the $handsfree array.
49 $node = $handsfree['node'];
50 $a->interactive = false; // notice() becomes a no-op since nobody is there to see it
51 } elseif ($a->argc > 1) {
56 * Main entry point. Scenario 1. Our user received a friend request notification (perhaps
57 * from another site) and clicked 'Approve'.
58 * $POST['source_url'] is not set. If it is, it indicates Scenario 2.
60 * We may also have been called directly from dfrn_request ($handsfree != null) due to
61 * this being a page type which supports automatic friend acceptance. That is also Scenario 1
62 * since we are operating on behalf of our registered user to approve a friendship.
64 if (empty($_POST['source_url'])) {
65 $uid = ($handsfree['uid'] ?? 0) ?: local_user();
67 notice(DI::l10n()->t('Permission denied.') . EOL);
71 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
72 if (!DBA::isResult($user)) {
73 notice(DI::l10n()->t('Profile not found.') . EOL);
77 // These data elements may come from either the friend request notification form or $handsfree array.
78 if (is_array($handsfree)) {
79 Logger::log('Confirm in handsfree mode');
80 $dfrn_id = $handsfree['dfrn_id'];
81 $intro_id = $handsfree['intro_id'];
82 $duplex = $handsfree['duplex'];
84 $hidden = intval($handsfree['hidden'] ?? 0);
86 $dfrn_id = Strings::escapeTags(trim($_POST['dfrn_id'] ?? ''));
87 $intro_id = intval($_POST['intro_id'] ?? 0);
88 $duplex = intval($_POST['duplex'] ?? 0);
89 $cid = intval($_POST['contact_id'] ?? 0);
90 $hidden = intval($_POST['hidden'] ?? 0);
94 * Ensure that dfrn_id has precedence when we go to find the contact record.
95 * We only want to search based on contact id if there is no dfrn_id,
96 * e.g. for OStatus network followers.
98 if (strlen($dfrn_id)) {
102 Logger::log('Confirming request for dfrn_id (issued) ' . $dfrn_id);
104 Logger::log('Confirming follower with contact_id: ' . $cid);
108 * The other person will have been issued an ID when they first requested friendship.
109 * Locate their record. At this time, their record will have both pending and blocked set to 1.
110 * There won't be any dfrn_id if this is a network follower, so use the contact_id instead.
115 (`issued-id` != '' AND `issued-id` = '%s')
117 (`id` = %d AND `id` != 0)
122 DBA::escape($dfrn_id),
126 if (!DBA::isResult($r)) {
127 Logger::log('Contact not found in DB.');
128 notice(DI::l10n()->t('Contact not found.') . EOL);
129 notice(DI::l10n()->t('This may occasionally happen if contact was requested by both persons and it has already been approved.') . EOL);
135 $contact_id = $contact['id'];
136 $relation = $contact['rel'];
137 $site_pubkey = $contact['site-pubkey'];
138 $dfrn_confirm = $contact['confirm'];
139 $aes_allow = $contact['aes_allow'];
140 $protocol = $contact['network'];
143 * Generate a key pair for all further communications with this person.
144 * We have a keypair for every contact, and a site key for unknown people.
145 * This provides a means to carry on relationships with other people if
146 * any single key is compromised. It is a robust key. We're much more
147 * worried about key leakage than anybody cracking it.
149 $res = Crypto::newKeypair(4096);
151 $private_key = $res['prvkey'];
152 $public_key = $res['pubkey'];
154 // Save the private key. Send them the public key.
155 $fields = ['prvkey' => $private_key, 'protocol' => Protocol::DFRN];
156 DBA::update('contact', $fields, ['id' => $contact_id]);
161 * Per the DFRN protocol, we will verify both ends by encrypting the dfrn_id with our
162 * site private key (person on the other end can decrypt it with our site public key).
163 * Then encrypt our profile URL with the other person's site public key. They can decrypt
164 * it with their site private key. If the decryption on the other end fails for either
165 * item, it indicates tampering or key failure on at least one site and we will not be
166 * able to provide a secure communication pathway.
168 * If other site is willing to accept full encryption, (aes_allow is 1 AND we have php5.3
169 * or later) then we encrypt the personal public key we send them using AES-256-CBC and a
170 * random key which is encrypted with their site public key.
173 $src_aes_key = openssl_random_pseudo_bytes(64);
176 openssl_private_encrypt($dfrn_id, $result, $user['prvkey']);
178 $params['dfrn_id'] = bin2hex($result);
179 $params['public_key'] = $public_key;
181 $my_url = DI::baseUrl() . '/profile/' . $user['nickname'];
183 openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey);
184 $params['source_url'] = bin2hex($params['source_url']);
186 if ($aes_allow && function_exists('openssl_encrypt')) {
187 openssl_public_encrypt($src_aes_key, $params['aes_key'], $site_pubkey);
188 $params['aes_key'] = bin2hex($params['aes_key']);
189 $params['public_key'] = bin2hex(openssl_encrypt($public_key, 'AES-256-CBC', $src_aes_key));
192 $params['dfrn_version'] = DFRN_PROTOCOL_VERSION;
194 $params['duplex'] = 1;
197 if ($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY) {
201 if ($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
205 Logger::log('Confirm: posting data to ' . $dfrn_confirm . ': ' . print_r($params, true), Logger::DATA);
209 * POST all this stuff to the other site.
210 * Temporarily raise the network timeout to 120 seconds because the default 60
211 * doesn't always give the other side quite enough time to decrypt everything.
215 $res = Network::post($dfrn_confirm, $params, [], 120)->getBody();
217 Logger::log(' Confirm: received data: ' . $res, Logger::DATA);
219 // Now figure out what they responded. Try to be robust if the remote site is
220 // having difficulty and throwing up errors of some kind.
222 $leading_junk = substr($res, 0, strpos($res, '<?xml'));
224 $res = substr($res, strpos($res, '<?xml'));
226 // No XML at all, this exchange is messed up really bad.
227 // We shouldn't proceed, because the xml parser might choke,
228 // and $status is going to be zero, which indicates success.
229 // We can hardly call this a success.
230 notice(DI::l10n()->t('Response from remote site was not understood.') . EOL);
234 if (strlen($leading_junk) && Config::get('system', 'debugging')) {
235 // This might be more common. Mixed error text and some XML.
236 // If we're configured for debugging, show the text. Proceed in either case.
237 notice(DI::l10n()->t('Unexpected response from remote site: ') . EOL . $leading_junk . EOL);
240 if (stristr($res, "<status") === false) {
241 // wrong xml! stop here!
242 Logger::log('Unexpected response posting to ' . $dfrn_confirm);
243 notice(DI::l10n()->t('Unexpected response from remote site: ') . EOL . htmlspecialchars($res) . EOL);
247 $xml = XML::parseString($res);
248 $status = (int) $xml->status;
249 $message = XML::unescape($xml->message); // human readable text of what may have gone wrong.
252 info(DI::l10n()->t("Confirmation completed successfully.") . EOL);
255 // birthday paradox - generate new dfrn-id and fall through.
256 $new_dfrn_id = Strings::getRandomHex();
257 q("UPDATE contact SET `issued-id` = '%s' WHERE `id` = %d AND `uid` = %d",
258 DBA::escape($new_dfrn_id),
264 notice(DI::l10n()->t("Temporary failure. Please wait and try again.") . EOL);
267 notice(DI::l10n()->t("Introduction failed or was revoked.") . EOL);
271 if (strlen($message)) {
272 notice(DI::l10n()->t('Remote site reported: ') . $message . EOL);
275 if (($status == 0) && $intro_id) {
276 $intro = DBA::selectFirst('intro', ['note'], ['id' => $intro_id]);
277 if (DBA::isResult($intro)) {
278 DBA::update('contact', ['reason' => $intro['note']], ['id' => $contact_id]);
281 // Success. Delete the notification.
282 DBA::delete('intro', ['id' => $intro_id]);
290 * We have now established a relationship with the other site.
291 * Let's make our own personal copy of their profile photo so we don't have
292 * to always load it from their site.
294 * We will also update the contact record with the nature and scope of the relationship.
296 Contact::updateAvatar($contact['photo'], $uid, $contact_id);
298 Logger::log('dfrn_confirm: confirm - imported photos');
300 $new_relation = Contact::FOLLOWER;
302 if (($relation == Contact::SHARING) || ($duplex)) {
303 $new_relation = Contact::FRIEND;
306 if (($relation == Contact::SHARING) && ($duplex)) {
310 $r = q("UPDATE `contact` SET `rel` = %d,
317 `network` = '%s' WHERE `id` = %d
319 intval($new_relation),
320 DBA::escape(DateTimeFormat::utcNow()),
321 DBA::escape(DateTimeFormat::utcNow()),
324 DBA::escape(Protocol::DFRN),
328 // reload contact info
329 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
331 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact['id']);
333 // Let's send our user to the contact editor in case they want to
334 // do anything special with this new friend.
335 if ($handsfree === null) {
336 DI::baseUrl()->redirect('contact/' . intval($contact_id));
344 * End of Scenario 1. [Local confirmation of remote friend request].
346 * Begin Scenario 2. This is the remote response to the above scenario.
347 * This will take place on the site that originally initiated the friend request.
348 * In the section above where the confirming party makes a POST and
349 * retrieves xml status information, they are communicating with the following code.
351 if (!empty($_POST['source_url'])) {
352 // We are processing an external confirmation to an introduction created by our user.
353 $public_key = $_POST['public_key'] ?? '';
354 $dfrn_id = hex2bin($_POST['dfrn_id'] ?? '');
355 $source_url = hex2bin($_POST['source_url'] ?? '');
356 $aes_key = $_POST['aes_key'] ?? '';
357 $duplex = intval($_POST['duplex'] ?? 0);
358 $page = intval($_POST['page'] ?? 0);
360 $forum = (($page == 1) ? 1 : 0);
361 $prv = (($page == 2) ? 1 : 0);
363 Logger::log('dfrn_confirm: requestee contacted: ' . $node);
365 Logger::log('dfrn_confirm: request: POST=' . print_r($_POST, true), Logger::DATA);
367 // If $aes_key is set, both of these items require unpacking from the hex transport encoding.
369 if (!empty($aes_key)) {
370 $aes_key = hex2bin($aes_key);
371 $public_key = hex2bin($public_key);
374 // Find our user's account
375 $user = DBA::selectFirst('user', [], ['nickname' => $node]);
376 if (!DBA::isResult($user)) {
377 $message = DI::l10n()->t('No user record found for \'%s\' ', $node);
378 System::xmlExit(3, $message); // failure
382 $my_prvkey = $user['prvkey'];
383 $local_uid = $user['uid'];
386 if (!strstr($my_prvkey, 'PRIVATE KEY')) {
387 $message = DI::l10n()->t('Our site encryption key is apparently messed up.');
388 System::xmlExit(3, $message);
393 $decrypted_source_url = "";
394 openssl_private_decrypt($source_url, $decrypted_source_url, $my_prvkey);
397 if (!strlen($decrypted_source_url)) {
398 $message = DI::l10n()->t('Empty site URL was provided or URL could not be decrypted by us.');
399 System::xmlExit(3, $message);
403 $contact = DBA::selectFirst('contact', [], ['url' => $decrypted_source_url, 'uid' => $local_uid]);
404 if (!DBA::isResult($contact)) {
405 if (strstr($decrypted_source_url, 'http:')) {
406 $newurl = str_replace('http:', 'https:', $decrypted_source_url);
408 $newurl = str_replace('https:', 'http:', $decrypted_source_url);
411 $contact = DBA::selectFirst('contact', [], ['url' => $newurl, 'uid' => $local_uid]);
412 if (!DBA::isResult($contact)) {
413 // this is either a bogus confirmation (?) or we deleted the original introduction.
414 $message = DI::l10n()->t('Contact record was not found for you on our site.');
415 System::xmlExit(3, $message);
416 return; // NOTREACHED
420 $relation = $contact['rel'];
422 // Decrypt all this stuff we just received
424 $foreign_pubkey = $contact['site-pubkey'];
425 $dfrn_record = $contact['id'];
427 if (!$foreign_pubkey) {
428 $message = DI::l10n()->t('Site public key not available in contact record for URL %s.', $decrypted_source_url);
429 System::xmlExit(3, $message);
432 $decrypted_dfrn_id = "";
433 openssl_public_decrypt($dfrn_id, $decrypted_dfrn_id, $foreign_pubkey);
435 if (strlen($aes_key)) {
436 $decrypted_aes_key = "";
437 openssl_private_decrypt($aes_key, $decrypted_aes_key, $my_prvkey);
438 $dfrn_pubkey = openssl_decrypt($public_key, 'AES-256-CBC', $decrypted_aes_key);
440 $dfrn_pubkey = $public_key;
443 if (DBA::exists('contact', ['dfrn-id' => $decrypted_dfrn_id])) {
444 $message = DI::l10n()->t('The ID provided by your system is a duplicate on our system. It should work if you try again.');
445 System::xmlExit(1, $message); // Birthday paradox - duplicate dfrn-id
449 $r = q("UPDATE `contact` SET `dfrn-id` = '%s', `pubkey` = '%s' WHERE `id` = %d",
450 DBA::escape($decrypted_dfrn_id),
451 DBA::escape($dfrn_pubkey),
454 if (!DBA::isResult($r)) {
455 $message = DI::l10n()->t('Unable to set your contact credentials on our system.');
456 System::xmlExit(3, $message);
459 // It's possible that the other person also requested friendship.
460 // If it is a duplex relationship, ditch the issued-id if one exists.
463 q("UPDATE `contact` SET `issued-id` = '' WHERE `id` = %d",
468 // We're good but now we have to scrape the profile photo and send notifications.
469 $contact = DBA::selectFirst('contact', ['photo'], ['id' => $dfrn_record]);
470 if (DBA::isResult($contact)) {
471 $photo = $contact['photo'];
473 $photo = DI::baseUrl() . '/images/person-300.jpg';
476 Contact::updateAvatar($photo, $local_uid, $dfrn_record);
478 Logger::log('dfrn_confirm: request - photos imported');
480 $new_relation = Contact::SHARING;
482 if (($relation == Contact::FOLLOWER) || ($duplex)) {
483 $new_relation = Contact::FRIEND;
486 if (($relation == Contact::FOLLOWER) && ($duplex)) {
490 $r = q("UPDATE `contact` SET
499 `network` = '%s' WHERE `id` = %d
501 intval($new_relation),
502 DBA::escape(DateTimeFormat::utcNow()),
503 DBA::escape(DateTimeFormat::utcNow()),
507 DBA::escape(Protocol::DFRN),
510 if (!DBA::isResult($r)) { // indicates schema is messed up or total db failure
511 $message = DI::l10n()->t('Unable to update your contact profile details on our system');
512 System::xmlExit(3, $message);
515 // Otherwise everything seems to have worked and we are almost done. Yay!
516 // Send an email notification
518 Logger::log('dfrn_confirm: request: info updated');
521 $r = q("SELECT `contact`.*, `user`.*
523 LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
524 WHERE `contact`.`id` = %d
528 if (DBA::isResult($r)) {
531 if ($combined['notify-flags'] & NOTIFY_CONFIRM) {
532 $mutual = ($new_relation == Contact::FRIEND);
534 'type' => NOTIFY_CONFIRM,
535 'notify_flags' => $combined['notify-flags'],
536 'language' => $combined['language'],
537 'to_name' => $combined['username'],
538 'to_email' => $combined['email'],
539 'uid' => $combined['uid'],
540 'link' => DI::baseUrl() . '/contact/' . $dfrn_record,
541 'source_name' => ((strlen(stripslashes($combined['name']))) ? stripslashes($combined['name']) : DI::l10n()->t('[Name Withheld]')),
542 'source_link' => $combined['url'],
543 'source_photo' => $combined['photo'],
544 'verb' => ($mutual ? Activity::FRIEND : Activity::FOLLOW),
550 System::xmlExit(0); // Success
551 return; // NOTREACHED
552 ////////////////////// End of this scenario ///////////////////////////////////////////////
555 // somebody arrived here by mistake or they are fishing. Send them to the homepage.
556 DI::baseUrl()->redirect();