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\Database\DBM;
13 use Friendica\Model\Group;
14 use Friendica\Util\DateTimeFormat;
17 * @brief Calculate the hash that is needed for the "Friendica" cookie
19 * @param array $user Record from "user" table
21 * @return string Hashed data
23 function cookie_hash($user)
25 return(hash("sha256", Config::get("system", "site_prvkey") .
31 * @brief Set the "Friendica" cookie
34 * @param array $user Record from "user" table
36 function new_cookie($time, $user = [])
39 $time = $time + time();
43 $value = json_encode(["uid" => $user["uid"],
44 "hash" => cookie_hash($user),
45 "ip" => defaults($_SERVER, 'REMOTE_ADDR', '0.0.0.0')]);
50 setcookie("Friendica", $value, $time, "/", "", (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL), true);
54 * @brief Sets the provided user's authenticated session
56 * @todo Should be moved to Friendica\Core\Session once it's created
58 * @param type $user_record
59 * @param type $login_initial
60 * @param type $interactive
61 * @param type $login_refresh
63 function authenticate_success($user_record, $login_initial = false, $interactive = false, $login_refresh = false)
67 $_SESSION['uid'] = $user_record['uid'];
68 $_SESSION['theme'] = $user_record['theme'];
69 $_SESSION['mobile-theme'] = PConfig::get($user_record['uid'], 'system', 'mobile_theme');
70 $_SESSION['authenticated'] = 1;
71 $_SESSION['page_flags'] = $user_record['page-flags'];
72 $_SESSION['my_url'] = System::baseUrl() . '/profile/' . $user_record['nickname'];
73 $_SESSION['my_address'] = $user_record['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
74 $_SESSION['addr'] = defaults($_SERVER, 'REMOTE_ADDR', '0.0.0.0');
76 $a->user = $user_record;
79 if ($a->user['login_date'] <= NULL_DATE) {
80 $_SESSION['return_url'] = 'profile_photo/new';
81 $a->module = 'profile_photo';
82 info(L10n::t("Welcome ") . $a->user['username'] . EOL);
83 info(L10n::t('Please upload a profile photo.') . EOL);
85 info(L10n::t("Welcome back ") . $a->user['username'] . EOL);
89 $member_since = strtotime($a->user['register_date']);
90 if (time() < ($member_since + ( 60 * 60 * 24 * 14))) {
91 $_SESSION['new_member'] = true;
93 $_SESSION['new_member'] = false;
95 if (strlen($a->user['timezone'])) {
96 date_default_timezone_set($a->user['timezone']);
97 $a->timezone = $a->user['timezone'];
100 $master_record = $a->user;
102 if ((x($_SESSION, 'submanage')) && intval($_SESSION['submanage'])) {
103 $user = dba::selectFirst('user', [], ['uid' => $_SESSION['submanage']]);
104 if (DBM::is_result($user)) {
105 $master_record = $user;
109 if ($master_record['parent-uid'] == 0) {
110 // First add our own entry
111 $a->identities = [['uid' => $master_record['uid'],
112 'username' => $master_record['username'],
113 'nickname' => $master_record['nickname']]];
115 // Then add all the children
116 $r = dba::select('user', ['uid', 'username', 'nickname'],
117 ['parent-uid' => $master_record['uid'], 'account_removed' => false]);
118 if (DBM::is_result($r)) {
119 $a->identities = array_merge($a->identities, dba::inArray($r));
122 // Just ensure that the array is always defined
125 // First entry is our parent
126 $r = dba::select('user', ['uid', 'username', 'nickname'],
127 ['uid' => $master_record['parent-uid'], 'account_removed' => false]);
128 if (DBM::is_result($r)) {
129 $a->identities = dba::inArray($r);
132 // Then add all siblings
133 $r = dba::select('user', ['uid', 'username', 'nickname'],
134 ['parent-uid' => $master_record['parent-uid'], 'account_removed' => false]);
135 if (DBM::is_result($r)) {
136 $a->identities = array_merge($a->identities, dba::inArray($r));
140 $r = dba::p("SELECT `user`.`uid`, `user`.`username`, `user`.`nickname`
142 INNER JOIN `user` ON `manage`.`mid` = `user`.`uid`
143 WHERE `user`.`account_removed` = 0 AND `manage`.`uid` = ?",
144 $master_record['uid']
146 if (DBM::is_result($r)) {
147 $a->identities = array_merge($a->identities, dba::inArray($r));
150 if ($login_initial) {
151 logger('auth_identities: ' . print_r($a->identities, true), LOGGER_DEBUG);
153 if ($login_refresh) {
154 logger('auth_identities refresh: ' . print_r($a->identities, true), LOGGER_DEBUG);
157 $contact = dba::selectFirst('contact', [], ['uid' => $_SESSION['uid'], 'self' => true]);
158 if (DBM::is_result($contact)) {
159 $a->contact = $contact;
160 $a->cid = $contact['id'];
161 $_SESSION['cid'] = $a->cid;
164 header('X-Account-Management-Status: active; name="' . $a->user['username'] . '"; id="' . $a->user['nickname'] . '"');
166 if ($login_initial || $login_refresh) {
167 dba::update('user', ['login_date' => DateTimeFormat::utcNow()], ['uid' => $_SESSION['uid']]);
169 // Set the login date for all identities of the user
170 dba::update('user', ['login_date' => DateTimeFormat::utcNow()],
171 ['parent-uid' => $master_record['uid'], 'account_removed' => false]);
174 if ($login_initial) {
176 * If the user specified to remember the authentication, then set a cookie
177 * that expires after one week (the default is when the browser is closed).
178 * The cookie will be renewed automatically.
179 * The week ensures that sessions will expire after some inactivity.
181 if ($_SESSION['remember']) {
182 logger('Injecting cookie for remembered user ' . $a->user['nickname']);
183 new_cookie(604800, $user_record);
184 unset($_SESSION['remember']);
188 if ($login_initial) {
189 Addon::callHooks('logged_in', $a->user);
191 if (($a->module !== 'home') && isset($_SESSION['return_url'])) {
192 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
197 function can_write_wall($owner)
199 static $verified = 0;
201 if (!local_user() && !remote_user()) {
206 if ($uid == $owner) {
210 if (local_user() && ($owner == 0)) {
215 // use remembered decision and avoid a DB lookup for each and every display item
216 // DO NOT use this function if there are going to be multiple owners
217 // We have a contact-id for an authenticated remote user, this block determines if the contact
218 // belongs to this page owner, and has the necessary permissions to post content
220 if ($verified === 2) {
222 } elseif ($verified === 1) {
227 if (is_array($_SESSION['remote'])) {
228 foreach ($_SESSION['remote'] as $visitor) {
229 if ($visitor['uid'] == $owner) {
230 $cid = $visitor['cid'];
240 $r = q("SELECT `contact`.*, `user`.`page-flags` FROM `contact` INNER JOIN `user` on `user`.`uid` = `contact`.`uid`
241 WHERE `contact`.`uid` = %d AND `contact`.`id` = %d AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
242 AND `user`.`blockwall` = 0 AND `readonly` = 0 AND ( `contact`.`rel` IN ( %d , %d ) OR `user`.`page-flags` = %d ) LIMIT 1",
245 intval(CONTACT_IS_SHARING),
246 intval(CONTACT_IS_FRIEND),
247 intval(PAGE_COMMUNITY)
250 if (DBM::is_result($r)) {
262 /// @TODO $groups should be array
263 function permissions_sql($owner_id, $remote_verified = false, $groups = null)
265 $local_user = local_user();
266 $remote_user = remote_user();
269 * Construct permissions
271 * default permissions - anonymous user
273 $sql = " AND allow_cid = ''
280 * Profile owner - everything is visible
282 if ($local_user && $local_user == $owner_id) {
285 * Authenticated visitor. Unless pre-verified,
286 * check that the contact belongs to this $owner_id
287 * and load the groups the visitor belongs to.
288 * If pre-verified, the caller is expected to have already
289 * done this and passed the groups into this function.
291 } elseif ($remote_user) {
293 * Authenticated visitor. Unless pre-verified,
294 * check that the contact belongs to this $owner_id
295 * and load the groups the visitor belongs to.
296 * If pre-verified, the caller is expected to have already
297 * done this and passed the groups into this function.
300 if (!$remote_verified) {
301 $r = q("SELECT id FROM contact WHERE id = %d AND uid = %d AND blocked = 0 LIMIT 1",
302 intval($remote_user),
305 if (DBM::is_result($r)) {
306 $remote_verified = true;
307 $groups = Group::getIdsByContactId($remote_user);
311 if ($remote_verified) {
312 $gs = '<<>>'; // should be impossible to match
314 if (is_array($groups)) {
315 foreach ($groups as $g) {
316 $gs .= '|<' . intval($g) . '>';
321 " AND ( NOT (deny_cid REGEXP '<%d>' OR deny_gid REGEXP '%s')
322 AND ( allow_cid REGEXP '<%d>' OR allow_gid REGEXP '%s' OR ( allow_cid = '' AND allow_gid = '') )
325 intval($remote_user),
327 intval($remote_user),
335 function item_permissions_sql($owner_id, $remote_verified = false, $groups = null)
337 $local_user = local_user();
338 $remote_user = remote_user();
341 * Construct permissions
343 * default permissions - anonymous user
345 $sql = " AND `item`.allow_cid = ''
346 AND `item`.allow_gid = ''
347 AND `item`.deny_cid = ''
348 AND `item`.deny_gid = ''
349 AND `item`.private != 1
352 // Profile owner - everything is visible
353 if ($local_user && ($local_user == $owner_id)) {
355 } elseif ($remote_user) {
357 * Authenticated visitor. Unless pre-verified,
358 * check that the contact belongs to this $owner_id
359 * and load the groups the visitor belongs to.
360 * If pre-verified, the caller is expected to have already
361 * done this and passed the groups into this function.
363 if (!$remote_verified) {
364 $r = q("SELECT id FROM contact WHERE id = %d AND uid = %d AND blocked = 0 LIMIT 1",
365 intval($remote_user),
368 if (DBM::is_result($r)) {
369 $remote_verified = true;
370 $groups = Group::getIdsByContactId($remote_user);
373 if ($remote_verified) {
375 $gs = '<<>>'; // should be impossible to match
377 if (is_array($groups) && count($groups)) {
378 foreach ($groups as $g) {
379 $gs .= '|<' . intval($g) . '>';
384 " AND ( `item`.private = 0 OR ( `item`.private in (1,2) AND `item`.`wall` = 1
385 AND ( NOT (`item`.deny_cid REGEXP '<%d>' OR `item`.deny_gid REGEXP '%s')
386 AND ( `item`.allow_cid REGEXP '<%d>' OR `item`.allow_gid REGEXP '%s' OR ( `item`.allow_cid = '' AND `item`.allow_gid = '')))))
388 intval($remote_user),
390 intval($remote_user),
400 * Functions used to protect against Cross-Site Request Forgery
401 * 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.
402 * In this implementation, a security token is reusable (if the user submits a form, goes back and resubmits the form, maybe with small changes;
403 * or if the security token is used for ajax-calls that happen several times), but only valid for a certain amout of time (3hours).
404 * The "typename" seperates the security tokens of different types of forms. This could be relevant in the following case:
405 * A security token is used to protekt a link from CSRF (e.g. the "delete this profile"-link).
406 * If the new page contains by any chance external elements, then the used security token is exposed by the referrer.
407 * Actually, important actions should not be triggered by Links / GET-Requests at all, but somethimes they still are,
408 * 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).
410 function get_form_security_token($typename = '')
415 $sec_hash = hash('whirlpool', $a->user['guid'] . $a->user['prvkey'] . session_id() . $timestamp . $typename);
417 return $timestamp . '.' . $sec_hash;
420 function check_form_security_token($typename = '', $formname = 'form_security_token')
424 if (!empty($_REQUEST[$formname])) {
425 /// @TODO Careful, not secured!
426 $hash = $_REQUEST[$formname];
429 if (!empty($_SERVER['HTTP_X_CSRF_TOKEN'])) {
430 /// @TODO Careful, not secured!
431 $hash = $_SERVER['HTTP_X_CSRF_TOKEN'];
438 $max_livetime = 10800; // 3 hours
442 $x = explode('.', $hash);
443 if (time() > (IntVal($x[0]) + $max_livetime)) {
447 $sec_hash = hash('whirlpool', $a->user['guid'] . $a->user['prvkey'] . session_id() . $x[0] . $typename);
449 return ($sec_hash == $x[1]);
452 function check_form_security_std_err_msg()
454 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;
457 function check_form_security_token_redirectOnErr($err_redirect, $typename = '', $formname = 'form_security_token')
459 if (!check_form_security_token($typename, $formname)) {
461 logger('check_form_security_token failed: user ' . $a->user['guid'] . ' - form element ' . $typename);
462 logger('check_form_security_token failed: _REQUEST data: ' . print_r($_REQUEST, true), LOGGER_DATA);
463 notice(check_form_security_std_err_msg());
464 goaway(System::baseUrl() . $err_redirect);
468 function check_form_security_token_ForbiddenOnErr($typename = '', $formname = 'form_security_token')
470 if (!check_form_security_token($typename, $formname)) {
472 logger('check_form_security_token failed: user ' . $a->user['guid'] . ' - form element ' . $typename);
473 logger('check_form_security_token failed: _REQUEST data: ' . print_r($_REQUEST, true), LOGGER_DATA);
474 header('HTTP/1.1 403 Forbidden');
480 * @brief Kills the "Friendica" cookie and all session data
482 function nuke_session()
484 new_cookie(-3600); // make sure cookie is deleted on browser close, as a security measure