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