]> git.mxchange.org Git - friendica.git/blob - mod/dfrn_confirm.php
Merge pull request #7893 from annando/api-attachments
[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\Model\Contact;
28 use Friendica\Model\Group;
29 use Friendica\Model\User;
30 use Friendica\Network\Probe;
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;
37
38 function dfrn_confirm_post(App $a, $handsfree = null)
39 {
40         $node = null;
41         if (is_array($handsfree)) {
42                 /*
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.
45                  *
46                  */
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) {
50                 $node = $a->argv[1];
51         }
52
53         /*
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.
57          *
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.
61          */
62         if (empty($_POST['source_url'])) {
63                 $uid = ($handsfree['uid'] ?? 0) ?: local_user();
64                 if (!$uid) {
65                         notice(L10n::t('Permission denied.') . EOL);
66                         return;
67                 }
68
69                 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
70                 if (!DBA::isResult($user)) {
71                         notice(L10n::t('Profile not found.') . EOL);
72                         return;
73                 }
74
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'];
81                         $cid      = 0;
82                         $hidden   = intval($handsfree['hidden'] ?? 0);
83                 } else {
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);
89                 }
90
91                 /*
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.
95                  */
96                 if (strlen($dfrn_id)) {
97                         $cid = 0;
98                 }
99
100                 Logger::log('Confirming request for dfrn_id (issued) ' . $dfrn_id);
101                 if ($cid) {
102                         Logger::log('Confirming follower with contact_id: ' . $cid);
103                 }
104
105                 /*
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.
109                  */
110                 $r = q("SELECT *
111                         FROM `contact`
112                         WHERE (
113                                 (`issued-id` != '' AND `issued-id` = '%s')
114                                 OR
115                                 (`id` = %d AND `id` != 0)
116                         )
117                         AND `uid` = %d
118                         AND `duplex` = 0
119                         LIMIT 1",
120                         DBA::escape($dfrn_id),
121                         intval($cid),
122                         intval($uid)
123                 );
124                 if (!DBA::isResult($r)) {
125                         Logger::log('Contact not found in DB.');
126                         notice(L10n::t('Contact not found.') . EOL);
127                         notice(L10n::t('This may occasionally happen if contact was requested by both persons and it has already been approved.') . EOL);
128                         return;
129                 }
130
131                 $contact = $r[0];
132
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'];
139
140                 /*
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.
146                  */
147                 $res = Crypto::newKeypair(4096);
148
149                 $private_key = $res['prvkey'];
150                 $public_key  = $res['pubkey'];
151
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]);
155
156                 $params = [];
157
158                 /*
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.
165                  *
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.
169                  */
170
171                 $src_aes_key = openssl_random_pseudo_bytes(64);
172
173                 $result = '';
174                 openssl_private_encrypt($dfrn_id, $result, $user['prvkey']);
175
176                 $params['dfrn_id'] = bin2hex($result);
177                 $params['public_key'] = $public_key;
178
179                 $my_url = System::baseUrl() . '/profile/' . $user['nickname'];
180
181                 openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey);
182                 $params['source_url'] = bin2hex($params['source_url']);
183
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));
188                 }
189
190                 $params['dfrn_version'] = DFRN_PROTOCOL_VERSION;
191                 if ($duplex == 1) {
192                         $params['duplex'] = 1;
193                 }
194
195                 if ($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY) {
196                         $params['page'] = 1;
197                 }
198
199                 if ($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
200                         $params['page'] = 2;
201                 }
202
203                 Logger::log('Confirm: posting data to ' . $dfrn_confirm . ': ' . print_r($params, true), Logger::DATA);
204
205                 /*
206                  *
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.
210                  *
211                  */
212
213                 $res = Network::post($dfrn_confirm, $params, [], 120)->getBody();
214
215                 Logger::log(' Confirm: received data: ' . $res, Logger::DATA);
216
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.
219
220                 $leading_junk = substr($res, 0, strpos($res, '<?xml'));
221
222                 $res = substr($res, strpos($res, '<?xml'));
223                 if (!strlen($res)) {
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(L10n::t('Response from remote site was not understood.') . EOL);
229                         return;
230                 }
231
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(L10n::t('Unexpected response from remote site: ') . EOL . $leading_junk . EOL);
236                 }
237
238                 if (stristr($res, "<status") === false) {
239                         // wrong xml! stop here!
240                         Logger::log('Unexpected response posting to ' . $dfrn_confirm);
241                         notice(L10n::t('Unexpected response from remote site: ') . EOL . htmlspecialchars($res) . EOL);
242                         return;
243                 }
244
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.
248                 switch ($status) {
249                         case 0:
250                                 info(L10n::t("Confirmation completed successfully.") . EOL);
251                                 break;
252                         case 1:
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),
257                                         intval($contact_id),
258                                         intval($uid)
259                                 );
260
261                         case 2:
262                                 notice(L10n::t("Temporary failure. Please wait and try again.") . EOL);
263                                 break;
264                         case 3:
265                                 notice(L10n::t("Introduction failed or was revoked.") . EOL);
266                                 break;
267                 }
268
269                 if (strlen($message)) {
270                         notice(L10n::t('Remote site reported: ') . $message . EOL);
271                 }
272
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]);
277                         }
278
279                         // Success. Delete the notification.
280                         DBA::delete('intro', ['id' => $intro_id]);
281                 }
282
283                 if ($status != 0) {
284                         return;
285                 }
286
287                 /*
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.
291                  *
292                  * We will also update the contact record with the nature and scope of the relationship.
293                  */
294                 Contact::updateAvatar($contact['photo'], $uid, $contact_id);
295
296                 Logger::log('dfrn_confirm: confirm - imported photos');
297
298                 $new_relation = Contact::FOLLOWER;
299
300                 if (($relation == Contact::SHARING) || ($duplex)) {
301                         $new_relation = Contact::FRIEND;
302                 }
303
304                 if (($relation == Contact::SHARING) && ($duplex)) {
305                         $duplex = 0;
306                 }
307
308                 $r = q("UPDATE `contact` SET `rel` = %d,
309                         `name-date` = '%s',
310                         `uri-date` = '%s',
311                         `blocked` = 0,
312                         `pending` = 0,
313                         `duplex` = %d,
314                         `hidden` = %d,
315                         `network` = '%s' WHERE `id` = %d
316                 ",
317                         intval($new_relation),
318                         DBA::escape(DateTimeFormat::utcNow()),
319                         DBA::escape(DateTimeFormat::utcNow()),
320                         intval($duplex),
321                         intval($hidden),
322                         DBA::escape(Protocol::DFRN),
323                         intval($contact_id)
324                 );
325
326                 // reload contact info
327                 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
328
329                 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact['id']);
330
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                         $a->internalRedirect('contact/' . intval($contact_id));
335                 } else {
336                         return;
337                 }
338                 //NOTREACHED
339         }
340
341         /*
342          * End of Scenario 1. [Local confirmation of remote friend request].
343          *
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.
348          */
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);
357
358                 $forum = (($page == 1) ? 1 : 0);
359                 $prv   = (($page == 2) ? 1 : 0);
360
361                 Logger::log('dfrn_confirm: requestee contacted: ' . $node);
362
363                 Logger::log('dfrn_confirm: request: POST=' . print_r($_POST, true), Logger::DATA);
364
365                 // If $aes_key is set, both of these items require unpacking from the hex transport encoding.
366
367                 if (!empty($aes_key)) {
368                         $aes_key = hex2bin($aes_key);
369                         $public_key = hex2bin($public_key);
370                 }
371
372                 // Find our user's account
373                 $user = DBA::selectFirst('user', [], ['nickname' => $node]);
374                 if (!DBA::isResult($user)) {
375                         $message = L10n::t('No user record found for \'%s\' ', $node);
376                         System::xmlExit(3, $message); // failure
377                         // NOTREACHED
378                 }
379
380                 $my_prvkey = $user['prvkey'];
381                 $local_uid = $user['uid'];
382
383
384                 if (!strstr($my_prvkey, 'PRIVATE KEY')) {
385                         $message = L10n::t('Our site encryption key is apparently messed up.');
386                         System::xmlExit(3, $message);
387                 }
388
389                 // verify everything
390
391                 $decrypted_source_url = "";
392                 openssl_private_decrypt($source_url, $decrypted_source_url, $my_prvkey);
393
394
395                 if (!strlen($decrypted_source_url)) {
396                         $message = L10n::t('Empty site URL was provided or URL could not be decrypted by us.');
397                         System::xmlExit(3, $message);
398                         // NOTREACHED
399                 }
400
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);
405                         } else {
406                                 $newurl = str_replace('https:', 'http:', $decrypted_source_url);
407                         }
408
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 = L10n::t('Contact record was not found for you on our site.');
413                                 System::xmlExit(3, $message);
414                                 return; // NOTREACHED
415                         }
416                 }
417
418                 $relation = $contact['rel'];
419
420                 // Decrypt all this stuff we just received
421
422                 $foreign_pubkey = $contact['site-pubkey'];
423                 $dfrn_record = $contact['id'];
424
425                 if (!$foreign_pubkey) {
426                         $message = L10n::t('Site public key not available in contact record for URL %s.', $decrypted_source_url);
427                         System::xmlExit(3, $message);
428                 }
429
430                 $decrypted_dfrn_id = "";
431                 openssl_public_decrypt($dfrn_id, $decrypted_dfrn_id, $foreign_pubkey);
432
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);
437                 } else {
438                         $dfrn_pubkey = $public_key;
439                 }
440
441                 if (DBA::exists('contact', ['dfrn-id' => $decrypted_dfrn_id])) {
442                         $message = 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
444                         // NOTREACHED
445                 }
446
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),
450                         intval($dfrn_record)
451                 );
452                 if (!DBA::isResult($r)) {
453                         $message = L10n::t('Unable to set your contact credentials on our system.');
454                         System::xmlExit(3, $message);
455                 }
456
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.
459
460                 if ($duplex) {
461                         q("UPDATE `contact` SET `issued-id` = '' WHERE `id` = %d",
462                                 intval($dfrn_record)
463                         );
464                 }
465
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'];
470                 } else {
471                         $photo = System::baseUrl() . '/images/person-300.jpg';
472                 }
473
474                 Contact::updateAvatar($photo, $local_uid, $dfrn_record);
475
476                 Logger::log('dfrn_confirm: request - photos imported');
477
478                 $new_relation = Contact::SHARING;
479
480                 if (($relation == Contact::FOLLOWER) || ($duplex)) {
481                         $new_relation = Contact::FRIEND;
482                 }
483
484                 if (($relation == Contact::FOLLOWER) && ($duplex)) {
485                         $duplex = 0;
486                 }
487
488                 $r = q("UPDATE `contact` SET
489                         `rel` = %d,
490                         `name-date` = '%s',
491                         `uri-date` = '%s',
492                         `blocked` = 0,
493                         `pending` = 0,
494                         `duplex` = %d,
495                         `forum` = %d,
496                         `prv` = %d,
497                         `network` = '%s' WHERE `id` = %d
498                 ",
499                         intval($new_relation),
500                         DBA::escape(DateTimeFormat::utcNow()),
501                         DBA::escape(DateTimeFormat::utcNow()),
502                         intval($duplex),
503                         intval($forum),
504                         intval($prv),
505                         DBA::escape(Protocol::DFRN),
506                         intval($dfrn_record)
507                 );
508                 if (!DBA::isResult($r)) {       // indicates schema is messed up or total db failure
509                         $message = L10n::t('Unable to update your contact profile details on our system');
510                         System::xmlExit(3, $message);
511                 }
512
513                 // Otherwise everything seems to have worked and we are almost done. Yay!
514                 // Send an email notification
515
516                 Logger::log('dfrn_confirm: request: info updated');
517
518                 $combined = null;
519                 $r = q("SELECT `contact`.*, `user`.*
520                         FROM `contact`
521                         LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
522                         WHERE `contact`.`id` = %d
523                         LIMIT 1",
524                         intval($dfrn_record)
525                 );
526                 if (DBA::isResult($r)) {
527                         $combined = $r[0];
528
529                         if ($combined['notify-flags'] & NOTIFY_CONFIRM) {
530                                 $mutual = ($new_relation == Contact::FRIEND);
531                                 notification([
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'         => System::baseUrl() . '/contact/' . $dfrn_record,
539                                         'source_name'  => ((strlen(stripslashes($combined['name']))) ? stripslashes($combined['name']) : L10n::t('[Name Withheld]')),
540                                         'source_link'  => $combined['url'],
541                                         'source_photo' => $combined['photo'],
542                                         'verb'         => ($mutual ? Activity::FRIEND : Activity::FOLLOW),
543                                         'otype'        => 'intro'
544                                 ]);
545                         }
546                 }
547
548                 System::xmlExit(0); // Success
549                 return; // NOTREACHED
550                 ////////////////////// End of this scenario ///////////////////////////////////////////////
551         }
552
553         // somebody arrived here by mistake or they are fishing. Send them to the homepage.
554         $a->internalRedirect();
555         // NOTREACHED
556 }