Security.php 7.7 KB

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