Security.php 8.1 KB

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