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