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