Author: canutethegreat

  • Credential stuffing: the signals that give it away, and why CAPTCHAs are the weakest layer

    Credential stuffing: the signals that give it away, and why CAPTCHAs are the weakest layer

    Credential stuffing is the dullest attack on the internet and one of the most productive. Nobody exploits your code. Someone takes a list of email and password pairs leaked from other sites, replays them against your login endpoint, and waits for the fraction of people who reused a password. The success rate is low, commonly quoted as around one percent or less, but the lists have millions of lines and the cost per attempt is close to zero.

    The 2023 23andMe incident is the one I point people at. The company said attackers got into roughly 14,000 accounts with reused credentials, and because of the DNA Relatives sharing feature the exposed data reached around 6.9 million users. No vulnerability in 23andMe’s software was needed. The same goes for the 2024 Snowflake customer intrusions, where Mandiant tied the access to stolen credentials from infostealer logs used against accounts without MFA.

    What the traffic looks like

    A brute force attack hammers one account with many passwords. Stuffing is the opposite: many accounts, usually one or two attempts each, every password a real one that worked somewhere. That shape is the first and best signal. Your per-account failure counters never trip, because no account sees more than a couple of failures.

    The signals I actually look at, in rough order of usefulness:

    • Distinct usernames per client. A browser session that tries 40 different accounts in ten minutes is not a person with a bad memory.
    • Failure ratio across the whole login endpoint. Normal traffic has some baseline failure rate you can measure. A stuffing run pushes the global failure rate up, and the unknown-username share of failures tells you whether the list was aimed at you or sprayed generically.
    • Client fingerprint reuse. Botnets rotate IPs but the tooling underneath is often one library with one TLS fingerprint (JA3 or the newer JA4) and one header ordering. Thousands of “different” users sharing a fingerprint no real browser emits is a strong tell.
    • Hits on old passwords. If you keep the previous hash on password change, a login that succeeds with a password the user retired months ago is almost certainly a replayed list.
    • Success from a new device and ASN straight after a burst of failures from the same pool.

    This is the first query I run. It assumes a login event table with client_id (fingerprint plus IP bucket), username, success and ts.

    SELECT client_id,
           count(*)                       AS attempts,
           count(DISTINCT username)       AS users_tried,
           avg(success::int)              AS success_rate
    FROM   login_events
    WHERE  ts > now() - interval '15 minutes'
    GROUP  BY client_id
    HAVING count(DISTINCT username) >= 10
       AND avg(success::int) < 0.2
    ORDER  BY users_tried DESC;

    The thresholds are guesses until you’ve run it against your own baseline for a week. Shared NAT and corporate proxies will show up as a client with many real users, so I tune with the success rate and the fingerprint, not the distinct-user count alone.

    Rate limits and where they stop working

    Per-IP limits are the first thing everyone builds and the first thing residential proxy networks defeat. When each request leaves from a different home IP address, a limit of five attempts per minute per IP does nothing, and a tight one blocks real people behind carrier-grade NAT. I keep the per-IP limit as a cheap filter for the lazy attackers and expect nothing from it against the serious ones.

    The counters that matter are per account and per target. Slowing down the attempts on one username, and telling the real owner that someone is trying, costs the attacker nothing but it does protect the account that has the weak password. Pair that with a global circuit: when the endpoint-wide failure rate jumps, move every login that is not from a known device into a stricter path (step-up, delay, email confirmation) for the duration of the spike.

    Responses should be uniform. If “unknown user” and “wrong password” differ in text, status code or timing, you are handing the attacker a free list validator and making the next run cheaper. This is the same enumeration problem that shows up in password reset flows.

    Why the CAPTCHA is the weakest layer

    I’ve seen teams answer a stuffing incident by putting a CAPTCHA on the login form and calling it done. It stops the lazy script for a week. Then the attacker buys a solving service or pays people to solve them, and the cost per solve is small next to the value of a hijacked account. Meanwhile your legitimate users lose conversion and accessibility, and you have collected one more signal than you started with and none of the controls you needed.

    A CAPTCHA is fine as one input to a risk score, triggered when the other signals are already bad. As the main control it is a tax on your own customers.

    Stop the passwords from working

    The durable fix is making a replayed password useless. Two controls do that.

    First, refuse known-breached passwords. NIST SP 800-63B (revision 4, published in 2025) says verifiers must compare chosen passwords against a blocklist of values known to be compromised, and the Have I Been Pwned Pwned Passwords service gives you a free way to do it without sending the password anywhere. You send the first five hex characters of the SHA-1 hash and get back every suffix in that bucket, then compare locally. This is k-anonymity, and it works at login as well as at signup, which is where it pays off for stuffing: a user whose password is in the corpus gets forced through a reset instead of being let in.

    import hashlib, urllib.request
    
    def pwned_count(password: str) -> int:
        sha1 = hashlib.sha1(password.encode()).hexdigest().upper()
        prefix, suffix = sha1[:5], sha1[5:]
        req = urllib.request.Request(
            f"https://api.pwnedpasswords.com/range/{prefix}",
            headers={"Add-Padding": "true"},
        )
        body = urllib.request.urlopen(req, timeout=5).read().decode()
        for line in body.splitlines():
            h, _, n = line.partition(":")
            if h == suffix:
                return int(n)
        return 0

    The Add-Padding header makes the response size less informative to anyone watching the connection. I ran the unpadded form by hand to show what comes back:

    Terminal output: SHA-1 of the word password, the 1977-line Pwned Passwords range response for prefix 5BAA6, and the matching suffix with a count of 52372427. Text rendered into an image from a real run.

    The screenshot is a real run of those commands against the public API. The bucket for the prefix 5BAA6 holds 1,977 suffixes, and the SHA-1 of the word “password” appears in it with a count of 52,372,427. I rendered the terminal text into an image myself, so the colours are mine, the output is not.

    Second, add a factor an attacker cannot replay. A passkey or a TOTP code turns a correct password into a necessary but not sufficient credential. Passkeys are better because there is nothing to type into a phishing page or an infostealer log. If you can’t require a second factor for everyone, require it when the risk score says new device, new ASN, or the account’s password appeared in a breach corpus.

    Putting it together

    Flow diagram of five login controls from edge rate limit to second factor, with red branches showing the action taken at each

    Detection feeds the controls, and none of them is enough alone. If I had to pick the two that matter most, they are the breached-password check and a real second factor, because they work no matter how good the attacker’s proxy pool is. Everything else buys time and gives you telemetry. Start by running the query above against last week’s logs.

  • Egress filtering and DNS exfiltration: the outbound controls most networks skip

    Egress filtering and DNS exfiltration: the outbound controls most networks skip

    Most of the firewall rules I review are about what can get in. The rule sets are long, argued over, and audited every year. Outbound is usually one line: allow any to any. Then an incident happens, the attacker’s implant calls home over 443 or 53, and nobody is surprised except the people who owned the firewall.

    Egress control is the cheapest high-value change a mid-sized network can make, and most teams put it off because it breaks things in the first week. This post is about doing it anyway, and about the outbound protocol almost nobody can block outright: DNS.

    Why default allow outbound hurts

    Before and after diagram: with default allow outbound, command and control and a DNS tunnel both reach the attacker; with controlled egress the server reaches only an internal resolver and proxy, direct connections are dropped and logged, and resolver queries are filtered

    The diagram compares a network with default allow outbound against one with controlled egress, showing where direct connections are dropped and where DNS queries get filtered and logged.

    An intrusion has to talk to something. Initial access might come through a phished laptop or an exposed service, but after that the attacker needs command and control, tooling downloaded from somewhere, and a path to carry data out. Inbound filtering does nothing about any of those.

    Servers are the easy case. A database host has no business browsing the web. An application server needs a handful of destinations: its database, a package mirror, a payment API, maybe a metrics endpoint. If you can name those, you can write a default-deny outbound policy and the attacker’s reverse shell to a random VPS simply fails. Log4Shell (CVE-2021-44228) made this concrete for a lot of people. Exploitation needed the vulnerable server to make an outbound LDAP or RMI connection to the attacker. Hosts with tight egress were far harder to exploit in practice, even before patching.

    Workstations are harder because people browse. For those I’d settle for forcing all web traffic through a proxy or a filtering resolver and blocking direct outbound on everything else.

    A default-deny starting point

    Here is a minimal nftables ruleset for an application server. The addresses are examples, replace them with your own resolver and proxy.

    table inet egress {
      set resolvers { type ipv4_addr; elements = { 10.0.0.2, 10.0.0.3 } }
      set proxies   { type ipv4_addr; elements = { 10.0.1.10 } }
    
      chain output {
        type filter hook output priority 0; policy drop;
        oifname "lo" accept
        ct state established,related accept
        ip daddr @resolvers udp dport 53 accept
        ip daddr @resolvers tcp dport 53 accept
        ip daddr @proxies tcp dport 3128 accept
        limit rate 5/minute log prefix "egress-drop "
      }
    }

    The last rule earns its place. Every outbound packet that matches nothing above gets logged just before the policy drops it, rate limited so a noisy host doesn’t flood the journal. In the first week that log is your to-do list: each entry is either a legitimate dependency you forgot or something you should be worried about. I’ve found a forgotten telemetry agent and a cron job posting to a defunct webhook this way, both on hosts I thought I understood.

    Run it in log-only mode first (swap the policy to accept and keep the log rule) for a week or two. Then flip it.

    Why DNS is different

    Everything above leaves the resolver alone, because the host has to be able to resolve names. And a resolver is a program that forwards arbitrary questions to arbitrary servers on the internet. If an attacker controls the authoritative server for a domain they registered, every query for a name under that domain is delivered to them by your own infrastructure.

    That is DNS tunneling. The client encodes data into the query name, for example `mfrggzdfmztwq2lk.a1.t.example.net`, and the attacker’s authoritative server decodes it and replies with data in a TXT, CNAME or NULL record. Tools like iodine and dnscat2 do exactly this, and so does a fair amount of real malware.

    The protocol limits shape what it looks like. A label can be 63 octets and a full name 253 characters in text form (RFC 1035). Names are case-insensitive, so the encoding is usually base32 or hex, which gives about 5 or 4 bits per character rather than 6. In practice that means a few dozen bytes of payload per query, so a tunnel needs a lot of queries to move anything. That volume is your best detection signal.

    What tunnels look like in the logs

    A tunnel tends to show three things, and none of them is reliable alone.

    Many unique subdomains under one parent domain. A CDN may generate some, but a tunnel generates thousands that are never repeated, so caching does not help the attacker or hide the traffic.

    Long, high-entropy labels. Legitimate names are made of words. Base32 payloads are not.

    Unusual record types and response sizes. A host that suddenly asks for lots of TXT or NULL records, or gets large responses, deserves a look.

    With Zeek writing JSON dns.log, the first signal is a one-liner. It counts distinct names per parent domain. The “last two labels” shortcut breaks on suffixes like co.uk, so use a public suffix list if you turn this into a real detection.

    jq -r '.query' dns.log \
      | awk -F. 'NF>2 && !($0 in seen) {seen[$0]=1; n[$(NF-1)"."$NF]++}
                 END {for (d in n) print n[d], d}' \
      | sort -rn | head -20

    And a small entropy check you can bolt onto a pipeline:

    import math
    from collections import Counter
    
    def entropy(label: str) -> float:
        counts = Counter(label)
        total = len(label)
        return -sum(c / total * math.log2(c / total) for c in counts.values())
    
    def suspicious(name: str) -> bool:
        first = name.split(".")[0]
        return len(first) >= 20 and entropy(first) > 3.5

    Those thresholds are mine, picked from eyeballing my own traffic, not from a paper. Treat them as a starting point and tune them against a week of your real logs, because CDN and anti-virus lookups will trip a naive version. I’d alert on the combination: many unique names to one parent domain from one host, plus long high-entropy labels.

    Controls that work better than detection

    Detection is the backstop. Shrinking what DNS can reach is the better investment.

    Force every client to use your internal resolver and block outbound 53 from everything else. Hosts that hardcode 8.8.8.8 are either misconfigured or hiding something, and the drop log will tell you which.

    Run the resolver with response policy zones (RPZ) or a filtering service so newly registered and known-bad domains don’t resolve. Domain age is a surprisingly good signal because attackers register throwaway names.

    Close the side doors. DNS over TLS (RFC 7858) uses port 853 and DNS over HTTPS (RFC 8484) uses 443, so a client can bypass your resolver entirely. Block 853 outright. For DoH, you can disable it in browsers by policy and block the well-known public DoH endpoints, but I won’t pretend that is complete, since anything on 443 can be a DoH server. This is the argument for forcing web traffic through a proxy, too.

    Pin the resolver’s own upstream. If the resolver can forward to the whole internet, restrict it to the recursion it needs and log its queries centrally. Query logs from the resolver are far better than logs from a tap, because they show which internal client asked.

    Expect it to break things

    I haven’t seen a first egress rollout that went without surprises. Package managers, license servers, NTP, OCSP and CRL fetches, and cloud metadata endpoints all show up as drops. That is the point of the log-only period. Budget a couple of weeks, start with the servers that matter most, and keep the allow list in version control so changes get reviewed like any other firewall change.

    If you do one thing this month, turn on logging for outbound drops and for resolver queries. A week of that data will teach you more about your network than most audits.

  • Encryption at rest done properly: envelope encryption, key hierarchies and rotation

    Encryption at rest done properly: envelope encryption, key hierarchies and rotation

    What “encrypted at rest” usually means

    Diagram of an envelope encryption key hierarchy: a root key in an HSM wraps per-tenant key encryption keys, which wrap per-object data keys stored beside the encrypted objects, with a side panel showing KEK rotation rewrapping only the data keys

    Most of the time it means someone ticked a box. The disk volume or the bucket is encrypted with a key the platform manages, and the checkbox on the compliance spreadsheet turns green. That is not worthless. It covers a stolen drive, a decommissioned array that gets resold, a snapshot that lands in the wrong account. It does nothing against the more common threat: a process or a person with legitimate read access to the storage service. The platform decrypts transparently for anyone it considers authorized, so the encryption never gets in their way.

    If you want encryption to be a control and not a label, the design question is where the keys live, who can use them, and what happens when you need to change them. Envelope encryption handles all three reasonably well, and that’s why the major cloud KMS products are built around it.

    The two-layer idea

    You use two kinds of keys. A data encryption key (DEK) encrypts the actual data, one DEK per object, file, row group or tenant, whatever granularity you pick. A key encryption key (KEK) encrypts the DEKs. The wrapped DEK is stored next to the ciphertext. The KEK stays inside a KMS or HSM and never leaves it in plaintext.

    The first reason for this design is practical, not security. KMS services only want to handle small payloads. AWS KMS Encrypt accepts at most 4096 bytes of plaintext, so you cannot send a 2 GB backup through it. Instead you ask for a fresh data key, encrypt locally with a fast library, and keep only the wrapped copy:

    import boto3
    from cryptography.hazmat.primitives.ciphers.aead import AESGCM
    import os
    
    kms = boto3.client("kms")
    r = kms.generate_data_key(
        KeyId="alias/billing-data",
        KeySpec="AES_256",
        EncryptionContext={"tenant": "acme", "object": "invoices/2026-11.csv"},
    )
    dek, wrapped = r["Plaintext"], r["CiphertextBlob"]
    
    nonce = os.urandom(12)
    ct = AESGCM(dek).encrypt(nonce, data, b"invoices/2026-11.csv")
    del dek  # best effort; Python will not zero it for you
    store(wrapped, nonce, ct)

    Decrypting reverses it: send wrapped to kms.decrypt with the same encryption context, get the DEK back, decrypt locally. Every decrypt is a KMS API call, which means every decrypt is an authorization decision and a CloudTrail line. That audit trail is the part people underrate. Without it you know the data is encrypted. With it you know who asked for the key and when.

    Binding ciphertext to its context

    The encryption context in that call does real work. KMS uses it as additional authenticated data, so a wrapped key issued for tenant acme will not unwrap if you present it with tenant globex. It is also logged in clear, which makes it useful for detection and for IAM conditions such as kms:EncryptionContext:tenant.

    Do the same thing on the data side. AES-GCM takes associated data that is authenticated but not encrypted, and the object’s identifier is a good candidate. Without it, an attacker who can write to your storage can swap one valid record for another and your decryption will happily succeed. NIST SP 800-38D defines GCM and is explicit that the authentication covers the AAD as well as the ciphertext. Binding the ID costs nothing and kills a whole class of substitution bugs.

    A runnable version without a cloud account

    To check the mechanics I wrote a small script using the Python cryptography package, with RFC 3394 AES key wrap standing in for the KMS. It seals a record, rotates the KEK by rewrapping, and tries two things that should fail. I ran it in a throwaway container. The output is below.

    Terminal output of a Python script that seals a record with a data key, rewraps the key under a new key encryption key with the ciphertext hash unchanged, then shows decryption failing with the old key and when the object id changes

    The screenshot shows real output from that script. Two lines matter here. The ciphertext hash is identical before and after the rotation, so the bulk data was never touched. And a record moved to a different object ID fails with InvalidTag even though the key is correct.

    Rotation without downtime

    This is where people get confused, because “rotate the key” means two different jobs.

    Rotating the KEK is cheap if you built the hierarchy properly. You decrypt each DEK with the old KEK and wrap it with the new one. The bulk data stays where it is. Vault’s transit engine calls this rewrap, and AWS KMS has ReEncrypt. A billion objects means a billion small operations on 40-byte blobs (a wrapped 256-bit DEK under RFC 3394 is 40 bytes, as the output above shows), which you can run in the background at whatever pace your KMS quota allows.

    AWS’s automatic rotation is a related but weaker thing. It makes new key material for the same key ID, on a 365-day period by default and configurable between 90 and 2560 days, and keeps the old material so existing ciphertext still decrypts. Nothing gets re-encrypted. That is fine for hygiene and for auditors who want to see a rotation date. It does not limit the damage from a leaked key, because old material stays usable for everything it ever protected.

    Rotating a DEK means re-encrypting the data, and that is expensive. You do it when you have a reason: a suspected exposure, an employee with DEK access leaving, or a cryptographic limit. The limit is real for GCM. With random 96-bit nonces, SP 800-38D caps you at 2^32 encryptions under one key before the collision probability gets uncomfortable. A DEK per object makes that a non-issue. One long-lived DEK for a busy table does not.

    To roll without downtime, store a key ID or version with every record. Reads pick the key by that ID, writes always use the current one, and a background job migrates old records. The version field has to exist from day one. Retrofitting it later means guessing which key encrypted which row. That is miserable.

    The hierarchy, and who gets which permission

    A realistic hierarchy has three levels. A root key sits in an HSM or the cloud KMS, and a per-service or per-tenant KEK is wrapped by it. Below that, DEKs are generated per object. SP 800-57 Part 1 describes this kind of key hierarchy and the reasoning behind separating key-wrapping from data keys.

    The permission split is the real security benefit. The storage admin can read and copy ciphertext but cannot call kms:Decrypt. The application role can decrypt only with its own KEK and only with a matching encryption context. The KMS administrator can manage and disable keys but has no access to the data. Compromise any one of those roles alone and you still do not have plaintext.

    Deleting a KEK also gives you something close to crypto-shredding. If a tenant leaves and you delete their KEK after the scheduled waiting period (7 to 30 days in AWS KMS), every DEK wrapped under it becomes unrecoverable. That works as deletion for backups you cannot practically scrub, assuming no copy of the plaintext KEK or any unwrapped DEK exists elsewhere. Check that assumption before you tell a regulator about it.

    Where this goes wrong

    Caching DEKs in memory for performance is fine, with a TTL and a usage cap. The AWS Encryption SDK has a caching layer with limits on both. Caching them forever turns your hierarchy into one long-lived key again.

    Logging is the sneaky one. A DEK in a debug log or a core dump undoes everything above. Treat plaintext key material as a secret with a lifetime of seconds.

    And test the failure path. Disable the KEK in a staging environment and watch what your application does. A common mistake is a fallback that stores plaintext “so the system keeps working” when the KMS call fails.