Module: Parse::RegexSecurity

Defined in:
lib/parse/query/constraints.rb

Overview

Security module for validating regex patterns to prevent ReDoS attacks. MongoDB uses PCRE which is susceptible to catastrophic backtracking.

Constant Summary collapse

MAX_PATTERN_LENGTH =

Maximum allowed length for regex patterns

500
ALLOWED_OPTIONS =

$options flags accepted on a caller-supplied $regex: case-insensitive, multiline, dot-all, and Unicode (u, emitted by the unicode form of the regex constraints). The extended flag x is refused: it turns whitespace and # into comments, which can hide a quantifier from any check that reads the pattern text. Parse Server accepts x; this SDK refuses it on input it did not build.

"imsu"
LITERAL_BODY =

A literal text optionally anchored or wrapped in .*: what starts_with, ends_with, and contains build from escaped input. Every regex metacharacter in the body is backslash-escaped, so the pattern cannot backtrack catastrophically.

/\A(?:\\.|[^\\.^$|?*+()\[\]{}])*\z/m
MAX_REPEAT_COUNT =

Largest repeat count PCRE accepts in {n} / {n,m}.

65_535
MAX_WIDE_RUN =

Most unbounded or wide-range quantified atoms (*, +, {n,}, or {n,m} spanning more than WIDE_RANGE) allowed in one sequence before a literal character none of them can match. Adjacent overlapping runs such as \d+\d+\d+\d+ or .*a.*a.*a.*a backtrack polynomially, which at a few hundred characters per document costs as much as the nested shapes the checker refuses.

3
WIDE_RANGE =

A {n,m} range wider than this counts as wide.

16
SHORTHAND_CLASSES =

Shorthand classes the membership check understands, as ASCII sets. Characters outside ASCII never reach this check: #literal_char only yields ASCII punctuation, letters, and digits.

{
  "d" => ->(c) { c.match?(/\A[0-9]\z/) },
  "w" => ->(c) { c.match?(/\A[A-Za-z0-9_]\z/) },
  "s" => ->(c) { c.match?(/\A[ \t\r\n\f\v]\z/) },
}.freeze

Class Method Summary collapse

Class Method Details

.literal_pattern?(pattern_str) ⇒ Boolean

Whether a pattern is escaped literal text, optionally anchored (^text, text$) or wrapped in .* (.*text.*). A pattern that is only .* wrappers (.*.*) is not literal text.

Parameters:

Returns:

  • (Boolean)


415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
# File 'lib/parse/query/constraints.rb', line 415

def literal_pattern?(pattern_str)
  body = pattern_str.dup
  dot_prefix = false
  if body.start_with?("^")
    body = body[1..]
  elsif body.start_with?(".*")
    body = body[2..]
    dot_prefix = true
  end
  dot_suffix = false
  if body.end_with?(".*") && !body.end_with?("\\.*")
    body = body[0..-3]
    dot_suffix = true
  elsif body.end_with?("$") && !body.end_with?("\\$")
    body = body[0..-2]
  end
  return false if dot_prefix && dot_suffix && body.empty?
  LITERAL_BODY.match?(body)
end

.safe?(pattern, max_length: MAX_PATTERN_LENGTH) ⇒ Boolean

Checks if a pattern is safe without raising an exception.

Parameters:

  • pattern (String, Regexp) —

    the pattern to check

Returns:

  • (Boolean) —

    true if safe, false if potentially dangerous



770
771
772
773
774
775
# File 'lib/parse/query/constraints.rb', line 770

def safe?(pattern, max_length: MAX_PATTERN_LENGTH)
  validate!(pattern, max_length: max_length)
  true
rescue ArgumentError
  false
end

.validate!(pattern, max_length: MAX_PATTERN_LENGTH) ⇒ String

Validates a regex pattern for potential ReDoS vulnerabilities.

