Notes
The core
The core is about a dozen symbols. A dot matches any character. Backslash d is a digit, backslash w a word character, backslash s a space, and capital S anything but a space. Square brackets list allowed characters. Plus means one or more, star zero or more, a question mark makes something optional, and braces give an exact count. Caret and dollar mark the start and end. Parentheses capture, a pipe means or, and a backslash before a dot means a real dot.
. any one character
\d \w \s digit, word char, space
\S anything but a space
[a-f0-9] one of these characters
+ * ? one+, zero+, optional
{2,5} between 2 and 5 times
^ $ start and end
( ) capture a group
(?: ) group without capturing
a|b a or b
\. a literal dot Named groups
The most useful feature for log work is the named group. This pattern describes a failed SSH login. The optional non-capturing group handles the words invalid user, which appear on some lines and not others. Each named group captures one field. Run it on a line and group dict returns a dictionary: user admin, the address, the port. A line of free text has become structured data, which is exactly what a log system does when it parses your logs.
pat = re.compile(
r"Failed password for "
r"(?:invalid user )?(?P<user>\S+)"
r" from (?P<ip>\d{1,3}(?:\.\d{1,3}){3})"
r" port (?P<port>\d+)")
pat.search(line).groupdict()
# {'user': 'admin',
# 'ip': '203.0.113.9',
# 'port': '51022'} Indicators
Investigators search for the same kinds of thing again and again, called indicators. An IPv4 address is four groups of digits separated by dots. An MD5 hash is thirty two hexadecimal characters, a SHA two fifty six is sixty four. Cloud and code platform keys have recognisable prefixes, which is how secret scanners find them in source code. The backslash b at each end is a word boundary, so the pattern does not match in the middle of a longer string.
IPv4 \b(?:\d{1,3}\.){3}\d{1,3}\b
MD5 \b[a-f0-9]{32}\b
SHA-256 \b[a-f0-9]{64}\b
AWS key id \bAKIA[0-9A-Z]{16}\b
GitHub token \bghp_[A-Za-z0-9]{36}\b
email [\w.+-]+@[\w-]+\.[\w.]+
JWT eyJ[\w-]+\.[\w-]+\.[\w-]+
# \b = a word boundary Good enough?
A warning about precision. We ran the address pattern over a sentence that also contained a version number, one dot two dot three dot four dot five. It returned both real addresses and a third match, two dot three dot four dot five, cut out of the version string. The pattern also accepts nine nine nine as a number. That is normal. Use the pattern to find candidates, then validate each with real code, such as the ipaddress module from the Python episode.
re.findall(IPV4,
"from 10.0.0.9 to 203.0.113.9"
" v1.2.3.4.5")
# ['10.0.0.9', '203.0.113.9',
# '2.3.4.5'] <- a version
# \d{1,3} also accepts 999
# so: regex to find, then
# ipaddress.ip_address() to check Trap 1 · Greedy
The first trap is greed. By default plus and star match as much as they possibly can. Asked to match an opening bracket, anything, and a closing bracket in a string with two tags, the greedy pattern returns both tags as one match. Adding a question mark makes it lazy, so it stops at the first closing bracket. Better still, say precisely what you mean: a bracket, then characters that are not a closing bracket. Precise patterns are faster and safer.
re.search(r"<.+>", "<a><b>").group() # '<a><b>' greedy: too much re.search(r"<.+?>", "<a><b>").group() # '<a>' lazy: stops early # better still: say what you mean re.search(r"<[^>]+>", "<a><b>") # a tag is "<", then anything # that is not ">", then ">"
Trap 2 · Anchors
The second trap turns into real vulnerabilities. A validation pattern must match the whole input, not part of it. Search finds digits anywhere, so a string with digits followed by a command passes. Even with caret and dollar there is a surprise: in Python, dollar also matches just before a final newline, so one two three followed by a newline passes. We ran it; it returns true. Full match returns false, which is correct. For validation, always use full match.
re.search(r"\d+", "12; rm -rf /") # matches: part of the input bool(re.match(r"^\d+$", "123\n")) # True <- $ allows a final newline bool(re.fullmatch(r"\d+", "123\n")) # False <- correct # for validation: fullmatch, # or \A ... \Z
Trap 3 · ReDoS
The third trap is a denial of service hiding in a pattern. A nested repeat, like one or more a's, repeated one or more times, can be matched in an exponential number of ways, and when the input almost matches, the engine tries them all. We timed it. Eighteen characters took a hundredth of a second. Twenty two took zero point one five. Twenty six took two point five four seconds. Forty would take days. An attacker who finds such a pattern in your input validation sends one short string and freezes the server.
pat = r"^(a+)+$" re.match(pat, "a"*18 + "!") # 0.01 s re.match(pat, "a"*22 + "!") # 0.15 s re.match(pat, "a"*26 + "!") # 2.54 s # each 4 extra characters: ~16x # 40 characters: days # an attacker sends that string # to your validation endpoint
Avoiding ReDoS
Avoiding it takes a few habits. Never nest one repeat inside another, and avoid repeating a choice whose options overlap. Limit the length of input before matching it at all. Where the language allows, set a timeout, or use an engine that guarantees linear time, such as RE two, which is what Go and Rust use by default. Prefer exact character classes to dot star. And run a pattern linter in your pipeline; tools exist that flag dangerous patterns automatically.
- no nested repeats: (a+)+, (a*)*, (a|aa)+ no repeats over overlapping choices
- limit input length before matching
- use a timeout or a linear-time engine (RE2, Go, Rust)
- prefer exact character classes to ".*"
- test patterns with a linter
Where you will use it
You will meet this syntax in every security tool. Grep and ripgrep for searching. The search and field extraction of log platforms. Detection rules in formats like Sigma and YARA. Web application firewall rules. Secret scanners and static analysis rules. And input validation in application code. The dialects differ slightly between tools, so check the details, but the dozen symbols from the start of this episode read the same in all of them.
- grep -E and ripgrep: searching
- SIEM searches and field extraction
- detection rules (Sigma, YARA)
- WAF rules (OWASP Core Rule Set)
- secret scanners (Gitleaks)
- SAST rules (Semgrep)
- input validation in code
- dialects differ slightly: check \d, lookbehind, flags
Common mistakes
Mistakes. Forgetting to escape a dot, so it matches any character and the pattern is looser than you think. Validating with search instead of full match. Dot star everywhere, which is slow and greedy. Nested repeats that open the door to denial of service. No word boundaries, so matches land inside longer strings. Trusting a match without validating it. And one enormous unreadable pattern, where three small readable ones would be easier to review and to fix.
- forgetting to escape the dot
- validating with search, not fullmatch
- ".*" everywhere
- nested repeats (ReDoS)
- no word boundaries, so matches inside longer text
- trusting a match without validating it
- one giant unreadable pattern
Say it like this
In the interview: ReDoS is regular expression denial of service. A pattern with nested or overlapping repeats can be matched in exponentially many ways, so on an input that almost matches, a backtracking engine tries them all and a short string can pin a CPU for minutes. I avoid nested quantifiers and overlapping alternatives, cap input length before matching, and use timeouts or a linear-time engine such as RE two for patterns that face untrusted input.
- "Regular expression denial of service: a pattern with nested
- or overlapping repeats, like
- (a+)+$, takes exponential time
- on a near-miss input, so a short string can pin a CPU.
- I avoid nested quantifiers, cap input length, and use
- timeouts or a linear-time
- engine such as RE2."