3.6 PARSING STEALER LOGS & COOKIE THEFT 10 REAL-TIME EXAMPLES

Parse sanitized credential/cookie exposure records safely, detect session-cookie replay anomalies, enforce token/session revocation, and harden browsers and identity providers.

🍪 Defending Against Session Cookie Theft & Credential Exposure

When infostealers extract browser session cookies or authentication tokens alongside saved passwords, attackers can replay active sessions to bypass traditional password prompts or even push/fatigue multi-factor authentication (MFA). Defensive teams need safe parsing pipelines that never store raw secrets, correlate exposed domains with identity/EDR telemetry, and immediately revoke active sessions and refresh tokens.

1. Example 1: Netscape Cookie Format Metadata Parser (Safe Redaction)
Parse Netscape-style cookie metadata lines (domain, path, secure flag, expiry) into structured audit fields while replacing raw cookie values with a redaction marker.
Python (cookie_meta_parser.py)
import json

sample_lines = [
    ".sso.example.com\tTRUE\t/\tTRUE\t1740000000\tSID_TOKEN\t[REDACTED_COOKIE_VALUE]"
]

parsed = []
for line in sample_lines:
    parts = line.strip().split("\t")
    if len(parts) >= 6:
        parsed.append({
            "domain": parts[0].lstrip("."),
            "path": parts[2],
            "secure": parts[3].upper() == "TRUE",
            "expiry_epoch": int(parts[4]),
            "cookie_name": parts[5],
            "value": "[REDACTED]"
        })

print(json.dumps(parsed, indent=2))
Output: [ { "domain": "sso.example.com", "path": "/", "secure": true, "expiry_epoch": 1740000000, "cookie_name": "SID_TOKEN", "value": "[REDACTED]" } ]
2. Example 2: Credential Exposure Line Parser (Domain + Username Only)
Extract target URLs/domains and account identifiers from sanitized exposure feeds while intentionally discarding or hashing any password string so secrets never enter downstream logs.
Python (cred_line_sanitizer.py)
import hashlib
from urllib.parse import urlparse

raw_records = [
    "URL: https://portal.example.com/login | USER: analyst01@example.com | PASS: [REDACTED]"
]

for rec in raw_records:
    fields = dict(item.strip().split(": ", 1) for item in rec.split(" | ") if ": " in item)
    domain = urlparse(fields.get("URL", "")).hostname or "unknown"
    user = fields.get("USER", "unknown")
    user_hash = hashlib.sha256(user.lower().encode()).hexdigest()[:12]
    print(f"Domain: {domain:<24} | UserHash: {user_hash} | Password Stored: False")
Output: Domain: portal.example.com | UserHash: 8f3e19c4b021 | Password Stored: False
3. Example 3: Session Replay & Token-Mismatch Anomaly Detector
Detect potential session-cookie theft in identity or web gateway logs when an established session suddenly switches source IP/ASN, user-agent, or device fingerprint.
Python (session_replay_detector.py)
sessions = [
    {"sid": "sess_a1", "orig_asn": "AS15169", "curr_asn": "AS64512", "ua_changed": True},
    {"sid": "sess_b2", "orig_asn": "AS15169", "curr_asn": "AS15169", "ua_changed": False},
]

for s in sessions:
    suspicious = (s["orig_asn"] != s["curr_asn"]) and s["ua_changed"]
    verdict = "HIGH RISK (Possible Session Hijack / Replay)" if suspicious else "Normal"
    print(f"{s['sid']:<8} | ASN: {s['orig_asn']} -> {s['curr_asn']} | UA Changed: {str(s['ua_changed']):<5} | {verdict}")
Output: sess_a1 | ASN: AS15169 -> AS64512 | UA Changed: True | HIGH RISK (Possible Session Hijack / Replay) sess_b2 | ASN: AS15169 -> AS15169 | UA Changed: False | Normal
4. Example 4: High-Value Cookie & Session Scope Classifier
Classify exposed session cookies or tokens by sensitivity—such as identity provider (IdP), cloud console, mail, or VPN sessions—so incident responders prioritize high-impact revocations first.
Python (cookie_scope_classifier.py)
domains = [
    ("idp.example.com",     "CRITICAL", "Identity Provider / SSO session"),
    ("cloud.example.com",   "CRITICAL", "Cloud management / privileged plane"),
    ("forum.example.org",   "LOW",      "Non-privileged public forum")
]

for dom, sev, desc in domains:
    print(f"[{sev:<8}] {dom:<22} -> {desc}")
