Merge pull request #22056 from eileenmcnaughton/context
[civicrm-core.git] / CRM / Core / IDS.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17 class CRM_Core_IDS {
18
19 /**
20 * Define the threshold for the ids reactions.
21 * @var array
22 */
23 private $threshold = [
24 'log' => 25,
25 'warn' => 50,
26 'kick' => 75,
27 ];
28
29 /**
30 * @var string
31 */
32 private $path;
33
34 /**
35 * Check function.
36 *
37 * This function includes the IDS vendor parts and runs the
38 * detection routines on the request array.
39 *
40 * @param array $route
41 *
42 * @return bool
43 */
44 public function check($route) {
45 if (CRM_Core_Permission::check('skip IDS check')) {
46 return NULL;
47 }
48
49 // lets bypass a few civicrm urls from this check
50 $skip = ['civicrm/admin/setting/updateConfigBackend', 'civicrm/admin/messageTemplates', 'civicrm/ajax/api4'];
51 CRM_Utils_Hook::idsException($skip);
52 $this->path = $route['path'];
53 if (in_array($this->path, $skip)) {
54 return NULL;
55 }
56
57 $init = self::create(self::createRouteConfig($route));
58
59 // Add request url and user agent.
60 $_REQUEST['IDS_request_uri'] = $_SERVER['REQUEST_URI'];
61 if (isset($_SERVER['HTTP_USER_AGENT'])) {
62 $_REQUEST['IDS_user_agent'] = $_SERVER['HTTP_USER_AGENT'];
63 }
64
65 require_once 'IDS/Monitor.php';
66 $ids = new \IDS_Monitor($_REQUEST, $init);
67
68 $result = $ids->run();
69 if (!$result->isEmpty()) {
70 $this->react($result);
71 }
72
73 return TRUE;
74 }
75
76 /**
77 * Create a new PHPIDS configuration object.
78 *
79 * @param array $config
80 * PHPIDS configuration array (per INI format).
81 * @return \IDS_Init
82 */
83 protected static function create($config) {
84 require_once 'IDS/Init.php';
85 $init = \IDS_Init::init(NULL);
86 $init->setConfig($config, TRUE);
87
88 // Cleanup
89 $reflection = new \ReflectionProperty('IDS_Init', 'instances');
90 $reflection->setAccessible(TRUE);
91 $value = $reflection->getValue(NULL);
92 unset($value[NULL]);
93 $reflection->setValue(NULL, $value);
94
95 return $init;
96 }
97
98 /**
99 * Create conservative, minimalist IDS configuration.
100 *
101 * @return array
102 */
103 public static function createBaseConfig() {
104 $config = \CRM_Core_Config::singleton();
105 $tmpDir = empty($config->uploadDir) ? Civi::paths()->getVariable('civicrm.compile', 'path') : $config->uploadDir;
106 $pkgs = Civi::paths()->getVariable('civicrm.packages', 'path');
107
108 return [
109 'General' => [
110 'filter_type' => 'xml',
111 'filter_path' => "{$pkgs}/IDS/default_filter.xml",
112 'tmp_path' => $tmpDir,
113 // Ignored, uses autoloader
114 'HTML_Purifier_Path' => TRUE,
115 'HTML_Purifier_Cache' => $tmpDir,
116 'scan_keys' => '',
117 'exceptions' => ['__utmz', '__utmc'],
118 ],
119 ];
120 }
121
122 /**
123 * Create the standard, general-purpose IDS configuration used by many pages.
124 *
125 * @return array
126 */
127 public static function createStandardConfig() {
128 $excs = [
129 'widget_code',
130 'html_message',
131 'text_message',
132 'body_html',
133 'msg_html',
134 'msg_text',
135 'msg_subject',
136 'description',
137 'intro',
138 'thankyou_text',
139 'intro_text',
140 'body_text',
141 'footer_text',
142 'thankyou_text',
143 'tf_thankyou_text',
144 'thankyou_footer',
145 'thankyou_footer_text',
146 'new_text',
147 'renewal_text',
148 'help_pre',
149 'help_post',
150 'confirm_title',
151 'confirm_text',
152 'confirm_footer_text',
153 'confirm_email_text',
154 'report_header',
155 'report_footer',
156 'data',
157 'json',
158 'instructions',
159 'suggested_message',
160 'page_text',
161 'details',
162 ];
163
164 $result = self::createBaseConfig();
165
166 $result['General']['exceptions'] = array_merge(
167 $result['General']['exceptions'],
168 $excs
169 );
170
171 return $result;
172 }
173
174 /**
175 * @param array $route
176 * @return array
177 */
178 public static function createRouteConfig($route) {
179 $config = \CRM_Core_IDS::createStandardConfig();
180 foreach (['json', 'html', 'exceptions'] as $section) {
181 if (isset($route['ids_arguments'][$section])) {
182 if (!isset($config['General'][$section])) {
183 $config['General'][$section] = [];
184 }
185 foreach ($route['ids_arguments'][$section] as $v) {
186 $config['General'][$section][] = $v;
187 }
188 $config['General'][$section] = array_unique($config['General'][$section]);
189 }
190 }
191 return $config;
192 }
193
194 /**
195 * This function reacts on the values in the incoming results array.
196 *
197 * Depending on the impact value certain actions are
198 * performed.
199 *
200 * @param IDS_Report $result
201 *
202 * @return bool
203 */
204 public function react(IDS_Report $result) {
205
206 $impact = $result->getImpact();
207 if ($impact >= $this->threshold['kick']) {
208 $this->log($result, 3, $impact);
209 $this->kick();
210 return TRUE;
211 }
212 elseif ($impact >= $this->threshold['warn']) {
213 $this->log($result, 2, $impact);
214 $this->warn($result);
215 return TRUE;
216 }
217 elseif ($impact >= $this->threshold['log']) {
218 $this->log($result, 0, $impact);
219 return TRUE;
220 }
221 else {
222 return TRUE;
223 }
224 }
225
226 /**
227 * This function writes an entry about the intrusion to the database.
228 *
229 * @param array $result
230 * @param int $reaction
231 *
232 * @return bool
233 */
234 private function log($result, $reaction = 0) {
235 // Include X_FORWARD_FOR ip address if set as per IDS patten.
236 $ip = $_SERVER['REMOTE_ADDR'] . (isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? ' (' . $_SERVER['HTTP_X_FORWARDED_FOR'] . ')' : '');
237
238 $data = [];
239 $session = CRM_Core_Session::singleton();
240 foreach ($result as $event) {
241 $data[] = [
242 'name' => $event->getName(),
243 'value' => stripslashes($event->getValue()),
244 'page' => $_SERVER['REQUEST_URI'],
245 'userid' => $session->get('userID'),
246 'session' => session_id() ? session_id() : '0',
247 'ip' => $ip,
248 'reaction' => $reaction,
249 'impact' => $result->getImpact(),
250 ];
251 }
252
253 CRM_Core_Error::debug_var('IDS Detector Details', $data);
254 return TRUE;
255 }
256
257 /**
258 * Warn about IDS.
259 *
260 * @param array $result
261 *
262 * @return array
263 */
264 private function warn($result) {
265 return $result;
266 }
267
268 /**
269 * Create an error that prevents the user from continuing.
270 *
271 * @throws \Exception
272 */
273 private function kick() {
274 $session = CRM_Core_Session::singleton();
275 $session->reset(2);
276
277 $msg = ts('There is a validation error with your HTML input. Your activity is a bit suspicious, hence aborting');
278
279 if (in_array(
280 $this->path,
281 ["civicrm/ajax/rest", "civicrm/api/json"]
282 )) {
283 require_once "api/v3/utils.php";
284 $error = civicrm_api3_create_error(
285 $msg,
286 [
287 'IP' => $_SERVER['REMOTE_ADDR'],
288 'error_code' => 'IDS_KICK',
289 'level' => 'security',
290 'referer' => $_SERVER['HTTP_REFERER'],
291 'reason' => 'XSS suspected',
292 ]
293 );
294 CRM_Utils_JSON::output($error);
295 }
296 throw new CRM_Core_Exception($msg);
297 }
298
299 }