]> git.mxchange.org Git - friendica.git/blob - src/Util/Security.php
remove unsed require_onces of security.php
[friendica.git] / src / Util / Security.php
1 <?php
2 /**
3  * @file /src/Util/Security.php
4  */
5
6 namespace Friendica\Util;
7
8 use Friendica\BaseObject;
9 use Friendica\Database\DBA;
10 use Friendica\Model\Contact;
11 use Friendica\Model\Group;
12 use Friendica\Core\L10n;
13 use Friendica\Model\PermissionSet;
14 use Friendica\Core\System;
15
16 /**
17  * Secures that User is allow to do requests
18  */
19 class Security extends BaseObject
20 {
21         public static function can_write_wall($owner)
22         {
23                 static $verified = 0;
24
25                 if (!local_user() && !remote_user()) {
26                         return false;
27                 }
28
29                 $uid = local_user();
30                 if ($uid == $owner) {
31                         return true;
32                 }
33
34                 if (local_user() && ($owner == 0)) {
35                         return true;
36                 }
37
38                 if (remote_user()) {
39                         // use remembered decision and avoid a DB lookup for each and every display item
40                         // DO NOT use this function if there are going to be multiple owners
41                         // We have a contact-id for an authenticated remote user, this block determines if the contact
42                         // belongs to this page owner, and has the necessary permissions to post content
43
44                         if ($verified === 2) {
45                                 return true;
46                         } elseif ($verified === 1) {
47                                 return false;
48                         } else {
49                                 $cid = 0;
50
51                                 if (!empty($_SESSION['remote'])) {
52                                         foreach ($_SESSION['remote'] as $visitor) {
53                                                 if ($visitor['uid'] == $owner) {
54                                                         $cid = $visitor['cid'];
55                                                         break;
56                                                 }
57                                         }
58                                 }
59
60                                 if (!$cid) {
61                                         return false;
62                                 }
63
64                                 $r = q("SELECT `contact`.*, `user`.`page-flags` FROM `contact` INNER JOIN `user` on `user`.`uid` = `contact`.`uid`
65                                         WHERE `contact`.`uid` = %d AND `contact`.`id` = %d AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
66                                         AND `user`.`blockwall` = 0 AND `readonly` = 0  AND ( `contact`.`rel` IN ( %d , %d ) OR `user`.`page-flags` = %d ) LIMIT 1",
67                                         intval($owner),
68                                         intval($cid),
69                                         intval(Contact::SHARING),
70                                         intval(Contact::FRIEND),
71                                         intval(Contact::PAGE_COMMUNITY)
72                                 );
73
74                                 if (DBA::isResult($r)) {
75                                         $verified = 2;
76                                         return true;
77                                 } else {
78                                         $verified = 1;
79                                 }
80                         }
81                 }
82
83                 return false;
84         }
85
86         /// @TODO $groups should be array
87         public static function permissions_sql($owner_id, $remote_verified = false, $groups = null)
88         {
89                 $local_user = local_user();
90                 $remote_user = remote_user();
91
92                 /**
93                  * Construct permissions
94                  *
95                  * default permissions - anonymous user
96                  */
97                 $sql = " AND allow_cid = ''
98                                  AND allow_gid = ''
99                                  AND deny_cid  = ''
100                                  AND deny_gid  = ''
101                 ";
102
103                 /**
104                  * Profile owner - everything is visible
105                  */
106                 if ($local_user && $local_user == $owner_id) {
107                         $sql = '';
108                 /**
109                  * Authenticated visitor. Unless pre-verified,
110                  * check that the contact belongs to this $owner_id
111                  * and load the groups the visitor belongs to.
112                  * If pre-verified, the caller is expected to have already
113                  * done this and passed the groups into this function.
114                  */
115                 } elseif ($remote_user) {
116                         /*
117                          * Authenticated visitor. Unless pre-verified,
118                          * check that the contact belongs to this $owner_id
119                          * and load the groups the visitor belongs to.
120                          * If pre-verified, the caller is expected to have already
121                          * done this and passed the groups into this function.
122                          */
123
124                         if (!$remote_verified) {
125                                 if (DBA::exists('contact', ['id' => $remote_user, 'uid' => $owner_id, 'blocked' => false])) {
126                                         $remote_verified = true;
127                                         $groups = Group::getIdsByContactId($remote_user);
128                                 }
129                         }
130
131                         if ($remote_verified) {
132                                 $gs = '<<>>'; // should be impossible to match
133
134                                 if (is_array($groups)) {
135                                         foreach ($groups as $g) {
136                                                 $gs .= '|<' . intval($g) . '>';
137                                         }
138                                 }
139
140                                 $sql = sprintf(
141                                         " AND ( NOT (deny_cid REGEXP '<%d>' OR deny_gid REGEXP '%s')
142                                           AND ( allow_cid REGEXP '<%d>' OR allow_gid REGEXP '%s' OR ( allow_cid = '' AND allow_gid = '') )
143                                           )
144                                         ",
145                                         intval($remote_user),
146                                         DBA::escape($gs),
147                                         intval($remote_user),
148                                         DBA::escape($gs)
149                                 );
150                         }
151                 }
152                 return $sql;
153         }
154
155         public static function item_permissions_sql($owner_id, $remote_verified = false, $groups = null)
156         {
157                 $local_user = local_user();
158                 $remote_user = remote_user();
159
160                 /*
161                  * Construct permissions
162                  *
163                  * default permissions - anonymous user
164                  */
165                 $sql = " AND NOT `item`.`private`";
166
167                 // Profile owner - everything is visible
168                 if ($local_user && ($local_user == $owner_id)) {
169                         $sql = '';
170                 } elseif ($remote_user) {
171                         /*
172                          * Authenticated visitor. Unless pre-verified,
173                          * check that the contact belongs to this $owner_id
174                          * and load the groups the visitor belongs to.
175                          * If pre-verified, the caller is expected to have already
176                          * done this and passed the groups into this function.
177                          */
178                         $set = PermissionSet::get($owner_id, $remote_user, $groups);
179
180                         if (!empty($set)) {
181                                 $sql_set = " OR (`item`.`private` IN (1,2) AND `item`.`wall` AND `item`.`psid` IN (" . implode(',', $set) . "))";
182                         } else {
183                                 $sql_set = '';
184                         }
185
186                         $sql = " AND (NOT `item`.`private`" . $sql_set . ")";
187                 }
188
189                 return $sql;
190         }
191
192         /*
193          * Functions used to protect against Cross-Site Request Forgery
194          * 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.
195          * In this implementation, a security token is reusable (if the user submits a form, goes back and resubmits the form, maybe with small changes;
196          * or if the security token is used for ajax-calls that happen several times), but only valid for a certain amout of time (3hours).
197          * The "typename" seperates the security tokens of different types of forms. This could be relevant in the following case:
198          *    A security token is used to protekt a link from CSRF (e.g. the "delete this profile"-link).
199          *    If the new page contains by any chance external elements, then the used security token is exposed by the referrer.
200          *    Actually, important actions should not be triggered by Links / GET-Requests at all, but somethimes they still are,
201          *    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).
202          */
203         public static function get_form_security_token($typename = '')
204         {
205                 $a = get_app();
206
207                 $timestamp = time();
208                 $sec_hash = hash('whirlpool', $a->user['guid'] . $a->user['prvkey'] . session_id() . $timestamp . $typename);
209
210                 return $timestamp . '.' . $sec_hash;
211         }
212
213         public static function check_form_security_token($typename = '', $formname = 'form_security_token')
214         {
215                 $hash = null;
216
217                 if (!empty($_REQUEST[$formname])) {
218                         /// @TODO Careful, not secured!
219                         $hash = $_REQUEST[$formname];
220                 }
221
222                 if (!empty($_SERVER['HTTP_X_CSRF_TOKEN'])) {
223                         /// @TODO Careful, not secured!
224                         $hash = $_SERVER['HTTP_X_CSRF_TOKEN'];
225                 }
226
227                 if (empty($hash)) {
228                         return false;
229                 }
230
231                 $max_livetime = 10800; // 3 hours
232
233                 $a = get_app();
234
235                 $x = explode('.', $hash);
236                 if (time() > (IntVal($x[0]) + $max_livetime)) {
237                         return false;
238                 }
239
240                 $sec_hash = hash('whirlpool', $a->user['guid'] . $a->user['prvkey'] . session_id() . $x[0] . $typename);
241
242                 return ($sec_hash == $x[1]);
243         }
244         
245         private static function check_form_security_std_err_msg()
246         {
247                 return L10n::t("The form security token was not correct. This probably happened because the form has been opened for too long \x28>3 hours\x29 before submitting it.") . EOL;
248         }
249
250         public static function check_form_security_token_redirectOnErr($err_redirect, $typename = '', $formname = 'form_security_token')
251         {
252                 if (!check_form_security_token($typename, $formname)) {
253                         $a = get_app();
254                         logger('check_form_security_token failed: user ' . $a->user['guid'] . ' - form element ' . $typename);
255                         logger('check_form_security_token failed: _REQUEST data: ' . print_r($_REQUEST, true), LOGGER_DATA);
256                         notice(check_form_security_std_err_msg());
257                         goaway(System::baseUrl() . $err_redirect);
258                 }
259         }
260
261         public static function check_form_security_token_ForbiddenOnErr($typename = '', $formname = 'form_security_token')
262         {
263                 if (!check_form_security_token($typename, $formname)) {
264                         $a = get_app();
265                         logger('check_form_security_token failed: user ' . $a->user['guid'] . ' - form element ' . $typename);
266                         logger('check_form_security_token failed: _REQUEST data: ' . print_r($_REQUEST, true), LOGGER_DATA);
267                         header('HTTP/1.1 403 Forbidden');
268                         killme();
269                 }
270         }
271 }
272
273 ?>