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