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