Problem/Motivation

The methods isNeededUrls() and isUaWhitelisted() in CookieBotProtectionMiddleware pass configuration patterns directly to preg_match() without any prior validation:

if ($pattern_found |= (preg_match('{' . $pcre_pattern . '}u', $user_agent, $matches) > 0)) {

If an administrator enters an invalid regular expression in the settings form (e.g. an unclosed group like (foo), preg_match() will emit a PHP Warning or throw an Error on every request matching a protected URL, until the configuration is manually fixed.

Steps to reproduce

  1. Install the module and go to the settings form.
  2. Enter (foo in the Url protected patterns or User-Agent whitelist patterns field and save.
  3. Visit a URL that matches the intended pattern.
  4. Observe a PHP warning or error in the logs.

Proposed resolution

Add a validateForm() method in src/Form/SettingsForm.php that iterates over each line of the url_protected_patterns and ua_whitelist_patterns fields and tests each pattern before the configuration is saved:

set_error_handler(static function (): bool { return TRUE; });
$valid = preg_match('{' . $pattern . '}u', '') !== FALSE;
restore_error_handler();

If a pattern is invalid, $form_state->setError() is called on the corresponding field with a message indicating which pattern failed.

Remaining tasks

  • Implement validateForm() in src/Form/SettingsForm.php
  • Add test coverage

User interface changes

A validation error message is displayed on the Url protected patterns and/or User-Agent whitelist patterns fields when an invalid regular expression is submitted.

API changes

None.

Data model changes

None.

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

macsim created an issue. See original summary.

macsim’s picture

Status: Active » Needs review
macsim’s picture

Status: Needs review » Reviewed & tested by the community

  • macsim committed ed548867 on 1.0.x
    task: #3595565 Add regex validation in the settings form to prevent PHP...
macsim’s picture

Status: Reviewed & tested by the community » Fixed

Now that this issue is closed, review the contribution record.

As a contributor, attribute any organization that helped you, or if you volunteered your own time.

Maintainers, credit people who helped resolve this issue.