Author: canutethegreat

  • Security headers that matter: CSP, HSTS and friends

    Security headers that matter: CSP, HSTS and friends

    Run any site through a header scanner and you’ll get a letter grade and a list of a dozen headers you’re “missing”. Some of them matter a lot. Some do almost nothing in 2026. One of them, if you follow old advice, can make things slightly worse. Chasing the grade is how teams end up with a Content-Security-Policy that allows 'unsafe-inline' from * and a perfect score.

    Here’s how I’d split them, roughly in the order I’d spend effort.

    HSTS: cheap, high value, one sharp edge

    Chart placing HTTP security headers by deployment effort and risk reduced: HSTS and nosniff low effort, strict CSP and Trusted Types high effort and high value, and X-XSS-Protection, Expect-CT and HPKP in a retire zone

    HTTP Strict Transport Security (RFC 6797) tells the browser to only talk to your host over HTTPS for a set period, and to refuse click-through on certificate errors. It closes the gap where a user types example.com, the first request goes out over plain HTTP, and someone on the coffee shop network rewrites the redirect. That’s the SSL stripping attack Moxie Marlinspike demonstrated back in 2009, and it still works against sites without HSTS.

    Strict-Transport-Security: max-age=63072000; includeSubDomains; preload

    The sharp edge is includeSubDomains. It applies to every subdomain, including that old internal tool on legacy.example.com that only speaks HTTP. Roll it out with a short max-age first (say 300 seconds), confirm nothing broke, then go to a year or two.

    The preload token only matters if you submit the domain to the browser preload list at hstspreload.org, which bakes it into Chrome, Firefox and Safari so even the very first visit is HTTPS. The list requires a max-age of at least a year, includeSubDomains and the preload token. Getting removed later takes months to reach users, so treat preload as a one-way door.

    CSP: the one worth real effort

    Content-Security-Policy is the only header on the list that meaningfully reduces the impact of cross-site scripting, which is still one of the most common web bugs. It’s also the one most often deployed in a form that does nothing.

    The traditional approach was an allowlist of script sources: script-src 'self' https://cdn.example.com https://www.google-analytics.com. Research from Google (Weichselbaum et al., “CSP Is Dead, Long Live CSP!”, ACM CCS 2016) looked at real-world policies and found that around 95% of them could be bypassed, mostly because allowlisted domains hosted JSONP endpoints or old libraries an attacker could abuse. If you allow a large CDN, you allow every script on that CDN.

    What works is a nonce-based strict policy (wrapped here for readability, it’s a single header line):

    Content-Security-Policy:
      script-src 'nonce-r4nd0mB4se64' 'strict-dynamic' https: 'unsafe-inline';
      object-src 'none';
      base-uri 'none';
      frame-ancestors 'self';
      report-to csp-endpoint

    The server generates a fresh random nonce per response and puts it on every legitimate script tag: <script nonce="r4nd0mB4se64">. Injected scripts don’t have the nonce, so they don’t run. 'strict-dynamic' lets scripts you trusted load further scripts, which is what makes this workable with modern bundlers and tag managers. The https: and 'unsafe-inline' entries look alarming, but they’re fallbacks for old browsers: any browser that understands nonces ignores 'unsafe-inline', and any browser that understands 'strict-dynamic' ignores host and scheme sources.

    object-src 'none' kills plugin-based injection. base-uri 'none' stops an attacker injecting a <base> tag that silently re-points every relative script URL.

    The hard part is the nonce. It has to be unpredictable and unique per response, which doesn’t play well with fully cached HTML. For static sites, hash-based CSP ('sha256-...' per inline script) is the alternative.

    Roll it out with Content-Security-Policy-Report-Only first and collect reports for a few weeks. Expect noise from browser extensions injecting scripts. Filter on the source-file and blocked-uri fields before you panic.

    If you want to go further, Trusted Types (require-trusted-types-for 'script') makes DOM XSS sinks like innerHTML refuse plain strings. Support started in Chromium-based browsers, so check where the other engines are before relying on it. It takes real refactoring, so I’d do it for high-value apps, not everywhere.

    frame-ancestors, not X-Frame-Options

    Clickjacking defence is easy. frame-ancestors 'none' (or 'self') in CSP says who’s allowed to frame your page. X-Frame-Options: DENY is the older equivalent and only supports DENY or SAMEORIGIN. Send both if you need to support very old browsers; modern ones use frame-ancestors when both are present.

    The small ones that are still worth one line

    X-Content-Type-Options: nosniff
    Referrer-Policy: strict-origin-when-cross-origin
    Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=()
    Cross-Origin-Opener-Policy: same-origin

    nosniff stops browsers from guessing a response’s type, which matters when users can upload files you later serve. Without it, a “text file” containing HTML or script could be treated as such.

    Referrer-Policy: strict-origin-when-cross-origin is already the default in current browsers. Set it explicitly anyway, especially if your URLs ever carry tokens or IDs. I’ve seen password reset tokens leak to third-party analytics through the Referer header more than once.

    Permissions-Policy turns off powerful browser features your site doesn’t use, including for any iframes you embed. It’s cheap and it limits what a compromised third-party script can ask for.

    Cross-Origin-Opener-Policy: same-origin puts your page in its own browsing context group, so a cross-origin window that opened you (or that you opened) can’t keep a handle to you. That blocks a family of cross-site leak attacks and is a prerequisite for cross-origin isolation. It can break OAuth and payment popups that rely on window.opener, so test those flows. same-origin-allow-popups is the usual compromise.

    The ones to stop worrying about

    X-XSS-Protection controlled a browser XSS filter that Chrome removed in 2019 and that no current major browser ships. The filter itself could be abused to leak information or selectively disable legitimate scripts. If you set it at all, set it to 0. Don’t set 1; mode=block because a scanner asked for it.

    Expect-CT is obsolete. Certificate Transparency is enforced by browsers regardless, and the header is deprecated.

    Public-Key-Pins (HPKP) is gone, and it was a footgun while it existed. Pin a key, lose the key, and your site is unreachable for returning visitors until the pin expires.

    Setting them without surprises

    Set headers in one place, at the edge or reverse proxy, so every response gets them. In nginx, two details catch people:

    server {
        add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always;
        add_header X-Content-Type-Options "nosniff" always;
        add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    
        location /api/ {
            # Any add_header here means NONE of the server-level ones are inherited.
            add_header Cache-Control "no-store" always;
            include /etc/nginx/snippets/security-headers.conf;
        }
    }

    Without always, nginx only adds the header to 2xx and 3xx responses, so your error pages ship without them. And add_header directives are inherited from the enclosing level only if the current level has none of its own. Add one header in a location block and you silently drop all the others there. Put the common set in a snippet and include it everywhere.

    Then test what’s actually returned, from outside, on a few representative URLs including an error page:

    curl -sI https://example.com/does-not-exist | grep -iE 'strict-transport|content-security|x-content-type|referrer|permissions'

    Headers are one layer of defence in depth. A strict CSP won’t fix the XSS bug, but it often turns an exploitable one into a blocked one and a report in your inbox. That’s a good trade for a few lines of config and a nonce.

  • Container image hardening: minimal images, non-root, read-only filesystems

    Container image hardening: minimal images, non-root, read-only filesystems

    Most container images in production are a full Linux distribution with an application on top. A Debian or Ubuntu base, a package manager, a shell, curl, and an application running as root with a writable filesystem. It works, it’s easy to debug, and it hands an attacker who gets code execution everything they need for the next step.

    Hardening an image is a handful of small changes, each removing a capability the application never needed, and that an attacker would very much like to have. None of them are new, and every one of them gets skipped all the time.

    Start with less: minimal and distroless bases

    Side-by-side comparison of a typical container image and a hardened one: distroless base, no shell, non-root UID 65532, read-only root with noexec tmpfs, all capabilities dropped, no privilege escalation, seccomp RuntimeDefault and pinned digests, with the attacker capability each change removes

    The fastest win is shipping fewer things. A typical debian or ubuntu base pulls in a hundred-odd packages, and your scanner will report CVEs against all of them, whether or not your app ever touches them. That noise has a real cost, which I covered in the vulnerability management series earlier this week. Every finding in a package you don’t use is triage time you’re not spending on one that matters.

    There are a few levels of minimal:

    • scratch is empty. Good for fully static binaries, like Go built with CGO_ENABLED=0. You have to bring your own CA certificates and timezone data if you need them.
    • Google’s distroless images contain the runtime pieces an app needs (libc, CA certs, tzdata, sometimes a language runtime) and no shell or package manager.
    • Wolfi-based images from Chainguard and minimal Alpine images sit somewhere in between, with a package manager available at build time.

    For a Go service, a multi-stage build onto distroless looks like this:

    FROM golang:1.25 AS build
    WORKDIR /src
    COPY go.mod go.sum ./
    RUN go mod download
    COPY . .
    RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/app ./cmd/app
    
    FROM gcr.io/distroless/static-debian12:nonroot
    COPY --from=build /out/app /app
    USER 65532:65532
    ENTRYPOINT ["/app"]

    The compiler, the source and the module cache stay in the build stage. The final image is your binary plus a few megabytes of support files.

    The objection I always hear is debugging. “How do I exec into it without a shell?” On Kubernetes you don’t need to: an ephemeral debug container shares the target’s process namespace and brings its own tools.

    kubectl debug -it pod/payments-api-7d9f8c --image=busybox:1.36 --target=app

    That’s better than a shell baked into every image anyway, because the tools only exist while someone is actually debugging.

    Don’t run as root

    Containers running as UID 0 are the default, and it’s a bad default. Root inside a container isn’t the same as root on the host, since namespaces and dropped capabilities limit it, but it’s much closer than people assume, and it turns every container runtime bug into a bigger problem.

    CVE-2019-5736 is the classic example. A malicious process in a container could overwrite the host’s runc binary and get root on the host the next time runc ran. The exploit needed root inside the container. A container running as an unprivileged user wasn’t exploitable that way.

    Set the user in the image, with a numeric UID so Kubernetes can verify it:

    USER 65532:65532

    Then enforce it at the platform level so an image that forgets doesn’t get scheduled. In Kubernetes that’s runAsNonRoot: true in the security context, which makes the kubelet refuse to start a container whose user resolves to 0.

    If the app needs to bind to port 80 or 443, don’t give it root. Bind to 8080 and let the Service or the load balancer map the port, or add only NET_BIND_SERVICE.

    Make the root filesystem read-only

    An attacker with code execution usually wants to write something: a downloaded tool, a modified config, a web shell, a cron entry. A read-only root filesystem takes that away, and it catches a surprising number of bugs where an app was quietly writing logs or caches into its own image.

    Most apps need somewhere to write, usually /tmp or a cache directory. Give them exactly that as a tmpfs or an emptyDir volume and nothing else. With plain Docker:

    docker run --read-only \
      --tmpfs /tmp:rw,noexec,nosuid,size=64m \
      --cap-drop=ALL \
      --security-opt=no-new-privileges:true \
      --user 65532:65532 \
      registry.example.com/payments-api@sha256:<digest>

    The noexec on the tmpfs matters. A writable directory that can also execute binaries is half of what an attacker needed from a writable root.

    The Kubernetes security context

    All of this comes together in the pod spec. This is the block I start every deployment from:

    securityContext:
      runAsNonRoot: true
      runAsUser: 65532
      runAsGroup: 65532
      seccompProfile:
        type: RuntimeDefault
    containers:
      - name: app
        image: registry.example.com/payments-api@sha256:<digest>
        securityContext:
          allowPrivilegeEscalation: false
          readOnlyRootFilesystem: true
          capabilities:
            drop: ["ALL"]
        volumeMounts:
          - name: tmp
            mountPath: /tmp
    volumes:
      - name: tmp
        emptyDir:
          medium: Memory
          sizeLimit: 64Mi

    allowPrivilegeEscalation: false sets the kernel’s no_new_privs flag, so setuid binaries can’t raise privileges. Dropping all capabilities removes things like CAP_NET_RAW, which some runtimes still grant by default and which lets a process craft raw packets. RuntimeDefault seccomp blocks a set of syscalls that normal apps never make.

    Kubernetes Pod Security Admission’s restricted profile enforces most of this for you: non-root, no privilege escalation, all capabilities dropped and a seccomp profile. It doesn’t require a read-only root filesystem, so that one you have to enforce with your own policy (Kyverno, Gatekeeper or a ValidatingAdmissionPolicy). Turn restricted on in warn mode for a namespace first, see what breaks, and fix those workloads before switching to enforce.

    Pin what you ship, rebuild what you pin

    Reference images by digest in deployment manifests, not by tag. A tag is a mutable pointer, and :1.42.0 can be repushed. The digest is a hash of the content and can’t.

    Pinning has a cost, though. A pinned base image never gets its security fixes unless you rebuild. Pair digest pinning with an automated job that rebuilds images on a schedule against fresh bases and opens the PR to bump the digest. Pinning without rebuilding is how you end up running a two-year-old OpenSSL with perfect reproducibility.

    What this doesn’t fix

    None of this stops an exploit in your own code. A read-only, non-root, distroless container with a SQL injection bug still has a SQL injection bug, and the attacker still reaches whatever the app’s database credentials can reach. Container runtime escapes still happen too. CVE-2024-21626, the runc file descriptor leak fixed in runc 1.1.12, allowed escape through a crafted working directory, and the fix was patching runc, not anything in the image.

    What hardening does is make the second step expensive. The attacker lands with no shell, no package manager, no writable path that can execute, no root and no extra capabilities. I’ve read enough incident reports to know that “the attacker had a foothold but couldn’t do much with it” is one of the better sentences you can have in one.

  • Patch SLAs that teams actually meet

    Patch SLAs that teams actually meet

    Part 3 of 3 in the Vulnerability management that works series. Part 1: Prioritising vulnerabilities: CVSS vs EPSS vs CISA KEV. Part 2: SBOMs: what they’re actually good for.

    Most patch SLAs I’ve reviewed were written once, by a security team, copied from a compliance framework, and then missed every month for years. Everyone knows they’re missed. The dashboard is red, the quarterly report says “remediation velocity is improving”, and the actual exposure doesn’t change much. An SLA that’s always missed stops being a control and turns into a number people have stopped reading.

    The first two parts of this series covered deciding what matters and knowing where it runs. This one is about the commitment itself: how to write an SLA that engineering teams can actually hit, and how to measure it so the number tells you something.

    Why SLAs get missed

    Table of patch SLA tiers: P1 7 days (72 hours for KEV on internet-facing assets), P2 30 days, P3 90 days, P4 untimed, with exception limits, per-tier metrics and a timeline showing the clock starting at the later of fix availability and first detection

    In my experience it’s rarely laziness. The usual causes are structural.

    The SLA is keyed to CVSS. “Criticals in 15 days, highs in 30” sounds reasonable until you see that a big share of your findings are high or critical, most of them in packages nobody can exploit. Teams triage by ignoring, and the ones that matter get lost in the pile.

    The clock starts at the wrong time. If the timer starts when the CVE is published, but your scanner only picks it up eleven days later, a team with a 15-day SLA has four days left before they’ve even heard about it.

    The fix is often outside the team’s hands. A vulnerable OpenSSL in a base image maintained by a platform team, or a library pinned by a vendor’s SDK, can’t be fixed by the team that gets the ticket. They miss the SLA and learn that the SLA is noise.

    There’s no legitimate way to say no. Without an exception process, a team facing a fix that would break a major integration has two options: silently miss, or mark the finding as a false positive. Both destroy the data.

    Tie tiers to priority, not severity

    Use the priority tiers from part one as the SLA tiers. Something like this, written as policy in a file that lives in a repo and gets reviewed like code:

    # vuln-sla.yaml
    tiers:
      P1:   # in CISA KEV, or high EPSS on an exposed asset
        remediate_within: 7d
        emergency_if: [kev, internet_facing]
        emergency_within: 72h
        max_exception: 14d
        exception_approver: security-lead
      P2:   # high EPSS, or CVSS >= 9.0 on an exposed asset
        remediate_within: 30d
        max_exception: 60d
        exception_approver: engineering-manager
      P3:   # CVSS >= 7.0
        remediate_within: 90d
        max_exception: 180d
        exception_approver: engineering-manager
      P4:
        remediate_within: null   # fixed by routine upgrades, tracked not timed
    clock_starts: max(fix_available, first_detected)

    These numbers aren’t arbitrary, though they aren’t magic either. PCI DSS v4.0 requirement 6.3.3 asks for critical patches to be installed within one month of release. FedRAMP’s continuous monitoring expects high-risk findings fixed within 30 days, moderate within 90 and low within 180. If you’re under one of those regimes, your tiers have to fit inside them. If you’re not, they’re still a sane reference point.

    P1 is deliberately short. The 72-hour emergency path exists because the gap between a fix being available and mass exploitation can be very short for internet-facing products. Equifax is the case everyone cites for a reason: the Apache Struts fix for CVE-2017-5638 was out in early March 2017, and attackers were in through an unpatched dispute portal by mid-May. That’s about two months, and the exploit was public within days of the advisory.

    Start the clock fairly

    Starting the clock at max(fix_available, first_detected) sounds generous. It’s the version that puts detection on the hook, which is where it belongs. If your SBOM store gets rescanned daily (part two), first detection is within a day of the advisory for anything you’ve inventoried, and the gap stops mattering. If it isn’t, the SLA report shows a lot of findings detected weeks after publication, and that’s a scanning problem you can fix.

    Starting at fix availability matters too. Holding a team to a 7-day SLA for a vulnerability with no patch measures nothing. For no-fix cases, the P1 action is a mitigation, such as a WAF rule, disabling the feature or pulling the service off the internet, and the SLA applies to the mitigation.

    Route the ticket to whoever can fix it

    The single most effective change I’ve seen is sending findings to the team that controls the fix instead of the team that owns the running service. A vulnerable package in a shared base image becomes one ticket for the platform team, not forty tickets for forty application teams who all have to wait on the same rebuild.

    That requires the asset inventory to know two owners per artifact: who runs it and who builds each layer. It’s worth the effort. Duplicate tickets for an unfixable root cause are the fastest way to teach people that the SLA isn’t real.

    Make the cheap path the default

    Teams meet SLAs when patching is boring. Concretely:

    • Rebuild container images on a schedule, not only when the app changes. A nightly rebuild against the latest base image clears most OS-package findings without anyone opening a ticket.
    • Let Renovate or Dependabot open dependency PRs continuously, and auto-merge patch-level updates when tests pass. The SLA work then becomes reviewing a PR that already exists.
    • Run unattended security updates on long-lived hosts, with a reboot window, so kernel and library fixes don’t wait for a human.
    • Keep a test suite good enough that people trust an automated upgrade. This is the hidden dependency of everything above.

    If a P3 finding requires a human to notice it, research it, write the fix and deploy it, a 90-day SLA will be missed in any organisation with more findings than engineers.

    Measure the distribution, not the average

    Mean time to remediate is the metric everyone reports and it’s nearly useless. A few ancient findings drag it up, a flood of auto-merged fixes drags it down, and it moves for reasons unrelated to risk. Report three things per tier instead: the percentage closed within SLA, the median and 90th percentile time to close, and the age of the oldest open finding.

    SELECT priority,
           round(100.0 * count(*) FILTER (WHERE closed_at - clock_start <= sla) / count(*), 1) AS pct_within_sla,
           percentile_cont(0.5) WITHIN GROUP (ORDER BY closed_at - clock_start) AS p50,
           percentile_cont(0.9) WITHIN GROUP (ORDER BY closed_at - clock_start) AS p90
    FROM findings
    WHERE closed_at >= now() - interval '90 days'
    GROUP BY priority
    ORDER BY priority;

    That query only sees closed findings, which flatters you. Pair it with the oldest open finding per tier, because a P1 that has been open for 40 days is the one an incident report will be about.

    Exceptions get reported too: how many are open, how many were renewed, and which teams hold most of them. An exception renewed three times is an accepted risk, and someone senior should sign it by name.

    The test of a good SLA

    An SLA is working when the percentage within SLA is high enough that a miss is surprising, and when a miss leads to a conversation about why. If your P1 compliance is 95% and every miss gets a short write-up, people will treat P1 seriously. If it’s 40%, nobody will, no matter what the policy document says.

    So start with tiers you can meet today, even if they feel loose, and tighten them as automation catches up. A 30-day P2 that’s met 95% of the time beats a 15-day P2 that’s met half the time, both for actual risk and for whether anyone believes the number.