]> git.mxchange.org Git - friendica.git/blob - mod/dfrn_notify.php
Reverting RINO crypto code to php-encryption version 1.2
[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 Friendica\App;
10 use Friendica\Core\Config;
11 use Friendica\Database\DBM;
12 use Friendica\Protocol\DFRN;
13
14 require_once 'include/items.php';
15 require_once 'include/event.php';
16
17 function dfrn_notify_post(App $a) {
18         logger(__function__, LOGGER_TRACE);
19         $dfrn_id      = ((x($_POST,'dfrn_id'))      ? notags(trim($_POST['dfrn_id']))   : '');
20         $dfrn_version = ((x($_POST,'dfrn_version')) ? (float) $_POST['dfrn_version']    : 2.0);
21         $challenge    = ((x($_POST,'challenge'))    ? notags(trim($_POST['challenge'])) : '');
22         $data         = ((x($_POST,'data'))         ? $_POST['data']                    : '');
23         $key          = ((x($_POST,'key'))          ? $_POST['key']                     : '');
24         $rino_remote  = ((x($_POST,'rino'))         ? intval($_POST['rino'])            :  0);
25         $dissolve     = ((x($_POST,'dissolve'))     ? intval($_POST['dissolve'])        :  0);
26         $perm         = ((x($_POST,'perm'))         ? notags(trim($_POST['perm']))      : 'r');
27         $ssl_policy   = ((x($_POST,'ssl_policy'))   ? notags(trim($_POST['ssl_policy'])): 'none');
28         $page         = ((x($_POST,'page'))         ? intval($_POST['page'])            :  0);
29
30         $forum = (($page == 1) ? 1 : 0);
31         $prv   = (($page == 2) ? 1 : 0);
32
33         $writable = (-1);
34         if ($dfrn_version >= 2.21) {
35                 $writable = (($perm === 'rw') ? 1 : 0);
36         }
37
38         $direction = (-1);
39         if (strpos($dfrn_id, ':') == 1) {
40                 $direction = intval(substr($dfrn_id, 0, 1));
41                 $dfrn_id = substr($dfrn_id, 2);
42         }
43
44         $r = q("SELECT * FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s' LIMIT 1",
45                 dbesc($dfrn_id),
46                 dbesc($challenge)
47         );
48         if (! DBM::is_result($r)) {
49                 logger('dfrn_notify: could not match challenge to dfrn_id ' . $dfrn_id . ' challenge=' . $challenge);
50                 xml_status(3, 'Could not match challenge');
51         }
52
53         $r = q("DELETE FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s'",
54                 dbesc($dfrn_id),
55                 dbesc($challenge)
56         );
57
58         // find the local user who owns this relationship.
59
60         $sql_extra = '';
61         switch ($direction) {
62                 case (-1):
63                         $sql_extra = sprintf(" AND ( `issued-id` = '%s' OR `dfrn-id` = '%s' ) ", dbesc($dfrn_id), dbesc($dfrn_id));
64                         break;
65                 case 0:
66                         $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
67                         break;
68                 case 1:
69                         $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
70                         break;
71                 default:
72                         xml_status(3, 'Invalid direction');
73                         break; // NOTREACHED
74         }
75
76         /*
77          * be careful - $importer will contain both the contact information for the contact
78          * sending us the post, and also the user information for the person receiving it.
79          * since they are mixed together, it is easy to get them confused.
80          */
81
82         $r = q("SELECT  `contact`.*, `contact`.`uid` AS `importer_uid`,
83                                         `contact`.`pubkey` AS `cpubkey`,
84                                         `contact`.`prvkey` AS `cprvkey`,
85                                         `contact`.`thumb` AS `thumb`,
86                                         `contact`.`url` as `url`,
87                                         `contact`.`name` as `senderName`,
88                                         `user`.*
89                         FROM `contact`
90                         LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
91                         WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
92                                 AND `user`.`nickname` = '%s' AND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 $sql_extra LIMIT 1",
93                 dbesc($a->argv[1])
94         );
95
96         if (! DBM::is_result($r)) {
97                 logger('dfrn_notify: contact not found for dfrn_id ' . $dfrn_id);
98                 xml_status(3, 'Contact not found');
99                 //NOTREACHED
100         }
101
102         // $importer in this case contains the contact record for the remote contact joined with the user record of our user.
103
104         $importer = $r[0];
105
106         logger("Remote rino version: ".$rino_remote." for ".$importer["url"], LOGGER_DEBUG);
107
108         if ((($writable != (-1)) && ($writable != $importer['writable'])) || ($importer['forum'] != $forum) || ($importer['prv'] != $prv)) {
109                 q("UPDATE `contact` SET `writable` = %d, forum = %d, prv = %d WHERE `id` = %d",
110                         intval(($writable == (-1)) ? $importer['writable'] : $writable),
111                         intval($forum),
112                         intval($prv),
113                         intval($importer['id'])
114                 );
115                 if ($writable != (-1)) {
116                         $importer['writable'] = $writable;
117                 }
118                 $importer['forum'] = $page;
119         }
120
121
122         // if contact's ssl policy changed, update our links
123
124         fix_contact_ssl_policy($importer,$ssl_policy);
125
126         logger('dfrn_notify: received notify from ' . $importer['name'] . ' for ' . $importer['username']);
127         logger('dfrn_notify: data: ' . $data, LOGGER_DATA);
128
129         if ($dissolve == 1) {
130
131                 /*
132                  * Relationship is dissolved permanently
133                  */
134
135                 require_once('include/Contact.php');
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::aes_decrypt(hex2bin($data), $final_key);
183                                 break;
184                         case 2:
185                                 try {
186                                         $data = \Crypto::decrypt(hex2bin($data), $final_key);
187                                 } catch (\InvalidCiphertextException $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 (\CryptoTestFailedException $ex) {
198                                         logger('Cannot safely perform dencryption');
199                                         xml_status(0, 'CryptoTestFailed');
200                                 } catch (\CannotPerformOperationException $ex) {
201                                         logger('Cannot safely perform decryption');
202                                         xml_status(0, 'Cannot safely perform decryption');
203                                 }
204                                 break;
205                         default:
206                                 logger("rino: invalid sent version '$rino_remote'");
207                                 xml_status(0, "Invalid sent version '$rino_remote'");
208                 }
209
210
211                 logger('rino: decrypted data: ' . $data, LOGGER_DATA);
212         }
213
214         $ret = DFRN::import($data, $importer);
215         xml_status($ret, 'Processed');
216
217         // NOTREACHED
218 }
219
220
221 function dfrn_notify_content(App $a) {
222
223         if(x($_GET,'dfrn_id')) {
224
225                 /*
226                  * initial communication from external contact, $direction is their direction.
227                  * If this is a duplex communication, ours will be the opposite.
228                  */
229
230                 $dfrn_id = notags(trim($_GET['dfrn_id']));
231                 $dfrn_version = (float) $_GET['dfrn_version'];
232                 $rino_remote = ((x($_GET,'rino')) ? intval($_GET['rino']) : 0);
233                 $type = "";
234                 $last_update = "";
235
236                 logger('dfrn_notify: new notification dfrn_id=' . $dfrn_id);
237
238                 $direction = (-1);
239                 if(strpos($dfrn_id,':') == 1) {
240                         $direction = intval(substr($dfrn_id,0,1));
241                         $dfrn_id = substr($dfrn_id,2);
242                 }
243
244                 $hash = random_string();
245
246                 $status = 0;
247
248                 $r = q("DELETE FROM `challenge` WHERE `expire` < " . intval(time()));
249
250                 $r = q("INSERT INTO `challenge` ( `challenge`, `dfrn-id`, `expire` , `type`, `last_update` )
251                         VALUES( '%s', '%s', %d, '%s', '%s' ) ",
252                         dbesc($hash),
253                         dbesc($dfrn_id),
254                         intval(time() + 90 ),
255                         dbesc($type),
256                         dbesc($last_update)
257                 );
258
259                 logger('dfrn_notify: challenge=' . $hash, LOGGER_DEBUG);
260
261                 $sql_extra = '';
262                 switch($direction) {
263                         case (-1):
264                                 $sql_extra = sprintf(" AND ( `issued-id` = '%s' OR `dfrn-id` = '%s' ) ", dbesc($dfrn_id), dbesc($dfrn_id));
265                                 $my_id = $dfrn_id;
266                                 break;
267                         case 0:
268                                 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
269                                 $my_id = '1:' . $dfrn_id;
270                                 break;
271                         case 1:
272                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
273                                 $my_id = '0:' . $dfrn_id;
274                                 break;
275                         default:
276                                 $status = 1;
277                                 break; // NOTREACHED
278                 }
279
280                 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`page-flags` FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
281                                 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0 AND `user`.`nickname` = '%s'
282                                 AND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 $sql_extra LIMIT 1",
283                                 dbesc($a->argv[1])
284                 );
285
286                 if (! DBM::is_result($r)) {
287                         $status = 1;
288                 }
289
290                 logger("Remote rino version: ".$rino_remote." for ".$r[0]["url"], LOGGER_DEBUG);
291
292                 $challenge    = '';
293                 $encrypted_id = '';
294                 $id_str       = $my_id . '.' . mt_rand(1000,9999);
295
296                 $prv_key = trim($r[0]['prvkey']);
297                 $pub_key = trim($r[0]['pubkey']);
298                 $dplx    = intval($r[0]['duplex']);
299
300                 if ((($dplx) && (strlen($prv_key))) || ((strlen($prv_key)) && (!(strlen($pub_key))))) {
301                         openssl_private_encrypt($hash, $challenge, $prv_key);
302                         openssl_private_encrypt($id_str, $encrypted_id, $prv_key);
303                 } elseif (strlen($pub_key)) {
304                         openssl_public_encrypt($hash, $challenge, $pub_key);
305                         openssl_public_encrypt($id_str, $encrypted_id, $pub_key);
306                 } else {
307                         /// @TODO these kind of else-blocks are making the code harder to understand
308                         $status = 1;
309                 }
310
311                 $challenge    = bin2hex($challenge);
312                 $encrypted_id = bin2hex($encrypted_id);
313
314
315                 $rino = Config::get('system', 'rino_encrypt');
316                 $rino = intval($rino);
317
318                 logger("Local rino version: ". $rino, LOGGER_DEBUG);
319
320                 // if requested rino is lower than enabled local rino, lower local rino version
321                 // if requested rino is higher than enabled local rino, reply with local rino
322                 if ($rino_remote < $rino) {
323                         $rino = $rino_remote;
324                 }
325
326                 if((($r[0]['rel']) && ($r[0]['rel'] != CONTACT_IS_SHARING)) || ($r[0]['page-flags'] == PAGE_COMMUNITY)) {
327                         $perm = 'rw';
328                 } else {
329                         $perm = 'r';
330                 }
331
332                 header("Content-type: text/xml");
333
334                 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n"
335                         . '<dfrn_notify>' . "\r\n"
336                         . "\t" . '<status>' . $status . '</status>' . "\r\n"
337                         . "\t" . '<dfrn_version>' . DFRN_PROTOCOL_VERSION . '</dfrn_version>' . "\r\n"
338                         . "\t" . '<rino>' . $rino . '</rino>' . "\r\n"
339                         . "\t" . '<perm>' . $perm . '</perm>' . "\r\n"
340                         . "\t" . '<dfrn_id>' . $encrypted_id . '</dfrn_id>' . "\r\n"
341                         . "\t" . '<challenge>' . $challenge . '</challenge>' . "\r\n"
342                         . '</dfrn_notify>' . "\r\n" ;
343
344                 killme();
345         }
346
347 }