Merge pull request #9833 from MrPetovan/task/9719-frio-block-author-more
[friendica.git/.git] / mod / dfrn_confirm.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  * Friendship acceptance for DFRN contacts
21  *
22  * There are two possible entry points and three scenarios.
23  *
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.
26  *
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.
29  *
30  *  @see PDF with dfrn specs: https://github.com/friendica/friendica/blob/stable/spec/dfrn2.pdf
31  *    You also find a graphic which describes the confirmation process at
32  *    https://github.com/friendica/friendica/blob/stable/spec/dfrn2_contact_confirmation.png
33  */
34
35 use Friendica\App;
36 use Friendica\Core\Logger;
37 use Friendica\Core\Protocol;
38 use Friendica\Core\System;
39 use Friendica\Database\DBA;
40 use Friendica\DI;
41 use Friendica\Model\Contact;
42 use Friendica\Model\Group;
43 use Friendica\Model\Notify;
44 use Friendica\Model\Notify\Type;
45 use Friendica\Model\User;
46 use Friendica\Protocol\Activity;
47 use Friendica\Util\Crypto;
48 use Friendica\Util\DateTimeFormat;
49 use Friendica\Util\Strings;
50 use Friendica\Util\XML;
51
52 function dfrn_confirm_post(App $a, $handsfree = null)
53 {
54         $node = null;
55         if (is_array($handsfree)) {
56                 /*
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.
59                  *
60                  */
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) {
64                 $node = $a->argv[1];
65         }
66
67         /*
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.
71          *
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.
75          */
76         if (empty($_POST['source_url'])) {
77                 $uid = ($handsfree['uid'] ?? 0) ?: local_user();
78                 if (!$uid) {
79                         notice(DI::l10n()->t('Permission denied.'));
80                         return;
81                 }
82
83                 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
84                 if (!DBA::isResult($user)) {
85                         notice(DI::l10n()->t('Profile not found.'));
86                         return;
87                 }
88
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'];
95                         $cid      = 0;
96                         $hidden   = intval($handsfree['hidden'] ?? 0);
97                 } else {
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);
103                 }
104
105                 /*
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.
109                  */
110                 if (strlen($dfrn_id)) {
111                         $cid = 0;
112                 }
113
114                 Logger::log('Confirming request for dfrn_id (issued) ' . $dfrn_id);
115                 if ($cid) {
116                         Logger::log('Confirming follower with contact_id: ' . $cid);
117                 }
118
119                 /*
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.
123                  */
124                 $r = q("SELECT *
125                         FROM `contact`
126                         WHERE (
127                                 (`issued-id` != '' AND `issued-id` = '%s')
128                                 OR
129                                 (`id` = %d AND `id` != 0)
130                         )
131                         AND `uid` = %d
132                         AND `duplex` = 0
133                         LIMIT 1",
134                         DBA::escape($dfrn_id),
135                         intval($cid),
136                         intval($uid)
137                 );
138                 if (!DBA::isResult($r)) {
139                         Logger::log('Contact not found in DB.');
140                         notice(DI::l10n()->t('Contact not found.'));
141                         notice(DI::l10n()->t('This may occasionally happen if contact was requested by both persons and it has already been approved.'));
142                         return;
143                 }
144
145                 $contact = $r[0];
146
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'];
153
154                 /*
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.
160                  */
161                 $res = Crypto::newKeypair(4096);
162
163                 $private_key = $res['prvkey'];
164                 $public_key  = $res['pubkey'];
165
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]);
169
170                 $params = [];
171
172                 /*
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.
179                  *
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.
183                  */
184
185                 $src_aes_key = openssl_random_pseudo_bytes(64);
186
187                 $result = '';
188                 openssl_private_encrypt($dfrn_id, $result, $user['prvkey']);
189
190                 $params['dfrn_id'] = bin2hex($result);
191                 $params['public_key'] = $public_key;
192
193                 $my_url = DI::baseUrl() . '/profile/' . $user['nickname'];
194
195                 openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey);
196                 $params['source_url'] = bin2hex($params['source_url']);
197
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));
202                 }
203
204                 $params['dfrn_version'] = DFRN_PROTOCOL_VERSION;
205                 if ($duplex == 1) {
206                         $params['duplex'] = 1;
207                 }
208
209                 if ($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY) {
210                         $params['page'] = 1;
211                 }
212
213                 if ($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
214                         $params['page'] = 2;
215                 }
216
217                 Logger::debug('Confirm: posting data', ['confirm'  => $dfrn_confirm, 'parameter' => $params]);
218
219                 /*
220                  *
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.
224                  *
225                  */
226
227                 $res = DI::httpRequest()->post($dfrn_confirm, $params, [], 120)->getBody();
228
229                 Logger::log(' Confirm: received data: ' . $res, Logger::DATA);
230
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.
233
234                 $leading_junk = substr($res, 0, strpos($res, '<?xml'));
235
236                 $res = substr($res, strpos($res, '<?xml'));
237                 if (!strlen($res)) {
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.'));
243                         return;
244                 }
245
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: ') . $leading_junk);
250                 }
251
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));
256                         return;
257                 }
258
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.
262                 switch ($status) {
263                         case 0:
264                                 info(DI::l10n()->t("Confirmation completed successfully."));
265                                 break;
266                         case 1:
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),
271                                         intval($contact_id),
272                                         intval($uid)
273                                 );
274
275                         case 2:
276                                 notice(DI::l10n()->t("Temporary failure. Please wait and try again."));
277                                 break;
278                         case 3:
279                                 notice(DI::l10n()->t("Introduction failed or was revoked."));
280                                 break;
281                 }
282
283                 if (strlen($message)) {
284                         notice(DI::l10n()->t('Remote site reported: ') . $message);
285                 }
286
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]);
291                         }
292
293                         // Success. Delete the notification.
294                         DBA::delete('intro', ['id' => $intro_id]);
295                 }
296
297                 if ($status != 0) {
298                         return;
299                 }
300
301                 /*
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.
305                  *
306                  * We will also update the contact record with the nature and scope of the relationship.
307                  */
308                 Contact::updateAvatar($contact_id, $contact['photo']);
309
310                 Logger::log('dfrn_confirm: confirm - imported photos');
311
312                 $new_relation = Contact::FOLLOWER;
313
314                 if (($relation == Contact::SHARING) || ($duplex)) {
315                         $new_relation = Contact::FRIEND;
316                 }
317
318                 if (($relation == Contact::SHARING) && ($duplex)) {
319                         $duplex = 0;
320                 }
321
322                 $r = q("UPDATE `contact` SET `rel` = %d,
323                         `name-date` = '%s',
324                         `uri-date` = '%s',
325                         `blocked` = 0,
326                         `pending` = 0,
327                         `duplex` = %d,
328                         `hidden` = %d,
329                         `network` = '%s' WHERE `id` = %d
330                 ",
331                         intval($new_relation),
332                         DBA::escape(DateTimeFormat::utcNow()),
333                         DBA::escape(DateTimeFormat::utcNow()),
334                         intval($duplex),
335                         intval($hidden),
336                         DBA::escape(Protocol::DFRN),
337                         intval($contact_id)
338                 );
339
340                 // reload contact info
341                 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
342
343                 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact['id']);
344
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));
349                 } else {
350                         return;
351                 }
352                 //NOTREACHED
353         }
354
355         /*
356          * End of Scenario 1. [Local confirmation of remote friend request].
357          *
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.
362          */
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);
371
372                 $forum = (($page == 1) ? 1 : 0);
373                 $prv   = (($page == 2) ? 1 : 0);
374
375                 Logger::notice('requestee contacted', ['node' => $node]);
376
377                 Logger::debug('request', ['POST' => $_POST]);
378
379                 // If $aes_key is set, both of these items require unpacking from the hex transport encoding.
380
381                 if (!empty($aes_key)) {
382                         $aes_key = hex2bin($aes_key);
383                         $public_key = hex2bin($public_key);
384                 }
385
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
391                         // NOTREACHED
392                 }
393
394                 $my_prvkey = $user['prvkey'];
395                 $local_uid = $user['uid'];
396
397
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);
401                 }
402
403                 // verify everything
404
405                 $decrypted_source_url = "";
406                 openssl_private_decrypt($source_url, $decrypted_source_url, $my_prvkey);
407
408
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);
412                         // NOTREACHED
413                 }
414
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);
419                         } else {
420                                 $newurl = str_replace('https:', 'http:', $decrypted_source_url);
421                         }
422
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
429                         }
430                 }
431
432                 $relation = $contact['rel'];
433
434                 // Decrypt all this stuff we just received
435
436                 $foreign_pubkey = $contact['site-pubkey'];
437                 $dfrn_record = $contact['id'];
438
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);
442                 }
443
444                 $decrypted_dfrn_id = "";
445                 openssl_public_decrypt($dfrn_id, $decrypted_dfrn_id, $foreign_pubkey);
446
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);
451                 } else {
452                         $dfrn_pubkey = $public_key;
453                 }
454
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
458                         // NOTREACHED
459                 }
460
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),
464                         intval($dfrn_record)
465                 );
466                 if (!DBA::isResult($r)) {
467                         $message = DI::l10n()->t('Unable to set your contact credentials on our system.');
468                         System::xmlExit(3, $message);
469                 }
470
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.
473
474                 if ($duplex) {
475                         q("UPDATE `contact` SET `issued-id` = '' WHERE `id` = %d",
476                                 intval($dfrn_record)
477                         );
478                 }
479
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'];
484                 } else {
485                         $photo = DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO;
486                 }
487
488                 Contact::updateAvatar($dfrn_record, $photo);
489
490                 Logger::log('dfrn_confirm: request - photos imported');
491
492                 $new_relation = Contact::SHARING;
493
494                 if (($relation == Contact::FOLLOWER) || ($duplex)) {
495                         $new_relation = Contact::FRIEND;
496                 }
497
498                 if (($relation == Contact::FOLLOWER) && ($duplex)) {
499                         $duplex = 0;
500                 }
501
502                 $r = q("UPDATE `contact` SET
503                         `rel` = %d,
504                         `name-date` = '%s',
505                         `uri-date` = '%s',
506                         `blocked` = 0,
507                         `pending` = 0,
508                         `duplex` = %d,
509                         `forum` = %d,
510                         `prv` = %d,
511                         `network` = '%s' WHERE `id` = %d
512                 ",
513                         intval($new_relation),
514                         DBA::escape(DateTimeFormat::utcNow()),
515                         DBA::escape(DateTimeFormat::utcNow()),
516                         intval($duplex),
517                         intval($forum),
518                         intval($prv),
519                         DBA::escape(Protocol::DFRN),
520                         intval($dfrn_record)
521                 );
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);
525                 }
526
527                 // Otherwise everything seems to have worked and we are almost done. Yay!
528                 // Send an email notification
529
530                 Logger::log('dfrn_confirm: request: info updated');
531
532                 $combined = null;
533                 $r = q("SELECT `contact`.*, `user`.*
534                         FROM `contact`
535                         LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
536                         WHERE `contact`.`id` = %d
537                         LIMIT 1",
538                         intval($dfrn_record)
539                 );
540                 if (DBA::isResult($r)) {
541                         $combined = $r[0];
542
543                         if ($combined['notify-flags'] & Type::CONFIRM) {
544                                 $mutual = ($new_relation == Contact::FRIEND);
545                                 notification([
546                                         'type'  => Type::CONFIRM,
547                                         'otype' => Notify\ObjectType::INTRO,
548                                         'verb'  => ($mutual ? Activity::FRIEND : Activity::FOLLOW),
549                                         'uid'   => $combined['uid'],
550                                         'cid'   => $combined['id'],
551                                         'link'  => DI::baseUrl() . '/contact/' . $dfrn_record,
552                                 ]);
553                         }
554                 }
555
556                 System::xmlExit(0); // Success
557                 return; // NOTREACHED
558                 ////////////////////// End of this scenario ///////////////////////////////////////////////
559         }
560
561         // somebody arrived here by mistake or they are fishing. Send them to the homepage.
562         DI::baseUrl()->redirect();
563         // NOTREACHED
564 }