3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 * Friendship acceptance for DFRN contacts
22 * There are two possible entry points and three scenarios.
24 * 1. A form was submitted by our user approving a friendship that originated elsewhere.
25 * This may also be called from dfrn_request to automatically approve a friendship.
27 * 2. We may be the target or other side of the conversation to scenario 1, and will
28 * interact with that process on our own user's behalf.
30 * @see PDF with dfrn specs: https://github.com/friendica/friendica/blob/master/spec/dfrn2.pdf
31 * You also find a graphic which describes the confirmation process at
32 * https://github.com/friendica/friendica/blob/master/spec/dfrn2_contact_confirmation.png
36 use Friendica\Core\Logger;
37 use Friendica\Core\Protocol;
38 use Friendica\Core\System;
39 use Friendica\Database\DBA;
41 use Friendica\Model\Contact;
42 use Friendica\Model\Group;
43 use Friendica\Model\Notify\Type;
44 use Friendica\Model\User;
45 use Friendica\Protocol\Activity;
46 use Friendica\Util\Crypto;
47 use Friendica\Util\DateTimeFormat;
48 use Friendica\Util\Network;
49 use Friendica\Util\Strings;
50 use Friendica\Util\XML;
52 function dfrn_confirm_post(App $a, $handsfree = null)
55 if (is_array($handsfree)) {
57 * We were called directly from dfrn_request due to automatic friend acceptance.
58 * Any $_POST parameters we may require are supplied in the $handsfree array.
61 $node = $handsfree['node'];
62 $a->interactive = false; // notice() becomes a no-op since nobody is there to see it
63 } elseif ($a->argc > 1) {
68 * Main entry point. Scenario 1. Our user received a friend request notification (perhaps
69 * from another site) and clicked 'Approve'.
70 * $POST['source_url'] is not set. If it is, it indicates Scenario 2.
72 * We may also have been called directly from dfrn_request ($handsfree != null) due to
73 * this being a page type which supports automatic friend acceptance. That is also Scenario 1
74 * since we are operating on behalf of our registered user to approve a friendship.
76 if (empty($_POST['source_url'])) {
77 $uid = ($handsfree['uid'] ?? 0) ?: local_user();
79 notice(DI::l10n()->t('Permission denied.') . EOL);
83 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
84 if (!DBA::isResult($user)) {
85 notice(DI::l10n()->t('Profile not found.') . EOL);
89 // These data elements may come from either the friend request notification form or $handsfree array.
90 if (is_array($handsfree)) {
91 Logger::log('Confirm in handsfree mode');
92 $dfrn_id = $handsfree['dfrn_id'];
93 $intro_id = $handsfree['intro_id'];
94 $duplex = $handsfree['duplex'];
96 $hidden = intval($handsfree['hidden'] ?? 0);
98 $dfrn_id = Strings::escapeTags(trim($_POST['dfrn_id'] ?? ''));
99 $intro_id = intval($_POST['intro_id'] ?? 0);
100 $duplex = intval($_POST['duplex'] ?? 0);
101 $cid = intval($_POST['contact_id'] ?? 0);
102 $hidden = intval($_POST['hidden'] ?? 0);
106 * Ensure that dfrn_id has precedence when we go to find the contact record.
107 * We only want to search based on contact id if there is no dfrn_id,
108 * e.g. for OStatus network followers.
110 if (strlen($dfrn_id)) {
114 Logger::log('Confirming request for dfrn_id (issued) ' . $dfrn_id);
116 Logger::log('Confirming follower with contact_id: ' . $cid);
120 * The other person will have been issued an ID when they first requested friendship.
121 * Locate their record. At this time, their record will have both pending and blocked set to 1.
122 * There won't be any dfrn_id if this is a network follower, so use the contact_id instead.
127 (`issued-id` != '' AND `issued-id` = '%s')
129 (`id` = %d AND `id` != 0)
134 DBA::escape($dfrn_id),
138 if (!DBA::isResult($r)) {
139 Logger::log('Contact not found in DB.');
140 notice(DI::l10n()->t('Contact not found.') . EOL);
141 notice(DI::l10n()->t('This may occasionally happen if contact was requested by both persons and it has already been approved.') . EOL);
147 $contact_id = $contact['id'];
148 $relation = $contact['rel'];
149 $site_pubkey = $contact['site-pubkey'];
150 $dfrn_confirm = $contact['confirm'];
151 $aes_allow = $contact['aes_allow'];
152 $protocol = $contact['network'];
155 * Generate a key pair for all further communications with this person.
156 * We have a keypair for every contact, and a site key for unknown people.
157 * This provides a means to carry on relationships with other people if
158 * any single key is compromised. It is a robust key. We're much more
159 * worried about key leakage than anybody cracking it.
161 $res = Crypto::newKeypair(4096);
163 $private_key = $res['prvkey'];
164 $public_key = $res['pubkey'];
166 // Save the private key. Send them the public key.
167 $fields = ['prvkey' => $private_key, 'protocol' => Protocol::DFRN];
168 DBA::update('contact', $fields, ['id' => $contact_id]);
173 * Per the DFRN protocol, we will verify both ends by encrypting the dfrn_id with our
174 * site private key (person on the other end can decrypt it with our site public key).
175 * Then encrypt our profile URL with the other person's site public key. They can decrypt
176 * it with their site private key. If the decryption on the other end fails for either
177 * item, it indicates tampering or key failure on at least one site and we will not be
178 * able to provide a secure communication pathway.
180 * If other site is willing to accept full encryption, (aes_allow is 1 AND we have php5.3
181 * or later) then we encrypt the personal public key we send them using AES-256-CBC and a
182 * random key which is encrypted with their site public key.
185 $src_aes_key = openssl_random_pseudo_bytes(64);
188 openssl_private_encrypt($dfrn_id, $result, $user['prvkey']);
190 $params['dfrn_id'] = bin2hex($result);
191 $params['public_key'] = $public_key;
193 $my_url = DI::baseUrl() . '/profile/' . $user['nickname'];
195 openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey);
196 $params['source_url'] = bin2hex($params['source_url']);
198 if ($aes_allow && function_exists('openssl_encrypt')) {
199 openssl_public_encrypt($src_aes_key, $params['aes_key'], $site_pubkey);
200 $params['aes_key'] = bin2hex($params['aes_key']);
201 $params['public_key'] = bin2hex(openssl_encrypt($public_key, 'AES-256-CBC', $src_aes_key));
204 $params['dfrn_version'] = DFRN_PROTOCOL_VERSION;
206 $params['duplex'] = 1;
209 if ($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY) {
213 if ($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
217 Logger::log('Confirm: posting data to ' . $dfrn_confirm . ': ' . print_r($params, true), Logger::DATA);
221 * POST all this stuff to the other site.
222 * Temporarily raise the network timeout to 120 seconds because the default 60
223 * doesn't always give the other side quite enough time to decrypt everything.
227 $res = Network::post($dfrn_confirm, $params, [], 120)->getBody();
229 Logger::log(' Confirm: received data: ' . $res, Logger::DATA);
231 // Now figure out what they responded. Try to be robust if the remote site is
232 // having difficulty and throwing up errors of some kind.
234 $leading_junk = substr($res, 0, strpos($res, '<?xml'));
236 $res = substr($res, strpos($res, '<?xml'));
238 // No XML at all, this exchange is messed up really bad.
239 // We shouldn't proceed, because the xml parser might choke,
240 // and $status is going to be zero, which indicates success.
241 // We can hardly call this a success.
242 notice(DI::l10n()->t('Response from remote site was not understood.') . EOL);
246 if (strlen($leading_junk) && DI::config()->get('system', 'debugging')) {
247 // This might be more common. Mixed error text and some XML.
248 // If we're configured for debugging, show the text. Proceed in either case.
249 notice(DI::l10n()->t('Unexpected response from remote site: ') . EOL . $leading_junk . EOL);
252 if (stristr($res, "<status") === false) {
253 // wrong xml! stop here!
254 Logger::log('Unexpected response posting to ' . $dfrn_confirm);
255 notice(DI::l10n()->t('Unexpected response from remote site: ') . EOL . htmlspecialchars($res) . EOL);
259 $xml = XML::parseString($res);
260 $status = (int) $xml->status;
261 $message = XML::unescape($xml->message); // human readable text of what may have gone wrong.
264 info(DI::l10n()->t("Confirmation completed successfully.") . EOL);
267 // birthday paradox - generate new dfrn-id and fall through.
268 $new_dfrn_id = Strings::getRandomHex();
269 q("UPDATE contact SET `issued-id` = '%s' WHERE `id` = %d AND `uid` = %d",
270 DBA::escape($new_dfrn_id),
276 notice(DI::l10n()->t("Temporary failure. Please wait and try again.") . EOL);
279 notice(DI::l10n()->t("Introduction failed or was revoked.") . EOL);
283 if (strlen($message)) {
284 notice(DI::l10n()->t('Remote site reported: ') . $message . EOL);
287 if (($status == 0) && $intro_id) {
288 $intro = DBA::selectFirst('intro', ['note'], ['id' => $intro_id]);
289 if (DBA::isResult($intro)) {
290 DBA::update('contact', ['reason' => $intro['note']], ['id' => $contact_id]);
293 // Success. Delete the notification.
294 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 $new_relation = Contact::FOLLOWER;
314 if (($relation == Contact::SHARING) || ($duplex)) {
315 $new_relation = Contact::FRIEND;
318 if (($relation == Contact::SHARING) && ($duplex)) {
322 $r = q("UPDATE `contact` SET `rel` = %d,
329 `network` = '%s' WHERE `id` = %d
331 intval($new_relation),
332 DBA::escape(DateTimeFormat::utcNow()),
333 DBA::escape(DateTimeFormat::utcNow()),
336 DBA::escape(Protocol::DFRN),
340 // reload contact info
341 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
343 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact['id']);
345 // Let's send our user to the contact editor in case they want to
346 // do anything special with this new friend.
347 if ($handsfree === null) {
348 DI::baseUrl()->redirect('contact/' . intval($contact_id));
356 * End of Scenario 1. [Local confirmation of remote friend request].
358 * Begin Scenario 2. This is the remote response to the above scenario.
359 * This will take place on the site that originally initiated the friend request.
360 * In the section above where the confirming party makes a POST and
361 * retrieves xml status information, they are communicating with the following code.
363 if (!empty($_POST['source_url'])) {
364 // We are processing an external confirmation to an introduction created by our user.
365 $public_key = $_POST['public_key'] ?? '';
366 $dfrn_id = hex2bin($_POST['dfrn_id'] ?? '');
367 $source_url = hex2bin($_POST['source_url'] ?? '');
368 $aes_key = $_POST['aes_key'] ?? '';
369 $duplex = intval($_POST['duplex'] ?? 0);
370 $page = intval($_POST['page'] ?? 0);
372 $forum = (($page == 1) ? 1 : 0);
373 $prv = (($page == 2) ? 1 : 0);
375 Logger::log('dfrn_confirm: requestee contacted: ' . $node);
377 Logger::log('dfrn_confirm: request: POST=' . print_r($_POST, true), Logger::DATA);
379 // If $aes_key is set, both of these items require unpacking from the hex transport encoding.
381 if (!empty($aes_key)) {
382 $aes_key = hex2bin($aes_key);
383 $public_key = hex2bin($public_key);
386 // Find our user's account
387 $user = DBA::selectFirst('user', [], ['nickname' => $node]);
388 if (!DBA::isResult($user)) {
389 $message = DI::l10n()->t('No user record found for \'%s\' ', $node);
390 System::xmlExit(3, $message); // failure
394 $my_prvkey = $user['prvkey'];
395 $local_uid = $user['uid'];
398 if (!strstr($my_prvkey, 'PRIVATE KEY')) {
399 $message = DI::l10n()->t('Our site encryption key is apparently messed up.');
400 System::xmlExit(3, $message);
405 $decrypted_source_url = "";
406 openssl_private_decrypt($source_url, $decrypted_source_url, $my_prvkey);
409 if (!strlen($decrypted_source_url)) {
410 $message = DI::l10n()->t('Empty site URL was provided or URL could not be decrypted by us.');
411 System::xmlExit(3, $message);
415 $contact = DBA::selectFirst('contact', [], ['url' => $decrypted_source_url, 'uid' => $local_uid]);
416 if (!DBA::isResult($contact)) {
417 if (strstr($decrypted_source_url, 'http:')) {
418 $newurl = str_replace('http:', 'https:', $decrypted_source_url);
420 $newurl = str_replace('https:', 'http:', $decrypted_source_url);
423 $contact = DBA::selectFirst('contact', [], ['url' => $newurl, 'uid' => $local_uid]);
424 if (!DBA::isResult($contact)) {
425 // this is either a bogus confirmation (?) or we deleted the original introduction.
426 $message = DI::l10n()->t('Contact record was not found for you on our site.');
427 System::xmlExit(3, $message);
428 return; // NOTREACHED
432 $relation = $contact['rel'];
434 // Decrypt all this stuff we just received
436 $foreign_pubkey = $contact['site-pubkey'];
437 $dfrn_record = $contact['id'];
439 if (!$foreign_pubkey) {
440 $message = DI::l10n()->t('Site public key not available in contact record for URL %s.', $decrypted_source_url);
441 System::xmlExit(3, $message);
444 $decrypted_dfrn_id = "";
445 openssl_public_decrypt($dfrn_id, $decrypted_dfrn_id, $foreign_pubkey);
447 if (strlen($aes_key)) {
448 $decrypted_aes_key = "";
449 openssl_private_decrypt($aes_key, $decrypted_aes_key, $my_prvkey);
450 $dfrn_pubkey = openssl_decrypt($public_key, 'AES-256-CBC', $decrypted_aes_key);
452 $dfrn_pubkey = $public_key;
455 if (DBA::exists('contact', ['dfrn-id' => $decrypted_dfrn_id])) {
456 $message = DI::l10n()->t('The ID provided by your system is a duplicate on our system. It should work if you try again.');
457 System::xmlExit(1, $message); // Birthday paradox - duplicate dfrn-id
461 $r = q("UPDATE `contact` SET `dfrn-id` = '%s', `pubkey` = '%s' WHERE `id` = %d",
462 DBA::escape($decrypted_dfrn_id),
463 DBA::escape($dfrn_pubkey),
466 if (!DBA::isResult($r)) {
467 $message = DI::l10n()->t('Unable to set your contact credentials on our system.');
468 System::xmlExit(3, $message);
471 // It's possible that the other person also requested friendship.
472 // If it is a duplex relationship, ditch the issued-id if one exists.
475 q("UPDATE `contact` SET `issued-id` = '' WHERE `id` = %d",
480 // We're good but now we have to scrape the profile photo and send notifications.
481 $contact = DBA::selectFirst('contact', ['photo'], ['id' => $dfrn_record]);
482 if (DBA::isResult($contact)) {
483 $photo = $contact['photo'];
485 $photo = DI::baseUrl() . '/images/person-300.jpg';
488 Contact::updateAvatar($photo, $local_uid, $dfrn_record);
490 Logger::log('dfrn_confirm: request - photos imported');
492 $new_relation = Contact::SHARING;
494 if (($relation == Contact::FOLLOWER) || ($duplex)) {
495 $new_relation = Contact::FRIEND;
498 if (($relation == Contact::FOLLOWER) && ($duplex)) {
502 $r = q("UPDATE `contact` SET
511 `network` = '%s' WHERE `id` = %d
513 intval($new_relation),
514 DBA::escape(DateTimeFormat::utcNow()),
515 DBA::escape(DateTimeFormat::utcNow()),
519 DBA::escape(Protocol::DFRN),
522 if (!DBA::isResult($r)) { // indicates schema is messed up or total db failure
523 $message = DI::l10n()->t('Unable to update your contact profile details on our system');
524 System::xmlExit(3, $message);
527 // Otherwise everything seems to have worked and we are almost done. Yay!
528 // Send an email notification
530 Logger::log('dfrn_confirm: request: info updated');
533 $r = q("SELECT `contact`.*, `user`.*
535 LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
536 WHERE `contact`.`id` = %d
540 if (DBA::isResult($r)) {
543 if ($combined['notify-flags'] & Type::CONFIRM) {
544 $mutual = ($new_relation == Contact::FRIEND);
546 'type' => Type::CONFIRM,
547 'notify_flags' => $combined['notify-flags'],
548 'language' => $combined['language'],
549 'to_name' => $combined['username'],
550 'to_email' => $combined['email'],
551 'uid' => $combined['uid'],
552 'link' => DI::baseUrl() . '/contact/' . $dfrn_record,
553 'source_name' => ((strlen(stripslashes($combined['name']))) ? stripslashes($combined['name']) : DI::l10n()->t('[Name Withheld]')),
554 'source_link' => $combined['url'],
555 'source_photo' => $combined['photo'],
556 'verb' => ($mutual ? Activity::FRIEND : Activity::FOLLOW),
562 System::xmlExit(0); // Success
563 return; // NOTREACHED
564 ////////////////////// End of this scenario ///////////////////////////////////////////////
567 // somebody arrived here by mistake or they are fishing. Send them to the homepage.
568 DI::baseUrl()->redirect();