]> git.mxchange.org Git - friendica.git/blob - include/security.php
Merge branch 'develop' into item-activities
[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" => defaults($_SERVER, 'REMOTE_ADDR', '0.0.0.0')]);
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'] = defaults($_SERVER, 'REMOTE_ADDR', '0.0.0.0');
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                 $user = dba::selectFirst('user', [], ['uid' => $_SESSION['submanage']]);
103                 if (DBM::is_result($user)) {
104                         $master_record = $user;
105                 }
106         }
107
108         if ($master_record['parent-uid'] == 0) {
109                 // First add our own entry
110                 $a->identities = [['uid' => $master_record['uid'],
111                                 'username' => $master_record['username'],
112                                 'nickname' => $master_record['nickname']]];
113
114                 // Then add all the children
115                 $r = dba::select('user', ['uid', 'username', 'nickname'],
116                         ['parent-uid' => $master_record['uid'], 'account_removed' => false]);
117                 if (DBM::is_result($r)) {
118                         $a->identities = array_merge($a->identities, dba::inArray($r));
119                 }
120         } else {
121                 // Just ensure that the array is always defined
122                 $a->identities = [];
123
124                 // First entry is our parent
125                 $r = dba::select('user', ['uid', 'username', 'nickname'],
126                         ['uid' => $master_record['parent-uid'], 'account_removed' => false]);
127                 if (DBM::is_result($r)) {
128                         $a->identities = dba::inArray($r);
129                 }
130
131                 // Then add all siblings
132                 $r = dba::select('user', ['uid', 'username', 'nickname'],
133                         ['parent-uid' => $master_record['parent-uid'], 'account_removed' => false]);
134                 if (DBM::is_result($r)) {
135                         $a->identities = array_merge($a->identities, dba::inArray($r));
136                 }
137         }
138
139         $r = dba::p("SELECT `user`.`uid`, `user`.`username`, `user`.`nickname`
140                 FROM `manage`
141                 INNER JOIN `user` ON `manage`.`mid` = `user`.`uid`
142                 WHERE `user`.`account_removed` = 0 AND `manage`.`uid` = ?",
143                 $master_record['uid']
144         );
145         if (DBM::is_result($r)) {
146                 $a->identities = array_merge($a->identities, dba::inArray($r));
147         }
148
149         if ($login_initial) {
150                 logger('auth_identities: ' . print_r($a->identities, true), LOGGER_DEBUG);
151         }
152         if ($login_refresh) {
153                 logger('auth_identities refresh: ' . print_r($a->identities, true), LOGGER_DEBUG);
154         }
155
156         $contact = dba::selectFirst('contact', [], ['uid' => $_SESSION['uid'], 'self' => true]);
157         if (DBM::is_result($contact)) {
158                 $a->contact = $contact;
159                 $a->cid = $contact['id'];
160                 $_SESSION['cid'] = $a->cid;
161         }
162
163         header('X-Account-Management-Status: active; name="' . $a->user['username'] . '"; id="' . $a->user['nickname'] . '"');
164
165         if ($login_initial || $login_refresh) {
166                 dba::update('user', ['login_date' => DateTimeFormat::utcNow()], ['uid' => $_SESSION['uid']]);
167
168                 // Set the login date for all identities of the user
169                 dba::update('user', ['login_date' => DateTimeFormat::utcNow()],
170                         ['parent-uid' => $master_record['uid'], 'account_removed' => false]);
171         }
172
173         if ($login_initial) {
174                 // If the user specified to remember the authentication, then set a cookie
175                 // that expires after one week (the default is when the browser is closed).
176                 // The cookie will be renewed automatically.
177                 // The week ensures that sessions will expire after some inactivity.
178                 if ($_SESSION['remember']) {
179                         logger('Injecting cookie for remembered user ' . $_SESSION['remember_user']['nickname']);
180                         new_cookie(604800, $user_record);
181                         unset($_SESSION['remember']);
182                 }
183         }
184
185         if ($login_initial) {
186                 Addon::callHooks('logged_in', $a->user);
187
188                 if (($a->module !== 'home') && isset($_SESSION['return_url'])) {
189                         goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
190                 }
191         }
192 }
193
194 function can_write_wall($owner)
195 {
196         static $verified = 0;
197
198         if (!local_user() && !remote_user()) {
199                 return false;
200         }
201
202         $uid = local_user();
203         if ($uid == $owner) {
204                 return true;
205         }
206
207         if (remote_user()) {
208                 // use remembered decision and avoid a DB lookup for each and every display item
209                 // DO NOT use this function if there are going to be multiple owners
210                 // We have a contact-id for an authenticated remote user, this block determines if the contact
211                 // belongs to this page owner, and has the necessary permissions to post content
212
213                 if ($verified === 2) {
214                         return true;
215                 } elseif ($verified === 1) {
216                         return false;
217                 } else {
218                         $cid = 0;
219
220                         if (is_array($_SESSION['remote'])) {
221                                 foreach ($_SESSION['remote'] as $visitor) {
222                                         if ($visitor['uid'] == $owner) {
223                                                 $cid = $visitor['cid'];
224                                                 break;
225                                         }
226                                 }
227                         }
228
229                         if (!$cid) {
230                                 return false;
231                         }
232
233                         $r = q("SELECT `contact`.*, `user`.`page-flags` FROM `contact` INNER JOIN `user` on `user`.`uid` = `contact`.`uid`
234                                 WHERE `contact`.`uid` = %d AND `contact`.`id` = %d AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
235                                 AND `user`.`blockwall` = 0 AND `readonly` = 0  AND ( `contact`.`rel` IN ( %d , %d ) OR `user`.`page-flags` = %d ) LIMIT 1",
236                                 intval($owner),
237                                 intval($cid),
238                                 intval(CONTACT_IS_SHARING),
239                                 intval(CONTACT_IS_FRIEND),
240                                 intval(PAGE_COMMUNITY)
241                         );
242
243                         if (DBM::is_result($r)) {
244                                 $verified = 2;
245                                 return true;
246                         } else {
247                                 $verified = 1;
248                         }
249                 }
250         }
251
252         return false;
253 }
254
255 /// @TODO $groups should be array
256 function permissions_sql($owner_id, $remote_verified = false, $groups = null)
257 {
258         $local_user = local_user();
259         $remote_user = remote_user();
260
261         /**
262          * Construct permissions
263          *
264          * default permissions - anonymous user
265          */
266         $sql = " AND allow_cid = ''
267                          AND allow_gid = ''
268                          AND deny_cid  = ''
269                          AND deny_gid  = ''
270         ";
271
272         /**
273          * Profile owner - everything is visible
274          */
275         if ($local_user && $local_user == $owner_id) {
276                 $sql = '';
277         /**
278          * Authenticated visitor. Unless pre-verified,
279          * check that the contact belongs to this $owner_id
280          * and load the groups the visitor belongs to.
281          * If pre-verified, the caller is expected to have already
282          * done this and passed the groups into this function.
283          */
284         } elseif ($remote_user) {
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
293                 if (!$remote_verified) {
294                         $r = q("SELECT id FROM contact WHERE id = %d AND uid = %d AND blocked = 0 LIMIT 1",
295                                 intval($remote_user),
296                                 intval($owner_id)
297                         );
298                         if (DBM::is_result($r)) {
299                                 $remote_verified = true;
300                                 $groups = Group::getIdsByContactId($remote_user);
301                         }
302                 }
303
304                 if ($remote_verified) {
305                         $gs = '<<>>'; // should be impossible to match
306
307                         if (is_array($groups)) {
308                                 foreach ($groups as $g) {
309                                         $gs .= '|<' . intval($g) . '>';
310                                 }
311                         }
312
313                         $sql = sprintf(
314                                 " AND ( NOT (deny_cid REGEXP '<%d>' OR deny_gid REGEXP '%s')
315                                   AND ( allow_cid REGEXP '<%d>' OR allow_gid REGEXP '%s' OR ( allow_cid = '' AND allow_gid = '') )
316                                   )
317                                 ",
318                                 intval($remote_user),
319                                 dbesc($gs),
320                                 intval($remote_user),
321                                 dbesc($gs)
322                         );
323                 }
324         }
325         return $sql;
326 }
327
328 function item_permissions_sql($owner_id, $remote_verified = false, $groups = null)
329 {
330         $local_user = local_user();
331         $remote_user = remote_user();
332
333         /*
334          * Construct permissions
335          *
336          * default permissions - anonymous user
337          */
338         $sql = " AND `item`.allow_cid = ''
339                          AND `item`.allow_gid = ''
340                          AND `item`.deny_cid  = ''
341                          AND `item`.deny_gid  = ''
342                          AND `item`.private = 0
343         ";
344
345         // Profile owner - everything is visible
346         if ($local_user && ($local_user == $owner_id)) {
347                 $sql = '';
348         } elseif ($remote_user) {
349                 /*
350                  * Authenticated visitor. Unless pre-verified,
351                  * check that the contact belongs to this $owner_id
352                  * and load the groups the visitor belongs to.
353                  * If pre-verified, the caller is expected to have already
354                  * done this and passed the groups into this function.
355                  */
356                 if (!$remote_verified) {
357                         $r = q("SELECT id FROM contact WHERE id = %d AND uid = %d AND blocked = 0 LIMIT 1",
358                                 intval($remote_user),
359                                 intval($owner_id)
360                         );
361                         if (DBM::is_result($r)) {
362                                 $remote_verified = true;
363                                 $groups = Group::getIdsByContactId($remote_user);
364                         }
365                 }
366                 if ($remote_verified) {
367
368                         $gs = '<<>>'; // should be impossible to match
369
370                         if (is_array($groups) && count($groups)) {
371                                 foreach ($groups as $g) {
372                                         $gs .= '|<' . intval($g) . '>';
373                                 }
374                         }
375
376                         $sql = sprintf(
377                                 " AND ( `item`.private = 0 OR ( `item`.private in (1,2) AND `item`.`wall` = 1
378                                   AND ( NOT (`item`.deny_cid REGEXP '<%d>' OR `item`.deny_gid REGEXP '%s')
379                                   AND ( `item`.allow_cid REGEXP '<%d>' OR `item`.allow_gid REGEXP '%s' OR ( `item`.allow_cid = '' AND `item`.allow_gid = '')))))
380                                 ",
381                                 intval($remote_user),
382                                 dbesc($gs),
383                                 intval($remote_user),
384                                 dbesc($gs)
385                         );
386                 }
387         }
388
389         return $sql;
390 }
391
392 /*
393  * Functions used to protect against Cross-Site Request Forgery
394  * 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.
395  * In this implementation, a security token is reusable (if the user submits a form, goes back and resubmits the form, maybe with small changes;
396  * or if the security token is used for ajax-calls that happen several times), but only valid for a certain amout of time (3hours).
397  * The "typename" seperates the security tokens of different types of forms. This could be relevant in the following case:
398  *    A security token is used to protekt a link from CSRF (e.g. the "delete this profile"-link).
399  *    If the new page contains by any chance external elements, then the used security token is exposed by the referrer.
400  *    Actually, important actions should not be triggered by Links / GET-Requests at all, but somethimes they still are,
401  *    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).
402  */
403 function get_form_security_token($typename = '')
404 {
405         $a = get_app();
406
407         $timestamp = time();
408         $sec_hash = hash('whirlpool', $a->user['guid'] . $a->user['prvkey'] . session_id() . $timestamp . $typename);
409
410         return $timestamp . '.' . $sec_hash;
411 }
412
413 function check_form_security_token($typename = '', $formname = 'form_security_token')
414 {
415         $hash = null;
416
417         if (!empty($_REQUEST[$formname])) {
418                 /// @TODO Careful, not secured!
419                 $hash = $_REQUEST[$formname];
420         }
421
422         if (!empty($_SERVER['HTTP_X_CSRF_TOKEN'])) {
423                 /// @TODO Careful, not secured!
424                 $hash = $_SERVER['HTTP_X_CSRF_TOKEN'];
425         }
426
427         if (empty($hash)) {
428                 return false;
429         }
430
431         $max_livetime = 10800; // 3 hours
432
433         $a = get_app();
434
435         $x = explode('.', $hash);
436         if (time() > (IntVal($x[0]) + $max_livetime)) {
437                 return false;
438         }
439
440         $sec_hash = hash('whirlpool', $a->user['guid'] . $a->user['prvkey'] . session_id() . $x[0] . $typename);
441
442         return ($sec_hash == $x[1]);
443 }
444
445 function check_form_security_std_err_msg()
446 {
447         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;
448 }
449
450 function check_form_security_token_redirectOnErr($err_redirect, $typename = '', $formname = 'form_security_token')
451 {
452         if (!check_form_security_token($typename, $formname)) {
453                 $a = get_app();
454                 logger('check_form_security_token failed: user ' . $a->user['guid'] . ' - form element ' . $typename);
455                 logger('check_form_security_token failed: _REQUEST data: ' . print_r($_REQUEST, true), LOGGER_DATA);
456                 notice(check_form_security_std_err_msg());
457                 goaway(System::baseUrl() . $err_redirect);
458         }
459 }
460
461 function check_form_security_token_ForbiddenOnErr($typename = '', $formname = 'form_security_token')
462 {
463         if (!check_form_security_token($typename, $formname)) {
464                 $a = get_app();
465                 logger('check_form_security_token failed: user ' . $a->user['guid'] . ' - form element ' . $typename);
466                 logger('check_form_security_token failed: _REQUEST data: ' . print_r($_REQUEST, true), LOGGER_DATA);
467                 header('HTTP/1.1 403 Forbidden');
468                 killme();
469         }
470 }
471
472 /**
473  * @brief Kills the "Friendica" cookie and all session data
474  */
475 function nuke_session()
476 {
477         new_cookie(-3600); // make sure cookie is deleted on browser close, as a security measure
478         session_unset();
479         session_destroy();
480 }