]> git.mxchange.org Git - friendica.git/blob - include/security.php
fixed parser error
[friendica.git] / include / security.php
1 <?php
2 /**
3  * @file include/security.php
4  */
5
6 use Friendica\Core\Addon;
7 use Friendica\Core\Config;
8 use Friendica\Core\L10n;
9 use Friendica\Core\PConfig;
10 use Friendica\Core\System;
11 use Friendica\Database\DBM;
12 use Friendica\Model\Group;
13 use Friendica\Util\DateTimeFormat;
14
15 /**
16  * @brief Calculate the hash that is needed for the "Friendica" cookie
17  *
18  * @param array $user Record from "user" table
19  *
20  * @return string Hashed data
21  */
22 function cookie_hash($user)
23 {
24         return(hash("sha256", Config::get("system", "site_prvkey") .
25                         $user["prvkey"] .
26                         $user["password"]));
27 }
28
29 /**
30  * @brief Set the "Friendica" cookie
31  *
32  * @param int $time
33  * @param array $user Record from "user" table
34  */
35 function new_cookie($time, $user = [])
36 {
37         if ($time != 0) {
38                 $time = $time + time();
39         }
40
41         if ($user) {
42                 $value = json_encode(["uid" => $user["uid"],
43                         "hash" => cookie_hash($user),
44                         "ip" => $_SERVER['REMOTE_ADDR']]);
45         } else {
46                 $value = "";
47         }
48
49         setcookie("Friendica", $value, $time, "/", "", (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL), true);
50 }
51
52 /**
53  * @brief Sets the provided user's authenticated session
54  *
55  * @todo Should be moved to Friendica\Core\Session once it's created
56  *
57  * @param type $user_record
58  * @param type $login_initial
59  * @param type $interactive
60  * @param type $login_refresh
61  */
62 function authenticate_success($user_record, $login_initial = false, $interactive = false, $login_refresh = false)
63 {
64         $a = get_app();
65
66         $_SESSION['uid'] = $user_record['uid'];
67         $_SESSION['theme'] = $user_record['theme'];
68         $_SESSION['mobile-theme'] = PConfig::get($user_record['uid'], 'system', 'mobile_theme');
69         $_SESSION['authenticated'] = 1;
70         $_SESSION['page_flags'] = $user_record['page-flags'];
71         $_SESSION['my_url'] = System::baseUrl() . '/profile/' . $user_record['nickname'];
72         $_SESSION['my_address'] = $user_record['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
73         $_SESSION['addr'] = $_SERVER['REMOTE_ADDR'];
74
75         $a->user = $user_record;
76
77         if ($interactive) {
78                 if ($a->user['login_date'] <= NULL_DATE) {
79                         $_SESSION['return_url'] = 'profile_photo/new';
80                         $a->module = 'profile_photo';
81                         info(L10n::t("Welcome ") . $a->user['username'] . EOL);
82                         info(L10n::t('Please upload a profile photo.') . EOL);
83                 } else {
84                         info(L10n::t("Welcome back ") . $a->user['username'] . EOL);
85                 }
86         }
87
88         $member_since = strtotime($a->user['register_date']);
89         if (time() < ($member_since + ( 60 * 60 * 24 * 14))) {
90                 $_SESSION['new_member'] = true;
91         } else {
92                 $_SESSION['new_member'] = false;
93         }
94         if (strlen($a->user['timezone'])) {
95                 date_default_timezone_set($a->user['timezone']);
96                 $a->timezone = $a->user['timezone'];
97         }
98
99         $master_record = $a->user;
100
101         if ((x($_SESSION, 'submanage')) && intval($_SESSION['submanage'])) {
102                 $r = dba::fetch_first("SELECT * FROM `user` WHERE `uid` = ? LIMIT 1",
103                         intval($_SESSION['submanage'])
104                 );
105                 if (DBM::is_result($r)) {
106                         $master_record = $r;
107                 }
108         }
109
110         if ($master_record['parent-uid'] == 0) {
111                 // First add our own entry
112                 $a->identities = [['uid' => $master_record['uid'],
113                                 'username' => $master_record['username'],
114                                 'nickname' => $master_record['nickname']]];
115
116                 // Then add all the children
117                 $r = dba::select('user', ['uid', 'username', 'nickname'],
118                         ['parent-uid' => $master_record['uid'], 'account_removed' => false]);
119                 if (DBM::is_result($r)) {
120                         $a->identities = array_merge($a->identities, dba::inArray($r));
121                 }
122         } else {
123                 // Just ensure that the array is always defined
124                 $a->identities = [];
125
126                 // First entry is our parent
127                 $r = dba::select('user', ['uid', 'username', 'nickname'],
128                         ['uid' => $master_record['parent-uid'], 'account_removed' => false]);
129                 if (DBM::is_result($r)) {
130                         $a->identities = dba::inArray($r);
131                 }
132
133                 // Then add all siblings
134                 $r = dba::select('user', ['uid', 'username', 'nickname'],
135                         ['parent-uid' => $master_record['parent-uid'], 'account_removed' => false]);
136                 if (DBM::is_result($r)) {
137                         $a->identities = array_merge($a->identities, dba::inArray($r));
138                 }
139         }
140
141         $r = dba::p("SELECT `user`.`uid`, `user`.`username`, `user`.`nickname`
142                 FROM `manage`
143                 INNER JOIN `user` ON `manage`.`mid` = `user`.`uid`
144                 WHERE `user`.`account_removed` = 0 AND `manage`.`uid` = ?",
145                 $master_record['uid']
146         );
147         if (DBM::is_result($r)) {
148                 $a->identities = array_merge($a->identities, dba::inArray($r));
149         }
150
151         if ($login_initial) {
152                 logger('auth_identities: ' . print_r($a->identities, true), LOGGER_DEBUG);
153         }
154         if ($login_refresh) {
155                 logger('auth_identities refresh: ' . print_r($a->identities, true), LOGGER_DEBUG);
156         }
157
158         $r = dba::fetch_first("SELECT * FROM `contact` WHERE `uid` = ? AND `self` LIMIT 1", $_SESSION['uid']);
159         if (DBM::is_result($r)) {
160                 $a->contact = $r;
161                 $a->cid = $r['id'];
162                 $_SESSION['cid'] = $a->cid;
163         }
164
165         header('X-Account-Management-Status: active; name="' . $a->user['username'] . '"; id="' . $a->user['nickname'] . '"');
166
167         if ($login_initial || $login_refresh) {
168                 dba::update('user', ['login_date' => DateTimeFormat::utcNow()], ['uid' => $_SESSION['uid']]);
169
170                 // Set the login date for all identities of the user
171                 dba::update('user', ['login_date' => DateTimeFormat::utcNow()],
172                         ['parent-uid' => $master_record['uid'], 'account_removed' => false]);
173         }
174
175         if ($login_initial) {
176                 // If the user specified to remember the authentication, then set a cookie
177                 // that expires after one week (the default is when the browser is closed).
178                 // The cookie will be renewed automatically.
179                 // The week ensures that sessions will expire after some inactivity.
180                 if ($_SESSION['remember']) {
181                         logger('Injecting cookie for remembered user ' . $_SESSION['remember_user']['nickname']);
182                         new_cookie(604800, $user_record);
183                         unset($_SESSION['remember']);
184                 }
185         }
186
187         if ($login_initial) {
188                 Addon::callHooks('logged_in', $a->user);
189
190                 if (($a->module !== 'home') && isset($_SESSION['return_url'])) {
191                         goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
192                 }
193         }
194 }
195
196 function can_write_wall($owner)
197 {
198         static $verified = 0;
199
200         if (!local_user() && !remote_user()) {
201                 return false;
202         }
203
204         $uid = local_user();
205         if ($uid == $owner) {
206                 return true;
207         }
208
209         if (remote_user()) {
210                 // use remembered decision and avoid a DB lookup for each and every display item
211                 // DO NOT use this function if there are going to be multiple owners
212                 // We have a contact-id for an authenticated remote user, this block determines if the contact
213                 // belongs to this page owner, and has the necessary permissions to post content
214
215                 if ($verified === 2) {
216                         return true;
217                 } elseif ($verified === 1) {
218                         return false;
219                 } else {
220                         $cid = 0;
221
222                         if (is_array($_SESSION['remote'])) {
223                                 foreach ($_SESSION['remote'] as $visitor) {
224                                         if ($visitor['uid'] == $owner) {
225                                                 $cid = $visitor['cid'];
226                                                 break;
227                                         }
228                                 }
229                         }
230
231                         if (!$cid) {
232                                 return false;
233                         }
234
235                         $r = q("SELECT `contact`.*, `user`.`page-flags` FROM `contact` INNER JOIN `user` on `user`.`uid` = `contact`.`uid`
236                                 WHERE `contact`.`uid` = %d AND `contact`.`id` = %d AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
237                                 AND `user`.`blockwall` = 0 AND `readonly` = 0  AND ( `contact`.`rel` IN ( %d , %d ) OR `user`.`page-flags` = %d ) LIMIT 1",
238                                 intval($owner),
239                                 intval($cid),
240                                 intval(CONTACT_IS_SHARING),
241                                 intval(CONTACT_IS_FRIEND),
242                                 intval(PAGE_COMMUNITY)
243                         );
244
245                         if (DBM::is_result($r)) {
246                                 $verified = 2;
247                                 return true;
248                         } else {
249                                 $verified = 1;
250                         }
251                 }
252         }
253
254         return false;
255 }
256
257 function permissions_sql($owner_id, $remote_verified = false, $groups = null)
258 {
259         $local_user = local_user();
260         $remote_user = remote_user();
261
262         /**
263          * Construct permissions
264          *
265          * default permissions - anonymous user
266          */
267         $sql = " AND allow_cid = ''
268                          AND allow_gid = ''
269                          AND deny_cid  = ''
270                          AND deny_gid  = ''
271         ";
272
273         /**
274          * Profile owner - everything is visible
275          */
276         if ($local_user && $local_user == $owner_id) {
277                 $sql = '';
278         /**
279          * Authenticated visitor. Unless pre-verified,
280          * check that the contact belongs to this $owner_id
281          * and load the groups the visitor belongs to.
282          * If pre-verified, the caller is expected to have already
283          * done this and passed the groups into this function.
284          */
285         } elseif ($remote_user) {
286                 /*
287                  * Authenticated visitor. Unless pre-verified,
288                  * check that the contact belongs to this $owner_id
289                  * and load the groups the visitor belongs to.
290                  * If pre-verified, the caller is expected to have already
291                  * done this and passed the groups into this function.
292                  */
293
294                 if (!$remote_verified) {
295                         $r = q("SELECT id FROM contact WHERE id = %d AND uid = %d AND blocked = 0 LIMIT 1",
296                                 intval($remote_user),
297                                 intval($owner_id)
298                         );
299                         if (DBM::is_result($r)) {
300                                 $remote_verified = true;
301                                 $groups = Group::getIdsByContactId($remote_user);
302                         }
303                 }
304
305                 if ($remote_verified) {
306                         $gs = '<<>>'; // should be impossible to match
307
308                         if (is_array($groups) && count($groups)) {
309                                 foreach ($groups as $g) {
310                                         $gs .= '|<' . intval($g) . '>';
311                                 }
312                         }
313
314                         $sql = sprintf(
315                                 " AND ( NOT (deny_cid REGEXP '<%d>' OR deny_gid REGEXP '%s')
316                                   AND ( allow_cid REGEXP '<%d>' OR allow_gid REGEXP '%s' OR ( allow_cid = '' AND allow_gid = '') )
317                                   )
318                                 ",
319                                 intval($remote_user),
320                                 dbesc($gs),
321                                 intval($remote_user),
322                                 dbesc($gs)
323                         );
324                 }
325         }
326         return $sql;
327 }
328
329 function item_permissions_sql($owner_id, $remote_verified = false, $groups = null)
330 {
331         $local_user = local_user();
332         $remote_user = remote_user();
333
334         /*
335          * Construct permissions
336          *
337          * default permissions - anonymous user
338          */
339         $sql = " AND `item`.allow_cid = ''
340                          AND `item`.allow_gid = ''
341                          AND `item`.deny_cid  = ''
342                          AND `item`.deny_gid  = ''
343                          AND `item`.private = 0
344         ";
345
346         // Profile owner - everything is visible
347         if ($local_user && ($local_user == $owner_id)) {
348                 $sql = '';
349         } elseif ($remote_user) {
350                 /*
351                  * Authenticated visitor. Unless pre-verified,
352                  * check that the contact belongs to this $owner_id
353                  * and load the groups the visitor belongs to.
354                  * If pre-verified, the caller is expected to have already
355                  * done this and passed the groups into this function.
356                  */
357                 if (!$remote_verified) {
358                         $r = q("SELECT id FROM contact WHERE id = %d AND uid = %d AND blocked = 0 LIMIT 1",
359                                 intval($remote_user),
360                                 intval($owner_id)
361                         );
362                         if (DBM::is_result($r)) {
363                                 $remote_verified = true;
364                                 $groups = Group::getIdsByContactId($remote_user);
365                         }
366                 }
367                 if ($remote_verified) {
368
369                         $gs = '<<>>'; // should be impossible to match
370
371                         if (is_array($groups) && count($groups)) {
372                                 foreach ($groups as $g) {
373                                         $gs .= '|<' . intval($g) . '>';
374                                 }
375                         }
376
377                         $sql = sprintf(
378                                 " AND ( `item`.private = 0 OR ( `item`.private in (1,2) AND `item`.`wall` = 1
379                                   AND ( NOT (`item`.deny_cid REGEXP '<%d>' OR `item`.deny_gid REGEXP '%s')
380                                   AND ( `item`.allow_cid REGEXP '<%d>' OR `item`.allow_gid REGEXP '%s' OR ( `item`.allow_cid = '' AND `item`.allow_gid = '')))))
381                                 ",
382                                 intval($remote_user),
383                                 dbesc($gs),
384                                 intval($remote_user),
385                                 dbesc($gs)
386                         );
387                 }
388         }
389
390         return $sql;
391 }
392
393 /*
394  * Functions used to protect against Cross-Site Request Forgery
395  * The security token has to base on at least one value that an attacker can't know - here it's the session ID and the private key.
396  * In this implementation, a security token is reusable (if the user submits a form, goes back and resubmits the form, maybe with small changes;
397  * or if the security token is used for ajax-calls that happen several times), but only valid for a certain amout of time (3hours).
398  * The "typename" seperates the security tokens of different types of forms. This could be relevant in the following case:
399  *    A security token is used to protekt a link from CSRF (e.g. the "delete this profile"-link).
400  *    If the new page contains by any chance external elements, then the used security token is exposed by the referrer.
401  *    Actually, important actions should not be triggered by Links / GET-Requests at all, but somethimes they still are,
402  *    so this mechanism brings in some damage control (the attacker would be able to forge a request to a form of this type, but not to forms of other types).
403  */
404 function get_form_security_token($typename = '')
405 {
406         $a = get_app();
407
408         $timestamp = time();
409         $sec_hash = hash('whirlpool', $a->user['guid'] . $a->user['prvkey'] . session_id() . $timestamp . $typename);
410
411         return $timestamp . '.' . $sec_hash;
412 }
413
414 function check_form_security_token($typename = '', $formname = 'form_security_token')
415 {
416         $hash = null;
417
418         if (!empty($_REQUEST[$formname])) {
419                 /// @TODO Careful, not secured!
420                 $hash = $_REQUEST[$formname];
421         }
422
423         if (!empty($_SERVER['HTTP_X_CSRF_TOKEN'])) {
424                 /// @TODO Careful, not secured!
425                 $hash = $_SERVER['HTTP_X_CSRF_TOKEN'];
426         }
427
428         if (empty($hash)) {
429                 return false;
430         }
431
432         $max_livetime = 10800; // 3 hours
433
434         $a = get_app();
435
436         $x = explode('.', $hash);
437         if (time() > (IntVal($x[0]) + $max_livetime)) {
438                 return false;
439         }
440
441         $sec_hash = hash('whirlpool', $a->user['guid'] . $a->user['prvkey'] . session_id() . $x[0] . $typename);
442
443         return ($sec_hash == $x[1]);
444 }
445
446 function check_form_security_std_err_msg()
447 {
448         return L10n::t("The form security token was not correct. This probably happened because the form has been opened for too long \x28>3 hours\x29 before submitting it.") . EOL;
449 }
450
451 function check_form_security_token_redirectOnErr($err_redirect, $typename = '', $formname = 'form_security_token')
452 {
453         if (!check_form_security_token($typename, $formname)) {
454                 $a = get_app();
455                 logger('check_form_security_token failed: user ' . $a->user['guid'] . ' - form element ' . $typename);
456                 logger('check_form_security_token failed: _REQUEST data: ' . print_r($_REQUEST, true), LOGGER_DATA);
457                 notice(check_form_security_std_err_msg());
458                 goaway(System::baseUrl() . $err_redirect);
459         }
460 }
461
462 function check_form_security_token_ForbiddenOnErr($typename = '', $formname = 'form_security_token')
463 {
464         if (!check_form_security_token($typename, $formname)) {
465                 $a = get_app();
466                 logger('check_form_security_token failed: user ' . $a->user['guid'] . ' - form element ' . $typename);
467                 logger('check_form_security_token failed: _REQUEST data: ' . print_r($_REQUEST, true), LOGGER_DATA);
468                 header('HTTP/1.1 403 Forbidden');
469                 killme();
470         }
471 }
472
473 /**
474  * @brief Kills the "Friendica" cookie and all session data
475  */
476 function nuke_session()
477 {
478         new_cookie(-3600); // make sure cookie is deleted on browser close, as a security measure
479         session_unset();
480         session_destroy();
481 }