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
9 use Defuse\Crypto\Crypto;
10 use Defuse\Crypto\Exception\EnvironmentIsBrokenException;
11 use Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException;
12 use Defuse\Crypto\Key;
14 use Friendica\Core\Config;
15 use Friendica\Database\DBM;
16 use Friendica\Model\Contact;
17 use Friendica\Protocol\DFRN;
19 require_once 'include/items.php';
20 require_once 'include/event.php';
22 function dfrn_notify_post(App $a) {
23 logger(__function__, LOGGER_TRACE);
24 $dfrn_id = ((x($_POST,'dfrn_id')) ? notags(trim($_POST['dfrn_id'])) : '');
25 $dfrn_version = ((x($_POST,'dfrn_version')) ? (float) $_POST['dfrn_version'] : 2.0);
26 $challenge = ((x($_POST,'challenge')) ? notags(trim($_POST['challenge'])) : '');
27 $data = ((x($_POST,'data')) ? $_POST['data'] : '');
28 $key = ((x($_POST,'key')) ? $_POST['key'] : '');
29 $rino_remote = ((x($_POST,'rino')) ? intval($_POST['rino']) : 0);
30 $dissolve = ((x($_POST,'dissolve')) ? intval($_POST['dissolve']) : 0);
31 $perm = ((x($_POST,'perm')) ? notags(trim($_POST['perm'])) : 'r');
32 $ssl_policy = ((x($_POST,'ssl_policy')) ? notags(trim($_POST['ssl_policy'])): 'none');
33 $page = ((x($_POST,'page')) ? intval($_POST['page']) : 0);
35 $forum = (($page == 1) ? 1 : 0);
36 $prv = (($page == 2) ? 1 : 0);
39 if ($dfrn_version >= 2.21) {
40 $writable = (($perm === 'rw') ? 1 : 0);
44 if (strpos($dfrn_id, ':') == 1) {
45 $direction = intval(substr($dfrn_id, 0, 1));
46 $dfrn_id = substr($dfrn_id, 2);
49 $r = q("SELECT * FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s' LIMIT 1",
53 if (! DBM::is_result($r)) {
54 logger('dfrn_notify: could not match challenge to dfrn_id ' . $dfrn_id . ' challenge=' . $challenge);
55 xml_status(3, 'Could not match challenge');
58 $r = q("DELETE FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s'",
63 // find the local user who owns this relationship.
68 $sql_extra = sprintf(" AND ( `issued-id` = '%s' OR `dfrn-id` = '%s' ) ", dbesc($dfrn_id), dbesc($dfrn_id));
71 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
74 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
77 xml_status(3, 'Invalid direction');
82 * be careful - $importer will contain both the contact information for the contact
83 * sending us the post, and also the user information for the person receiving it.
84 * since they are mixed together, it is easy to get them confused.
87 $r = q("SELECT `contact`.*, `contact`.`uid` AS `importer_uid`,
88 `contact`.`pubkey` AS `cpubkey`,
89 `contact`.`prvkey` AS `cprvkey`,
90 `contact`.`thumb` AS `thumb`,
91 `contact`.`url` as `url`,
92 `contact`.`name` as `senderName`,
95 LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
96 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
97 AND `user`.`nickname` = '%s' AND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 $sql_extra LIMIT 1",
101 if (! DBM::is_result($r)) {
102 logger('dfrn_notify: contact not found for dfrn_id ' . $dfrn_id);
103 xml_status(3, 'Contact not found');
107 // $importer in this case contains the contact record for the remote contact joined with the user record of our user.
111 logger("Remote rino version: ".$rino_remote." for ".$importer["url"], LOGGER_DEBUG);
113 if ((($writable != (-1)) && ($writable != $importer['writable'])) || ($importer['forum'] != $forum) || ($importer['prv'] != $prv)) {
114 q("UPDATE `contact` SET `writable` = %d, forum = %d, prv = %d WHERE `id` = %d",
115 intval(($writable == (-1)) ? $importer['writable'] : $writable),
118 intval($importer['id'])
120 if ($writable != (-1)) {
121 $importer['writable'] = $writable;
123 $importer['forum'] = $page;
127 // if contact's ssl policy changed, update our links
129 fix_contact_ssl_policy($importer,$ssl_policy);
131 logger('dfrn_notify: received notify from ' . $importer['name'] . ' for ' . $importer['username']);
132 logger('dfrn_notify: data: ' . $data, LOGGER_DATA);
134 if ($dissolve == 1) {
135 // Relationship is dissolved permanently
136 Contact::remove($importer['id']);
137 logger('relationship dissolved : ' . $importer['name'] . ' dissolved ' . $importer['username']);
138 xml_status(0, 'relationship dissolved');
141 $rino = Config::get('system', 'rino_encrypt');
142 $rino = intval($rino);
144 logger("Local rino version: " . $rino, LOGGER_DEBUG);
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'");
155 $rawkey = hex2bin(trim($key));
156 logger('rino: md5 raw key: ' . md5($rawkey));
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']);
163 openssl_public_decrypt($rawkey, $final_key, $importer['cpubkey']);
166 if ((($importer['duplex']) && strlen($importer['cpubkey'])) || (! strlen($importer['cprvkey']))) {
167 openssl_public_decrypt($rawkey, $final_key, $importer['cpubkey']);
169 openssl_private_decrypt($rawkey, $final_key, $importer['cprvkey']);
173 #logger('rino: received key : ' . $final_key);
175 switch($rino_remote) {
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
182 $data = DFRN::aesDecrypt(hex2bin($data), $final_key);
186 $data = Crypto::legacyDecrypt(hex2bin($data), $final_key);
187 } catch (WrongKeyOrModifiedCiphertextException $ex) { // VERY IMPORTANT
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.
195 logger('The ciphertext has been tampered with!');
196 xml_status(0, 'The ciphertext has been tampered with!');
197 } catch (EnvironmentIsBrokenException $ex) {
198 logger('Cannot safely perform decryption');
199 xml_status(0, 'Environment is broken');
203 $KeyObject = Key::loadFromAsciiSafeString($final_key);
205 $data = Crypto::decrypt(hex2bin($data), $KeyObject);
206 } catch (WrongKeyOrModifiedCiphertextException $ex) { // VERY IMPORTANT
209 * 1. The ciphertext was modified by the attacker,
210 * 2. The key is wrong, or
211 * 3. $ciphertext is not a valid ciphertext or was corrupted.
214 logger('The ciphertext has been tampered with!');
215 xml_status(0, 'The ciphertext has been tampered with!');
216 } catch (EnvironmentIsBrokenException $ex) {
217 logger('Cannot safely perform decryption');
218 xml_status(0, 'Environment is broken');
222 logger("rino: invalid sent version '$rino_remote'");
223 xml_status(0, "Invalid sent version '$rino_remote'");
227 logger('rino: decrypted data: ' . $data, LOGGER_DATA);
230 $ret = DFRN::import($data, $importer);
231 xml_status($ret, 'Processed');
237 function dfrn_notify_content(App $a) {
239 if(x($_GET,'dfrn_id')) {
242 * initial communication from external contact, $direction is their direction.
243 * If this is a duplex communication, ours will be the opposite.
246 $dfrn_id = notags(trim($_GET['dfrn_id']));
247 $dfrn_version = (float) $_GET['dfrn_version'];
248 $rino_remote = ((x($_GET,'rino')) ? intval($_GET['rino']) : 0);
252 logger('dfrn_notify: new notification dfrn_id=' . $dfrn_id);
255 if(strpos($dfrn_id,':') == 1) {
256 $direction = intval(substr($dfrn_id,0,1));
257 $dfrn_id = substr($dfrn_id,2);
260 $hash = random_string();
264 $r = q("DELETE FROM `challenge` WHERE `expire` < " . intval(time()));
266 $r = q("INSERT INTO `challenge` ( `challenge`, `dfrn-id`, `expire` , `type`, `last_update` )
267 VALUES( '%s', '%s', %d, '%s', '%s' ) ",
270 intval(time() + 90 ),
275 logger('dfrn_notify: challenge=' . $hash, LOGGER_DEBUG);
280 $sql_extra = sprintf(" AND ( `issued-id` = '%s' OR `dfrn-id` = '%s' ) ", dbesc($dfrn_id), dbesc($dfrn_id));
284 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
285 $my_id = '1:' . $dfrn_id;
288 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
289 $my_id = '0:' . $dfrn_id;
296 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`page-flags` FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
297 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0 AND `user`.`nickname` = '%s'
298 AND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 $sql_extra LIMIT 1",
302 if (! DBM::is_result($r)) {
306 logger("Remote rino version: ".$rino_remote." for ".$r[0]["url"], LOGGER_DEBUG);
310 $id_str = $my_id . '.' . mt_rand(1000,9999);
312 $prv_key = trim($r[0]['prvkey']);
313 $pub_key = trim($r[0]['pubkey']);
314 $dplx = intval($r[0]['duplex']);
316 if ((($dplx) && (strlen($prv_key))) || ((strlen($prv_key)) && (!(strlen($pub_key))))) {
317 openssl_private_encrypt($hash, $challenge, $prv_key);
318 openssl_private_encrypt($id_str, $encrypted_id, $prv_key);
319 } elseif (strlen($pub_key)) {
320 openssl_public_encrypt($hash, $challenge, $pub_key);
321 openssl_public_encrypt($id_str, $encrypted_id, $pub_key);
323 /// @TODO these kind of else-blocks are making the code harder to understand
327 $challenge = bin2hex($challenge);
328 $encrypted_id = bin2hex($encrypted_id);
331 $rino = Config::get('system', 'rino_encrypt');
332 $rino = intval($rino);
334 logger("Local rino version: ". $rino, LOGGER_DEBUG);
336 // if requested rino is lower than enabled local rino, lower local rino version
337 // if requested rino is higher than enabled local rino, reply with local rino
338 if ($rino_remote < $rino) {
339 $rino = $rino_remote;
342 if((($r[0]['rel']) && ($r[0]['rel'] != CONTACT_IS_SHARING)) || ($r[0]['page-flags'] == PAGE_COMMUNITY)) {
348 header("Content-type: text/xml");
350 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n"
351 . '<dfrn_notify>' . "\r\n"
352 . "\t" . '<status>' . $status . '</status>' . "\r\n"
353 . "\t" . '<dfrn_version>' . DFRN_PROTOCOL_VERSION . '</dfrn_version>' . "\r\n"
354 . "\t" . '<rino>' . $rino . '</rino>' . "\r\n"
355 . "\t" . '<perm>' . $perm . '</perm>' . "\r\n"
356 . "\t" . '<dfrn_id>' . $encrypted_id . '</dfrn_id>' . "\r\n"
357 . "\t" . '<challenge>' . $challenge . '</challenge>' . "\r\n"
358 . '</dfrn_notify>' . "\r\n" ;