JavaScript

JavaScript

Made by DeepSource

Audit: Regex range is too permissive JS-A1002

Security
Critical
a03 cwe-20 sans top 25 owasp top 10

In regular expressions, the - operator can be used to match a range of characters. For example, /a-z/ will match any character that has a character code between 'a' and 'z'. Large ranges, like A-z, are often the result of typos or incorrect refactors. The range A-z will match any character that has an ASCII code between 65 and 122, which includes non-alphabetic characters.

Such behaviour is not obvious from the regex, and might open your application up to vulnerabilities where incoming data isn't properly validated.

If the overly permissive regex is intentional, and does not harm the security or performance of your application, consider adding a skipcq comment to 1. prevent this issue from being raised in the future and 2. have your code documented for other developers.

If your application uses too many of these large regex ranges and it's not a security concern, you can disable this issue project-wide from the repository settings.

Bad Practice

// INSECURE: The `A-f` range allows 'B', 'C' ... 'Z'
// which aren't valid hex characters
const hexColorRegex = /^#[0-9a-fA-f]{6}$/i
function validateColor(color: string) {
  return hexColorRegex.test(color)
}

// INSECURE: This regex may have been written
// with the intention of matching ',', '.' or '-'.
// Since `-` acts like an operator inside `[]`, it will
// instead match all characters that have a char code between
// `,` and `.`.
const specialCharRegex = /[,-.]/i

Recommended

const hexColorRegex = /^#[0-9a-fa-f]{6}$/i
function validateColor(color: string) {
  return hexColorRegex.test(color)
}

// To match `-` inside `[]`, it needs to be escaped.
const specialCharRegex = /[,\-.]/i

References