3 namespace Drupal\Core\Security;
5 use Symfony\Component\HttpFoundation\Request;
8 * Sanitizes user input.
10 class RequestSanitizer {
13 * Request attribute to mark the request as sanitized.
15 const SANITIZED = '_drupal_request_sanitized';
18 * The name of the setting that configures the whitelist.
20 const SANITIZE_WHITELIST = 'sanitize_input_whitelist';
23 * The name of the setting that determines if sanitized keys are logged.
25 const SANITIZE_LOG = 'sanitize_input_logging';
28 * Strips dangerous keys from user input.
30 * @param \Symfony\Component\HttpFoundation\Request $request
31 * The incoming request to sanitize.
32 * @param string[] $whitelist
33 * An array of keys to whitelist as safe. See default.settings.php.
34 * @param bool $log_sanitized_keys
35 * (optional) Set to TRUE to log an keys that are sanitized.
37 * @return \Symfony\Component\HttpFoundation\Request
38 * The sanitized request.
40 public static function sanitize(Request $request, $whitelist, $log_sanitized_keys = FALSE) {
41 if (!$request->attributes->get(self::SANITIZED, FALSE)) {
42 // Process query string parameters.
43 $get_sanitized_keys = [];
44 $request->query->replace(static::stripDangerousValues($request->query->all(), $whitelist, $get_sanitized_keys));
45 if ($log_sanitized_keys && !empty($get_sanitized_keys)) {
46 trigger_error(sprintf('Potentially unsafe keys removed from query string parameters (GET): %s', implode(', ', $get_sanitized_keys)));
49 // Request body parameters.
50 $post_sanitized_keys = [];
51 $request->request->replace(static::stripDangerousValues($request->request->all(), $whitelist, $post_sanitized_keys));
52 if ($log_sanitized_keys && !empty($post_sanitized_keys)) {
53 trigger_error(sprintf('Potentially unsafe keys removed from request body parameters (POST): %s', implode(', ', $post_sanitized_keys)));
57 $cookie_sanitized_keys = [];
58 $request->cookies->replace(static::stripDangerousValues($request->cookies->all(), $whitelist, $cookie_sanitized_keys));
59 if ($log_sanitized_keys && !empty($cookie_sanitized_keys)) {
60 trigger_error(sprintf('Potentially unsafe keys removed from cookie parameters: %s', implode(', ', $cookie_sanitized_keys)));
63 if (!empty($get_sanitized_keys) || !empty($post_sanitized_keys) || !empty($cookie_sanitized_keys)) {
64 $request->overrideGlobals();
66 $request->attributes->set(self::SANITIZED, TRUE);
72 * Strips dangerous keys from $input.
75 * The input to sanitize.
76 * @param string[] $whitelist
77 * An array of keys to whitelist as safe.
78 * @param string[] $sanitized_keys
79 * An array of keys that have been removed.
82 * The sanitized input.
84 protected static function stripDangerousValues($input, array $whitelist, array &$sanitized_keys) {
85 if (is_array($input)) {
86 foreach ($input as $key => $value) {
87 if ($key !== '' && $key[0] === '#' && !in_array($key, $whitelist, TRUE)) {
89 $sanitized_keys[] = $key;
92 $input[$key] = static::stripDangerousValues($input[$key], $whitelist, $sanitized_keys);