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