Tag: detection engineering

  • Credential stuffing: the signals that give it away, and why CAPTCHAs are the weakest layer

    Credential stuffing: the signals that give it away, and why CAPTCHAs are the weakest layer

    Credential stuffing is the dullest attack on the internet and one of the most productive. Nobody exploits your code. Someone takes a list of email and password pairs leaked from other sites, replays them against your login endpoint, and waits for the fraction of people who reused a password. The success rate is low, commonly quoted as around one percent or less, but the lists have millions of lines and the cost per attempt is close to zero.

    The 2023 23andMe incident is the one I point people at. The company said attackers got into roughly 14,000 accounts with reused credentials, and because of the DNA Relatives sharing feature the exposed data reached around 6.9 million users. No vulnerability in 23andMe’s software was needed. The same goes for the 2024 Snowflake customer intrusions, where Mandiant tied the access to stolen credentials from infostealer logs used against accounts without MFA.

    What the traffic looks like

    A brute force attack hammers one account with many passwords. Stuffing is the opposite: many accounts, usually one or two attempts each, every password a real one that worked somewhere. That shape is the first and best signal. Your per-account failure counters never trip, because no account sees more than a couple of failures.

    The signals I actually look at, in rough order of usefulness:

    • Distinct usernames per client. A browser session that tries 40 different accounts in ten minutes is not a person with a bad memory.
    • Failure ratio across the whole login endpoint. Normal traffic has some baseline failure rate you can measure. A stuffing run pushes the global failure rate up, and the unknown-username share of failures tells you whether the list was aimed at you or sprayed generically.
    • Client fingerprint reuse. Botnets rotate IPs but the tooling underneath is often one library with one TLS fingerprint (JA3 or the newer JA4) and one header ordering. Thousands of “different” users sharing a fingerprint no real browser emits is a strong tell.
    • Hits on old passwords. If you keep the previous hash on password change, a login that succeeds with a password the user retired months ago is almost certainly a replayed list.
    • Success from a new device and ASN straight after a burst of failures from the same pool.

    This is the first query I run. It assumes a login event table with client_id (fingerprint plus IP bucket), username, success and ts.

    SELECT client_id,
           count(*)                       AS attempts,
           count(DISTINCT username)       AS users_tried,
           avg(success::int)              AS success_rate
    FROM   login_events
    WHERE  ts > now() - interval '15 minutes'
    GROUP  BY client_id
    HAVING count(DISTINCT username) >= 10
       AND avg(success::int) < 0.2
    ORDER  BY users_tried DESC;

    The thresholds are guesses until you’ve run it against your own baseline for a week. Shared NAT and corporate proxies will show up as a client with many real users, so I tune with the success rate and the fingerprint, not the distinct-user count alone.

    Rate limits and where they stop working

    Per-IP limits are the first thing everyone builds and the first thing residential proxy networks defeat. When each request leaves from a different home IP address, a limit of five attempts per minute per IP does nothing, and a tight one blocks real people behind carrier-grade NAT. I keep the per-IP limit as a cheap filter for the lazy attackers and expect nothing from it against the serious ones.

    The counters that matter are per account and per target. Slowing down the attempts on one username, and telling the real owner that someone is trying, costs the attacker nothing but it does protect the account that has the weak password. Pair that with a global circuit: when the endpoint-wide failure rate jumps, move every login that is not from a known device into a stricter path (step-up, delay, email confirmation) for the duration of the spike.

    Responses should be uniform. If “unknown user” and “wrong password” differ in text, status code or timing, you are handing the attacker a free list validator and making the next run cheaper. This is the same enumeration problem that shows up in password reset flows.

    Why the CAPTCHA is the weakest layer

    I’ve seen teams answer a stuffing incident by putting a CAPTCHA on the login form and calling it done. It stops the lazy script for a week. Then the attacker buys a solving service or pays people to solve them, and the cost per solve is small next to the value of a hijacked account. Meanwhile your legitimate users lose conversion and accessibility, and you have collected one more signal than you started with and none of the controls you needed.

    A CAPTCHA is fine as one input to a risk score, triggered when the other signals are already bad. As the main control it is a tax on your own customers.

    Stop the passwords from working

    The durable fix is making a replayed password useless. Two controls do that.

    First, refuse known-breached passwords. NIST SP 800-63B (revision 4, published in 2025) says verifiers must compare chosen passwords against a blocklist of values known to be compromised, and the Have I Been Pwned Pwned Passwords service gives you a free way to do it without sending the password anywhere. You send the first five hex characters of the SHA-1 hash and get back every suffix in that bucket, then compare locally. This is k-anonymity, and it works at login as well as at signup, which is where it pays off for stuffing: a user whose password is in the corpus gets forced through a reset instead of being let in.

    import hashlib, urllib.request
    
    def pwned_count(password: str) -> int:
        sha1 = hashlib.sha1(password.encode()).hexdigest().upper()
        prefix, suffix = sha1[:5], sha1[5:]
        req = urllib.request.Request(
            f"https://api.pwnedpasswords.com/range/{prefix}",
            headers={"Add-Padding": "true"},
        )
        body = urllib.request.urlopen(req, timeout=5).read().decode()
        for line in body.splitlines():
            h, _, n = line.partition(":")
            if h == suffix:
                return int(n)
        return 0

    The Add-Padding header makes the response size less informative to anyone watching the connection. I ran the unpadded form by hand to show what comes back:

    Terminal output: SHA-1 of the word password, the 1977-line Pwned Passwords range response for prefix 5BAA6, and the matching suffix with a count of 52372427. Text rendered into an image from a real run.

    The screenshot is a real run of those commands against the public API. The bucket for the prefix 5BAA6 holds 1,977 suffixes, and the SHA-1 of the word “password” appears in it with a count of 52,372,427. I rendered the terminal text into an image myself, so the colours are mine, the output is not.

    Second, add a factor an attacker cannot replay. A passkey or a TOTP code turns a correct password into a necessary but not sufficient credential. Passkeys are better because there is nothing to type into a phishing page or an infostealer log. If you can’t require a second factor for everyone, require it when the risk score says new device, new ASN, or the account’s password appeared in a breach corpus.

    Putting it together

    Flow diagram of five login controls from edge rate limit to second factor, with red branches showing the action taken at each

    Detection feeds the controls, and none of them is enough alone. If I had to pick the two that matter most, they are the breached-password check and a real second factor, because they work no matter how good the attacker’s proxy pool is. Everything else buys time and gives you telemetry. Start by running the query above against last week’s logs.

  • Egress filtering and DNS exfiltration: the outbound controls most networks skip

    Egress filtering and DNS exfiltration: the outbound controls most networks skip

    Most of the firewall rules I review are about what can get in. The rule sets are long, argued over, and audited every year. Outbound is usually one line: allow any to any. Then an incident happens, the attacker’s implant calls home over 443 or 53, and nobody is surprised except the people who owned the firewall.

    Egress control is the cheapest high-value change a mid-sized network can make, and most teams put it off because it breaks things in the first week. This post is about doing it anyway, and about the outbound protocol almost nobody can block outright: DNS.

    Why default allow outbound hurts

    Before and after diagram: with default allow outbound, command and control and a DNS tunnel both reach the attacker; with controlled egress the server reaches only an internal resolver and proxy, direct connections are dropped and logged, and resolver queries are filtered

    The diagram compares a network with default allow outbound against one with controlled egress, showing where direct connections are dropped and where DNS queries get filtered and logged.

    An intrusion has to talk to something. Initial access might come through a phished laptop or an exposed service, but after that the attacker needs command and control, tooling downloaded from somewhere, and a path to carry data out. Inbound filtering does nothing about any of those.

    Servers are the easy case. A database host has no business browsing the web. An application server needs a handful of destinations: its database, a package mirror, a payment API, maybe a metrics endpoint. If you can name those, you can write a default-deny outbound policy and the attacker’s reverse shell to a random VPS simply fails. Log4Shell (CVE-2021-44228) made this concrete for a lot of people. Exploitation needed the vulnerable server to make an outbound LDAP or RMI connection to the attacker. Hosts with tight egress were far harder to exploit in practice, even before patching.

    Workstations are harder because people browse. For those I’d settle for forcing all web traffic through a proxy or a filtering resolver and blocking direct outbound on everything else.

    A default-deny starting point

    Here is a minimal nftables ruleset for an application server. The addresses are examples, replace them with your own resolver and proxy.

    table inet egress {
      set resolvers { type ipv4_addr; elements = { 10.0.0.2, 10.0.0.3 } }
      set proxies   { type ipv4_addr; elements = { 10.0.1.10 } }
    
      chain output {
        type filter hook output priority 0; policy drop;
        oifname "lo" accept
        ct state established,related accept
        ip daddr @resolvers udp dport 53 accept
        ip daddr @resolvers tcp dport 53 accept
        ip daddr @proxies tcp dport 3128 accept
        limit rate 5/minute log prefix "egress-drop "
      }
    }

    The last rule earns its place. Every outbound packet that matches nothing above gets logged just before the policy drops it, rate limited so a noisy host doesn’t flood the journal. In the first week that log is your to-do list: each entry is either a legitimate dependency you forgot or something you should be worried about. I’ve found a forgotten telemetry agent and a cron job posting to a defunct webhook this way, both on hosts I thought I understood.

    Run it in log-only mode first (swap the policy to accept and keep the log rule) for a week or two. Then flip it.

    Why DNS is different

    Everything above leaves the resolver alone, because the host has to be able to resolve names. And a resolver is a program that forwards arbitrary questions to arbitrary servers on the internet. If an attacker controls the authoritative server for a domain they registered, every query for a name under that domain is delivered to them by your own infrastructure.

    That is DNS tunneling. The client encodes data into the query name, for example `mfrggzdfmztwq2lk.a1.t.example.net`, and the attacker’s authoritative server decodes it and replies with data in a TXT, CNAME or NULL record. Tools like iodine and dnscat2 do exactly this, and so does a fair amount of real malware.

    The protocol limits shape what it looks like. A label can be 63 octets and a full name 253 characters in text form (RFC 1035). Names are case-insensitive, so the encoding is usually base32 or hex, which gives about 5 or 4 bits per character rather than 6. In practice that means a few dozen bytes of payload per query, so a tunnel needs a lot of queries to move anything. That volume is your best detection signal.

    What tunnels look like in the logs

    A tunnel tends to show three things, and none of them is reliable alone.

    Many unique subdomains under one parent domain. A CDN may generate some, but a tunnel generates thousands that are never repeated, so caching does not help the attacker or hide the traffic.

    Long, high-entropy labels. Legitimate names are made of words. Base32 payloads are not.

    Unusual record types and response sizes. A host that suddenly asks for lots of TXT or NULL records, or gets large responses, deserves a look.

    With Zeek writing JSON dns.log, the first signal is a one-liner. It counts distinct names per parent domain. The “last two labels” shortcut breaks on suffixes like co.uk, so use a public suffix list if you turn this into a real detection.

    jq -r '.query' dns.log \
      | awk -F. 'NF>2 && !($0 in seen) {seen[$0]=1; n[$(NF-1)"."$NF]++}
                 END {for (d in n) print n[d], d}' \
      | sort -rn | head -20

    And a small entropy check you can bolt onto a pipeline:

    import math
    from collections import Counter
    
    def entropy(label: str) -> float:
        counts = Counter(label)
        total = len(label)
        return -sum(c / total * math.log2(c / total) for c in counts.values())
    
    def suspicious(name: str) -> bool:
        first = name.split(".")[0]
        return len(first) >= 20 and entropy(first) > 3.5

    Those thresholds are mine, picked from eyeballing my own traffic, not from a paper. Treat them as a starting point and tune them against a week of your real logs, because CDN and anti-virus lookups will trip a naive version. I’d alert on the combination: many unique names to one parent domain from one host, plus long high-entropy labels.

    Controls that work better than detection

    Detection is the backstop. Shrinking what DNS can reach is the better investment.

    Force every client to use your internal resolver and block outbound 53 from everything else. Hosts that hardcode 8.8.8.8 are either misconfigured or hiding something, and the drop log will tell you which.

    Run the resolver with response policy zones (RPZ) or a filtering service so newly registered and known-bad domains don’t resolve. Domain age is a surprisingly good signal because attackers register throwaway names.

    Close the side doors. DNS over TLS (RFC 7858) uses port 853 and DNS over HTTPS (RFC 8484) uses 443, so a client can bypass your resolver entirely. Block 853 outright. For DoH, you can disable it in browsers by policy and block the well-known public DoH endpoints, but I won’t pretend that is complete, since anything on 443 can be a DoH server. This is the argument for forcing web traffic through a proxy, too.

    Pin the resolver’s own upstream. If the resolver can forward to the whole internet, restrict it to the recursion it needs and log its queries centrally. Query logs from the resolver are far better than logs from a tap, because they show which internal client asked.

    Expect it to break things

    I haven’t seen a first egress rollout that went without surprises. Package managers, license servers, NTP, OCSP and CRL fetches, and cloud metadata endpoints all show up as drops. That is the point of the log-only period. Budget a couple of weeks, start with the servers that matter most, and keep the allow list in version control so changes get reviewed like any other firewall change.

    If you do one thing this month, turn on logging for outbound drops and for resolver queries. A week of that data will teach you more about your network than most audits.

  • Threat hunting with ATT&CK: from a technique to a hypothesis to a query

    Threat hunting with ATT&CK: from a technique to a hypothesis to a query

    Why most hunts go nowhere

    Flowchart of a threat hunting loop: ATT&CK technique, hypothesis, telemetry check, query, triage, then either a detection or a periodic hunt, and finally a hunt log entry that feeds back to the start

    The hunt loop as a flowchart, drawn by me (not a screenshot).

    The usual failed hunt starts with “let’s look for anything weird in the logs.” Three hours later someone has a pivot table of 40,000 rare process names, none of them malicious, and the hunt gets written up as “no findings.” That isn’t a hunt. It’s browsing.

    A hunt is a falsifiable question about your own environment. “Has an attacker established persistence through scheduled tasks on a server that never creates them?” can be answered yes or no with data you already collect. MITRE ATT&CK is useful here for one reason: it gives you a catalog of behaviors to turn into those questions, so you don’t start from a blank page.

    ATT&CK isn’t a detection strategy on its own. It’s a vocabulary, and the work is translating it.

    Start from a technique, then add a constraint

    Pick one technique and one place it would matter. Scheduled task persistence is T1053.005, and it’s a good teaching case because it is both common in real intrusions and common in legitimate software, which forces you to deal with noise.

    The hypothesis needs three parts: the behavior, the population it applies to, and what normal looks like there. Mine:

    “On our Windows servers, schtasks.exe creating a task that runs a binary from a user-writable path (Temp, ProgramData, Users\Public) is rare, and nearly all of it is explained by a short list of installers and management tools.”

    That sentence tells you the telemetry (process creation with command lines), the filter (create plus a writable path), and the success condition (a short, explainable list). If the data comes back with 900 distinct parents, the hypothesis was wrong and you’ve learned something about your estate, which is a legitimate outcome.

    Check that the data exists before you write the query

    This is the step people skip. Process creation events with full command lines are Sysmon event ID 1, or Windows Security event 4688 with the “Include command line in process creation events” policy enabled. Without that policy 4688 records the image but not the arguments, and a hunt for /create flags is impossible. Scheduled task creation is also logged directly as Security event 4698, but only if the “Audit Other Object Access Events” subcategory is on, and many baselines leave it off.

    Before hunting, count the events per host per day. A server that reports zero process events is not clean. It’s blind. I’ve seen hunts conclude “no activity” on a host where the agent had been dead for three weeks.

    A first query

    Here is the hypothesis as KQL against the Microsoft Defender for Endpoint DeviceProcessEvents table. The table and column names are real. Adapt the path list to your environment.

    DeviceProcessEvents
    | where Timestamp > ago(30d)
    | where FileName =~ "schtasks.exe"
    | where ProcessCommandLine has "/create"
    | where ProcessCommandLine has_any (@"\Temp\", @"\ProgramData\", @"\Users\Public\", @"\AppData\")
    | summarize runs = count(),
                hosts = dcount(DeviceName),
                first = min(Timestamp),
                last = max(Timestamp)
        by InitiatingProcessFileName, InitiatingProcessParentFileName
    | order by hosts asc, runs asc

    Sort ascending on hosts. The interesting rows are parents that appear on one or two machines, not the ones appearing on 300. A software deployment tool hits everything. An intruder hits what they can reach.

    Then look at the rows that survive and read the actual command lines. Don’t trust the summary. A parent of cmd.exe launched from w3wp.exe on a web server is a very different story from cmd.exe launched by your patching agent, and both would collapse into the same “cmd.exe” row if you stopped at the first column.

    Triage the results like an investigator

    For each unexplained hit, answer four things and write them down:

    1. What launched it, and what launched that? Walk the process tree up at least two levels.
    2. What does the task execute, and does that file exist, and who wrote it?
    3. What else did that host do in the ten minutes around it: new services, new outbound connections, credential access?
    4. Is the account that did it one that ever does admin work?

    Most hits will be benign, and that’s fine, as long as you record why. “Backup agent vendor X creates this task on install” becomes an allowlist entry with an owner and a date. Next quarter that entry is what keeps the hunt from re-triaging the same 30 rows.

    Turn the hunt into a detection

    A hunt that finds nothing still produced something: a query with a known false-positive profile. If the allowlist is short and stable, promote it into a scheduled detection. If it’s long and churns every month, don’t. Keep it as a periodic hunt, because an alert nobody trusts is worse than no alert (the previous posts on alert fatigue and Sigma rules cover that tradeoff).

    Writing it up as Sigma makes the logic portable. The process_creation category and fields like Image and CommandLine are standard Sigma taxonomy:

    title: Scheduled task created pointing at user-writable path
    status: experimental
    logsource:
      category: process_creation
      product: windows
    detection:
      selection_img:
        Image|endswith: '\schtasks.exe'
        CommandLine|contains: '/create'
      selection_path:
        CommandLine|contains:
          - '\Temp\'
          - '\ProgramData\'
          - '\Users\Public\'
      condition: selection_img and selection_path
    falsepositives:
      - Software installers and management agents (maintain an allowlist)
    level: medium
    tags:
      - attack.persistence
      - attack.t1053.005

    Keep a hunt log

    Each hunt gets a short record: hypothesis, ATT&CK ID, data source, date range, query, results, disposition, and what changed afterward (new detection, new logging, or nothing). It takes ten minutes and it’s the difference between a program and a series of afternoons. It also shows your coverage gaps. If you can’t write the data source line because the telemetry doesn’t exist, the first deliverable of that hunt is a logging change.

    I’d rather run six well-scoped hunts a quarter than one sprawling exercise. Pick techniques that your actual intrusions or your peers’ public incident reports use, not the ones that look good on a heatmap. A fully green ATT&CK coverage matrix tells you which boxes someone ticked, and says nothing about whether the detections fire.

    What this doesn't do

    A hunt of this kind finds behavior that reuses a known technique through a known tool. It won’t find an operator who creates the task through the Task Scheduler COM API, never touching schtasks.exe, which is exactly what several public tools do. That’s why the next iteration of the hypothesis should target the outcome (a new task registered, event 4698 or the task XML files under C:\Windows\System32\Tasks) rather than one binary. Hunting the artifact rather than the tool is slower to write and survives much longer.