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