3 * @file include/security.php
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\Group;
13 use Friendica\Util\DateTimeFormat;
16 * @brief Calculate the hash that is needed for the "Friendica" cookie
18 * @param array $user Record from "user" table
20 * @return string Hashed data
22 function cookie_hash($user)
24 return(hash("sha256", Config::get("system", "site_prvkey") .
30 * @brief Set the "Friendica" cookie
33 * @param array $user Record from "user" table
35 function new_cookie($time, $user = [])
38 $time = $time + time();
42 $value = json_encode(["uid" => $user["uid"],
43 "hash" => cookie_hash($user),
44 "ip" => defaults($_SERVER, 'REMOTE_ADDR', '0.0.0.0')]);
49 setcookie("Friendica", $value, $time, "/", "", (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL), true);
53 * @brief Sets the provided user's authenticated session
55 * @todo Should be moved to Friendica\Core\Session once it's created
57 * @param type $user_record
58 * @param type $login_initial
59 * @param type $interactive
60 * @param type $login_refresh
62 function authenticate_success($user_record, $login_initial = false, $interactive = false, $login_refresh = false)
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');
75 $a->user = $user_record;
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);
84 info(L10n::t("Welcome back ") . $a->user['username'] . EOL);
88 $member_since = strtotime($a->user['register_date']);
89 if (time() < ($member_since + ( 60 * 60 * 24 * 14))) {
90 $_SESSION['new_member'] = true;
92 $_SESSION['new_member'] = false;
94 if (strlen($a->user['timezone'])) {
95 date_default_timezone_set($a->user['timezone']);
96 $a->timezone = $a->user['timezone'];
99 $master_record = $a->user;
101 if ((x($_SESSION, 'submanage')) && intval($_SESSION['submanage'])) {
102 $user = DBA::selectFirst('user', [], ['uid' => $_SESSION['submanage']]);
103 if (DBA::isResult($user)) {
104 $master_record = $user;
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']]];
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 (DBA::isResult($r)) {
118 $a->identities = array_merge($a->identities, DBA::toArray($r));
121 // Just ensure that the array is always defined
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 (DBA::isResult($r)) {
128 $a->identities = DBA::toArray($r);
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 (DBA::isResult($r)) {
135 $a->identities = array_merge($a->identities, DBA::toArray($r));
139 $r = DBA::p("SELECT `user`.`uid`, `user`.`username`, `user`.`nickname`
141 INNER JOIN `user` ON `manage`.`mid` = `user`.`uid`
142 WHERE `user`.`account_removed` = 0 AND `manage`.`uid` = ?",
143 $master_record['uid']
145 if (DBA::isResult($r)) {
146 $a->identities = array_merge($a->identities, DBA::toArray($r));
149 if ($login_initial) {
150 logger('auth_identities: ' . print_r($a->identities, true), LOGGER_DEBUG);
152 if ($login_refresh) {
153 logger('auth_identities refresh: ' . print_r($a->identities, true), LOGGER_DEBUG);
156 $contact = DBA::selectFirst('contact', [], ['uid' => $_SESSION['uid'], 'self' => true]);
157 if (DBA::isResult($contact)) {
158 $a->contact = $contact;
159 $a->cid = $contact['id'];
160 $_SESSION['cid'] = $a->cid;
163 header('X-Account-Management-Status: active; name="' . $a->user['username'] . '"; id="' . $a->user['nickname'] . '"');
165 if ($login_initial || $login_refresh) {
166 DBA::update('user', ['login_date' => DateTimeFormat::utcNow()], ['uid' => $_SESSION['uid']]);
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]);
173 if ($login_initial) {
175 * If the user specified to remember the authentication, then set a cookie
176 * that expires after one week (the default is when the browser is closed).
177 * The cookie will be renewed automatically.
178 * The week ensures that sessions will expire after some inactivity.
180 if ($_SESSION['remember']) {
181 logger('Injecting cookie for remembered user ' . $a->user['nickname']);
182 new_cookie(604800, $user_record);
183 unset($_SESSION['remember']);
187 if ($login_initial) {
188 Addon::callHooks('logged_in', $a->user);
190 if (($a->module !== 'home') && isset($_SESSION['return_url'])) {
191 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
196 function can_write_wall($owner)
198 static $verified = 0;
200 if (!local_user() && !remote_user()) {
205 if ($uid == $owner) {
209 if (local_user() && ($owner == 0)) {
214 // use remembered decision and avoid a DB lookup for each and every display item
215 // DO NOT use this function if there are going to be multiple owners
216 // We have a contact-id for an authenticated remote user, this block determines if the contact
217 // belongs to this page owner, and has the necessary permissions to post content
219 if ($verified === 2) {
221 } elseif ($verified === 1) {
226 if (is_array($_SESSION['remote'])) {
227 foreach ($_SESSION['remote'] as $visitor) {
228 if ($visitor['uid'] == $owner) {
229 $cid = $visitor['cid'];
239 $r = q("SELECT `contact`.*, `user`.`page-flags` FROM `contact` INNER JOIN `user` on `user`.`uid` = `contact`.`uid`
240 WHERE `contact`.`uid` = %d AND `contact`.`id` = %d AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
241 AND `user`.`blockwall` = 0 AND `readonly` = 0 AND ( `contact`.`rel` IN ( %d , %d ) OR `user`.`page-flags` = %d ) LIMIT 1",
244 intval(CONTACT_IS_SHARING),
245 intval(CONTACT_IS_FRIEND),
246 intval(PAGE_COMMUNITY)
249 if (DBA::isResult($r)) {
261 /// @TODO $groups should be array
262 function permissions_sql($owner_id, $remote_verified = false, $groups = null)
264 $local_user = local_user();
265 $remote_user = remote_user();
268 * Construct permissions
270 * default permissions - anonymous user
272 $sql = " AND allow_cid = ''
279 * Profile owner - everything is visible
281 if ($local_user && $local_user == $owner_id) {
284 * Authenticated visitor. Unless pre-verified,
285 * check that the contact belongs to this $owner_id
286 * and load the groups the visitor belongs to.
287 * If pre-verified, the caller is expected to have already
288 * done this and passed the groups into this function.
290 } elseif ($remote_user) {
292 * Authenticated visitor. Unless pre-verified,
293 * check that the contact belongs to this $owner_id
294 * and load the groups the visitor belongs to.
295 * If pre-verified, the caller is expected to have already
296 * done this and passed the groups into this function.
299 if (!$remote_verified) {
300 $r = q("SELECT id FROM contact WHERE id = %d AND uid = %d AND blocked = 0 LIMIT 1",
301 intval($remote_user),
304 if (DBA::isResult($r)) {
305 $remote_verified = true;
306 $groups = Group::getIdsByContactId($remote_user);
310 if ($remote_verified) {
311 $gs = '<<>>'; // should be impossible to match
313 if (is_array($groups)) {
314 foreach ($groups as $g) {
315 $gs .= '|<' . intval($g) . '>';
320 " AND ( NOT (deny_cid REGEXP '<%d>' OR deny_gid REGEXP '%s')
321 AND ( allow_cid REGEXP '<%d>' OR allow_gid REGEXP '%s' OR ( allow_cid = '' AND allow_gid = '') )
324 intval($remote_user),
326 intval($remote_user),
334 function item_permissions_sql($owner_id, $remote_verified = false, $groups = null)
336 $local_user = local_user();
337 $remote_user = remote_user();
340 * Construct permissions
342 * default permissions - anonymous user
344 $sql = " AND `item`.allow_cid = ''
345 AND `item`.allow_gid = ''
346 AND `item`.deny_cid = ''
347 AND `item`.deny_gid = ''
348 AND `item`.private != 1
351 // Profile owner - everything is visible
352 if ($local_user && ($local_user == $owner_id)) {
354 } elseif ($remote_user) {
356 * Authenticated visitor. Unless pre-verified,
357 * check that the contact belongs to this $owner_id
358 * and load the groups the visitor belongs to.
359 * If pre-verified, the caller is expected to have already
360 * done this and passed the groups into this function.
362 if (!$remote_verified) {
363 $r = q("SELECT id FROM contact WHERE id = %d AND uid = %d AND blocked = 0 LIMIT 1",
364 intval($remote_user),
367 if (DBA::isResult($r)) {
368 $remote_verified = true;
369 $groups = Group::getIdsByContactId($remote_user);
372 if ($remote_verified) {
374 $gs = '<<>>'; // should be impossible to match
376 if (is_array($groups) && count($groups)) {
377 foreach ($groups as $g) {
378 $gs .= '|<' . intval($g) . '>';
383 " AND ( `item`.private = 0 OR ( `item`.private in (1,2) AND `item`.`wall` = 1
384 AND ( NOT (`item`.deny_cid REGEXP '<%d>' OR `item`.deny_gid REGEXP '%s')
385 AND ( `item`.allow_cid REGEXP '<%d>' OR `item`.allow_gid REGEXP '%s' OR ( `item`.allow_cid = '' AND `item`.allow_gid = '')))))
387 intval($remote_user),
389 intval($remote_user),
399 * Functions used to protect against Cross-Site Request Forgery
400 * 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.
401 * In this implementation, a security token is reusable (if the user submits a form, goes back and resubmits the form, maybe with small changes;
402 * or if the security token is used for ajax-calls that happen several times), but only valid for a certain amout of time (3hours).
403 * The "typename" seperates the security tokens of different types of forms. This could be relevant in the following case:
404 * A security token is used to protekt a link from CSRF (e.g. the "delete this profile"-link).
405 * If the new page contains by any chance external elements, then the used security token is exposed by the referrer.
406 * Actually, important actions should not be triggered by Links / GET-Requests at all, but somethimes they still are,
407 * 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).
409 function get_form_security_token($typename = '')
414 $sec_hash = hash('whirlpool', $a->user['guid'] . $a->user['prvkey'] . session_id() . $timestamp . $typename);
416 return $timestamp . '.' . $sec_hash;
419 function check_form_security_token($typename = '', $formname = 'form_security_token')
423 if (!empty($_REQUEST[$formname])) {
424 /// @TODO Careful, not secured!
425 $hash = $_REQUEST[$formname];
428 if (!empty($_SERVER['HTTP_X_CSRF_TOKEN'])) {
429 /// @TODO Careful, not secured!
430 $hash = $_SERVER['HTTP_X_CSRF_TOKEN'];
437 $max_livetime = 10800; // 3 hours
441 $x = explode('.', $hash);
442 if (time() > (IntVal($x[0]) + $max_livetime)) {
446 $sec_hash = hash('whirlpool', $a->user['guid'] . $a->user['prvkey'] . session_id() . $x[0] . $typename);
448 return ($sec_hash == $x[1]);
451 function check_form_security_std_err_msg()
453 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;
456 function check_form_security_token_redirectOnErr($err_redirect, $typename = '', $formname = 'form_security_token')
458 if (!check_form_security_token($typename, $formname)) {
460 logger('check_form_security_token failed: user ' . $a->user['guid'] . ' - form element ' . $typename);
461 logger('check_form_security_token failed: _REQUEST data: ' . print_r($_REQUEST, true), LOGGER_DATA);
462 notice(check_form_security_std_err_msg());
463 goaway(System::baseUrl() . $err_redirect);
467 function check_form_security_token_ForbiddenOnErr($typename = '', $formname = 'form_security_token')
469 if (!check_form_security_token($typename, $formname)) {
471 logger('check_form_security_token failed: user ' . $a->user['guid'] . ' - form element ' . $typename);
472 logger('check_form_security_token failed: _REQUEST data: ' . print_r($_REQUEST, true), LOGGER_DATA);
473 header('HTTP/1.1 403 Forbidden');
479 * @brief Kills the "Friendica" cookie and all session data
481 function nuke_session()
483 new_cookie(-3600); // make sure cookie is deleted on browser close, as a security measure