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