Перейти к основному содержимому
Regular Expressions for Logs & Indicator Extraction
Урок 2 из 10

Regular Expressions for Logs & Indicator Extraction

Build accurate regular expressions with grep -E and Python re to extract IPv4 addresses, request paths, and security tokens from noisy log files without falling into greedy-match or backtracking traps.

Средний 24 мин Программирование
Этого урока пока нет на выбранном языке — показана версия на другом языке. Перевод готовится.

Цели обучения

  • Construct regular expressions using character classes, quantifiers, anchors, and word boundaries
  • Distinguish greedy from non-greedy quantifiers when parsing quoted log fields
  • Extract structured indicators from logs using grep -E and Python re named groups
  • Prevent false positives and catastrophic backtracking (ReDoS) in log-parsing patterns

Рекомендуется заранее: Python Fundamentals for Security Tasks

#Why this matters

In the previous lesson, you split structured log lines on whitespace with .split(). Real incident logs and CTF artifacts rarely stay that tidy: user-agent strings contain spaces, timestamps sit inside brackets, and an attacker's payload may be buried mid-line inside JSON or URL parameters.

Regular expressions (regex) let you describe the shape of what you are looking for rather than hardcoding column positions. Security analysts use regex daily with grep -E for fast terminal triage and with Python's re module to pull out indicators of compromise (IoCs) such as IP addresses, suspicious paths, hashes, or lab flag tokens.

#Core regex building blocks

A regex mixes literal characters (which match themselves) with metacharacters that describe sets, counts, and positions.

Token Meaning Example match
\d, \w, \s Digit, word char (a-zA-Z0-9_), whitespace \d{3} matches 401
[0-9a-f] Character class (one char from the set) [0-9a-f]{6} matches a1b2c3
[^"] Negated class (any char except ") "[^"]+" matches "GET /"
+, *, ? 1 or more, 0 or more, 0 or 1 https? matches http and https
{n,m} Between n and m repetitions \d{1,3} matches 10 or 192
^, $, \b Line start, line end, word boundary \b10\.0\.0\.1\b avoids 10.0.0.12

Because . matches any character except a newline, always escape literal dots as \. when matching IP addresses or domains. In Python, always write patterns as raw strings (r"...") so backslashes like \d and \b pass straight to re instead of being interpreted by Python (in a normal string, "\b" becomes an ASCII backspace character).

#Grouping and greedy vs non-greedy matching

Parentheses (...) capture part of a match so you can extract it, while (?:...) groups tokens without creating a capture group. In Python, named groups (?P<name>...) make log parsers self-documenting.

By default, * and + are greedy: they consume as much text as possible while still allowing the whole pattern to succeed. Consider this web log line:

text
192.0.2.14 - - [18/Nov/2026:10:15:02 +0000] "POST /login HTTP/1.1" 401 512 "curl/8.5"

If you write r'".*"', the regex starts at the first quote before POST and stretches all the way to the final quote after curl/8.5, swallowing the status code in between. You have two clean fixes:

  1. Add ? to make the quantifier non-greedy (r'".*?"'), so it stops at the first closing quote.
  2. Better yet, use a negated character class (r'"([^"]*)"'), which explicitly forbids quotes inside the match and runs faster with less backtracking.

#Extracting indicators with grep -E and Python re

Use grep -E (extended regex) when you want a quick terminal filter across gigabytes of logs, and switch to Python re when you need named fields, counting, or validation.

  1. Raw log linesstream from file or stdin
  2. Filter or compilegrep -E or re.compile(r"...")
  3. Extract groupsisolate IP, path, status, or token
  4. Validateverify IP octets or deduplicate hits

In grep -E, use -o to print only the matched substring (useful for extracting tokens or IPs from messy dumps) and -n to show line numbers:

Filtering 401 login bursts and extracting tokens with grep -E
$ grep -E '"POST /login HTTP/1\.[01]" 401' access.log | head -n 2
192.0.2.14 - - [18/Nov/2026:10:15:02 +0000] "POST /login HTTP/1.1" 401 512
192.0.2.14 - - [18/Nov/2026:10:15:04 +0000] "POST /login HTTP/1.1" 401 512
$ grep -Eo 'TOKEN\{[A-Za-z0-9_]{8,32}\}' capture.txt
TOKEN{lab_regex_042}

In Python, re.compile() compiles a pattern once before looping over a file. Know the difference between re.match() (checks only the beginning of the string), re.search() (finds the first match anywhere), and re.finditer() (yields every match object lazily):

python
import ipaddress
import re

LOG_RE = re.compile(
    r'(?P<ip>\b\d{1,3}(?:\.\d{1,3}){3}\b).*?"(?P<method>GET|POST)\s+(?P<path>\S+)\s+[^"]+"\s+(?P<status>\d{3})'
)

with open("access.log", "r", encoding="utf-8") as handle:
    for line in handle:
        match = LOG_RE.search(line)
        if not match:
            continue
        data = match.groupdict()
        try:
            ipaddress.ip_address(data["ip"])
        except ValueError:
            continue
        if data["status"] == "401":
            print(data["ip"], data["method"], data["path"])

Pairing regex extraction with ipaddress.ip_address() keeps the pattern readable while rejecting invalid strings such as 999.999.999.999 that four \d{1,3} groups would otherwise accept.

#Defending and common mistakes

  • Catastrophic backtracking (ReDoS): Nested quantifiers such as (a+)+ or (\w+\s*)+ can cause Python's backtracking re engine to stall for seconds or minutes on crafted input that fails to match at the end. Keep patterns specific, avoid nested +/* quantifiers, and never compile untrusted user-supplied regexes.
  • Missing word boundaries or escaped dots: Writing 10.0.0.1 matches 10x0y0z1 and 10.0.0.105. Always escape dots (\.) and anchor with \b, ^, or $.
  • Using normal Python strings instead of raw strings: Writing "\b\d+" causes \b to become a backspace byte rather than a word boundary. Always use r"...".
  • Using regex as a sole security filter: Regex is great for log triage and simple format checks, not for parsing nested HTML/SQL or preventing injection on its own.

#Summary

Regular expressions let you match flexible log structures and pull out indicators with grep -E and Python's re module. Always use raw strings (r"..."), escape literal dots, add word boundaries, and prefer negated character classes ([^"]*) or non-greedy quantifiers (.*?) over greedy .*. Combine regex extraction with proper validators like ipaddress.ip_address() and avoid nested quantifiers so your parsers stay fast and accurate.

Проверка знаний

Войдите, чтобы проходить тест, завершать уроки и сохранять прогресс. Войти в систему

Практика: проверьте свои знания