Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion Model/Rule.php
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,11 @@ private function scalarValueMatchesCondition(string $value, Condition $condition

switch ($condition->type) {
case 'regex':
return (bool)preg_match('/' . str_replace('/', '\/', $condition->value) . '/', $value);
$result = preg_match('/' . str_replace('/', '\/', $condition->value) . '/', $value);
if ($result === false) {
$this->logPcreFailure($condition);
}
return (bool)$result;
case 'contains':
return strpos($value, $condition->value) !== false;
case 'equals':
Expand All @@ -131,6 +135,15 @@ private function scalarValueMatchesCondition(string $value, Condition $condition
}
}

private function logPcreFailure(Condition $condition): void
{
$this->logger->warning('Regex condition failed with a PCRE error.', [
'error' => function_exists('preg_last_error_msg') ? preg_last_error_msg() : preg_last_error(),
'target' => $condition->target,
'pattern' => $condition->value
]);
}

private function targetValueMatchesCondition($value, Condition $condition): bool
{
if ($condition->type === 'network') {
Expand Down
21 changes: 21 additions & 0 deletions Test/Model/RuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,27 @@ public function testRuleWithMultipleConditions()
$this->assertTrue($rule->matches($request));
}

public function testRuleRegexLogsAndFailsOpenOnPcreError()
{
$originalBacktrackLimit = ini_get('pcre.backtrack_limit');
ini_set('pcre.backtrack_limit', '1');

try {
$logger = $this->createMock(Logger::class);
$logger->expects($this->once())->method('warning');
$request = $this->createConfiguredMock(Http::class, [
'getContent' => str_repeat('a', 50) . 'X'
]);
$rule = new Rule(new IP(), $logger, 'block', [
new Condition('req.body', 'regex', '(a+)+$')
]);

$this->assertFalse($rule->matches($request));
} finally {
ini_set('pcre.backtrack_limit', $originalBacktrackLimit);
}
}

public function testRuleWithoutConditions()
{
$rule = new Rule(new IP(), $this->createMock(Logger::class), 'block', []);
Expand Down