Escaped literal text (what starts_with, ends_with, and contains build) always passes; its length cap is 2 * max_length + 4 because escaping can double it. Any other pattern is parsed and refused when it contains a shape that backtracks catastrophically on PCRE:

  • a group repeated more than once (+, *, {n,}, {n} or {n,m} with a top above 1) whose body holds a quantifier, an alternation, or a backreference: (a+)+, (a|aa)+, ((a+))+, (a+){2,}, (a+){20}; A repeated group stays allowed when each repeat cannot split its input more than one way: an alternation of fixed literals with distinct first characters ((foo|bar)+), or a literal separator next to one quantified atom that cannot match it ((-[a-z0-9]+)*, (\.[\w-]+)+, ([\w-]+\.)+);
  • two adjacent unbounded .* / .+ with more pattern after them;
  • more than three unbounded or wide quantified atoms in a row with no literal between them that they cannot match (\d+\d+\d+\d+, .*a.*a.*a.*a); groups without a quantifier are read as part of the surrounding sequence;
  • a subroutine call (\g<1>), whitespace inside a repeat count ({ 2,}), which newer PCRE2 reads as a quantifier;
  • an inline comment (?#...), extended mode ((?x) or a Regexp with Regexp::EXTENDED), recursion, conditionals, or anything else the reader does not recognize, and unbalanced patterns.

Repeats of a single atom (.{1,255}, \d{1,100}, x{1000}, a+) and lookarounds without such a shape inside (^(?!test)) pass.

Parameters:

  • pattern (String, Regexp) —

    the pattern to validate

  • max_length (Integer) (defaults to: MAX_PATTERN_LENGTH) —

    maximum allowed pattern length

Returns:

  • (String) —

    the validated pattern string

Raises:

  • (ArgumentError) —

    if the pattern is potentially dangerous



381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
# File 'lib/parse/query/constraints.rb', line 381

def validate!(pattern, max_length: MAX_PATTERN_LENGTH)
  if pattern.is_a?(Regexp) && (pattern.options & Regexp::EXTENDED) != 0
    raise ArgumentError, "Regex pattern uses extended mode (the x flag), which is not allowed: " \
                         "it can hide quantifiers in comments. Pattern: #{pattern.source.inspect}"
  end
  pattern_str = pattern.is_a?(Regexp) ? pattern.source : pattern.to_s
  literal = literal_pattern?(pattern_str)
  cap = literal ? (2 * max_length) + 4 : max_length

  if pattern_str.length > cap
    raise ArgumentError, "Regex pattern too long (#{pattern_str.length} chars, max #{cap}). " \
                         "Long patterns can cause performance issues."
  end

  return pattern_str if literal

  reason = begin
      check_tree(Parser.new(pattern_str).parse)
    rescue Refused => e
      e.message
    end
  if reason
    raise ArgumentError, "Regex pattern contains potentially dangerous constructs that could cause " \
                         "ReDoS (Regular Expression Denial of Service): #{reason}. Pattern: #{pattern_str.inspect}"
  end

  pattern_str
end

.validate_options!(options) ⇒ Object

Validates $options flags against ALLOWED_OPTIONS.

Parameters:

Raises:

  • (ArgumentError) —

    on a non-String or an unknown flag.



438
439
440
441
442
443
444
445
446
447
448
# File 'lib/parse/query/constraints.rb', line 438

def validate_options!(options)
  unless options.is_a?(String)
    raise ArgumentError, "Regex $options must be a String (got #{options.class})."
  end
  bad = options.chars.uniq.reject { |c| ALLOWED_OPTIONS.include?(c) }
  unless bad.empty?
    raise ArgumentError, "Regex $options contains unsupported flags #{bad.join.inspect}. " \
                         "Allowed: #{ALLOWED_OPTIONS.chars.join(", ")}."
  end
  options
end

.validate_where!(node)

This method returns an undefined value.

Validates every $regex (and its $options) inside a compiled where clause, at any depth: field values, $not / $elemMatch wrappers, and $or / $and / $nor branches, plus Regexp and BSON regex values anywhere (equality, $not, $in, $nin, $all). SDK routing markers (__ keys) are skipped. Literal patterns built from escaped input pass.

Parameters:

  • node (Object) —

    a compiled where clause or part of one.

Raises:

  • (ArgumentError) —

    when a pattern or its options are unsafe.



459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
# File 'lib/parse/query/constraints.rb', line 459

def validate_where!(node)
  case node
  when Hash
    node.each do |key, value|
      key_str = key.to_s
      next if key_str.start_with?("__")
      if key_str == "$regex"
        value.is_a?(String) ? validate!(value) : validate_where!(value)
      elsif key_str == "$options" && (node.key?("$regex") || node.key?(:$regex))
        validate_options!(value)
      else
        validate_where!(value)
      end
    end
  when Array
    node.each { |item| validate_where!(item) }
  when Regexp
    # A Regexp value (equality, `$not`, `$in`) is a regex match too.
    validate!(node)
  else
    if defined?(BSON::Regexp::Raw) && node.is_a?(BSON::Regexp::Raw)
      if node.options.to_s.include?("x")
        raise ArgumentError, "Regex pattern uses extended mode (the x flag), which is not allowed."
      end
      validate!(node.pattern.to_s)
    end
  end
  nil
end