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