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