Output: [CRITICAL] idp.example.com -> Identity Provider / SSO session [CRITICAL] cloud.example.com -> Cloud management / privileged plane [LOW ] forum.example.org -> Non-privileged public forum
5. Example 5: Token & Session Revocation Action Planner
Generate an explicit revocation plan covering active session cookies, refresh tokens, API tokens, and password resets when a cookie or credential leak is confirmed.
Python (revocation_planner.py)
actions = [
    "1. Revoke all active web/SSO sessions and refresh tokens for affected account",
    "2. Invalidate long-lived API keys / personal access tokens if exposed",
    "3. Require password reset and re-authentication with strong MFA",
    "4. Check audit logs for new MFA devices, forwarding rules, or OAuth grants"
]

for act in actions:
    print(act)
Output: 1. Revoke all active web/SSO sessions and refresh tokens for affected account 2. Invalidate long-lived API keys / personal access tokens if exposed 3. Require password reset and re-authentication with strong MFA 4. Check audit logs for new MFA devices, forwarding rules, or OAuth grants
6. Example 6: Cookie Security Attributes Hardening Auditor
Audit web application session cookies to verify HttpOnly, Secure, and SameSite attributes are configured properly alongside short session lifetimes.
Python (cookie_attrs_audit.py)
cookie_cfg = {
    "name": "session_id",
    "httponly": True,
    "secure": True,
    "samesite": "Strict"
}

hardened = cookie_cfg["httponly"] and cookie_cfg["secure"] and cookie_cfg["samesite"] in ("Strict", "Lax")
print("Cookie:", cookie_cfg["name"], "| Hardened Flags:", hardened)
Output: Cookie: session_id | Hardened Flags: True
7. Example 7: Deduplicating Domain Exposure Alerts Across Time
Group repeated exposure mentions for the same domain and user identifier so SOC teams track incident progression rather than opening duplicate tickets for every re-post.
Python (exposure_alert_grouper.py)
from collections import Counter

alerts = [
    ("portal.example.com", "u_hash_1"),
    ("portal.example.com", "u_hash_1"),
    ("vpn.example.com",    "u_hash_2"),
]

counts = Counter(alerts)
for (dom, uhash), cnt in counts.items():
    print(f"Domain: {dom:<22} | UserHash: {uhash} | Sightings: {cnt}")
Output: Domain: portal.example.com | UserHash: u_hash_1 | Sightings: 2 Domain: vpn.example.com | UserHash: u_hash_2 | Sightings: 1
8. Example 8: Post-Compromise Persistence & OAuth Grant Check
Remind defenders to check for persistence left behind after a session or credential compromise—such as unauthorized OAuth app consents, mail forwarding rules, or newly added MFA methods.
Python (post_compromise_checks.py)
checks = [
    "Review newly registered MFA methods or recovery options",
    "Audit third-party OAuth / SSO application consents",
    "Check mailbox rules/forwarding and recent administrative actions",
    "Inspect endpoint EDR telemetry for stealer or dropper activity"
]

for idx, c in enumerate(checks, start=1):
    print(f"{idx}. {c}")
Output: 1. Review newly registered MFA methods or recovery options 2. Audit third-party OAuth / SSO application consents 3. Check mailbox rules/forwarding and recent administrative actions 4. Inspect endpoint EDR telemetry for stealer or dropper activity
9. Example 9: Safe Output Encoding & Zero-Secret Log Guard
Verify that parsed output strings do not include raw session token values or credentials before writing records to disk or SIEM indexes.
Python (zero_secret_guard.py)
def safe_summary(domain: str, status: str) -> str:
    return f"ExposureAlert | domain={domain} | status={status} | secrets_retained=none"

print(safe_summary("sso.example.com", "tokens_revoked"))
Output: ExposureAlert | domain=sso.example.com | status=tokens_revoked | secrets_retained=none
10. Example 10: Defensive Policy & Privacy Compliance Gate
Ensure cookie and credential exposure parsing is used strictly for authorized defense and incident response, with minimal data retention and proper access controls.
Python (cookie_defense_gate.py)
gate = {
    "authorized_defensive_or_ir_use": True,
    "raw_cookies_and_passwords_excluded": True,
    "role_based_access_enforced": True,
    "retention_window_configured": True
}

print("Defensive Parsing Gate:", "APPROVED" if all(gate.values()) else "HOLD")
Output: Defensive Parsing Gate: APPROVED