3 * @file /src/Util/Security.php
6 namespace Friendica\Util;
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;
17 * Secures that User is allow to do requests
19 class Security extends BaseObject
21 public static function can_write_wall($owner)
25 if (!local_user() && !remote_user()) {
34 if (local_user() && ($owner == 0)) {
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
44 if ($verified === 2) {
46 } elseif ($verified === 1) {
51 if (!empty($_SESSION['remote'])) {
52 foreach ($_SESSION['remote'] as $visitor) {
53 if ($visitor['uid'] == $owner) {
54 $cid = $visitor['cid'];
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",
69 intval(Contact::SHARING),
70 intval(Contact::FRIEND),
71 intval(Contact::PAGE_COMMUNITY)
74 if (DBA::isResult($r)) {
86 /// @TODO $groups should be array
87 public static function permissions_sql($owner_id, $remote_verified = false, $groups = null)
89 $local_user = local_user();
90 $remote_user = remote_user();
93 * Construct permissions
95 * default permissions - anonymous user
97 $sql = " AND allow_cid = ''
104 * Profile owner - everything is visible
106 if ($local_user && $local_user == $owner_id) {
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.
115 } elseif ($remote_user) {
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.
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);
131 if ($remote_verified) {
132 $gs = '<<>>'; // should be impossible to match
134 if (is_array($groups)) {
135 foreach ($groups as $g) {
136 $gs .= '|<' . intval($g) . '>';
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 = '') )
145 intval($remote_user),
147 intval($remote_user),
155 public static function item_permissions_sql($owner_id, $remote_verified = false, $groups = null)
157 $local_user = local_user();
158 $remote_user = remote_user();
161 * Construct permissions
163 * default permissions - anonymous user
165 $sql = " AND NOT `item`.`private`";
167 // Profile owner - everything is visible
168 if ($local_user && ($local_user == $owner_id)) {
170 } elseif ($remote_user) {
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.
178 $set = PermissionSet::get($owner_id, $remote_user, $groups);
181 $sql_set = " OR (`item`.`private` IN (1,2) AND `item`.`wall` AND `item`.`psid` IN (" . implode(',', $set) . "))";
186 $sql = " AND (NOT `item`.`private`" . $sql_set . ")";
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).
203 public static function get_form_security_token($typename = '')
208 $sec_hash = hash('whirlpool', $a->user['guid'] . $a->user['prvkey'] . session_id() . $timestamp . $typename);
210 return $timestamp . '.' . $sec_hash;
213 public static function check_form_security_token($typename = '', $formname = 'form_security_token')
217 if (!empty($_REQUEST[$formname])) {
218 /// @TODO Careful, not secured!
219 $hash = $_REQUEST[$formname];
222 if (!empty($_SERVER['HTTP_X_CSRF_TOKEN'])) {
223 /// @TODO Careful, not secured!
224 $hash = $_SERVER['HTTP_X_CSRF_TOKEN'];
231 $max_livetime = 10800; // 3 hours
235 $x = explode('.', $hash);
236 if (time() > (IntVal($x[0]) + $max_livetime)) {
240 $sec_hash = hash('whirlpool', $a->user['guid'] . $a->user['prvkey'] . session_id() . $x[0] . $typename);
242 return ($sec_hash == $x[1]);
245 private static function check_form_security_std_err_msg()
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;
250 public static function check_form_security_token_redirectOnErr($err_redirect, $typename = '', $formname = 'form_security_token')
252 if (!check_form_security_token($typename, $formname)) {
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);
261 public static function check_form_security_token_ForbiddenOnErr($typename = '', $formname = 'form_security_token')
263 if (!check_form_security_token($typename, $formname)) {
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');