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