Monitor.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. <?php
  2. /**
  3. * PHPIDS
  4. *
  5. * Requirements: PHP5, SimpleXML
  6. *
  7. * Copyright (c) 2008 PHPIDS group (http://php-ids.org)
  8. *
  9. * PHPIDS is free software; you can redistribute it and/or modify
  10. * it under the terms of the GNU Lesser General Public License as published by
  11. * the Free Software Foundation, version 3 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * PHPIDS is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU Lesser General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU Lesser General Public License
  20. * along with PHPIDS. If not, see <http://www.gnu.org/licenses/>.
  21. *
  22. * PHP version 5.1.6+
  23. *
  24. * @category Security
  25. * @package PHPIDS
  26. * @author Mario Heiderich <mario.heiderich@gmail.com>
  27. * @author Christian Matthies <ch0012@gmail.com>
  28. * @author Lars Strojny <lars@strojny.net>
  29. * @license http://www.gnu.org/licenses/lgpl.html LGPL
  30. * @link http://php-ids.org/
  31. */
  32. /**
  33. * Monitoring engine
  34. *
  35. * This class represents the core of the frameworks attack detection mechanism
  36. * and provides functions to scan incoming data for malicious appearing script
  37. * fragments.
  38. *
  39. * @category Security
  40. * @package PHPIDS
  41. * @author Christian Matthies <ch0012@gmail.com>
  42. * @author Mario Heiderich <mario.heiderich@gmail.com>
  43. * @author Lars Strojny <lars@strojny.net>
  44. * @copyright 2007-2009 The PHPIDS Group
  45. * @license http://www.gnu.org/licenses/lgpl.html LGPL
  46. * @version Release: $Id:Monitor.php 949 2008-06-28 01:26:03Z christ1an $
  47. * @link http://php-ids.org/
  48. */
  49. class IDS_Monitor
  50. {
  51. /**
  52. * Tags to define what to search for
  53. *
  54. * Accepted values are xss, csrf, sqli, dt, id, lfi, rfe, spam, dos
  55. *
  56. * @var array
  57. */
  58. private $tags = null;
  59. /**
  60. * Request array
  61. *
  62. * Array containing raw data to search in
  63. *
  64. * @var array
  65. */
  66. private $request = null;
  67. /**
  68. * Container for filter rules
  69. *
  70. * Holds an instance of IDS_Filter_Storage
  71. *
  72. * @var object
  73. */
  74. private $storage = null;
  75. /**
  76. * Results
  77. *
  78. * Holds an instance of IDS_Report which itself provides an API to
  79. * access the detected results
  80. *
  81. * @var object
  82. */
  83. private $report = null;
  84. /**
  85. * Scan keys switch
  86. *
  87. * Enabling this property will cause the monitor to scan both the key and
  88. * the value of variables
  89. *
  90. * @var boolean
  91. */
  92. public $scanKeys = false;
  93. /**
  94. * Exception container
  95. *
  96. * Using this array it is possible to define variables that must not be
  97. * scanned. Per default, utmz google analytics parameters are permitted.
  98. *
  99. * @var array
  100. */
  101. private $exceptions = array();
  102. /**
  103. * Html container
  104. *
  105. * Using this array it is possible to define variables that legally
  106. * contain html and have to be prepared before hitting the rules to
  107. * avoid too many false alerts
  108. *
  109. * @var array
  110. */
  111. private $html = array();
  112. /**
  113. * JSON container
  114. *
  115. * Using this array it is possible to define variables that contain
  116. * JSON data - and should be treated as such
  117. *
  118. * @var array
  119. */
  120. private $json = array();
  121. /**
  122. * Holds HTMLPurifier object
  123. *
  124. * @var object
  125. */
  126. private $htmlpurifier = NULL;
  127. /**
  128. * Path to HTMLPurifier source
  129. *
  130. * This path might be changed in case one wishes to make use of a
  131. * different HTMLPurifier source file e.g. if already used in the
  132. * application PHPIDS is protecting
  133. *
  134. * @var string
  135. */
  136. private $pathToHTMLPurifier = '';
  137. /**
  138. * HTMLPurifier cache directory
  139. *
  140. * @var string
  141. */
  142. private $HTMLPurifierCache = '';
  143. /**
  144. * This property holds the tmp JSON string from the
  145. * _jsonDecodeValues() callback
  146. *
  147. * @var string
  148. */
  149. private $tmpJsonString = '';
  150. /**
  151. * Constructor
  152. *
  153. * @param array $request array to scan
  154. * @param object $init instance of IDS_Init
  155. * @param array $tags list of tags to which filters should be applied
  156. *
  157. * @return void
  158. */
  159. public function __construct(array $request, IDS_Init $init, array $tags = null)
  160. {
  161. $version = isset($init->config['General']['min_php_version'])
  162. ? $init->config['General']['min_php_version'] : '5.1.6';
  163. if (version_compare(PHP_VERSION, $version, '<')) {
  164. throw new Exception(
  165. 'PHP version has to be equal or higher than ' . $version . ' or
  166. PHP version couldn\'t be determined'
  167. );
  168. }
  169. if (!empty($request)) {
  170. $this->storage = new IDS_Filter_Storage($init);
  171. $this->request = $request;
  172. $this->tags = $tags;
  173. $this->scanKeys = $init->config['General']['scan_keys'];
  174. $this->exceptions = isset($init->config['General']['exceptions'])
  175. ? $init->config['General']['exceptions'] : false;
  176. $this->html = isset($init->config['General']['html'])
  177. ? $init->config['General']['html'] : false;
  178. $this->json = isset($init->config['General']['json'])
  179. ? $init->config['General']['json'] : false;
  180. if(isset($init->config['General']['HTML_Purifier_Path'])
  181. && isset($init->config['General']['HTML_Purifier_Cache'])) {
  182. $this->pathToHTMLPurifier =
  183. $init->config['General']['HTML_Purifier_Path'];
  184. $this->HTMLPurifierCache = $init->getBasePath()
  185. . $init->config['General']['HTML_Purifier_Cache'];
  186. }
  187. }
  188. if (!is_writeable($init->getBasePath()
  189. . $init->config['General']['tmp_path'])) {
  190. throw new Exception(
  191. 'Please make sure the ' .
  192. htmlspecialchars($init->getBasePath() .
  193. $init->config['General']['tmp_path'], ENT_QUOTES, 'UTF-8') .
  194. ' folder is writable'
  195. );
  196. }
  197. include_once 'IDS/Report.php';
  198. $this->report = new IDS_Report;
  199. }
  200. /**
  201. * Starts the scan mechanism
  202. *
  203. * @return object IDS_Report
  204. */
  205. public function run()
  206. {
  207. if (!empty($this->request)) {
  208. foreach ($this->request as $key => $value) {
  209. $this->_iterate($key, $value);
  210. }
  211. }
  212. return $this->getReport();
  213. }
  214. /**
  215. * Iterates through given data and delegates it to IDS_Monitor::_detect() in
  216. * order to check for malicious appearing fragments
  217. *
  218. * @param mixed $key the former array key
  219. * @param mixed $value the former array value
  220. *
  221. * @return void
  222. */
  223. private function _iterate($key, $value)
  224. {
  225. if (!is_array($value)) {
  226. if (is_string($value)) {
  227. if ($filter = $this->_detect($key, $value)) {
  228. include_once 'IDS/Event.php';
  229. $this->report->addEvent(
  230. new IDS_Event(
  231. $key,
  232. $value,
  233. $filter
  234. )
  235. );
  236. }
  237. }
  238. } else {
  239. foreach ($value as $subKey => $subValue) {
  240. $this->_iterate($key . '.' . $subKey, $subValue);
  241. }
  242. }
  243. }
  244. /**
  245. * Checks whether given value matches any of the supplied filter patterns
  246. *
  247. * @param mixed $key the key of the value to scan
  248. * @param mixed $value the value to scan
  249. *
  250. * @return bool|array false or array of filter(s) that matched the value
  251. */
  252. private function _detect($key, $value)
  253. {
  254. // define the pre-filter
  255. $prefilter = '/[^\w\s\/@!?\.]+|(?:\.\/)|(?:@@\w+)/';
  256. // to increase performance, only start detection if value
  257. // isn't alphanumeric
  258. if (!$this->scanKeys
  259. && (!$value || !preg_match($prefilter, $value))) {
  260. return false;
  261. } elseif($this->scanKeys) {
  262. if((!$key || !preg_match($prefilter, $key))
  263. && (!$value || !preg_match($prefilter, $value))) {
  264. return false;
  265. }
  266. }
  267. // check if this field is part of the exceptions
  268. if (is_array($this->exceptions)) {
  269. foreach($this->exceptions as $exception) {
  270. $matches = array();
  271. if(preg_match('/(\/.*\/[^eE]*)$/', $exception, $matches)) {
  272. if(isset($matches[1]) && preg_match($matches[1], $key)) {
  273. return false;
  274. }
  275. } else {
  276. if($exception === $key) {
  277. return false;
  278. }
  279. }
  280. }
  281. }
  282. // check for magic quotes and remove them if necessary
  283. if (function_exists('get_magic_quotes_gpc')
  284. && get_magic_quotes_gpc()) {
  285. $value = stripslashes($value);
  286. }
  287. // if html monitoring is enabled for this field - then do it!
  288. if (is_array($this->html) && in_array($key, $this->html, true)) {
  289. list($key, $value) = $this->_purifyValues($key, $value);
  290. }
  291. // check if json monitoring is enabled for this field
  292. if (is_array($this->json) && in_array($key, $this->json, true)) {
  293. list($key, $value) = $this->_jsonDecodeValues($key, $value);
  294. }
  295. // use the converter
  296. include_once 'IDS/Converter.php';
  297. $value = IDS_Converter::runAll($value);
  298. $value = IDS_Converter::runCentrifuge($value, $this);
  299. // scan keys if activated via config
  300. $key = $this->scanKeys ? IDS_Converter::runAll($key)
  301. : $key;
  302. $key = $this->scanKeys ? IDS_Converter::runCentrifuge($key, $this)
  303. : $key;
  304. $filters = array();
  305. $filterSet = $this->storage->getFilterSet();
  306. foreach ($filterSet as $filter) {
  307. /*
  308. * in case we have a tag array specified the IDS will only
  309. * use those filters that are meant to detect any of the
  310. * defined tags
  311. */
  312. if (is_array($this->tags)) {
  313. if (array_intersect($this->tags, $filter->getTags())) {
  314. if ($this->_match($key, $value, $filter)) {
  315. $filters[] = $filter;
  316. }
  317. }
  318. } else {
  319. if ($this->_match($key, $value, $filter)) {
  320. $filters[] = $filter;
  321. }
  322. }
  323. }
  324. return empty($filters) ? false : $filters;
  325. }
  326. /**
  327. * Purifies given key and value variables using HTMLPurifier
  328. *
  329. * This function is needed whenever there is variables for which HTML
  330. * might be allowed like e.g. WYSIWYG post bodies. It will dectect malicious
  331. * code fragments and leaves harmless parts untouched.
  332. *
  333. * @param mixed $key
  334. * @param mixed $value
  335. * @since 0.5
  336. * @throws Exception
  337. *
  338. * @return array
  339. */
  340. private function _purifyValues($key, $value)
  341. {
  342. /*
  343. * Perform a pre-check if string is valid for purification
  344. */
  345. if(!$this->_purifierPreCheck($key, $value)) {
  346. return array($key, $value);
  347. }
  348. include_once $this->pathToHTMLPurifier;
  349. if (!is_writeable($this->HTMLPurifierCache)) {
  350. throw new Exception(
  351. $this->HTMLPurifierCache . ' must be writeable');
  352. }
  353. if (class_exists('HTMLPurifier')) {
  354. $config = HTMLPurifier_Config::createDefault();
  355. $config->set('Attr.EnableID', true);
  356. $config->set('Cache.SerializerPath', $this->HTMLPurifierCache);
  357. $config->set('Output.Newline', "\n");
  358. $this->htmlpurifier = new HTMLPurifier($config);
  359. } else {
  360. throw new Exception(
  361. 'HTMLPurifier class could not be found - ' .
  362. 'make sure the purifier files are valid and' .
  363. ' the path is correct'
  364. );
  365. }
  366. $value = preg_replace('/[\x0b-\x0c]/', ' ', $value);
  367. $key = preg_replace('/[\x0b-\x0c]/', ' ', $key);
  368. $purified_value = $this->htmlpurifier->purify($value);
  369. $purified_key = $this->htmlpurifier->purify($key);
  370. $redux_value = strip_tags($value);
  371. $redux_key = strip_tags($key);
  372. if ($value != $purified_value || $redux_value) {
  373. $value = $this->_diff($value, $purified_value, $redux_value);
  374. } else {
  375. $value = NULL;
  376. }
  377. if ($key != $purified_key) {
  378. $key = $this->_diff($key, $purified_key, $redux_key);
  379. } else {
  380. $key = NULL;
  381. }
  382. return array($key, $value);
  383. }
  384. /**
  385. * This method makes sure no dangerous markup can be smuggled in
  386. * attributes when HTML mode is switched on.
  387. *
  388. * If the precheck considers the string too dangerous for
  389. * purification false is being returned.
  390. *
  391. * @param mixed $key
  392. * @param mixed $value
  393. * @since 0.6
  394. *
  395. * @return boolean
  396. */
  397. private function _purifierPreCheck($key = '', $value = '')
  398. {
  399. /*
  400. * Remove control chars before pre-check
  401. */
  402. $tmp_value = preg_replace('/\p{C}/', null, $value);
  403. $tmp_key = preg_replace('/\p{C}/', null, $key);
  404. $precheck = '/<(script|iframe|applet|object)\W/i';
  405. if(preg_match($precheck, $tmp_key)
  406. || preg_match($precheck, $tmp_value)) {
  407. return false;
  408. }
  409. return true;
  410. }
  411. /**
  412. * This method calculates the difference between the original
  413. * and the purified markup strings.
  414. *
  415. * @param string $original the original markup
  416. * @param string $purified the purified markup
  417. * @param string $redux the string without html
  418. * @since 0.5
  419. *
  420. * @return string the difference between the strings
  421. */
  422. private function _diff($original, $purified, $redux)
  423. {
  424. /*
  425. * deal with over-sensitive alt-attribute addition of the purifier
  426. * and other common html formatting problems
  427. */
  428. $purified = preg_replace('/\s+alt="[^"]*"/m', null, $purified);
  429. $purified = preg_replace('/=?\s*"\s*"/m', null, $purified);
  430. $original = preg_replace('/\s+alt="[^"]*"/m', null, $original);
  431. $original = preg_replace('/=?\s*"\s*"/m', null, $original);
  432. $original = preg_replace('/style\s*=\s*([^"])/m', 'style = "$1', $original);
  433. # strip whitespace between tags
  434. $original = trim(preg_replace('/>\s*</m', '><', $original));
  435. $purified = trim(preg_replace('/>\s*</m', '><', $purified));
  436. $original = preg_replace(
  437. '/(=\s*(["\'`])[^>"\'`]*>[^>"\'`]*["\'`])/m', 'alt$1', $original
  438. );
  439. // no purified html is left
  440. if (!$purified) {
  441. return $original;
  442. }
  443. // calculate the diff length
  444. $length = mb_strlen($original) - mb_strlen($purified);
  445. /*
  446. * Calculate the difference between the original html input
  447. * and the purified string.
  448. */
  449. $array_1 = str_split(html_entity_decode(urldecode($original)));
  450. $array_2 = str_split($purified);
  451. // create an array containing the single character differences
  452. $differences = array();
  453. foreach ($array_1 as $key => $value) {
  454. if (!isset($array_2[$key]) || $value !== $array_2[$key]) {
  455. $differences[] = $value;
  456. }
  457. }
  458. // return the diff - ready to hit the converter and the rules
  459. if(intval($length) <= 10) {
  460. $diff = trim(join('', $differences));
  461. } else {
  462. $diff = substr(trim(join('', $differences)), 0, strlen($original));
  463. }
  464. // clean up spaces between tag delimiters
  465. $diff = preg_replace('/>\s*</m', '><', $diff);
  466. // correct over-sensitively stripped bad html elements
  467. $diff = preg_replace('/[^<](iframe|script|embed|object' .
  468. '|applet|base|img|style)/m', '<$1', $diff);
  469. if (strlen($diff) < 4) {
  470. return null;
  471. }
  472. return $diff . $redux;
  473. }
  474. /**
  475. * This method prepares incoming JSON data for the PHPIDS detection
  476. * process. It utilizes _jsonConcatContents() as callback and returns a
  477. * string version of the JSON data structures.
  478. *
  479. * @param mixed $key
  480. * @param mixed $value
  481. * @since 0.5.3
  482. *
  483. * @return array
  484. */
  485. private function _jsonDecodeValues($key, $value) {
  486. $tmp_key = json_decode($key);
  487. $tmp_value = json_decode($value);
  488. if($tmp_value && is_array($tmp_value) || is_object($tmp_value)) {
  489. array_walk_recursive($tmp_value, array($this, '_jsonConcatContents'));
  490. $value = $this->tmpJsonString;
  491. } else {
  492. $this->tmpJsonString .= " " . $tmp_value . "\n";
  493. }
  494. if($tmp_key && is_array($tmp_key) || is_object($tmp_key)) {
  495. array_walk_recursive($tmp_key, array($this, '_jsonConcatContents'));
  496. $key = $this->tmpJsonString;
  497. } else {
  498. $this->tmpJsonString .= " " . $tmp_key . "\n";
  499. }
  500. return array($key, $value);
  501. }
  502. /**
  503. * This is the callback used in _jsonDecodeValues(). The method
  504. * concatenates key and value and stores them in $this->tmpJsonString.
  505. *
  506. * @param mixed $key
  507. * @param mixed $value
  508. * @since 0.5.3
  509. *
  510. * @return void
  511. */
  512. private function _jsonConcatContents($key, $value) {
  513. if(is_string($key) && is_string($value)) {
  514. $this->tmpJsonString .= $key . " " . $value . "\n";
  515. } else {
  516. $this->_jsonDecodeValues(
  517. json_encode($key), json_encode($value)
  518. );
  519. }
  520. }
  521. /**
  522. * Matches given value and/or key against given filter
  523. *
  524. * @param mixed $key the key to optionally scan
  525. * @param mixed $value the value to scan
  526. * @param object $filter the filter object
  527. *
  528. * @return boolean
  529. */
  530. private function _match($key, $value, $filter)
  531. {
  532. if ($this->scanKeys) {
  533. if ($filter->match($key)) {
  534. return true;
  535. }
  536. }
  537. if ($filter->match($value)) {
  538. return true;
  539. }
  540. return false;
  541. }
  542. /**
  543. * Sets exception array
  544. *
  545. * @param mixed $exceptions the thrown exceptions
  546. *
  547. * @return void
  548. */
  549. public function setExceptions($exceptions)
  550. {
  551. if (!is_array($exceptions)) {
  552. $exceptions = array($exceptions);
  553. }
  554. $this->exceptions = $exceptions;
  555. }
  556. /**
  557. * Returns exception array
  558. *
  559. * @return array
  560. */
  561. public function getExceptions()
  562. {
  563. return $this->exceptions;
  564. }
  565. /**
  566. * Sets html array
  567. *
  568. * @param mixed $html the fields containing html
  569. * @since 0.5
  570. *
  571. * @return void
  572. */
  573. public function setHtml($html)
  574. {
  575. if (!is_array($html)) {
  576. $html = array($html);
  577. }
  578. $this->html = $html;
  579. }
  580. /**
  581. * Adds a value to the html array
  582. *
  583. * @since 0.5
  584. *
  585. * @return void
  586. */
  587. public function addHtml($value)
  588. {
  589. $this->html[] = $value;
  590. }
  591. /**
  592. * Returns html array
  593. *
  594. * @since 0.5
  595. *
  596. * @return array the fields that contain allowed html
  597. */
  598. public function getHtml()
  599. {
  600. return $this->html;
  601. }
  602. /**
  603. * Sets json array
  604. *
  605. * @param mixed $json the fields containing json
  606. * @since 0.5.3
  607. *
  608. * @return void
  609. */
  610. public function setJson($json)
  611. {
  612. if (!is_array($json)) {
  613. $json = array($json);
  614. }
  615. $this->json = $json;
  616. }
  617. /**
  618. * Adds a value to the json array
  619. *
  620. * @param string the value containing JSON data
  621. * @since 0.5.3
  622. *
  623. * @return void
  624. */
  625. public function addJson($value)
  626. {
  627. $this->json[] = $value;
  628. }
  629. /**
  630. * Returns json array
  631. *
  632. * @since 0.5.3
  633. *
  634. * @return array the fields that contain json
  635. */
  636. public function getJson()
  637. {
  638. return $this->json;
  639. }
  640. /**
  641. * Returns storage container
  642. *
  643. * @return array
  644. */
  645. public function getStorage()
  646. {
  647. return $this->storage;
  648. }
  649. /**
  650. * Returns report object providing various functions to work with
  651. * detected results. Also the centrifuge data is being set as property
  652. * of the report object.
  653. *
  654. * @return object IDS_Report
  655. */
  656. public function getReport()
  657. {
  658. if (isset($this->centrifuge) && $this->centrifuge) {
  659. $this->report->setCentrifuge($this->centrifuge);
  660. }
  661. return $this->report;
  662. }
  663. }
  664. /**
  665. * Local variables:
  666. * tab-width: 4
  667. * c-basic-offset: 4
  668. * End:
  669. * vim600: sw=4 ts=4 expandtab
  670. */