Security.php 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. <?php
  2. /**
  3. * @package Grav\Common
  4. *
  5. * @copyright Copyright (c) 2015 - 2022 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Common;
  9. use Exception;
  10. use Grav\Common\Config\Config;
  11. use Grav\Common\Filesystem\Folder;
  12. use Grav\Common\Page\Pages;
  13. use Rhukster\DomSanitizer\DOMSanitizer;
  14. use function chr;
  15. use function count;
  16. use function is_array;
  17. use function is_string;
  18. /**
  19. * Class Security
  20. * @package Grav\Common
  21. */
  22. class Security
  23. {
  24. /**
  25. * @param string $filepath
  26. * @param array|null $options
  27. * @return string|null
  28. */
  29. public static function detectXssFromSvgFile(string $filepath, array $options = null): ?string
  30. {
  31. if (file_exists($filepath) && Grav::instance()['config']->get('security.sanitize_svg')) {
  32. $content = file_get_contents($filepath);
  33. return static::detectXss($content, $options);
  34. }
  35. return null;
  36. }
  37. /**
  38. * Sanitize SVG string for XSS code
  39. *
  40. * @param string $svg
  41. * @return string
  42. */
  43. public static function sanitizeSvgString(string $svg): string
  44. {
  45. if (Grav::instance()['config']->get('security.sanitize_svg')) {
  46. $sanitizer = new DOMSanitizer(DOMSanitizer::SVG);
  47. $sanitized = $sanitizer->sanitize($svg);
  48. if (is_string($sanitized)) {
  49. $svg = $sanitized;
  50. }
  51. }
  52. return $svg;
  53. }
  54. /**
  55. * Sanitize SVG for XSS code
  56. *
  57. * @param string $file
  58. * @return void
  59. */
  60. public static function sanitizeSVG(string $file): void
  61. {
  62. if (file_exists($file) && Grav::instance()['config']->get('security.sanitize_svg')) {
  63. $sanitizer = new DOMSanitizer(DOMSanitizer::SVG);
  64. $original_svg = file_get_contents($file);
  65. $clean_svg = $sanitizer->sanitize($original_svg);
  66. // Quarantine bad SVG files and throw exception
  67. if ($clean_svg !== false ) {
  68. file_put_contents($file, $clean_svg);
  69. } else {
  70. $quarantine_file = Utils::basename($file);
  71. $quarantine_dir = 'log://quarantine';
  72. Folder::mkdir($quarantine_dir);
  73. file_put_contents("$quarantine_dir/$quarantine_file", $original_svg);
  74. unlink($file);
  75. throw new Exception('SVG could not be sanitized, it has been moved to the logs/quarantine folder');
  76. }
  77. }
  78. }
  79. /**
  80. * Detect XSS code in Grav pages
  81. *
  82. * @param Pages $pages
  83. * @param bool $route
  84. * @param callable|null $status
  85. * @return array
  86. */
  87. public static function detectXssFromPages(Pages $pages, $route = true, callable $status = null)
  88. {
  89. $routes = $pages->getList(null, 0, true);
  90. // Remove duplicate for homepage
  91. unset($routes['/']);
  92. $list = [];
  93. // This needs Symfony 4.1 to work
  94. $status && $status([
  95. 'type' => 'count',
  96. 'steps' => count($routes),
  97. ]);
  98. foreach (array_keys($routes) as $route) {
  99. $status && $status([
  100. 'type' => 'progress',
  101. ]);
  102. try {
  103. $page = $pages->find($route);
  104. if ($page->exists()) {
  105. // call the content to load/cache it
  106. $header = (array) $page->header();
  107. $content = $page->value('content');
  108. $data = ['header' => $header, 'content' => $content];
  109. $results = static::detectXssFromArray($data);
  110. if (!empty($results)) {
  111. $list[$page->rawRoute()] = $results;
  112. }
  113. }
  114. } catch (Exception $e) {
  115. continue;
  116. }
  117. }
  118. return $list;
  119. }
  120. /**
  121. * Detect XSS in an array or strings such as $_POST or $_GET
  122. *
  123. * @param array $array Array such as $_POST or $_GET
  124. * @param array|null $options Extra options to be passed.
  125. * @param string $prefix Prefix for returned values.
  126. * @return array Returns flatten list of potentially dangerous input values, such as 'data.content'.
  127. */
  128. public static function detectXssFromArray(array $array, string $prefix = '', array $options = null)
  129. {
  130. if (null === $options) {
  131. $options = static::getXssDefaults();
  132. }
  133. $list = [[]];
  134. foreach ($array as $key => $value) {
  135. if (is_array($value)) {
  136. $list[] = static::detectXssFromArray($value, $prefix . $key . '.', $options);
  137. }
  138. if ($result = static::detectXss($value, $options)) {
  139. $list[] = [$prefix . $key => $result];
  140. }
  141. }
  142. return array_merge(...$list);
  143. }
  144. /**
  145. * Determine if string potentially has a XSS attack. This simple function does not catch all XSS and it is likely to
  146. *
  147. * return false positives because of it tags all potentially dangerous HTML tags and attributes without looking into
  148. * their content.
  149. *
  150. * @param string|null $string The string to run XSS detection logic on
  151. * @param array|null $options
  152. * @return string|null Type of XSS vector if the given `$string` may contain XSS, false otherwise.
  153. *
  154. * Copies the code from: https://github.com/symphonycms/xssfilter/blob/master/extension.driver.php#L138
  155. */
  156. public static function detectXss($string, array $options = null): ?string
  157. {
  158. // Skip any null or non string values
  159. if (null === $string || !is_string($string) || empty($string)) {
  160. return null;
  161. }
  162. if (null === $options) {
  163. $options = static::getXssDefaults();
  164. }
  165. $enabled_rules = (array)($options['enabled_rules'] ?? null);
  166. $dangerous_tags = (array)($options['dangerous_tags'] ?? null);
  167. if (!$dangerous_tags) {
  168. $enabled_rules['dangerous_tags'] = false;
  169. }
  170. $invalid_protocols = (array)($options['invalid_protocols'] ?? null);
  171. if (!$invalid_protocols) {
  172. $enabled_rules['invalid_protocols'] = false;
  173. }
  174. $enabled_rules = array_filter($enabled_rules, static function ($val) { return !empty($val); });
  175. if (!$enabled_rules) {
  176. return null;
  177. }
  178. // Keep a copy of the original string before cleaning up
  179. $orig = $string;
  180. // URL decode
  181. $string = urldecode($string);
  182. // Convert Hexadecimals
  183. $string = (string)preg_replace_callback('!(&#|\\\)[xX]([0-9a-fA-F]+);?!u', static function ($m) {
  184. return chr(hexdec($m[2]));
  185. }, $string);
  186. // Clean up entities
  187. $string = preg_replace('!(&#[0-9]+);?!u', '$1;', $string);
  188. // Decode entities
  189. $string = html_entity_decode($string, ENT_NOQUOTES | ENT_HTML5, 'UTF-8');
  190. // Strip whitespace characters
  191. $string = preg_replace('!\s!u', ' ', $string);
  192. $stripped = preg_replace('!\s!u', '', $string);
  193. // Set the patterns we'll test against
  194. $patterns = [
  195. // Match any attribute starting with "on" or xmlns
  196. 'on_events' => '#(<[^>]+[[a-z\x00-\x20\"\'\/])([\s\/]on|\sxmlns)[a-z].*=>?#iUu',
  197. // Match javascript:, livescript:, vbscript:, mocha:, feed: and data: protocols
  198. 'invalid_protocols' => '#(' . implode('|', array_map('preg_quote', $invalid_protocols, ['#'])) . ')(:|\&\#58)\S.*?#iUu',
  199. // Match -moz-bindings
  200. 'moz_binding' => '#-moz-binding[a-z\x00-\x20]*:#u',
  201. // Match style attributes
  202. 'html_inline_styles' => '#(<[^>]+[a-z\x00-\x20\"\'\/])(style=[^>]*(url\:|x\:expression).*)>?#iUu',
  203. // Match potentially dangerous tags
  204. 'dangerous_tags' => '#</*(' . implode('|', array_map('preg_quote', $dangerous_tags, ['#'])) . ')[^>]*>?#ui'
  205. ];
  206. // Iterate over rules and return label if fail
  207. foreach ($patterns as $name => $regex) {
  208. if (!empty($enabled_rules[$name])) {
  209. if (preg_match($regex, $string) || preg_match($regex, $stripped) || preg_match($regex, $orig)) {
  210. return $name;
  211. }
  212. }
  213. }
  214. return null;
  215. }
  216. public static function getXssDefaults(): array
  217. {
  218. /** @var Config $config */
  219. $config = Grav::instance()['config'];
  220. return [
  221. 'enabled_rules' => $config->get('security.xss_enabled'),
  222. 'dangerous_tags' => array_map('trim', $config->get('security.xss_dangerous_tags')),
  223. 'invalid_protocols' => array_map('trim', $config->get('security.xss_invalid_protocols')),
  224. ];
  225. }
  226. }