Security.php 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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->routes();
  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 ($routes as $path) {
  99. $status && $status([
  100. 'type' => 'progress',
  101. ]);
  102. try {
  103. $page = $pages->get($path);
  104. // call the content to load/cache it
  105. $header = (array) $page->header();
  106. $content = $page->value('content');
  107. $data = ['header' => $header, 'content' => $content];
  108. $results = static::detectXssFromArray($data);
  109. if (!empty($results)) {
  110. if ($route) {
  111. $list[$page->route()] = $results;
  112. } else {
  113. $list[$page->filePathClean()] = $results;
  114. }
  115. }
  116. } catch (Exception $e) {
  117. continue;
  118. }
  119. }
  120. return $list;
  121. }
  122. /**
  123. * Detect XSS in an array or strings such as $_POST or $_GET
  124. *
  125. * @param array $array Array such as $_POST or $_GET
  126. * @param array|null $options Extra options to be passed.
  127. * @param string $prefix Prefix for returned values.
  128. * @return array Returns flatten list of potentially dangerous input values, such as 'data.content'.
  129. */
  130. public static function detectXssFromArray(array $array, string $prefix = '', array $options = null)
  131. {
  132. if (null === $options) {
  133. $options = static::getXssDefaults();
  134. }
  135. $list = [[]];
  136. foreach ($array as $key => $value) {
  137. if (is_array($value)) {
  138. $list[] = static::detectXssFromArray($value, $prefix . $key . '.', $options);
  139. }
  140. if ($result = static::detectXss($value, $options)) {
  141. $list[] = [$prefix . $key => $result];
  142. }
  143. }
  144. return array_merge(...$list);
  145. }
  146. /**
  147. * Determine if string potentially has a XSS attack. This simple function does not catch all XSS and it is likely to
  148. *
  149. * return false positives because of it tags all potentially dangerous HTML tags and attributes without looking into
  150. * their content.
  151. *
  152. * @param string|null $string The string to run XSS detection logic on
  153. * @param array|null $options
  154. * @return string|null Type of XSS vector if the given `$string` may contain XSS, false otherwise.
  155. *
  156. * Copies the code from: https://github.com/symphonycms/xssfilter/blob/master/extension.driver.php#L138
  157. */
  158. public static function detectXss($string, array $options = null): ?string
  159. {
  160. // Skip any null or non string values
  161. if (null === $string || !is_string($string) || empty($string)) {
  162. return null;
  163. }
  164. if (null === $options) {
  165. $options = static::getXssDefaults();
  166. }
  167. $enabled_rules = (array)($options['enabled_rules'] ?? null);
  168. $dangerous_tags = (array)($options['dangerous_tags'] ?? null);
  169. if (!$dangerous_tags) {
  170. $enabled_rules['dangerous_tags'] = false;
  171. }
  172. $invalid_protocols = (array)($options['invalid_protocols'] ?? null);
  173. if (!$invalid_protocols) {
  174. $enabled_rules['invalid_protocols'] = false;
  175. }
  176. $enabled_rules = array_filter($enabled_rules, static function ($val) { return !empty($val); });
  177. if (!$enabled_rules) {
  178. return null;
  179. }
  180. // Keep a copy of the original string before cleaning up
  181. $orig = $string;
  182. // URL decode
  183. $string = urldecode($string);
  184. // Convert Hexadecimals
  185. $string = (string)preg_replace_callback('!(&#|\\\)[xX]([0-9a-fA-F]+);?!u', static function ($m) {
  186. return chr(hexdec($m[2]));
  187. }, $string);
  188. // Clean up entities
  189. $string = preg_replace('!(&#[0-9]+);?!u', '$1;', $string);
  190. // Decode entities
  191. $string = html_entity_decode($string, ENT_NOQUOTES | ENT_HTML5, 'UTF-8');
  192. // Strip whitespace characters
  193. $string = preg_replace('!\s!u', '', $string);
  194. // Set the patterns we'll test against
  195. $patterns = [
  196. // Match any attribute starting with "on" or xmlns
  197. 'on_events' => '#(<[^>]+[[a-z\x00-\x20\"\'\/])([\s\/]on|\sxmlns)[a-z].*=>?#iUu',
  198. // Match javascript:, livescript:, vbscript:, mocha:, feed: and data: protocols
  199. 'invalid_protocols' => '#(' . implode('|', array_map('preg_quote', $invalid_protocols, ['#'])) . ')(:|\&\#58)\S.*?#iUu',
  200. // Match -moz-bindings
  201. 'moz_binding' => '#-moz-binding[a-z\x00-\x20]*:#u',
  202. // Match style attributes
  203. 'html_inline_styles' => '#(<[^>]+[a-z\x00-\x20\"\'\/])(style=[^>]*(url\:|x\:expression).*)>?#iUu',
  204. // Match potentially dangerous tags
  205. 'dangerous_tags' => '#</*(' . implode('|', array_map('preg_quote', $dangerous_tags, ['#'])) . ')[^>]*>?#ui'
  206. ];
  207. // Iterate over rules and return label if fail
  208. foreach ($patterns as $name => $regex) {
  209. if (!empty($enabled_rules[$name])) {
  210. if (preg_match($regex, $string) || preg_match($regex, $orig)) {
  211. return $name;
  212. }
  213. }
  214. }
  215. return null;
  216. }
  217. public static function getXssDefaults(): array
  218. {
  219. /** @var Config $config */
  220. $config = Grav::instance()['config'];
  221. return [
  222. 'enabled_rules' => $config->get('security.xss_enabled'),
  223. 'dangerous_tags' => array_map('trim', $config->get('security.xss_dangerous_tags')),
  224. 'invalid_protocols' => array_map('trim', $config->get('security.xss_invalid_protocols')),
  225. ];
  226. }
  227. }