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