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