-
Notifications
You must be signed in to change notification settings - Fork 75
fix: add ReDoS protection to regex pattern validation #522
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
kami922
wants to merge
1
commit into
certego:develop
Choose a base branch
from
kami922:fix/redos-vulnerability-regex-validation
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,4 @@ | ||
| import logging | ||
| import re | ||
| from ipaddress import AddressValueError, IPv4Address, IPv4Network | ||
| from typing import Any, Dict, Optional, Union | ||
|
|
@@ -10,6 +11,60 @@ | |
| from impossible_travel.views.utils import read_config | ||
|
|
||
| ALLOWED_RISK_STRINGS = ["High", "Medium", "Low", "No Risk"] | ||
| logger = logging.getLogger(__name__) | ||
|
|
||
| # Security constants for ReDoS protection | ||
| MAX_REGEX_LENGTH = 100 | ||
| MAX_REGEX_COMPLEXITY = 50 # Maximum number of special regex characters | ||
|
|
||
|
|
||
| def _is_safe_regex(pattern: str) -> bool: | ||
| """ | ||
| Validates that a regex pattern is safe to compile and execute. | ||
| Protects against Regular Expression Denial of Service (ReDoS) attacks. | ||
|
|
||
| Args: | ||
| pattern: Regular expression pattern string | ||
|
|
||
| Returns: | ||
| True if pattern is safe, False otherwise | ||
| """ | ||
| # Check pattern length | ||
| if len(pattern) > MAX_REGEX_LENGTH: | ||
| logger.warning(f"Regex pattern exceeds maximum length ({MAX_REGEX_LENGTH}): {len(pattern)}") | ||
| return False | ||
|
|
||
| # Count special regex characters that can cause complexity | ||
| dangerous_chars = ["*", "+", "{", "(", "|", "["] | ||
| complexity = sum(pattern.count(char) for char in dangerous_chars) | ||
|
|
||
| if complexity > MAX_REGEX_COMPLEXITY: | ||
| logger.warning(f"Regex pattern too complex ({complexity} special chars, max {MAX_REGEX_COMPLEXITY})") | ||
| return False | ||
|
|
||
| # Check for known dangerous patterns that can cause catastrophic backtracking | ||
| # These patterns check for nested quantifiers which are the primary cause of ReDoS | ||
| dangerous_patterns = [ | ||
| r"\(.+[*+]\)[*+]", # Direct nested quantifiers like (a+)+ or (a*)* | ||
| r"\(.+[*+]\).?[*+]", # Nested quantifiers with optional char like (a+)+b | ||
| r"\(.+\|.+\)[*+]", # Alternation with quantifier like (a|ab)* | ||
| ] | ||
|
|
||
| for dangerous in dangerous_patterns: | ||
| try: | ||
| if re.search(dangerous, pattern): | ||
| logger.warning(f"Regex pattern contains dangerous construct: {pattern}") | ||
| return False | ||
| except re.error: | ||
| pass | ||
|
|
||
| # Try to compile to catch syntax errors | ||
| try: | ||
| re.compile(pattern) | ||
| return True | ||
| except re.error as e: | ||
| logger.error(f"Invalid regex syntax: {pattern}, error: {e}") | ||
| return False | ||
|
|
||
|
|
||
| def validate_string_or_regex(value): | ||
|
|
@@ -27,6 +82,34 @@ def validate_string_or_regex(value): | |
| raise ValidationError(f"The single element '{item}' in the '{value}' list field is not a valid regex pattern") | ||
|
|
||
|
|
||
| def validate_regex_patterns(patterns_list): | ||
| """Validator for regex patterns - rejects unsafe patterns that could cause ReDoS attacks. | ||
|
|
||
| Args: | ||
| patterns_list: List of regex pattern strings | ||
|
|
||
| Raises: | ||
| ValidationError: If any pattern is unsafe | ||
| """ | ||
| if not patterns_list: | ||
| return | ||
|
|
||
| if not isinstance(patterns_list, list): | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. isn't this check a duplication? |
||
| raise ValidationError("Must be a list of patterns") | ||
|
|
||
| unsafe = set() | ||
| for p in patterns_list: | ||
| if p and not _is_safe_regex(p): | ||
| unsafe.add(p) | ||
|
|
||
| if unsafe: | ||
| raise ValidationError( | ||
| f"The following regex patterns are unsafe and have been rejected: {list(unsafe)}. " | ||
| "Patterns must not exceed 100 characters, contain more than 50 special characters, " | ||
| "or contain nested quantifiers like (a+)+, (a*)*, or (a|ab)*." | ||
| ) | ||
|
|
||
|
|
||
| def validate_ips_or_network(value): | ||
| """Validator for models' fields list that must have IPs or networks""" | ||
| for item in value: | ||
|
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
please define all the imports at the beginning of the file