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