]> git.mxchange.org Git - friendica.git/blob - include/security.php
Issue-#3873
[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
8 /**
9  * @brief Calculate the hash that is needed for the "Friendica" cookie
10  *
11  * @param array $user Record from "user" table
12  *
13  * @return string Hashed data
14  */
15 function cookie_hash($user) {
16         return(hash("sha256", Config::get("system", "site_prvkey").
17                                 $user["uprvkey"].
18                                 $user["password"]));
19 }
20
21 /**
22  * @brief Set the "Friendica" cookie
23  *
24  * @param int $time
25  * @param array $user Record from "user" table
26  */
27 function new_cookie($time, $user = array()) {
28
29         if ($time != 0) {
30                 $time = $time + time();
31         }
32
33         if ($user) {
34                 $value = json_encode(array("uid" => $user["uid"],
35                                         "hash" => cookie_hash($user),
36                                         "ip" => $_SERVER['REMOTE_ADDR']));
37         }
38         else {
39                 $value = "";
40         }
41
42         setcookie("Friendica", $value, $time, "/", "",
43                 (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL), true);
44
45 }
46
47 function authenticate_success($user_record, $login_initial = false, $interactive = false, $login_refresh = false) {
48
49         $a = get_app();
50
51         $_SESSION['uid'] = $user_record['uid'];
52         $_SESSION['theme'] = $user_record['theme'];
53         $_SESSION['mobile-theme'] = PConfig::get($user_record['uid'], 'system', 'mobile_theme');
54         $_SESSION['authenticated'] = 1;
55         $_SESSION['page_flags'] = $user_record['page-flags'];
56         $_SESSION['my_url'] = System::baseUrl() . '/profile/' . $user_record['nickname'];
57         $_SESSION['my_address'] = $user_record['nickname'] . '@' . substr(System::baseUrl(),strpos(System::baseUrl(),'://')+3);
58         $_SESSION['addr'] = $_SERVER['REMOTE_ADDR'];
59
60         $a->user = $user_record;
61
62         if ($interactive) {
63                 if ($a->user['login_date'] <= NULL_DATE) {
64                         $_SESSION['return_url'] = 'profile_photo/new';
65                         $a->module = 'profile_photo';
66                         info( t("Welcome ") . $a->user['username'] . EOL);
67                         info( t('Please upload a profile photo.') . EOL);
68                 } else {
69                         info( t("Welcome back ") . $a->user['username'] . EOL);
70                 }
71         }
72
73         $member_since = strtotime($a->user['register_date']);
74         if (time() < ($member_since + ( 60 * 60 * 24 * 14))) {
75                 $_SESSION['new_member'] = true;
76         } else {
77                 $_SESSION['new_member'] = false;
78         }
79         if (strlen($a->user['timezone'])) {
80                 date_default_timezone_set($a->user['timezone']);
81                 $a->timezone = $a->user['timezone'];
82         }
83
84         $master_record = $a->user;
85
86         if ((x($_SESSION,'submanage')) && intval($_SESSION['submanage'])) {
87                 $r = dba::fetch_first("SELECT * FROM `user` WHERE `uid` = ? LIMIT 1",
88                         intval($_SESSION['submanage'])
89                 );
90                 if (dbm::is_result($r)) {
91                         $master_record = $r;
92                 }
93         }
94
95         $r = dba::select('user', array('uid', 'username', 'nickname'),
96                 array('password' => $master_record['password'], 'email' => $master_record['email'], 'account_removed' => false));
97         if (dbm::is_result($r)) {
98                 $a->identities = dba::inArray($r);
99         } else {
100                 $a->identities = array();
101         }
102
103         $r = dba::p("SELECT `user`.`uid`, `user`.`username`, `user`.`nickname`
104                 FROM `manage`
105                 INNER JOIN `user` ON `manage`.`mid` = `user`.`uid`
106                 WHERE `user`.`account_removed` = 0 AND `manage`.`uid` = ?",
107                 $master_record['uid']
108         );
109         if (dbm::is_result($r)) {
110                 $a->identities = array_merge($a->identities, dba::inArray($r));
111         }
112
113         if ($login_initial) {
114                 logger('auth_identities: ' . print_r($a->identities,true), LOGGER_DEBUG);
115         }
116         if ($login_refresh) {
117                 logger('auth_identities refresh: ' . print_r($a->identities,true), LOGGER_DEBUG);
118         }
119
120         $r = dba::fetch_first("SELECT * FROM `contact` WHERE `uid` = ? AND `self` LIMIT 1", $_SESSION['uid']);
121         if (dbm::is_result($r)) {
122                 $a->contact = $r;
123                 $a->cid = $r['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                 dba::update('user', array('login_date' => datetime_convert()), array('uid' => $_SESSION['uid']));
131
132                 // Set the login date for all identities of the user
133                 dba::update('user', array('login_date' => datetime_convert()),
134                         array('password' => $master_record['password'], 'email' => $master_record['email'], 'account_removed' => false));
135         }
136
137         if ($login_initial) {
138                 // If the user specified to remember the authentication, then set a cookie
139                 // that expires after one week (the default is when the browser is closed).
140                 // The cookie will be renewed automatically.
141                 // The week ensures that sessions will expire after some inactivity.
142                 if ($_SESSION['remember']) {
143                         logger('Injecting cookie for remembered user '. $_SESSION['remember_user']['nickname']);
144                         new_cookie(604800, $user_record);
145                         unset($_SESSION['remember']);
146                 }
147         }
148
149         if ($login_initial) {
150                 call_hooks('logged_in', $a->user);
151
152                 if (($a->module !== 'home') && isset($_SESSION['return_url'])) {
153                         goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
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         $sql = " AND allow_cid = ''
237                          AND allow_gid = ''
238                          AND deny_cid  = ''
239                          AND deny_gid  = ''
240         ";
241
242         /**
243          * Profile owner - everything is visible
244          */
245
246         if (($local_user) && ($local_user == $owner_id)) {
247                 $sql = '';
248         } elseif ($remote_user) {
249                 /*
250                  * Authenticated visitor. Unless pre-verified,
251                  * check that the contact belongs to this $owner_id
252                  * and load the groups the visitor belongs to.
253                  * If pre-verified, the caller is expected to have already
254                  * done this and passed the groups into this function.
255                  */
256
257                 if (! $remote_verified) {
258                         $r = q("SELECT id FROM contact WHERE id = %d AND uid = %d AND blocked = 0 LIMIT 1",
259                                 intval($remote_user),
260                                 intval($owner_id)
261                         );
262                         if (dbm::is_result($r)) {
263                                 $remote_verified = true;
264                                 $groups = init_groups_visitor($remote_user);
265                         }
266                 }
267                 if ($remote_verified) {
268
269                         $gs = '<<>>'; // should be impossible to match
270
271                         if (is_array($groups) && count($groups)) {
272                                 foreach ($groups as $g)
273                                         $gs .= '|<' . intval($g) . '>';
274                         }
275
276                         /*
277                          * @TODO old-lost code found?
278                         $sql = sprintf(
279                                 " AND ( allow_cid = '' OR allow_cid REGEXP '<%d>' )
280                                   AND ( deny_cid  = '' OR  NOT deny_cid REGEXP '<%d>' )
281                                   AND ( allow_gid = '' OR allow_gid REGEXP '%s' )
282                                   AND ( deny_gid  = '' OR NOT deny_gid REGEXP '%s')
283                                 ",
284                                 intval($remote_user),
285                                 intval($remote_user),
286                                 dbesc($gs),
287                                 dbesc($gs)
288                         );
289                         */
290                         $sql = sprintf(
291                                 " AND ( NOT (deny_cid REGEXP '<%d>' OR deny_gid REGEXP '%s')
292                                   AND ( allow_cid REGEXP '<%d>' OR allow_gid REGEXP '%s' OR ( allow_cid = '' AND allow_gid = '') )
293                                   )
294                                 ",
295                                 intval($remote_user),
296                                 dbesc($gs),
297                                 intval($remote_user),
298                                 dbesc($gs)
299                         );
300                 }
301         }
302         return $sql;
303 }
304
305
306 function item_permissions_sql($owner_id, $remote_verified = false, $groups = null) {
307
308         $local_user = local_user();
309         $remote_user = remote_user();
310
311         /**
312          * Construct permissions
313          *
314          * default permissions - anonymous user
315          */
316         $sql = " AND `item`.allow_cid = ''
317                          AND `item`.allow_gid = ''
318                          AND `item`.deny_cid  = ''
319                          AND `item`.deny_gid  = ''
320                          AND `item`.private = 0
321         ";
322
323         /**
324          * Profile owner - everything is visible
325          */
326         if ($local_user && ($local_user == $owner_id)) {
327                 $sql = '';
328         } elseif ($remote_user) {
329                 /*
330                  * Authenticated visitor. Unless pre-verified,
331                  * check that the contact belongs to this $owner_id
332                  * and load the groups the visitor belongs to.
333                  * If pre-verified, the caller is expected to have already
334                  * done this and passed the groups into this function.
335                  */
336                 if (! $remote_verified) {
337                         $r = q("SELECT id FROM contact WHERE id = %d AND uid = %d AND blocked = 0 LIMIT 1",
338                                 intval($remote_user),
339                                 intval($owner_id)
340                         );
341                         if (dbm::is_result($r)) {
342                                 $remote_verified = true;
343                                 $groups = init_groups_visitor($remote_user);
344                         }
345                 }
346                 if ($remote_verified) {
347
348                         $gs = '<<>>'; // should be impossible to match
349
350                         if (is_array($groups) && count($groups)) {
351                                 foreach ($groups as $g) {
352                                         $gs .= '|<' . intval($g) . '>';
353                                 }
354                         }
355
356                         $sql = sprintf(
357                                 /*" AND ( private = 0 OR ( private in (1,2) AND wall = 1 AND ( allow_cid = '' OR allow_cid REGEXP '<%d>' )
358                                   AND ( deny_cid  = '' OR  NOT deny_cid REGEXP '<%d>' )
359                                   AND ( allow_gid = '' OR allow_gid REGEXP '%s' )
360                                   AND ( deny_gid  = '' OR NOT deny_gid REGEXP '%s')))
361                                 ",
362                                 intval($remote_user),
363                                 intval($remote_user),
364                                 dbesc($gs),
365                                 dbesc($gs)
366 */
367                                 " AND ( `item`.private = 0 OR ( `item`.private in (1,2) AND `item`.`wall` = 1
368                                   AND ( NOT (`item`.deny_cid REGEXP '<%d>' OR `item`.deny_gid REGEXP '%s')
369                                   AND ( `item`.allow_cid REGEXP '<%d>' OR `item`.allow_gid REGEXP '%s' OR ( `item`.allow_cid = '' AND `item`.allow_gid = '')))))
370                                 ",
371                                 intval($remote_user),
372                                 dbesc($gs),
373                                 intval($remote_user),
374                                 dbesc($gs)
375                         );
376                 }
377         }
378
379         return $sql;
380 }
381
382
383 /*
384  * Functions used to protect against Cross-Site Request Forgery
385  * 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.
386  * In this implementation, a security token is reusable (if the user submits a form, goes back and resubmits the form, maybe with small changes;
387  * or if the security token is used for ajax-calls that happen several times), but only valid for a certain amout of time (3hours).
388  * The "typename" seperates the security tokens of different types of forms. This could be relevant in the following case:
389  *    A security token is used to protekt a link from CSRF (e.g. the "delete this profile"-link).
390  *    If the new page contains by any chance external elements, then the used security token is exposed by the referrer.
391  *    Actually, important actions should not be triggered by Links / GET-Requests at all, but somethimes they still are,
392  *    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).
393  */
394 function get_form_security_token($typename = '') {
395         $a = get_app();
396
397         $timestamp = time();
398         $sec_hash = hash('whirlpool', $a->user['guid'] . $a->user['prvkey'] . session_id() . $timestamp . $typename);
399
400         return $timestamp . '.' . $sec_hash;
401 }
402
403 function check_form_security_token($typename = '', $formname = 'form_security_token') {
404         if (!x($_REQUEST, $formname)) {
405                 return false;
406         }
407
408         /// @TODO Careful, not secured!
409         $hash = $_REQUEST[$formname];
410
411         $max_livetime = 10800; // 3 hours
412
413         $a = get_app();
414
415         $x = explode('.', $hash);
416         if (time() > (IntVal($x[0]) + $max_livetime)) {
417                 return false;
418         }
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(System::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 }}