SECURITY ENGINEERING · PART 3 · SCRIPTING AND AUTOMATION · PYTHON · 41 OF 229

Regex for Security: Parse Logs and Find IOCs

Regular expressions are the query language of security work: the handful of symbols that matter, named groups that turn a log line into fields, patterns for addresses, hashes and leaked keys, greedy versus lazy matching, the anchor mistake that lets bad input through, and ReDoS, where one bad pattern took 2.54 seconds on 26 characters in our test.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 9
  9. 10
  10. 11
  11. 12
  12. 13
  13. 14
  14. 15
  15. 16
  16. 17
  17. 18
  18. 19
  19. 20
  20. 21
  21. 22
  22. 23
  23. 24
  24. 25
  25. 26
  26. 27
  27. 28
  28. 29
  29. 30
  30. 31
  31. 32
  32. 33
  33. 34
  34. 35
  35. 36
  36. 37
  37. 38
  38. 39
  39. 40
  40. 41
  41. 42
  42. 43
  43. 44
  44. 45
  45. 46
  46. 47
  47. 48
  48. 49
  49. 50
  50. 51
  51. 52
  52. 53
  53. 54
  54. 55
  55. 56
  56. 57
  57. 58
  58. 59
  59. 60
  60. 61
  61. 62
  62. 63
  63. 64
  64. 106
  65. 107
  66. 108
  67. 109
  68. 110
  69. 111
  70. 112
  71. 113
  72. 114
  73. 115
  74. 116
  75. 117
  76. 118
  77. 119
  78. 120
  79. 121
  80. 122
  81. 123
  82. 124
  83. 125
  84. 126
  85. 127
  86. 128
  87. 129
  88. 130
  89. 131
  90. 132
  91. 133
  92. 134
  93. 135
  94. 136
  95. 137
  96. 138
  97. 139
  98. 140
  99. 141
  100. 142
  101. 143
  102. 144
1 / 13

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • A dozen symbols
  • named groups make fields
  • patterns find candidates
  • greedy, anchors and ReDoS are the traps

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.

The symbols that matter
.        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.

parse an SSH failure
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.

common security patterns
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.

patterns over-match
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.

greedy and lazy
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.

validate the whole string
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.

catastrophic backtracking
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.

Safe pattern habits
  • 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.

Regex in the wild
  • 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.

Avoid these
  • 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.

In the interview
  • "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."

Interview questions

Q1Why are regular expressions important in security work?

They are the common pattern language behind log searching (grep, SIEM queries), field extraction, detection rules (Sigma, YARA), WAF rules, secret scanners, SAST rules and input validation, so reading and writing them is a daily skill.

Q2What is a named capture group and why use it?

A group written (?P<name>...) that captures part of a match under a label. It turns an unstructured log line into named fields such as user, ip and port, which is how parsers convert text logs into structured events.

Q3What is the difference between greedy and lazy matching?

Greedy quantifiers (+, *) match as much as possible, so <.+> on "<a><b>" matches the whole string. Lazy quantifiers (+?, *?) match as little as possible, giving "<a>". A negated character class such as <[^>]+> is usually clearer and faster than either.

Q4Why should input validation use fullmatch rather than search or match?

search matches anywhere in the string and match only anchors the start, so extra content can slip through. In Python, $ also matches before a trailing newline, so ^\d+$ accepts "123\n". fullmatch (or \A...\Z) requires the entire string to match.

Q5What is ReDoS?

Regular expression denial of service: patterns with nested or overlapping quantifiers, such as (a+)+$, cause exponential backtracking on inputs that almost match, so a short crafted string can consume CPU for seconds, minutes or longer and stall the service.

Q6How do you prevent ReDoS?

Avoid nested quantifiers and overlapping alternations, limit input length before matching, apply match timeouts, use linear-time engines such as RE2 (the default in Go and Rust) for untrusted input, and lint patterns in CI.

Q7Why validate regex matches with code afterwards?

Patterns are approximations: an IPv4 pattern using \d{1,3} accepts 999.999.999.999 and can match inside version strings. Regex is good for finding candidates; a parser such as Python’s ipaddress module confirms that each candidate is valid.

Q8What do word boundaries (\b) do in indicator patterns?

They require the match to start and end at a boundary between word and non-word characters, so a pattern for a 32-character hash or an access key does not match a fragment in the middle of a longer string.