https://github.com/grosser/safe_regexp
Ruby Regex Timeout / Backtracking Bomb Safety
https://github.com/grosser/safe_regexp
regex regexp ruby
Last synced: 8 months ago
JSON representation
Ruby Regex Timeout / Backtracking Bomb Safety
- Host: GitHub
- URL: https://github.com/grosser/safe_regexp
- Owner: grosser
- License: mit
- Created: 2019-03-28T22:14:01.000Z (almost 7 years ago)
- Default Branch: master
- Last Pushed: 2022-04-07T20:38:10.000Z (almost 4 years ago)
- Last Synced: 2025-05-19T11:15:04.794Z (9 months ago)
- Topics: regex, regexp, ruby
- Language: Ruby
- Homepage:
- Size: 41 KB
- Stars: 31
- Watchers: 2
- Forks: 3
- Open Issues: 1
-
Metadata Files:
- Readme: Readme.md
- License: MIT-LICENSE
Awesome Lists containing this project
README
Ruby Regex Timeout / Backtracking Bomb Safety
Don't let untrusted regular expressions kill your servers (cannot be caught with a `Timeout`).
DEPRECATED: Ruby 3.2+ [supports this natively](https://www.ruby-lang.org/en/news/2022/04/03/ruby-3-2-0-preview1-released/)
Install
=======
```Bash
gem install safe_regexp
```
Usage
=====
```Ruby
# normal
/a/.match?('a') # -> true in 0.0001ms
SafeRegexp.execute(/a/, :match?, 'a') # -> true in 0.13568ms
# bomb
require "safe_regexp"
regex = /aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?aa?/
value = "a" * 46
regex.match? value # false in ~60s
SafeRegexp.execute(regex, :match?, value) # -> SafeRegexp::RegexpTimeout
# methods without arguments
regex = "^(The '(?.*)' parameter of the (?.*))$"
SafeRegexp.execute(regex, :names) # -> ["first_group", "second_group"]
```
Behind the scenes
=================
- not using `Thread` or `Timeout`
- spawns a co-processor and `kill -9` it if it takes too long, shuts down after 10s of not being used (to avoid process boot cost), use `keepalive: 0` to shutdown immediately
- defaults to 1s timeout
- uses 1 co-processor per thread
- any `MatchData` object is returned as Array since it cannot be dumped
Author
======
[Michael Grosser](http://grosser.it)
michael@grosser.it
License: MIT
[](https://travis-ci.org/grosser/safe_regexp)