]> git.mxchange.org Git - friendica.git/blob - mod/dfrn_notify.php
Add RINO version 3 encrypt/decrypt
[friendica.git] / mod / dfrn_notify.php
1 <?php
2
3 /**
4  * @file mod/dfrn_notify.php
5  * @brief The dfrn notify endpoint
6  * @see PDF with dfrn specs: https://github.com/friendica/friendica/blob/master/spec/dfrn2.pdf
7  */
8
9 use Defuse\Crypto\Crypto;
10 use Defuse\Crypto\Exception\EnvironmentIsBrokenException;
11 use Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException;
12 use Defuse\Crypto\Key;
13 use Friendica\App;
14 use Friendica\Core\Config;
15 use Friendica\Database\DBM;
16 use Friendica\Model\Contact;
17 use Friendica\Protocol\DFRN;
18
19 require_once 'include/items.php';
20 require_once 'include/event.php';
21
22 function dfrn_notify_post(App $a) {
23         logger(__function__, LOGGER_TRACE);
24         $dfrn_id      = ((x($_POST,'dfrn_id'))      ? notags(trim($_POST['dfrn_id']))   : '');
25         $dfrn_version = ((x($_POST,'dfrn_version')) ? (float) $_POST['dfrn_version']    : 2.0);
26         $challenge    = ((x($_POST,'challenge'))    ? notags(trim($_POST['challenge'])) : '');
27         $data         = ((x($_POST,'data'))         ? $_POST['data']                    : '');
28         $key          = ((x($_POST,'key'))          ? $_POST['key']                     : '');
29         $rino_remote  = ((x($_POST,'rino'))         ? intval($_POST['rino'])            :  0);
30         $dissolve     = ((x($_POST,'dissolve'))     ? intval($_POST['dissolve'])        :  0);
31         $perm         = ((x($_POST,'perm'))         ? notags(trim($_POST['perm']))      : 'r');
32         $ssl_policy   = ((x($_POST,'ssl_policy'))   ? notags(trim($_POST['ssl_policy'])): 'none');
33         $page         = ((x($_POST,'page'))         ? intval($_POST['page'])            :  0);
34
35         $forum = (($page == 1) ? 1 : 0);
36         $prv   = (($page == 2) ? 1 : 0);
37
38         $writable = (-1);
39         if ($dfrn_version >= 2.21) {
40                 $writable = (($perm === 'rw') ? 1 : 0);
41         }
42
43         $direction = (-1);
44         if (strpos($dfrn_id, ':') == 1) {
45                 $direction = intval(substr($dfrn_id, 0, 1));
46                 $dfrn_id = substr($dfrn_id, 2);
47         }
48
49         $r = q("SELECT * FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s' LIMIT 1",
50                 dbesc($dfrn_id),
51                 dbesc($challenge)
52         );
53         if (! DBM::is_result($r)) {
54                 logger('dfrn_notify: could not match challenge to dfrn_id ' . $dfrn_id . ' challenge=' . $challenge);
55                 xml_status(3, 'Could not match challenge');
56         }
57
58         $r = q("DELETE FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s'",
59                 dbesc($dfrn_id),
60                 dbesc($challenge)
61         );
62
63         // find the local user who owns this relationship.
64
65         $sql_extra = '';
66         switch ($direction) {
67                 case (-1):
68                         $sql_extra = sprintf(" AND ( `issued-id` = '%s' OR `dfrn-id` = '%s' ) ", dbesc($dfrn_id), dbesc($dfrn_id));
69                         break;
70                 case 0:
71                         $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
72                         break;
73                 case 1:
74                         $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
75                         break;
76                 default:
77                         xml_status(3, 'Invalid direction');
78                         break; // NOTREACHED
79         }
80
81         /*
82          * be careful - $importer will contain both the contact information for the contact
83          * sending us the post, and also the user information for the person receiving it.
84          * since they are mixed together, it is easy to get them confused.
85          */
86
87         $r = q("SELECT  `contact`.*, `contact`.`uid` AS `importer_uid`,
88                                         `contact`.`pubkey` AS `cpubkey`,
89                                         `contact`.`prvkey` AS `cprvkey`,
90                                         `contact`.`thumb` AS `thumb`,
91                                         `contact`.`url` as `url`,
92                                         `contact`.`name` as `senderName`,
93                                         `user`.*
94                         FROM `contact`
95                         LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
96                         WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
97                                 AND `user`.`nickname` = '%s' AND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 $sql_extra LIMIT 1",
98                 dbesc($a->argv[1])
99         );
100
101         if (! DBM::is_result($r)) {
102                 logger('dfrn_notify: contact not found for dfrn_id ' . $dfrn_id);
103                 xml_status(3, 'Contact not found');
104                 //NOTREACHED
105         }
106
107         // $importer in this case contains the contact record for the remote contact joined with the user record of our user.
108
109         $importer = $r[0];
110
111         logger("Remote rino version: ".$rino_remote." for ".$importer["url"], LOGGER_DEBUG);
112
113         if ((($writable != (-1)) && ($writable != $importer['writable'])) || ($importer['forum'] != $forum) || ($importer['prv'] != $prv)) {
114                 q("UPDATE `contact` SET `writable` = %d, forum = %d, prv = %d WHERE `id` = %d",
115                         intval(($writable == (-1)) ? $importer['writable'] : $writable),
116                         intval($forum),
117                         intval($prv),
118                         intval($importer['id'])
119                 );
120                 if ($writable != (-1)) {
121                         $importer['writable'] = $writable;
122                 }
123                 $importer['forum'] = $page;
124         }
125
126
127         // if contact's ssl policy changed, update our links
128
129         fix_contact_ssl_policy($importer,$ssl_policy);
130
131         logger('dfrn_notify: received notify from ' . $importer['name'] . ' for ' . $importer['username']);
132         logger('dfrn_notify: data: ' . $data, LOGGER_DATA);
133
134         if ($dissolve == 1) {
135                 // Relationship is dissolved permanently
136                 Contact::remove($importer['id']);
137                 logger('relationship dissolved : ' . $importer['name'] . ' dissolved ' . $importer['username']);
138                 xml_status(0, 'relationship dissolved');
139         }
140
141         $rino = Config::get('system', 'rino_encrypt');
142         $rino = intval($rino);
143
144         logger("Local rino version: " .  $rino, LOGGER_DEBUG);
145
146         if (strlen($key)) {
147
148                 // if local rino is lower than remote rino, abort: should not happen!
149                 // but only for $remote_rino > 1, because old code did't send rino version
150                 if ($rino_remote_version > 1 && $rino < $rino_remote) {
151                         logger("rino version '$rino_remote' is lower than supported '$rino'");
152                         xml_status(0, "rino version '$rino_remote' is lower than supported '$rino'");
153                 }
154
155                 $rawkey = hex2bin(trim($key));
156                 logger('rino: md5 raw key: ' . md5($rawkey));
157                 $final_key = '';
158
159                 if ($dfrn_version >= 2.1) {
160                         if ((($importer['duplex']) && strlen($importer['cprvkey'])) || (! strlen($importer['cpubkey']))) {
161                                 openssl_private_decrypt($rawkey, $final_key, $importer['cprvkey']);
162                         } else {
163                                 openssl_public_decrypt($rawkey, $final_key, $importer['cpubkey']);
164                         }
165                 } else {
166                         if ((($importer['duplex']) && strlen($importer['cpubkey'])) || (! strlen($importer['cprvkey']))) {
167                                 openssl_public_decrypt($rawkey, $final_key, $importer['cpubkey']);
168                         } else {
169                                 openssl_private_decrypt($rawkey, $final_key, $importer['cprvkey']);
170                         }
171                 }
172
173                 #logger('rino: received key : ' . $final_key);
174
175                 switch($rino_remote) {
176                         case 0:
177                         case 1:
178                                 /*
179                                  *we got a key. old code send only the key, without RINO version.
180                                  * we assume RINO 1 if key and no RINO version
181                                  */
182                                 $data = DFRN::aesDecrypt(hex2bin($data), $final_key);
183                                 break;
184                         case 2:
185                                 try {
186                                         $data = Crypto::legacyDecrypt(hex2bin($data), $final_key);
187                                 } catch (WrongKeyOrModifiedCiphertextException $ex) { // VERY IMPORTANT
188                                         /*
189                                          * Either:
190                                          *   1. The ciphertext was modified by the attacker,
191                                          *   2. The key is wrong, or
192                                          *   3. $ciphertext is not a valid ciphertext or was corrupted.
193                                          * Assume the worst.
194                                          */
195                                         logger('The ciphertext has been tampered with!');
196                                         xml_status(0, 'The ciphertext has been tampered with!');
197                                 } catch (EnvironmentIsBrokenException $ex) {
198                                         logger('Cannot safely perform decryption');
199                                         xml_status(0, 'Environment is broken');
200                                 }
201                                 break;
202                         case 3:
203                                 $KeyObject = Key::loadFromAsciiSafeString($final_key);
204                                 try {
205                                         $data = Crypto::decrypt(hex2bin($data), $KeyObject);
206                                 } catch (WrongKeyOrModifiedCiphertextException $ex) { // VERY IMPORTANT
207                                         /*
208                                          * Either:
209                                          *   1. The ciphertext was modified by the attacker,
210                                          *   2. The key is wrong, or
211                                          *   3. $ciphertext is not a valid ciphertext or was corrupted.
212                                          * Assume the worst.
213                                          */
214                                         logger('The ciphertext has been tampered with!');
215                                         xml_status(0, 'The ciphertext has been tampered with!');
216                                 } catch (EnvironmentIsBrokenException $ex) {
217                                         logger('Cannot safely perform decryption');
218                                         xml_status(0, 'Environment is broken');
219                                 }
220                                 break;
221                         default:
222                                 logger("rino: invalid sent version '$rino_remote'");
223                                 xml_status(0, "Invalid sent version '$rino_remote'");
224                 }
225
226
227                 logger('rino: decrypted data: ' . $data, LOGGER_DATA);
228         }
229
230         $ret = DFRN::import($data, $importer);
231         xml_status($ret, 'Processed');
232
233         // NOTREACHED
234 }
235
236
237 function dfrn_notify_content(App $a) {
238
239         if(x($_GET,'dfrn_id')) {
240
241                 /*
242                  * initial communication from external contact, $direction is their direction.
243                  * If this is a duplex communication, ours will be the opposite.
244                  */
245
246                 $dfrn_id = notags(trim($_GET['dfrn_id']));
247                 $dfrn_version = (float) $_GET['dfrn_version'];
248                 $rino_remote = ((x($_GET,'rino')) ? intval($_GET['rino']) : 0);
249                 $type = "";
250                 $last_update = "";
251
252                 logger('dfrn_notify: new notification dfrn_id=' . $dfrn_id);
253
254                 $direction = (-1);
255                 if(strpos($dfrn_id,':') == 1) {
256                         $direction = intval(substr($dfrn_id,0,1));
257                         $dfrn_id = substr($dfrn_id,2);
258                 }
259
260                 $hash = random_string();
261
262                 $status = 0;
263
264                 $r = q("DELETE FROM `challenge` WHERE `expire` < " . intval(time()));
265
266                 $r = q("INSERT INTO `challenge` ( `challenge`, `dfrn-id`, `expire` , `type`, `last_update` )
267                         VALUES( '%s', '%s', %d, '%s', '%s' ) ",
268                         dbesc($hash),
269                         dbesc($dfrn_id),
270                         intval(time() + 90 ),
271                         dbesc($type),
272                         dbesc($last_update)
273                 );
274
275                 logger('dfrn_notify: challenge=' . $hash, LOGGER_DEBUG);
276
277                 $sql_extra = '';
278                 switch($direction) {
279                         case (-1):
280                                 $sql_extra = sprintf(" AND ( `issued-id` = '%s' OR `dfrn-id` = '%s' ) ", dbesc($dfrn_id), dbesc($dfrn_id));
281                                 $my_id = $dfrn_id;
282                                 break;
283                         case 0:
284                                 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
285                                 $my_id = '1:' . $dfrn_id;
286                                 break;
287                         case 1:
288                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
289                                 $my_id = '0:' . $dfrn_id;
290                                 break;
291                         default:
292                                 $status = 1;
293                                 break; // NOTREACHED
294                 }
295
296                 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`page-flags` FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
297                                 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0 AND `user`.`nickname` = '%s'
298                                 AND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 $sql_extra LIMIT 1",
299                                 dbesc($a->argv[1])
300                 );
301
302                 if (! DBM::is_result($r)) {
303                         $status = 1;
304                 }
305
306                 logger("Remote rino version: ".$rino_remote." for ".$r[0]["url"], LOGGER_DEBUG);
307
308                 $challenge    = '';
309                 $encrypted_id = '';
310                 $id_str       = $my_id . '.' . mt_rand(1000,9999);
311
312                 $prv_key = trim($r[0]['prvkey']);
313                 $pub_key = trim($r[0]['pubkey']);
314                 $dplx    = intval($r[0]['duplex']);
315
316                 if ((($dplx) && (strlen($prv_key))) || ((strlen($prv_key)) && (!(strlen($pub_key))))) {
317                         openssl_private_encrypt($hash, $challenge, $prv_key);
318                         openssl_private_encrypt($id_str, $encrypted_id, $prv_key);
319                 } elseif (strlen($pub_key)) {
320                         openssl_public_encrypt($hash, $challenge, $pub_key);
321                         openssl_public_encrypt($id_str, $encrypted_id, $pub_key);
322                 } else {
323                         /// @TODO these kind of else-blocks are making the code harder to understand
324                         $status = 1;
325                 }
326
327                 $challenge    = bin2hex($challenge);
328                 $encrypted_id = bin2hex($encrypted_id);
329
330
331                 $rino = Config::get('system', 'rino_encrypt');
332                 $rino = intval($rino);
333
334                 logger("Local rino version: ". $rino, LOGGER_DEBUG);
335
336                 // if requested rino is lower than enabled local rino, lower local rino version
337                 // if requested rino is higher than enabled local rino, reply with local rino
338                 if ($rino_remote < $rino) {
339                         $rino = $rino_remote;
340                 }
341
342                 if((($r[0]['rel']) && ($r[0]['rel'] != CONTACT_IS_SHARING)) || ($r[0]['page-flags'] == PAGE_COMMUNITY)) {
343                         $perm = 'rw';
344                 } else {
345                         $perm = 'r';
346                 }
347
348                 header("Content-type: text/xml");
349
350                 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n"
351                         . '<dfrn_notify>' . "\r\n"
352                         . "\t" . '<status>' . $status . '</status>' . "\r\n"
353                         . "\t" . '<dfrn_version>' . DFRN_PROTOCOL_VERSION . '</dfrn_version>' . "\r\n"
354                         . "\t" . '<rino>' . $rino . '</rino>' . "\r\n"
355                         . "\t" . '<perm>' . $perm . '</perm>' . "\r\n"
356                         . "\t" . '<dfrn_id>' . $encrypted_id . '</dfrn_id>' . "\r\n"
357                         . "\t" . '<challenge>' . $challenge . '</challenge>' . "\r\n"
358                         . '</dfrn_notify>' . "\r\n" ;
359
360                 killme();
361         }
362
363 }