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