Incorrect Regular Expression
Description
An incorrectly-bounded regex was passed to `validates_format_of` or `validate... format =>...`. Ruby regex behavior is multiline by default and lines should be terminated by `\A` for beginning of line and `\Z` for end of line, respectively.
Examples
Insecure Code
ruby
validates :username, format: { with: /(?=.*[a-zA-Z])[a-zA-Z0-9]+/ }Secure Code
ruby
validates :username, format: { with: /\A(?=.*[a-zA-Z])[a-zA-Z0-9]+\z/ }Remediation
Anchor the regex from start to end of the string using `\A` and `\z`.
Rule Details
| Field | Value |
|---|---|
| ID | CODE-0548 |
| Category | Injection |
| Severity | MEDIUM |
| CWE | CWE-185 |
| Confidence | HIGH |
| Impact | MEDIUM |
| Likelihood | MEDIUM |
| Exploitability | MODERATE |
| Tags | regex, validation |
| OWASP | A5:2017-Broken Access Control, A01:2021-Broken Access Control |
References
- https://brakemanscanner.org/docs/warning_types/format_validation/
- https://github.com/semgrep/semgrep-rules/blob/develop/ruby/rails/security/brakeman/check-validation-regex.yaml