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