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