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