]> git.mxchange.org Git - friendica.git/blob - include/security.php
Merge pull request #4092 from MrPetovan/task/3954-move-auth-to-src
[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(App $a, $owner)
169 {
170         static $verified = 0;
171
172         if (!local_user() && !remote_user()) {
173                 return false;
174         }
175
176         $uid = local_user();
177
178         if (($uid) && ($uid == $owner)) {
179                 return true;
180         }
181
182         if (remote_user()) {
183                 // use remembered decision and avoid a DB lookup for each and every display item
184                 // DO NOT use this function if there are going to be multiple owners
185                 // We have a contact-id for an authenticated remote user, this block determines if the contact
186                 // belongs to this page owner, and has the necessary permissions to post content
187
188                 if ($verified === 2) {
189                         return true;
190                 } elseif ($verified === 1) {
191                         return false;
192                 } else {
193                         $cid = 0;
194
195                         if (is_array($_SESSION['remote'])) {
196                                 foreach ($_SESSION['remote'] as $visitor) {
197                                         if ($visitor['uid'] == $owner) {
198                                                 $cid = $visitor['cid'];
199                                                 break;
200                                         }
201                                 }
202                         }
203
204                         if (!$cid) {
205                                 return false;
206                         }
207
208                         $r = q("SELECT `contact`.*, `user`.`page-flags` FROM `contact` INNER JOIN `user` on `user`.`uid` = `contact`.`uid`
209                                 WHERE `contact`.`uid` = %d AND `contact`.`id` = %d AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
210                                 AND `user`.`blockwall` = 0 AND `readonly` = 0  AND ( `contact`.`rel` IN ( %d , %d ) OR `user`.`page-flags` = %d ) LIMIT 1",
211                                 intval($owner),
212                                 intval($cid),
213                                 intval(CONTACT_IS_SHARING),
214                                 intval(CONTACT_IS_FRIEND),
215                                 intval(PAGE_COMMUNITY)
216                         );
217
218                         if (DBM::is_result($r)) {
219                                 $verified = 2;
220                                 return true;
221                         } else {
222                                 $verified = 1;
223                         }
224                 }
225         }
226
227         return false;
228 }
229
230 function permissions_sql($owner_id, $remote_verified = false, $groups = null)
231 {
232         $local_user = local_user();
233         $remote_user = remote_user();
234
235         /**
236          * Construct permissions
237          *
238          * default permissions - anonymous user
239          */
240         $sql = " AND allow_cid = ''
241                          AND allow_gid = ''
242                          AND deny_cid  = ''
243                          AND deny_gid  = ''
244         ";
245
246         /**
247          * Profile owner - everything is visible
248          */
249         if ($local_user && $local_user == $owner_id) {
250                 $sql = '';
251         } elseif ($remote_user) {
252                 /*
253                  * Authenticated visitor. Unless pre-verified,
254                  * check that the contact belongs to this $owner_id
255                  * and load the groups the visitor belongs to.
256                  * If pre-verified, the caller is expected to have already
257                  * done this and passed the groups into this function.
258                  */
259
260                 if (!$remote_verified) {
261                         $r = q("SELECT id FROM contact WHERE id = %d AND uid = %d AND blocked = 0 LIMIT 1",
262                                 intval($remote_user),
263                                 intval($owner_id)
264                         );
265                         if (DBM::is_result($r)) {
266                                 $remote_verified = true;
267                                 $groups = Group::getIdsByContactId($remote_user);
268                         }
269                 }
270
271                 if ($remote_verified) {
272                         $gs = '<<>>'; // should be impossible to match
273
274                         if (is_array($groups) && count($groups)) {
275                                 foreach ($groups as $g)
276                                         $gs .= '|<' . intval($g) . '>';
277                         }
278
279                         $sql = sprintf(
280                                 " AND ( NOT (deny_cid REGEXP '<%d>' OR deny_gid REGEXP '%s')
281                                   AND ( allow_cid REGEXP '<%d>' OR allow_gid REGEXP '%s' OR ( allow_cid = '' AND allow_gid = '') )
282                                   )
283                                 ",
284                                 intval($remote_user),
285                                 dbesc($gs),
286                                 intval($remote_user),
287                                 dbesc($gs)
288                         );
289                 }
290         }
291         return $sql;
292 }
293
294 function item_permissions_sql($owner_id, $remote_verified = false, $groups = null)
295 {
296         $local_user = local_user();
297         $remote_user = remote_user();
298
299         /*
300          * Construct permissions
301          *
302          * default permissions - anonymous user
303          */
304         $sql = " AND `item`.allow_cid = ''
305                          AND `item`.allow_gid = ''
306                          AND `item`.deny_cid  = ''
307                          AND `item`.deny_gid  = ''
308                          AND `item`.private = 0
309         ";
310
311         // Profile owner - everything is visible
312         if ($local_user && ($local_user == $owner_id)) {
313                 $sql = '';
314         } elseif ($remote_user) {
315                 /*
316                  * Authenticated visitor. Unless pre-verified,
317                  * check that the contact belongs to this $owner_id
318                  * and load the groups the visitor belongs to.
319                  * If pre-verified, the caller is expected to have already
320                  * done this and passed the groups into this function.
321                  */
322                 if (!$remote_verified) {
323                         $r = q("SELECT id FROM contact WHERE id = %d AND uid = %d AND blocked = 0 LIMIT 1",
324                                 intval($remote_user),
325                                 intval($owner_id)
326                         );
327                         if (DBM::is_result($r)) {
328                                 $remote_verified = true;
329                                 $groups = Group::getIdsByContactId($remote_user);
330                         }
331                 }
332                 if ($remote_verified) {
333
334                         $gs = '<<>>'; // should be impossible to match
335
336                         if (is_array($groups) && count($groups)) {
337                                 foreach ($groups as $g) {
338                                         $gs .= '|<' . intval($g) . '>';
339                                 }
340                         }
341
342                         $sql = sprintf(
343                                 " AND ( `item`.private = 0 OR ( `item`.private in (1,2) AND `item`.`wall` = 1
344                                   AND ( NOT (`item`.deny_cid REGEXP '<%d>' OR `item`.deny_gid REGEXP '%s')
345                                   AND ( `item`.allow_cid REGEXP '<%d>' OR `item`.allow_gid REGEXP '%s' OR ( `item`.allow_cid = '' AND `item`.allow_gid = '')))))
346                                 ",
347                                 intval($remote_user),
348                                 dbesc($gs),
349                                 intval($remote_user),
350                                 dbesc($gs)
351                         );
352                 }
353         }
354
355         return $sql;
356 }
357
358 /*
359  * Functions used to protect against Cross-Site Request Forgery
360  * 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.
361  * In this implementation, a security token is reusable (if the user submits a form, goes back and resubmits the form, maybe with small changes;
362  * or if the security token is used for ajax-calls that happen several times), but only valid for a certain amout of time (3hours).
363  * The "typename" seperates the security tokens of different types of forms. This could be relevant in the following case:
364  *    A security token is used to protekt a link from CSRF (e.g. the "delete this profile"-link).
365  *    If the new page contains by any chance external elements, then the used security token is exposed by the referrer.
366  *    Actually, important actions should not be triggered by Links / GET-Requests at all, but somethimes they still are,
367  *    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).
368  */
369 function get_form_security_token($typename = '')
370 {
371         $a = get_app();
372
373         $timestamp = time();
374         $sec_hash = hash('whirlpool', $a->user['guid'] . $a->user['prvkey'] . session_id() . $timestamp . $typename);
375
376         return $timestamp . '.' . $sec_hash;
377 }
378
379 function check_form_security_token($typename = '', $formname = 'form_security_token')
380 {
381         if (!x($_REQUEST, $formname)) {
382                 return false;
383         }
384
385         /// @TODO Careful, not secured!
386         $hash = $_REQUEST[$formname];
387
388         $max_livetime = 10800; // 3 hours
389
390         $a = get_app();
391
392         $x = explode('.', $hash);
393         if (time() > (IntVal($x[0]) + $max_livetime)) {
394                 return false;
395         }
396
397         $sec_hash = hash('whirlpool', $a->user['guid'] . $a->user['prvkey'] . session_id() . $x[0] . $typename);
398
399         return ($sec_hash == $x[1]);
400 }
401
402 function check_form_security_std_err_msg()
403 {
404         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;
405 }
406
407 function check_form_security_token_redirectOnErr($err_redirect, $typename = '', $formname = 'form_security_token')
408 {
409         if (!check_form_security_token($typename, $formname)) {
410                 $a = get_app();
411                 logger('check_form_security_token failed: user ' . $a->user['guid'] . ' - form element ' . $typename);
412                 logger('check_form_security_token failed: _REQUEST data: ' . print_r($_REQUEST, true), LOGGER_DATA);
413                 notice(check_form_security_std_err_msg());
414                 goaway(System::baseUrl() . $err_redirect);
415         }
416 }
417
418 function check_form_security_token_ForbiddenOnErr($typename = '', $formname = 'form_security_token')
419 {
420         if (!check_form_security_token($typename, $formname)) {
421                 $a = get_app();
422                 logger('check_form_security_token failed: user ' . $a->user['guid'] . ' - form element ' . $typename);
423                 logger('check_form_security_token failed: _REQUEST data: ' . print_r($_REQUEST, true), LOGGER_DATA);
424                 header('HTTP/1.1 403 Forbidden');
425                 killme();
426         }
427 }
428
429 /**
430  * @brief Kills the "Friendica" cookie and all session data
431  */
432 function nuke_session()
433 {
434         new_cookie(-3600); // make sure cookie is deleted on browser close, as a security measure
435         session_unset();
436         session_destroy();
437 }