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