]> git.mxchange.org Git - friendica.git/blob - include/security.php
fix bug that wouldn't show posts to a user who was in an allowed group when individua...
[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'",
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 left join user on manage.mid = user.uid 
60                 where `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 LIMIT 1",
85                         dbesc(datetime_convert()),
86                         dbesc($l),
87                         intval($_SESSION['uid'])
88                 );
89         }
90         if($login_initial) {
91                 call_hooks('logged_in', $a->user);
92
93                 if(($a->module !== 'home') && isset($_SESSION['return_url']))
94                         goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
95         }
96
97 }
98
99
100
101 function can_write_wall(&$a,$owner) {
102
103         static $verified = 0;
104
105         if((! (local_user())) && (! (remote_user())))
106                 return false;
107
108         $uid = local_user();
109
110         if(($uid) && ($uid == $owner)) {
111                 return true;
112         }
113
114         if(remote_user()) {
115
116                 // use remembered decision and avoid a DB lookup for each and every display item
117                 // DO NOT use this function if there are going to be multiple owners
118
119                 // We have a contact-id for an authenticated remote user, this block determines if the contact
120                 // belongs to this page owner, and has the necessary permissions to post content
121
122                 if($verified === 2)
123                         return true;
124                 elseif($verified === 1)
125                         return false;
126                 else {
127                         $cid = 0;
128
129                         if(is_array($_SESSION['remote'])) {
130                                 foreach($_SESSION['remote'] as $visitor) {
131                                         if($visitor['uid'] == $owner) {
132                                                 $cid = $visitor['cid'];
133                                                 break;
134                                         }
135                                 }
136                         }
137
138                         if(! $cid)
139                                 return false;
140
141
142                         $r = q("SELECT `contact`.*, `user`.`page-flags` FROM `contact` LEFT JOIN `user` on `user`.`uid` = `contact`.`uid` 
143                                 WHERE `contact`.`uid` = %d AND `contact`.`id` = %d AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0 
144                                 AND `user`.`blockwall` = 0 AND `readonly` = 0  AND ( `contact`.`rel` IN ( %d , %d ) OR `user`.`page-flags` = %d ) LIMIT 1",
145                                 intval($owner),
146                                 intval($cid),
147                                 intval(CONTACT_IS_SHARING),
148                                 intval(CONTACT_IS_FRIEND),
149                                 intval(PAGE_COMMUNITY)
150                         );
151
152                         if(count($r)) {
153                                 $verified = 2;
154                                 return true;
155                         }
156                         else {
157                                 $verified = 1;
158                         }
159                 }
160         }
161
162         return false;
163 }
164
165
166 function permissions_sql($owner_id,$remote_verified = false,$groups = null) {
167
168         $local_user = local_user();
169         $remote_user = remote_user();
170
171         /**
172          * Construct permissions
173          *
174          * default permissions - anonymous user
175          */
176
177         $sql = " AND allow_cid = '' 
178                          AND allow_gid = '' 
179                          AND deny_cid  = '' 
180                          AND deny_gid  = '' 
181         ";
182
183         /**
184          * Profile owner - everything is visible
185          */
186
187         if(($local_user) && ($local_user == $owner_id)) {
188                 $sql = ''; 
189         }
190
191         /**
192          * Authenticated visitor. Unless pre-verified, 
193          * check that the contact belongs to this $owner_id
194          * and load the groups the visitor belongs to.
195          * If pre-verified, the caller is expected to have already
196          * done this and passed the groups into this function.
197          */
198
199         elseif($remote_user) {
200
201                 if(! $remote_verified) {
202                         $r = q("SELECT id FROM contact WHERE id = %d AND uid = %d AND blocked = 0 LIMIT 1",
203                                 intval($remote_user),
204                                 intval($owner_id)
205                         );
206                         if(count($r)) {
207                                 $remote_verified = true;
208                                 $groups = init_groups_visitor($remote_user);
209                         }
210                 }
211                 if($remote_verified) {
212                 
213                         $gs = '<<>>'; // should be impossible to match
214
215                         if(is_array($groups) && count($groups)) {
216                                 foreach($groups as $g)
217                                         $gs .= '|<' . intval($g) . '>';
218                         } 
219
220                         /*$sql = sprintf(
221                                 " AND ( allow_cid = '' OR allow_cid REGEXP '<%d>' ) 
222                                   AND ( deny_cid  = '' OR  NOT deny_cid REGEXP '<%d>' ) 
223                                   AND ( allow_gid = '' OR allow_gid REGEXP '%s' )
224                                   AND ( deny_gid  = '' OR NOT deny_gid REGEXP '%s')
225                                 ",
226                                 intval($remote_user),
227                                 intval($remote_user),
228                                 dbesc($gs),
229                                 dbesc($gs)
230                         );*/
231                         $sql = sprintf(
232                                 " AND ( NOT (deny_cid REGEXP '<%d>' OR deny_gid REGEXP '%s')
233                                   AND ( allow_cid REGEXP '<%d>' OR allow_gid REGEXP '%s' OR ( allow_cid = '' AND allow_gid = '') )
234                                   )
235                                 ",
236                                 intval($remote_user),
237                                 dbesc($gs),
238                                 intval($remote_user),
239                                 dbesc($gs)
240                         );
241                 }
242         }
243         return $sql;
244 }
245
246
247 function item_permissions_sql($owner_id,$remote_verified = false,$groups = null) {
248
249         $local_user = local_user();
250         $remote_user = remote_user();
251
252         /**
253          * Construct permissions
254          *
255          * default permissions - anonymous user
256          */
257
258         $sql = " AND allow_cid = '' 
259                          AND allow_gid = '' 
260                          AND deny_cid  = '' 
261                          AND deny_gid  = '' 
262                          AND private = 0
263         ";
264
265         /**
266          * Profile owner - everything is visible
267          */
268
269         if($local_user && ($local_user == $owner_id)) {
270                 $sql = '';
271         }
272
273         /**
274          * Authenticated visitor. Unless pre-verified, 
275          * check that the contact belongs to this $owner_id
276          * and load the groups the visitor belongs to.
277          * If pre-verified, the caller is expected to have already
278          * done this and passed the groups into this function.
279          */
280
281         elseif($remote_user) {
282
283                 if(! $remote_verified) {
284                         $r = q("SELECT id FROM contact WHERE id = %d AND uid = %d AND blocked = 0 LIMIT 1",
285                                 intval($remote_user),
286                                 intval($owner_id)
287                         );
288                         if(count($r)) {
289                                 $remote_verified = true;
290                                 $groups = init_groups_visitor($remote_user);
291                         }
292                 }
293                 if($remote_verified) {
294                 
295                         $gs = '<<>>'; // should be impossible to match
296
297                         if(is_array($groups) && count($groups)) {
298                                 foreach($groups as $g)
299                                         $gs .= '|<' . intval($g) . '>';
300                         } 
301
302                         $sql = sprintf(
303                                 /*" AND ( private = 0 OR ( private in (1,2) AND wall = 1 AND ( allow_cid = '' OR allow_cid REGEXP '<%d>' ) 
304                                   AND ( deny_cid  = '' OR  NOT deny_cid REGEXP '<%d>' ) 
305                                   AND ( allow_gid = '' OR allow_gid REGEXP '%s' )
306                                   AND ( deny_gid  = '' OR NOT deny_gid REGEXP '%s'))) 
307                                 ",
308                                 intval($remote_user),
309                                 intval($remote_user),
310                                 dbesc($gs),
311                                 dbesc($gs)
312 */
313                                 " AND ( private = 0 OR ( private in (1,2) AND wall = 1
314                                   AND ( NOT (deny_cid REGEXP '<%d>' OR deny_gid REGEXP '%s')
315                                   AND ( allow_cid REGEXP '<%d>' OR allow_gid REGEXP '%s' OR ( allow_cid = '' AND allow_gid = '')))))
316                                 ",
317                                 intval($remote_user),
318                                 dbesc($gs),
319                                 intval($remote_user),
320                                 dbesc($gs)
321                         );
322                 }
323         }
324
325         return $sql;
326 }
327
328
329 /*
330  * Functions used to protect against Cross-Site Request Forgery
331  * 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.
332  * In this implementation, a security token is reusable (if the user submits a form, goes back and resubmits the form, maybe with small changes;
333  * or if the security token is used for ajax-calls that happen several times), but only valid for a certain amout of time (3hours).
334  * The "typename" seperates the security tokens of different types of forms. This could be relevant in the following case:
335  *    A security token is used to protekt a link from CSRF (e.g. the "delete this profile"-link).
336  *    If the new page contains by any chance external elements, then the used security token is exposed by the referrer.
337  *    Actually, important actions should not be triggered by Links / GET-Requests at all, but somethimes they still are,
338  *    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).
339  */ 
340 function get_form_security_token($typename = '') {
341         $a = get_app();
342         
343         $timestamp = time();
344         $sec_hash = hash('whirlpool', $a->user['guid'] . $a->user['prvkey'] . session_id() . $timestamp . $typename);
345         
346         return $timestamp . '.' . $sec_hash;
347 }
348
349 function check_form_security_token($typename = '', $formname = 'form_security_token') {
350         if (!x($_REQUEST, $formname)) return false;
351         $hash = $_REQUEST[$formname];
352         
353         $max_livetime = 10800; // 3 hours
354         
355         $a = get_app();
356         
357         $x = explode('.', $hash);
358         if (time() > (IntVal($x[0]) + $max_livetime)) return false;
359         
360         $sec_hash = hash('whirlpool', $a->user['guid'] . $a->user['prvkey'] . session_id() . $x[0] . $typename);
361         
362         return ($sec_hash == $x[1]);
363 }
364
365 function check_form_security_std_err_msg() {
366         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;
367 }
368 function check_form_security_token_redirectOnErr($err_redirect, $typename = '', $formname = 'form_security_token') {
369         if (!check_form_security_token($typename, $formname)) {
370                 $a = get_app();
371                 logger('check_form_security_token failed: user ' . $a->user['guid'] . ' - form element ' . $typename);
372                 logger('check_form_security_token failed: _REQUEST data: ' . print_r($_REQUEST, true), LOGGER_DATA);
373                 notice( check_form_security_std_err_msg() );
374                 goaway($a->get_baseurl() . $err_redirect );
375         }
376 }
377 function check_form_security_token_ForbiddenOnErr($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                 header('HTTP/1.1 403 Forbidden');
383                 killme();
384         }
385 }
386
387 // Returns an array of group id's this contact is a member of.
388 // This array will only contain group id's related to the uid of this
389 // DFRN contact. They are *not* neccessarily unique across the entire site. 
390
391
392 if(! function_exists('init_groups_visitor')) {
393 function init_groups_visitor($contact_id) {
394         $groups = array();
395         $r = q("SELECT `gid` FROM `group_member` 
396                 WHERE `contact-id` = %d ",
397                 intval($contact_id)
398         );
399         if(count($r)) {
400                 foreach($r as $rr)
401                         $groups[] = $rr['gid'];
402         }
403         return $groups;
404 }}
405