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