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