]> git.mxchange.org Git - friendica.git/blob - mod/dfrn_confirm.php
use sha1 keys for friends as well
[friendica.git] / mod / dfrn_confirm.php
1 <?php
2
3 // There are two possible entry points. 
4
5
6 function dfrn_confirm_post(&$a,$handsfree = null) {
7
8         if(is_array($handsfree)) {
9
10                 // called directly from dfrn_request due to automatic friend acceptance
11                 // any $_POST parameters we may require are supplied in the $handsfree array
12
13                 $node = $handsfree['node'];
14                 $a->interactive = false; // notice() becomes a no-op since nobody is there to see it
15
16         }
17         else {
18                 if($a->argc > 1)
19                         $node = $a->argv[1];
20         }
21
22                 // Main entry point. Our user received a friend request notification (perhaps 
23                 // from another site) and clicked 'Approve'. $POST['source_url'] is not set.
24                 // OR we have been called directly from dfrn_request ($handsfree != null) due to 
25                 // this being a page type which supports automatic friend acceptance.
26
27         if(! x($_POST,'source_url')) {
28
29                 $uid = ((is_array($handsfree)) ? $handsfree['uid'] : local_user());
30
31                 if(! $uid) {
32                         notice( t('Permission denied.') . EOL );
33                         return;
34                 }       
35
36                 $user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
37                         intval($uid)
38                 );
39
40                 if(! $user) {
41                         notice( t('Profile not found.') . EOL );
42                         return;
43                 }       
44
45
46                 // These come from either the friend request notification form or $handsfree array.
47
48                 if(is_array($handsfree)) {
49                         $dfrn_id = $handsfree['dfrn_id'];
50                         $intro_id = $handsfree['intro_id'];
51                         $duplex = $handsfree['duplex'];
52                         logger('dfrn_confirm: Confirm in handsfree mode');
53                 }
54                 else {
55                         $dfrn_id  = ((x($_POST,'dfrn_id')) ? notags(trim($_POST['dfrn_id'])) : "");
56                         $intro_id = intval($_POST['intro_id']);
57                         $duplex   = intval($_POST['duplex']);
58                         $cid      = intval($_POST['contact_id']);
59                 }
60
61                 logger('dfrn_confirm: Confirming request for dfrn_id (issued) ' . $dfrn_id);
62
63
64                 // The other person will have been issued an ID when they first requested friendship.
65                 // Locate their record. At this time, their record will have both pending and blocked set to 1. 
66                 // There won't be any dfrn_id if this is a network follower, so use the contact_id instead.
67
68                 $r = q("SELECT * FROM `contact` WHERE ( ( `issued-id` != '' AND `issued-id` = '%s' ) OR ( `id` = %d AND `id` != 0 ) ) AND `uid` = %d LIMIT 1",
69                                 dbesc($dfrn_id),
70                                 intval($cid),
71                                 intval($uid)
72                 );
73
74                 if(! count($r)) {
75                         notice( t('Contact not found.') . EOL );
76                         return;
77                 }
78
79                 $contact = $r[0];
80
81                 $contact_id   = $contact['id'];
82                 $relation     = $contact['rel'];
83                 $site_pubkey  = $contact['site-pubkey'];
84                 $dfrn_confirm = $contact['confirm'];
85                 $aes_allow    = $contact['aes_allow'];
86
87                 $network = ((strlen($contact['issued-id'])) ? 'dfrn' : 'stat');
88
89                 if($network === 'dfrn') {
90
91                         // Generate a key pair for all further communications with this person.
92                         // We have a keypair for every contact, and a site key for unknown people.
93                         // This provides a means to carry on relationships with other people if 
94                         // any single key is compromised. It is a robust key. We're much more 
95                         // worried about key leakage than anybody cracking it.  
96
97                         $res = openssl_pkey_new(array(
98                                 'digest_alg' => 'sha1',
99                                 'private_key_bits' => 4096,
100                                 'encrypt_key' => false )
101                         );
102
103
104                         $private_key = '';
105
106                         openssl_pkey_export($res, $private_key);
107
108                         $pubkey = openssl_pkey_get_details($res);
109                         $public_key = $pubkey["key"];
110
111                         // Save the private key. Send them the public key.
112
113                         $r = q("UPDATE `contact` SET `prvkey` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
114                                 dbesc($private_key),
115                                 intval($contact_id),
116                                 intval($uid) 
117                         );
118
119                         $params = array();
120
121                         // Per the protocol document, we will verify both ends by encrypting the dfrn_id with our 
122                         // site private key (person on the other end can decrypt it with our site public key).
123                         // Then encrypt our profile URL with the other person's site public key. They can decrypt
124                         // it with their site private key. If the decryption on the other end fails for either
125                         // item, it indicates tampering or key failure on at least one site and we will not be 
126                         // able to provide a secure communication pathway.
127
128                         // If other site is willing to accept full encryption, (aes_allow is 1 AND we have php5.3 
129                         // or later) then we encrypt the personal public key we send them using AES-256-CBC and a 
130                         // random key which is encrypted with their site public key.  
131
132                         $src_aes_key = random_string();
133
134                         $result = '';
135                         openssl_private_encrypt($dfrn_id,$result,$user[0]['prvkey']);
136
137                         $params['dfrn_id'] = bin2hex($result);
138                         $params['public_key'] = $public_key;
139
140
141                         $my_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
142
143                         openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey);
144                         $params['source_url'] = bin2hex($params['source_url']);
145
146                         if($aes_allow && function_exists('openssl_encrypt')) {
147                                 openssl_public_encrypt($src_aes_key, $params['aes_key'], $site_pubkey);
148                                 $params['aes_key'] = bin2hex($params['aes_key']);
149                                 $params['public_key'] = bin2hex(openssl_encrypt($public_key,'AES-256-CBC',$src_aes_key));
150                         }
151
152                         $params['dfrn_version'] = DFRN_PROTOCOL_VERSION ;
153                         if($duplex == 1)
154                                 $params['duplex'] = 1;
155
156                         logger('dfrn_confirm: Confirm: posted data: ' . print_r($params,true), LOGGER_DATA);
157
158                         // POST all this stuff to the other site.
159
160                         $res = post_url($dfrn_confirm,$params);
161
162                         logger('dfrn_confirm: Confirm: received data: ' . $res, LOGGER_DATA);
163
164                         // Now figure out what they responded. Try to be robust if the remote site is 
165                         // having difficulty and throwing up errors of some kind. 
166
167                         $leading_junk = substr($res,0,strpos($res,'<?xml'));
168
169                         $res = substr($res,strpos($res,'<?xml'));
170                         if(! strlen($res)) {
171
172                                         // No XML at all, this exchange is messed up really bad.
173                                         // We shouldn't proceed, because the xml parser might choke,
174                                         // and $status is going to be zero, which indicates success.
175                                         // We can hardly call this a success.  
176         
177                                 notice( t('Response from remote site was not understood.') . EOL);
178                                 return;
179                         }
180
181                         if(strlen($leading_junk) && get_config('system','debugging')) {
182         
183                                         // This might be more common. Mixed error text and some XML.
184                                         // If we're configured for debugging, show the text. Proceed in either case.
185
186                                 notice( t('Unexpected response from remote site: ') . EOL . $leading_junk . EOL );
187                         }
188
189                         $xml = simplexml_load_string($res);
190                         $status = (int) $xml->status;
191                         $message = unxmlify($xml->message);   // human readable text of what may have gone wrong.
192                         switch($status) {
193                                 case 0:
194                                         notice( t("Confirmation completed successfully.") . EOL);
195                                         if(strlen($message))
196                                                 notice( t('Remote site reported: ') . $message . EOL);
197                                         break;
198                                 case 1:
199                                         // birthday paradox - generate new dfrn-id and fall through.
200                                         $new_dfrn_id = random_string();
201                                         $r = q("UPDATE contact SET `issued-id` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
202                                                 dbesc($new_dfrn_id),
203                                                 intval($contact_id),
204                                                 intval($uid) 
205                                         );
206
207                                 case 2:
208                                         notice( t("Temporary failure. Please wait and try again.") . EOL);
209                                         if(strlen($message))
210                                                 notice( t('Remote site reported: ') . $message . EOL);
211                                         break;
212
213
214                                 case 3:
215                                         notice( t("Introduction failed or was revoked.") . EOL);
216                                         if(strlen($message))
217                                                 notice( t('Remote site reported: ') . $message . EOL);
218                                         break;
219                                 }
220
221                         if(($status == 0) && ($intro_id)) {
222         
223                                 // Success. Delete the notification.
224         
225                                 $r = q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d LIMIT 1",
226                                         intval($intro_id),
227                                         intval($uid)
228                                 );
229                                 
230                         }
231
232                         if($status != 0) 
233                                 return;
234                 }
235
236                 // We have now established a relationship with the other site.
237                 // Let's make our own personal copy of their profile photo so we don't have
238                 // to always load it from their site.
239
240                 require_once("Photo.php");
241
242                 $photos = import_profile_photo($contact['photo'],$uid,$contact_id);
243                 
244                 logger('dfrn_confirm: confirm - imported photos');
245
246                 if($network === 'dfrn') {
247
248                         $new_relation = REL_VIP;
249                         if(($relation == REL_FAN) || ($duplex))
250                                 $new_relation = REL_BUD;
251
252                         if(($relation == REL_FAN) && ($duplex))
253                                 $duplex = 0;
254
255                         $r = q("UPDATE `contact` SET `photo` = '%s', 
256                                 `thumb` = '%s',
257                                 `micro` = '%s', 
258                                 `rel` = %d, 
259                                 `name-date` = '%s', 
260                                 `uri-date` = '%s', 
261                                 `avatar-date` = '%s', 
262                                 `blocked` = 0, 
263                                 `pending` = 0,
264                                 `duplex` = %d,
265                                 `network` = 'dfrn' WHERE `id` = %d LIMIT 1
266                         ",
267                                 dbesc($photos[0]),
268                                 dbesc($photos[1]),
269                                 dbesc($photos[2]),
270                                 intval($new_relation),
271                                 dbesc(datetime_convert()),
272                                 dbesc(datetime_convert()),
273                                 dbesc(datetime_convert()),
274                                 intval($duplex),
275                                 intval($contact_id)
276                         );
277                 }
278                 else {  
279
280                         $notify = '';
281                         $poll   = '';
282
283                         // $network !== 'dfrn'
284
285                         $arr = lrdd($contact['url']);
286                         if(count($arr)) {
287                                 foreach($arr as $link) {
288                                         if($link['@attributes']['rel'] === 'salmon')
289                                                 $notify = $link['@attributes']['href'];
290                                         if($link['@attributes']['rel'] === NAMESPACE_FEED)
291                                                 $poll = $link['@attributes']['href'];
292                                 }
293                         }
294
295                         $r = q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d LIMIT 1",
296                                 intval($intro_id),
297                                 intval($uid)
298                         );
299
300
301                         $r = q("UPDATE `contact` SET `photo` = '%s', 
302                                 `thumb` = '%s',
303                                 `micro` = '%s', 
304                                 `name-date` = '%s', 
305                                 `uri-date` = '%s', 
306                                 `avatar-date` = '%s', 
307                                 `notify` = '%s',
308                                 `poll` = '%s',
309                                 `blocked` = 0, 
310                                 `pending` = 0,
311                                 `network` = 'stat'
312                                 WHERE `id` = %d LIMIT 1
313                         ",
314                                 dbesc($photos[0]),
315                                 dbesc($photos[1]),
316                                 dbesc($photos[2]),
317                                 dbesc(datetime_convert()),
318                                 dbesc(datetime_convert()),
319                                 dbesc(datetime_convert()),
320                                 dbesc($notify),
321                                 dbesc($poll),
322                                 intval($contact_id)
323                         );                      
324                 }
325
326                 if($r === false)
327                                 notice( t('Unable to set contact photo.') . EOL);
328
329
330                 // Let's send our user to the contact editor in case they want to
331                 // do anything special with this new friend.
332
333                 if($handsfree === null)
334                         goaway($a->get_baseurl() . '/contacts/' . intval($contact_id));
335                 return;  //NOTREACHED
336
337         }
338
339
340
341         // End of first scenario. [Local confirmation of remote friend request].
342
343
344
345         // Begin scenario two. 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(x($_POST,'source_url')) {
351
352                 // We are processing an external confirmation to an introduction created by our user.
353
354                 $public_key = $_POST['public_key'];
355                 $dfrn_id    = hex2bin($_POST['dfrn_id']);
356                 $source_url = hex2bin($_POST['source_url']);
357                 $aes_key    = $_POST['aes_key'];
358                 $duplex     = $_POST['duplex'];
359                 $version_id = (float) $_POST['dfrn_version'];
360         
361                 logger('dfrn_confirm: requestee contacted: ' . $node);
362
363                 logger('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(x($aes_key)) {
368                         $aes_key = hex2bin($aes_key);
369                         $public_key = hex2bin($public_key);
370                 }
371
372                 // Find our user's account
373
374                 $r = q("SELECT * FROM `user` WHERE `nickname` = '%s' LIMIT 1",
375                         dbesc($node));
376
377                 if(! count($r)) {
378                         $message = t('No user record found for ') . '\'' . $node . '\'';
379                         xml_status(3,$message); // failure
380                         // NOTREACHED
381                 }
382
383                 $my_prvkey = $r[0]['prvkey'];
384                 $local_uid = $r[0]['uid'];
385
386
387                 if(! strstr($my_prvkey,'BEGIN RSA PRIVATE KEY')) {
388                         $message = t('Our site encryption key is apparently messed up.');
389                         xml_status(3,$message);
390                 }
391
392                 // verify everything
393
394                 $decrypted_source_url = "";
395                 openssl_private_decrypt($source_url,$decrypted_source_url,$my_prvkey);
396
397
398                 if(! strlen($decrypted_source_url)) {
399                         $message = t('Empty site URL was provided or URL could not be decrypted by us.');
400                         xml_status(3,$message);
401                         // NOTREACHED
402                 }
403
404                 $ret = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
405                         dbesc($decrypted_source_url),
406                         intval($local_uid)
407                 );
408
409                 if(! count($ret)) {
410                         // this is either a bogus confirmation (?) or we deleted the original introduction.
411                         $message = t('Contact record was not found for you on our site.');
412                         xml_status(3,$message);
413                         return; // NOTREACHED 
414                 }
415
416                 $relation = $ret[0]['rel'];
417
418                 // Decrypt all this stuff we just received
419
420                 $foreign_pubkey = $ret[0]['site-pubkey'];
421                 $dfrn_record    = $ret[0]['id'];
422
423                 $decrypted_dfrn_id = "";
424                 openssl_public_decrypt($dfrn_id,$decrypted_dfrn_id,$foreign_pubkey);
425
426                 if(strlen($aes_key)) {
427                         $decrypted_aes_key = "";
428                         openssl_private_decrypt($aes_key,$decrypted_aes_key,$my_prvkey);
429                         $dfrn_pubkey = openssl_decrypt($public_key,'AES-256-CBC',$decrypted_aes_key);
430                 }
431                 else {
432                         $dfrn_pubkey = $public_key;
433                 }
434
435                 $r = q("SELECT * FROM `contact` WHERE `dfrn-id` = '%s' LIMIT 1",
436                         dbesc($decrypted_dfrn_id)
437                 );
438                 if(count($r)) {
439                         $message = t('The ID provided by your system is a duplicate on our system. It should work if you try again.');
440                         xml_status(1,$message); // Birthday paradox - duplicate dfrn-id
441                         // NOTREACHED
442                 }
443
444                 $r = q("UPDATE `contact` SET `dfrn-id` = '%s', `pubkey` = '%s' WHERE `id` = %d LIMIT 1",
445                         dbesc($decrypted_dfrn_id),
446                         dbesc($dfrn_pubkey),
447                         intval($dfrn_record)
448                 );
449                 if(! count($r)) {
450                         $message = t('Unable to set your contact credentials on our system.');
451                         xml_status(3,$message);
452                 }
453
454                 // We're good but now we have to scrape the profile photo and send notifications.
455
456
457
458                 $r = q("SELECT `photo` FROM `contact` WHERE `id` = %d LIMIT 1",
459                         intval($dfrn_record));
460
461                 if(count($r))
462                         $photo = $r[0]['photo'];
463                 else
464                         $photo = $a->get_baseurl() . '/images/default-profile.jpg';
465                                 
466                 require_once("Photo.php");
467
468                 $photos = import_profile_photo($photo,$local_uid,$dfrn_record);
469
470                 logger('dfrn_confirm: request - photos imported');
471
472                 $new_relation = REL_FAN;
473                 if(($relation == REL_VIP) || ($duplex))
474                         $new_relation = REL_BUD;
475
476                 if(($relation == REL_VIP) && ($duplex))
477                         $duplex = 0;
478
479                 $r = q("UPDATE `contact` SET 
480                         `photo` = '%s', 
481                         `thumb` = '%s', 
482                         `micro` = '%s',
483                         `rel` = %d, 
484                         `name-date` = '%s', 
485                         `uri-date` = '%s', 
486                         `avatar-date` = '%s', 
487                         `blocked` = 0, 
488                         `pending` = 0,
489                         `duplex` = %d, 
490                         `network` = 'dfrn' WHERE `id` = %d LIMIT 1
491                 ",
492                         dbesc($photos[0]),
493                         dbesc($photos[1]),
494                         dbesc($photos[2]),
495                         intval($new_relation),
496                         dbesc(datetime_convert()),
497                         dbesc(datetime_convert()),
498                         dbesc(datetime_convert()),
499                         intval($duplex),
500                         intval($dfrn_record)
501                 );
502                 if($r === false) {    // indicates schema is messed up or total db failure
503                         $message = t('Unable to update your contact profile details on our system');
504                         xml_status(3,$message);
505                 }
506
507                 // Otherwise everything seems to have worked and we are almost done. Yay!
508                 // Send an email notification
509
510                 logger('dfrn_confirm: request: info updated');
511
512                 $r = q("SELECT * FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
513                         WHERE `contact`.`id` = %d LIMIT 1",
514                         intval($dfrn_record)
515                 );
516                 if((count($r)) && ($r[0]['notify-flags'] & NOTIFY_CONFIRM)) {
517
518                         $tpl = (($new_relation == REL_BUD) 
519                                 ? load_view_file('view/friend_complete_eml.tpl')
520                                 : load_view_file('view/intro_complete_eml.tpl'));
521                 
522                         $email_tpl = replace_macros($tpl, array(
523                                 '$sitename' => $a->config['sitename'],
524                                 '$siteurl' =>  $a->get_baseurl(),
525                                 '$username' => $r[0]['username'],
526                                 '$email' => $r[0]['email'],
527                                 '$fn' => $r[0]['name'],
528                                 '$dfrn_url' => $r[0]['url'],
529                                 '$uid' => $newuid )
530                         );
531         
532                         $res = mail($r[0]['email'], t("Connection accepted at ") . $a->config['sitename'],
533                                 $email_tpl, 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] );
534                         if(!$res) {
535                                 // pointless throwing an error here and confusing the person at the other end of the wire.
536                         }
537                 }
538                 xml_status(0); // Success
539                 return; // NOTREACHED
540
541                         ////////////////////// End of this scenario ///////////////////////////////////////////////
542         }
543
544         // somebody arrived here by mistake or they are fishing. Send them to the homepage.
545
546         goaway($a->get_baseurl());
547         // NOTREACHED
548
549 }