]> git.mxchange.org Git - friendica.git/blob - mod/dfrn_confirm.php
Merge remote-tracking branch 'upstream/develop' into item-notification
[friendica.git] / mod / dfrn_confirm.php
1 <?php
2 /**
3  * @file mod/dfrn_confirm.php
4  * @brief Module: dfrn_confirm
5  * Purpose: Friendship acceptance for DFRN contacts
6  *
7  * There are two possible entry points and three scenarios.
8  *
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.
11  *
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.
14  *
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
18  */
19
20 use Friendica\App;
21 use Friendica\Core\Config;
22 use Friendica\Core\L10n;
23 use Friendica\Core\Logger;
24 use Friendica\Core\Protocol;
25 use Friendica\Core\System;
26 use Friendica\Database\DBA;
27 use Friendica\DI;
28 use Friendica\Model\Contact;
29 use Friendica\Model\Group;
30 use Friendica\Model\User;
31 use Friendica\Network\Probe;
32 use Friendica\Protocol\Activity;
33 use Friendica\Util\Crypto;
34 use Friendica\Util\DateTimeFormat;
35 use Friendica\Util\Network;
36 use Friendica\Util\Strings;
37 use Friendica\Util\XML;
38
39 function dfrn_confirm_post(App $a, $handsfree = null)
40 {
41         $node = null;
42         if (is_array($handsfree)) {
43                 /*
44                  * We were called directly from dfrn_request due to automatic friend acceptance.
45                  * Any $_POST parameters we may require are supplied in the $handsfree array.
46                  *
47                  */
48                 $node = $handsfree['node'];
49                 $a->interactive = false; // notice() becomes a no-op since nobody is there to see it
50         } elseif ($a->argc > 1) {
51                 $node = $a->argv[1];
52         }
53
54         /*
55          * Main entry point. Scenario 1. Our user received a friend request notification (perhaps
56          * from another site) and clicked 'Approve'.
57          * $POST['source_url'] is not set. If it is, it indicates Scenario 2.
58          *
59          * We may also have been called directly from dfrn_request ($handsfree != null) due to
60          * this being a page type which supports automatic friend acceptance. That is also Scenario 1
61          * since we are operating on behalf of our registered user to approve a friendship.
62          */
63         if (empty($_POST['source_url'])) {
64                 $uid = ($handsfree['uid'] ?? 0) ?: local_user();
65                 if (!$uid) {
66                         notice(L10n::t('Permission denied.') . EOL);
67                         return;
68                 }
69
70                 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
71                 if (!DBA::isResult($user)) {
72                         notice(L10n::t('Profile not found.') . EOL);
73                         return;
74                 }
75
76                 // These data elements may come from either the friend request notification form or $handsfree array.
77                 if (is_array($handsfree)) {
78                         Logger::log('Confirm in handsfree mode');
79                         $dfrn_id  = $handsfree['dfrn_id'];
80                         $intro_id = $handsfree['intro_id'];
81                         $duplex   = $handsfree['duplex'];
82                         $cid      = 0;
83                         $hidden   = intval($handsfree['hidden'] ?? 0);
84                 } else {
85                         $dfrn_id  = Strings::escapeTags(trim($_POST['dfrn_id'] ?? ''));
86                         $intro_id = intval($_POST['intro_id']   ?? 0);
87                         $duplex   = intval($_POST['duplex']     ?? 0);
88                         $cid      = intval($_POST['contact_id'] ?? 0);
89                         $hidden   = intval($_POST['hidden']     ?? 0);
90                 }
91
92                 /*
93                  * Ensure that dfrn_id has precedence when we go to find the contact record.
94                  * We only want to search based on contact id if there is no dfrn_id,
95                  * e.g. for OStatus network followers.
96                  */
97                 if (strlen($dfrn_id)) {
98                         $cid = 0;
99                 }
100
101                 Logger::log('Confirming request for dfrn_id (issued) ' . $dfrn_id);
102                 if ($cid) {
103                         Logger::log('Confirming follower with contact_id: ' . $cid);
104                 }
105
106                 /*
107                  * The other person will have been issued an ID when they first requested friendship.
108                  * Locate their record. At this time, their record will have both pending and blocked set to 1.
109                  * There won't be any dfrn_id if this is a network follower, so use the contact_id instead.
110                  */
111                 $r = q("SELECT *
112                         FROM `contact`
113                         WHERE (
114                                 (`issued-id` != '' AND `issued-id` = '%s')
115                                 OR
116                                 (`id` = %d AND `id` != 0)
117                         )
118                         AND `uid` = %d
119                         AND `duplex` = 0
120                         LIMIT 1",
121                         DBA::escape($dfrn_id),
122                         intval($cid),
123                         intval($uid)
124                 );
125                 if (!DBA::isResult($r)) {
126                         Logger::log('Contact not found in DB.');
127                         notice(L10n::t('Contact not found.') . EOL);
128                         notice(L10n::t('This may occasionally happen if contact was requested by both persons and it has already been approved.') . EOL);
129                         return;
130                 }
131
132                 $contact = $r[0];
133
134                 $contact_id   = $contact['id'];
135                 $relation     = $contact['rel'];
136                 $site_pubkey  = $contact['site-pubkey'];
137                 $dfrn_confirm = $contact['confirm'];
138                 $aes_allow    = $contact['aes_allow'];
139                 $protocol     = $contact['network'];
140
141                 /*
142                  * Generate a key pair for all further communications with this person.
143                  * We have a keypair for every contact, and a site key for unknown people.
144                  * This provides a means to carry on relationships with other people if
145                  * any single key is compromised. It is a robust key. We're much more
146                  * worried about key leakage than anybody cracking it.
147                  */
148                 $res = Crypto::newKeypair(4096);
149
150                 $private_key = $res['prvkey'];
151                 $public_key  = $res['pubkey'];
152
153                 // Save the private key. Send them the public key.
154                 $fields = ['prvkey' => $private_key, 'protocol' => Protocol::DFRN];
155                 DBA::update('contact', $fields, ['id' => $contact_id]);
156
157                 $params = [];
158
159                 /*
160                  * Per the DFRN protocol, we will verify both ends by encrypting the dfrn_id with our
161                  * site private key (person on the other end can decrypt it with our site public key).
162                  * Then encrypt our profile URL with the other person's site public key. They can decrypt
163                  * it with their site private key. If the decryption on the other end fails for either
164                  * item, it indicates tampering or key failure on at least one site and we will not be
165                  * able to provide a secure communication pathway.
166                  *
167                  * If other site is willing to accept full encryption, (aes_allow is 1 AND we have php5.3
168                  * or later) then we encrypt the personal public key we send them using AES-256-CBC and a
169                  * random key which is encrypted with their site public key.
170                  */
171
172                 $src_aes_key = openssl_random_pseudo_bytes(64);
173
174                 $result = '';
175                 openssl_private_encrypt($dfrn_id, $result, $user['prvkey']);
176
177                 $params['dfrn_id'] = bin2hex($result);
178                 $params['public_key'] = $public_key;
179
180                 $my_url = DI::baseUrl() . '/profile/' . $user['nickname'];
181
182                 openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey);
183                 $params['source_url'] = bin2hex($params['source_url']);
184
185                 if ($aes_allow && function_exists('openssl_encrypt')) {
186                         openssl_public_encrypt($src_aes_key, $params['aes_key'], $site_pubkey);
187                         $params['aes_key'] = bin2hex($params['aes_key']);
188                         $params['public_key'] = bin2hex(openssl_encrypt($public_key, 'AES-256-CBC', $src_aes_key));
189                 }
190
191                 $params['dfrn_version'] = DFRN_PROTOCOL_VERSION;
192                 if ($duplex == 1) {
193                         $params['duplex'] = 1;
194                 }
195
196                 if ($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY) {
197                         $params['page'] = 1;
198                 }
199
200                 if ($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
201                         $params['page'] = 2;
202                 }
203
204                 Logger::log('Confirm: posting data to ' . $dfrn_confirm . ': ' . print_r($params, true), Logger::DATA);
205
206                 /*
207                  *
208                  * POST all this stuff to the other site.
209                  * Temporarily raise the network timeout to 120 seconds because the default 60
210                  * doesn't always give the other side quite enough time to decrypt everything.
211                  *
212                  */
213
214                 $res = Network::post($dfrn_confirm, $params, [], 120)->getBody();
215
216                 Logger::log(' Confirm: received data: ' . $res, Logger::DATA);
217
218                 // Now figure out what they responded. Try to be robust if the remote site is
219                 // having difficulty and throwing up errors of some kind.
220
221                 $leading_junk = substr($res, 0, strpos($res, '<?xml'));
222
223                 $res = substr($res, strpos($res, '<?xml'));
224                 if (!strlen($res)) {
225                         // No XML at all, this exchange is messed up really bad.
226                         // We shouldn't proceed, because the xml parser might choke,
227                         // and $status is going to be zero, which indicates success.
228                         // We can hardly call this a success.
229                         notice(L10n::t('Response from remote site was not understood.') . EOL);
230                         return;
231                 }
232
233                 if (strlen($leading_junk) && Config::get('system', 'debugging')) {
234                         // This might be more common. Mixed error text and some XML.
235                         // If we're configured for debugging, show the text. Proceed in either case.
236                         notice(L10n::t('Unexpected response from remote site: ') . EOL . $leading_junk . EOL);
237                 }
238
239                 if (stristr($res, "<status") === false) {
240                         // wrong xml! stop here!
241                         Logger::log('Unexpected response posting to ' . $dfrn_confirm);
242                         notice(L10n::t('Unexpected response from remote site: ') . EOL . htmlspecialchars($res) . EOL);
243                         return;
244                 }
245
246                 $xml = XML::parseString($res);
247                 $status = (int) $xml->status;
248                 $message = XML::unescape($xml->message);   // human readable text of what may have gone wrong.
249                 switch ($status) {
250                         case 0:
251                                 info(L10n::t("Confirmation completed successfully.") . EOL);
252                                 break;
253                         case 1:
254                                 // birthday paradox - generate new dfrn-id and fall through.
255                                 $new_dfrn_id = Strings::getRandomHex();
256                                 q("UPDATE contact SET `issued-id` = '%s' WHERE `id` = %d AND `uid` = %d",
257                                         DBA::escape($new_dfrn_id),
258                                         intval($contact_id),
259                                         intval($uid)
260                                 );
261
262                         case 2:
263                                 notice(L10n::t("Temporary failure. Please wait and try again.") . EOL);
264                                 break;
265                         case 3:
266                                 notice(L10n::t("Introduction failed or was revoked.") . EOL);
267                                 break;
268                 }
269
270                 if (strlen($message)) {
271                         notice(L10n::t('Remote site reported: ') . $message . EOL);
272                 }
273
274                 if (($status == 0) && $intro_id) {
275                         $intro = DBA::selectFirst('intro', ['note'], ['id' => $intro_id]);
276                         if (DBA::isResult($intro)) {
277                                 DBA::update('contact', ['reason' => $intro['note']], ['id' => $contact_id]);
278                         }
279
280                         // Success. Delete the notification.
281                         DBA::delete('intro', ['id' => $intro_id]);
282                 }
283
284                 if ($status != 0) {
285                         return;
286                 }
287
288                 /*
289                  * We have now established a relationship with the other site.
290                  * Let's make our own personal copy of their profile photo so we don't have
291                  * to always load it from their site.
292                  *
293                  * We will also update the contact record with the nature and scope of the relationship.
294                  */
295                 Contact::updateAvatar($contact['photo'], $uid, $contact_id);
296
297                 Logger::log('dfrn_confirm: confirm - imported photos');
298
299                 $new_relation = Contact::FOLLOWER;
300
301                 if (($relation == Contact::SHARING) || ($duplex)) {
302                         $new_relation = Contact::FRIEND;
303                 }
304
305                 if (($relation == Contact::SHARING) && ($duplex)) {
306                         $duplex = 0;
307                 }
308
309                 $r = q("UPDATE `contact` SET `rel` = %d,
310                         `name-date` = '%s',
311                         `uri-date` = '%s',
312                         `blocked` = 0,
313                         `pending` = 0,
314                         `duplex` = %d,
315                         `hidden` = %d,
316                         `network` = '%s' WHERE `id` = %d
317                 ",
318                         intval($new_relation),
319                         DBA::escape(DateTimeFormat::utcNow()),
320                         DBA::escape(DateTimeFormat::utcNow()),
321                         intval($duplex),
322                         intval($hidden),
323                         DBA::escape(Protocol::DFRN),
324                         intval($contact_id)
325                 );
326
327                 // reload contact info
328                 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
329
330                 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact['id']);
331
332                 // Let's send our user to the contact editor in case they want to
333                 // do anything special with this new friend.
334                 if ($handsfree === null) {
335                         DI::baseUrl()->redirect('contact/' . intval($contact_id));
336                 } else {
337                         return;
338                 }
339                 //NOTREACHED
340         }
341
342         /*
343          * End of Scenario 1. [Local confirmation of remote friend request].
344          *
345          * Begin Scenario 2. This is the remote response to the above scenario.
346          * This will take place on the site that originally initiated the friend request.
347          * In the section above where the confirming party makes a POST and
348          * retrieves xml status information, they are communicating with the following code.
349          */
350         if (!empty($_POST['source_url'])) {
351                 // We are processing an external confirmation to an introduction created by our user.
352                 $public_key =         $_POST['public_key'] ?? '';
353                 $dfrn_id    = hex2bin($_POST['dfrn_id']    ?? '');
354                 $source_url = hex2bin($_POST['source_url'] ?? '');
355                 $aes_key    =         $_POST['aes_key']    ?? '';
356                 $duplex     =  intval($_POST['duplex']     ?? 0);
357                 $page       =  intval($_POST['page']       ?? 0);
358
359                 $forum = (($page == 1) ? 1 : 0);
360                 $prv   = (($page == 2) ? 1 : 0);
361
362                 Logger::log('dfrn_confirm: requestee contacted: ' . $node);
363
364                 Logger::log('dfrn_confirm: request: POST=' . print_r($_POST, true), Logger::DATA);
365
366                 // If $aes_key is set, both of these items require unpacking from the hex transport encoding.
367
368                 if (!empty($aes_key)) {
369                         $aes_key = hex2bin($aes_key);
370                         $public_key = hex2bin($public_key);
371                 }
372
373                 // Find our user's account
374                 $user = DBA::selectFirst('user', [], ['nickname' => $node]);
375                 if (!DBA::isResult($user)) {
376                         $message = L10n::t('No user record found for \'%s\' ', $node);
377                         System::xmlExit(3, $message); // failure
378                         // NOTREACHED
379                 }
380
381                 $my_prvkey = $user['prvkey'];
382                 $local_uid = $user['uid'];
383
384
385                 if (!strstr($my_prvkey, 'PRIVATE KEY')) {
386                         $message = L10n::t('Our site encryption key is apparently messed up.');
387                         System::xmlExit(3, $message);
388                 }
389
390                 // verify everything
391
392                 $decrypted_source_url = "";
393                 openssl_private_decrypt($source_url, $decrypted_source_url, $my_prvkey);
394
395
396                 if (!strlen($decrypted_source_url)) {
397                         $message = L10n::t('Empty site URL was provided or URL could not be decrypted by us.');
398                         System::xmlExit(3, $message);
399                         // NOTREACHED
400                 }
401
402                 $contact = DBA::selectFirst('contact', [], ['url' => $decrypted_source_url, 'uid' => $local_uid]);
403                 if (!DBA::isResult($contact)) {
404                         if (strstr($decrypted_source_url, 'http:')) {
405                                 $newurl = str_replace('http:', 'https:', $decrypted_source_url);
406                         } else {
407                                 $newurl = str_replace('https:', 'http:', $decrypted_source_url);
408                         }
409
410                         $contact = DBA::selectFirst('contact', [], ['url' => $newurl, 'uid' => $local_uid]);
411                         if (!DBA::isResult($contact)) {
412                                 // this is either a bogus confirmation (?) or we deleted the original introduction.
413                                 $message = L10n::t('Contact record was not found for you on our site.');
414                                 System::xmlExit(3, $message);
415                                 return; // NOTREACHED
416                         }
417                 }
418
419                 $relation = $contact['rel'];
420
421                 // Decrypt all this stuff we just received
422
423                 $foreign_pubkey = $contact['site-pubkey'];
424                 $dfrn_record = $contact['id'];
425
426                 if (!$foreign_pubkey) {
427                         $message = L10n::t('Site public key not available in contact record for URL %s.', $decrypted_source_url);
428                         System::xmlExit(3, $message);
429                 }
430
431                 $decrypted_dfrn_id = "";
432                 openssl_public_decrypt($dfrn_id, $decrypted_dfrn_id, $foreign_pubkey);
433
434                 if (strlen($aes_key)) {
435                         $decrypted_aes_key = "";
436                         openssl_private_decrypt($aes_key, $decrypted_aes_key, $my_prvkey);
437                         $dfrn_pubkey = openssl_decrypt($public_key, 'AES-256-CBC', $decrypted_aes_key);
438                 } else {
439                         $dfrn_pubkey = $public_key;
440                 }
441
442                 if (DBA::exists('contact', ['dfrn-id' => $decrypted_dfrn_id])) {
443                         $message = L10n::t('The ID provided by your system is a duplicate on our system. It should work if you try again.');
444                         System::xmlExit(1, $message); // Birthday paradox - duplicate dfrn-id
445                         // NOTREACHED
446                 }
447
448                 $r = q("UPDATE `contact` SET `dfrn-id` = '%s', `pubkey` = '%s' WHERE `id` = %d",
449                         DBA::escape($decrypted_dfrn_id),
450                         DBA::escape($dfrn_pubkey),
451                         intval($dfrn_record)
452                 );
453                 if (!DBA::isResult($r)) {
454                         $message = L10n::t('Unable to set your contact credentials on our system.');
455                         System::xmlExit(3, $message);
456                 }
457
458                 // It's possible that the other person also requested friendship.
459                 // If it is a duplex relationship, ditch the issued-id if one exists.
460
461                 if ($duplex) {
462                         q("UPDATE `contact` SET `issued-id` = '' WHERE `id` = %d",
463                                 intval($dfrn_record)
464                         );
465                 }
466
467                 // We're good but now we have to scrape the profile photo and send notifications.
468                 $contact = DBA::selectFirst('contact', ['photo'], ['id' => $dfrn_record]);
469                 if (DBA::isResult($contact)) {
470                         $photo = $contact['photo'];
471                 } else {
472                         $photo = DI::baseUrl() . '/images/person-300.jpg';
473                 }
474
475                 Contact::updateAvatar($photo, $local_uid, $dfrn_record);
476
477                 Logger::log('dfrn_confirm: request - photos imported');
478
479                 $new_relation = Contact::SHARING;
480
481                 if (($relation == Contact::FOLLOWER) || ($duplex)) {
482                         $new_relation = Contact::FRIEND;
483                 }
484
485                 if (($relation == Contact::FOLLOWER) && ($duplex)) {
486                         $duplex = 0;
487                 }
488
489                 $r = q("UPDATE `contact` SET
490                         `rel` = %d,
491                         `name-date` = '%s',
492                         `uri-date` = '%s',
493                         `blocked` = 0,
494                         `pending` = 0,
495                         `duplex` = %d,
496                         `forum` = %d,
497                         `prv` = %d,
498                         `network` = '%s' WHERE `id` = %d
499                 ",
500                         intval($new_relation),
501                         DBA::escape(DateTimeFormat::utcNow()),
502                         DBA::escape(DateTimeFormat::utcNow()),
503                         intval($duplex),
504                         intval($forum),
505                         intval($prv),
506                         DBA::escape(Protocol::DFRN),
507                         intval($dfrn_record)
508                 );
509                 if (!DBA::isResult($r)) {       // indicates schema is messed up or total db failure
510                         $message = L10n::t('Unable to update your contact profile details on our system');
511                         System::xmlExit(3, $message);
512                 }
513
514                 // Otherwise everything seems to have worked and we are almost done. Yay!
515                 // Send an email notification
516
517                 Logger::log('dfrn_confirm: request: info updated');
518
519                 $combined = null;
520                 $r = q("SELECT `contact`.*, `user`.*
521                         FROM `contact`
522                         LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
523                         WHERE `contact`.`id` = %d
524                         LIMIT 1",
525                         intval($dfrn_record)
526                 );
527                 if (DBA::isResult($r)) {
528                         $combined = $r[0];
529
530                         if ($combined['notify-flags'] & NOTIFY_CONFIRM) {
531                                 $mutual = ($new_relation == Contact::FRIEND);
532                                 notification([
533                                         'type'         => NOTIFY_CONFIRM,
534                                         'notify_flags' => $combined['notify-flags'],
535                                         'language'     => $combined['language'],
536                                         'to_name'      => $combined['username'],
537                                         'to_email'     => $combined['email'],
538                                         'uid'          => $combined['uid'],
539                                         'link'         => DI::baseUrl() . '/contact/' . $dfrn_record,
540                                         'source_name'  => ((strlen(stripslashes($combined['name']))) ? stripslashes($combined['name']) : L10n::t('[Name Withheld]')),
541                                         'source_link'  => $combined['url'],
542                                         'source_photo' => $combined['photo'],
543                                         'verb'         => ($mutual ? Activity::FRIEND : Activity::FOLLOW),
544                                         'otype'        => 'intro'
545                                 ]);
546                         }
547                 }
548
549                 System::xmlExit(0); // Success
550                 return; // NOTREACHED
551                 ////////////////////// End of this scenario ///////////////////////////////////////////////
552         }
553
554         // somebody arrived here by mistake or they are fishing. Send them to the homepage.
555         DI::baseUrl()->redirect();
556         // NOTREACHED
557 }