Lesson 1 of 9 · 22m
Parsing Everything Without Lying to Yourself
Security data is malformed, partial, and hostile; build parsers that preserve evidence, surface uncertainty, and fail loudly.
Security automation starts with an unglamorous job: turning scanner exports, logs, CSVs, XML blobs, emails, and API responses into facts you can compute on. The dangerous parser is the one that silently drops half the input and still exits zero.
Parse the format, not the vibes
Reach for real parsers before regular expressions. CSV has quoting rules, XML has namespaces, JSON lines can contain one broken line in ten million, and syslog has at least three dialects pretending to be one format.
import csv, json
from pathlib import Path
def read_scan_csv(path: Path):
with path.open(newline="", encoding="utf-8-sig") as fh:
for row in csv.DictReader(fh):
yield {"host": row.get("Host", "").strip(),
"port": int(row["Port"]) if row.get("Port") else None,
"severity": row.get("Risk", "unknown").lower()}
def read_jsonl(path: Path):
for lineno, line in enumerate(path.open(encoding="utf-8"), 1):
try:
yield json.loads(line)
except json.JSONDecodeError as exc:
raise ValueError(f"{path}:{lineno}: invalid JSON") from excThis code does not guess encodings silently, does not treat a missing port as port zero, and does not swallow a broken line because most of the file looked fine.
Preserve the original evidence
Normalized data is for computation. Raw data is for proof. Store both; when a vulnerability is disputed three months later, the exact input row and its hash beat memory.
from hashlib import sha256
def evidence(raw: str) -> dict:
return {"raw": raw, "sha256": sha256(raw.encode()).hexdigest()}Keep parse errors as data when the input stream is large. A dead-letter file with source line numbers is operationally useful; a traceback at 02:13 with no artifact is not.
Normalize names once, at the boundary
Every source invents its own vocabulary: critical, Critical, 5, P1, high-plus. Pick one internal schema and translate at ingestion; if translation tables live in twelve scripts, you have folklore, not a schema.
SEVERITIES = {"critical": "critical", "high": "high", "medium": "medium",
"low": "low", "info": "info", "5": "critical", "4": "high"}
def severity(value: str) -> str:
key = value.strip().lower()
if key not in SEVERITIES:
raise ValueError(f"unmapped severity: {value!r}")
return SEVERITIES[key]The exception is deliberate: new input vocabulary is a schema change, not an inconvenience. Regular expressions are a last resort — fine for CVE-[0-9]{4}-[0-9]{4,7}, terrible for nested structures, quoted CSV, XML, URLs, or attacker-controlled text.
Field notes
utf-8-sighandles the byte-order mark Excel loves to insert into CSV exports.- Never let a parser invent confidence; if a field was absent, represent absence.
- Include source, line number, and input hash in normalized output; test hostile samples such as embedded newlines and truncated final lines.
Was this lesson helpful?