Regular Expressions for Log Parsing
Logs are the analyst's main evidence, and most of them are lines of text in a format that some program chose: syslog, the web server's "combined" format, an application's own key=value lines. Turning those lines into fields is the first step of every investigation, and regular expressions are the everyday tool for it. Done carelessly, a pattern silently drops the very lines you need, or it can be made to run for minutes on a single crafted line. This lesson writes patterns that are explicit, readable and safe. The regex syntax itself is taught in Regular Expressions; here it meets hostile data.
Definitions
- Named group
(?P<name>...): a capture you read asm["name"], so the code says what each field is. - Anchors
^and$(orre.fullmatch): the whole line must match, not a piece of it. re.VERBOSE: whitespace and#comments inside the pattern are ignored, so a long pattern can be laid out field by field.- Greedy and lazy:
.*takes as much as possible,.*?as little as possible. Prefer a negated class such as[^"]*("anything but a quote"): it is both precise and fast. - ReDoS (regular-expression denial of service): a pattern with nested or overlapping repetition, such as
(a+)+$, that a backtracking engine needs exponential time to reject on some inputs. - Log injection: user-controlled text containing a newline or a delimiter, which forges an extra log line or field.
Parsing an access log
The lines below are a synthetic access log of a lab web server www.lab.test, in the combined format: client, identity, user, time, request line, status, size, referrer and user agent. The pattern names each field and anchors both ends. A second step labels requests that match well-known probing shapes.
import re
from collections import Counter
LINE = re.compile(r"""
^(?P<ip>\d{1,3}(?:\.\d{1,3}){3})\s
\S+\s(?P<user>\S+)\s
\[(?P<time>[^\]]+)\]\s
"(?P<method>[A-Z]+)\s(?P<path>[^"\s]*)\s(?P<proto>HTTP/[\d.]+)"\s
(?P<status>\d{3})\s(?P<size>\d+|-)\s
"(?P<ref>[^"]*)"\s"(?P<ua>[^"]*)"$
""", re.VERBOSE)
PROBES = {
"traversal": re.compile(r"\.\./|%2e%2e|%2f", re.I),
"sqli": re.compile(r"('|%27)(\s|%20|\+)*(or|union)\b|union(\s|%20|\+)+select", re.I),
"admin-scan": re.compile(r"^/(wp-admin|phpmyadmin|\.env|\.git/)", re.I),
}
log = r'''10.10.0.5 - - [15/Jan/2026:10:00:01 +0000] "GET / HTTP/1.1" 200 512 "-" "Mozilla/5.0"
10.10.0.5 - - [15/Jan/2026:10:00:02 +0000] "GET /style.css HTTP/1.1" 200 1300 "http://www.lab.test/" "Mozilla/5.0"
203.0.113.7 - - [15/Jan/2026:10:01:00 +0000] "GET /.env HTTP/1.1" 404 0 "-" "lab-scanner/1.0"
203.0.113.7 - - [15/Jan/2026:10:01:01 +0000] "GET /static/..%2f..%2fetc/passwd HTTP/1.1" 400 0 "-" "lab-scanner/1.0"
203.0.113.7 - - [15/Jan/2026:10:01:02 +0000] "GET /search?q=1'%20OR%201=1-- HTTP/1.1" 200 88 "-" "lab-scanner/1.0"
198.51.100.9 - - [15/Jan/2026:10:02:00 +0000] "GET /products?id=5 UNION SELECT HTTP/1.1" 400 0 "-" "curl/8.5.0"
10.10.0.6 - bob [15/Jan/2026:10:03:00 +0000] "POST /login HTTP/1.1" 302 0 "-" "Mozilla/5.0"'''
parsed, unparsed, hits = [], [], Counter()
for line in log.splitlines():
m = LINE.match(line)
if not m:
unparsed.append(line)
continue
parsed.append(m)
for name, rx in PROBES.items():
if rx.search(m["path"]):
hits[(m["ip"], name)] += 1
print(f"{name:<10} {m['ip']:<13} {m['status']} {m['path']}")
print(f"parsed {len(parsed)}, unparsed {len(unparsed)}")
for bad in unparsed:
print("UNPARSED:", bad[:60])
print(Counter(m["status"] for m in parsed).most_common())admin-scan 203.0.113.7 404 /.env
traversal 203.0.113.7 400 /static/..%2f..%2fetc/passwd
sqli 203.0.113.7 200 /search?q=1'%20OR%201=1--
parsed 6, unparsed 1
UNPARSED: 198.51.100.9 - - [15/Jan/2026:10:02:00 +0000] "GET /products
[('200', 3), ('404', 1), ('400', 1), ('302', 1)]
The pattern refused one line, and that refusal is a finding in itself: the request line GET /products?id=5 UNION SELECT HTTP/1.1 contains spaces inside the path, which a real browser would have encoded. A well-formed request can't look like that, so a client that sends it is a hand-made tool. A loose pattern such as "(.*)" would have "parsed" it into wrong fields and the SQL-injection probe from 198.51.100.9 would have been lost.
Forged lines and slow patterns
Two attacks target the log pipeline itself. Log injection puts a newline into a field the application logs, such as the user name, so the log gets a forged line. ReDoS sends a line that makes a badly written pattern backtrack for a very long time.
import re
def log_login(user, ok):
return f"login user={user} result={'ok' if ok else 'fail'}"
def log_login_safe(user, ok):
clean = user.encode("unicode_escape").decode("ascii") # \n becomes the two characters \ and n
return f"login user={clean!s} result={'ok' if ok else 'fail'}"
evil = "mallory result=fail\nlogin user=admin"
print(log_login(evil, False))
print("---")
print(log_login_safe(evil, False))
RECORD = re.compile(r"login user=(?P<user>\S+) result=(?P<result>ok|fail)")
forged = log_login(evil, False).splitlines()
print([RECORD.fullmatch(l) is not None for l in forged])
# Overlapping repetition: (\w+\s?)+ can split "aaaa" in many ways before failing.
risky = re.compile(r"^(\w+\s?)+quot;)
safe = re.compile(r"^\w+(?:\s\w+)*quot;) # one way to match each word
text = "word " * 3 + "word!"
print(bool(risky.match(text)), bool(safe.match(text)))login user=mallory result=fail
login user=admin result=fail
---
login user=mallory result=fail\nlogin user=admin result=fail
[True, True]
False False
The unsafe logger writes a second line login user=admin result=fail that the attacker never had: it looks like a failed admin login. The safe version escapes the newline, so the record stays on one line. Note that the forged second line does match the strict record pattern; anchoring alone can't detect forgery, only escaping at the writer can prevent it.
Both slow and fast patterns answer False on this short input. Add words and the risky one explodes: each run of letters can be split between \w+ and the outer + in exponentially many ways, so every extra four-letter word multiplies the work by about eight. With eight words it already took about two seconds in CPython on a desktop machine, with ten more than a minute, and a line of twenty words would not finish in any useful time. The safe one has exactly one way to match each word, so it fails in linear time.
How problems are detected
- Count unparsed lines and show them: a sudden rise means a format change, a new client or an attack on the parser.
- Test patterns against adversarial lines: empty fields, quotes inside fields, very long lines, newlines, non-ASCII.
- Look for ReDoS shapes in review: a group with a quantifier that contains another quantifier (
(a+)+,(\w+\s?)*), or alternatives that overlap ((a|aa)*). Linters such asregexploitand Semgrep rules flag them. - Watch the pipeline's own latency: a log shipper suddenly stuck at 100 % CPU on one line is a ReDoS symptom.
How they are prevented
- Anchor and be specific:
fullmatch,[^"]*instead of.*,\d{3}for a status code. - Escape on write (the application's job): encode control characters and the delimiter, or log structured JSON where the encoder does it.
- Avoid nested quantifiers; when you need them, use an atomic group
(?>...)or a possessive quantifier\w++(Python 3.11 and later), or an engine without backtracking such as RE2. - Bound the input: cap line length before matching.
- Parse structured logs as structure: JSON lines with
json.loads, not regex.
Pitfalls
re.matchis not anchored at the end. It only anchors at the start; usefullmatchor$(and remember$also matches before a final\n;\Zdoes not)..does not match a newline unlessre.DOTALLis set, which hides multi-line payloads.- Case.
UNION selectand%2E%2Edefeat case-sensitive probes; usere.Ifor signatures. - Signatures are not a security control. A regex list will always miss encodings; use it to find probing, and fix the application with parameterised queries and path normalisation.
Practice
1. Why does LINE use (?P<size>\d+|-) instead of \d+?
The combined format writes - when no body was sent (for example a 304 response). With \d+ those legitimate lines would be "unparsed" noise that hides real anomalies.
2. Write a pattern for key=value pairs where values may be quoted with spaces, like user="bob smith" ip=10.10.0.6.
re.findall(r'(\w+)=("[^"]*"|\S+)', line) gives [('user', '"bob smith"'), ('ip', '10.10.0.6')]. Strip the quotes afterwards. \S+ can also start with " (it takes over when a closing quote is missing), but the alternation is not inside a repeated group, so a failure costs at most a second try per position and cannot backtrack badly.
3. An application logs JSON lines. Is log injection still possible?
Not through newlines, because the JSON encoder writes \n inside a string as the two characters \ and n. It is still possible if the code builds the JSON by string concatenation ('{"user":"' + user + '"}'): a quote in the user name then adds fields. Always use the encoder.
Test yourself
Why is [^"]* preferred to .* for a quoted log field?
- It is shorter
- It stops at the closing quote, so it can't swallow the next field, and it doesn't backtrack
- It matches newlines
- It is case-insensitive
Which pattern is a ReDoS risk?
^\d{3}$^[a-z]+$^(\w+\s?)+$^GET /[^ ]*$
Where is log injection prevented?
- In the regex that reads the log
- In the application that writes the log, by escaping control characters or using a structured encoder
- In the firewall
- By making logs read-only
The example's pattern refused one line. What did that line reveal?
- A broken log file
- A client sending spaces in the path, i.e. a hand-made tool probing for SQL injection
- A normal browser request
- A server error