Author: canutethegreat

  • Buffer overflow exploit mitigations and how they actually work under the hood

    Buffer overflow exploit mitigations and how they actually work under the hood

    In 1988, Robert Morris Jr. wrote a worm that exploited a buffer overflow in the fingerd daemon’s gets() call, and it took down something like 10% of the internet’s connected machines in a day. The bug was embarrassingly simple: fingerd read input into a fixed-size buffer with no bounds checking, so a crafted request could overwrite the return address on the stack and redirect execution into attacker-supplied shellcode. There was no canary, no ASLR and no NX bit. The stack was writable and executable, and the return address sat right there to be overwritten.

    Almost forty years later we still see buffer overflows in CVE feeds every week, but exploitation looks very different now because stack canaries, ASLR and NX/DEP ship by default on nearly every mainstream OS. None of them fix the underlying bug class. They raise the cost of exploitation, sometimes a lot and sometimes only a little, so it helps to know where each one stops.

    Stack canaries are tripwires, not fences

    x86-64 stack frame showing stack canary, ASLR, and NX/DEP coverage

    A stack canary is a known value placed between local buffers and the saved return address/frame pointer on the stack, written at function entry and checked at function exit. If a buffer overflow overwrites it on the way to clobbering the return address, the check fails before the function returns and the process dies loudly instead of jumping to attacker-controlled code.

    Mechanically, on glibc/GCC, the canary value comes from a per-process random value stored in the thread control block (accessible via the %fs segment on x86-64, specifically fs:0x28). The prologue of a protected function does something like:

    mov rax, fs:0x28
    mov [rbp-8], rax    ; stash canary on stack

    and the epilogue reloads it and compares:

    mov rax, [rbp-8]
    xor rax, fs:0x28
    jnz __stack_chk_fail

    If the XOR isn’t zero, the stored value was changed, meaning something wrote past its intended buffer, and __stack_chk_fail() gets called. That function doesn’t try to recover. It prints something like “* stack smashing detected *” and calls abort(), which raises SIGABRT. It fails fast on purpose, because you can’t negotiate with a corrupted stack.

    What canaries protect against specifically: sequential buffer overflows that overwrite the canary before reaching the return address. That’s a narrower category than “stack overflow” sounds. They do nothing for:

    – Overflows that use a format string bug or an arbitrary write primitive to hit the return address directly without touching the canary

    – Overflows in a different memory region entirely, heap, BSS, a global function pointer

    – Information leaks that read the canary value first, then write a matching value back (this is the standard bypass once you have an arbitrary-read primitive, since the canary is constant for the life of the process, only randomized at process start, not per-call)

    – Thread-local races where a leaked canary from one thread gets reused against another, if the attacker can pivot

    So a canary catches one common shape of overflow. It’s cheap (a few instructions per call) and it stops the “smash the return address with a long string” attack that made the Morris worm easy. It is not a memory-safety guarantee.

    ASLR randomizes, it doesn’t prevent

    Address Space Layout Randomization randomizes the base addresses of the stack, heap, shared libraries, and (with PIE binaries) the executable itself, at process load time. The idea: even if an attacker has a working exploit that redirects execution, they don’t know where anything useful lives in memory, so they can’t point to it.

    Entropy sources vary by platform and region. On 64-bit Linux, mmap’d regions (including shared libraries) get randomized within a range that’s typically 28-30 bits of entropy depending on kernel config, giving you roughly 2^28 possible base addresses. The stack gets somewhat less, historically around 2^24-2^28 bits of usable entropy after accounting for how addresses get used. Heap randomization is weaker still on many systems. None of these numbers are secure in the cryptographic sense. They make brute-force guessing impractical in a reasonable number of attempts, not impossible.

    ASLR is probabilistic, not absolute, and a few things follow from that:

    1. Brute force is viable against fork-happy daemons. If a service forks a new child per connection without re-randomizing (classic case: Apache’s mod_php on some old configs, or earlier Linux implementations before fork-based ASLR fixes), an attacker can just guess repeatedly. Each failed guess might crash the child, but the parent keeps forking new ones with the same layout. The 2009 “Heap Feng Shui” era and various Apache/PHP remote exploits used exactly this pattern, fork-and-retry until the guess lands.

    2. 32-bit systems have far less entropy (roughly 8 bits of usable randomization for mmap in some configs), making brute force practical in seconds rather than requiring days.

    3. Information leaks defeat ASLR completely, no guessing required. This is the dominant bypass in modern exploitation. If an attacker can read even one pointer, a leaked stack address from an uninitialized variable, a libc address disclosed via a format string bug, a heap pointer printed in an error message, they can compute the base of the containing region (since offsets within a loaded module are fixed, only the base is randomized) and derive the address of literally anything else in that same module. ASLR fails as a unit: leak one address in libc, you have all of libc.

    That’s why so much modern exploit development is “find a memory disclosure bug, then a corruption bug” instead of one bug doing everything. ASLR didn’t stop exploitation. It turned “overwrite and jump” into “leak, compute, then overwrite and jump.”

    NX/DEP: write or execute, not both

    NX (No-eXecute, called DEP on Windows) marks memory pages as either writable or executable, never both, the W^X principle. Stack and heap memory, which an attacker can write shellcode into, gets marked non-executable. The CPU enforces this at the hardware level via a bit in the page table entry (the NX bit on x86, XN on ARM), so even if execution somehow jumps into attacker-controlled data, the processor refuses to fetch instructions from that page and faults instead.

    This single-handedly killed the classic “overflow the buffer, put shellcode in the buffer, redirect return address to the buffer” attack that worked against fingerd in 1988. You can’t do that on a properly configured modern system. That specific technique is dead.

    What it does not stop: reusing existing executable code already mapped in memory. That’s return-oriented programming (ROP). Instead of injecting new code, the attacker chains together short existing instruction sequences ending in ret (called gadgets), already present in the binary or libc, each one doing a small piece of useful work (pop a register, call a function, set up arguments) before “returning” into the next gadget. The stack holds a sequence of addresses instead of shellcode, and the CPU is just executing legitimate, already-mapped, already-executable code the entire time. NX doesn’t care, because no new executable memory was ever introduced. A classic ROP chain redirects into libc’s system() function with a controlled argument, achieving the same “spawn a shell” result the Morris worm got, just via a completely different mechanical path. Return-to-libc attacks predate even the term ROP and were already circumventing early NX deployments in the early 2000s.

    Where this leaves us

    Layer all three together and the 1988 fingerd attack doesn’t work anymore in its original form: the canary catches the naive overflow, NX stops shellcode injection even if you dodge the canary, and ASLR means you don’t know where libc or the stack live even if you’re trying to build a ROP chain. That’s real progress.

    But plenty is left. Heap exploitation (use-after-free, double-free, heap metadata corruption) is barely touched by any of these three, canaries are a stack-only mechanism, and heap corruption routes around them entirely. ROP and its descendants (JOP, COOP for C++ vtables) route around NX by construction. And ASLR’s entire security model collapses the moment there’s an info leak, which is why modern CVEs so often chain a disclosure bug with a corruption bug rather than relying on one or the other alone. Control-Flow Integrity, stack clash protections and Intel CET’s shadow stack exist because the three classic mitigations were never a complete answer. They are worth having, and they set a much higher bar than the one Robert Morris cleared in 1988.

  • Horcrux: I backed up a Postgres container, deleted it, restored it, and the tables were gone

    Horcrux: I backed up a Postgres container, deleted it, restored it, and the tables were gone

    Full disclosure: I make Horcrux. It’s my Gentoo-based hypervisor, it’s pre-1.0, and this is my notebook for the week.

    Everybody has a backup story that ends with “and then I found out it didn’t include the data”. I didn’t want that story to be about my own software, so last Saturday morning I tested exactly that. A Postgres container, a backup from the Backups page, everything deleted, a restore. The restore finished with a running database in it and no tables.

    The setup

    The daily server image from that morning (horcrux-bin 0.1.0_p202611210632), installed by answer file onto a ZFS root in a KVM guest on one of my lab laptops. 4 vCPUs, 6 GB of RAM, OpenRC. I logged into the web UI as the administrator account the installer makes and clicked everything below. The only things I did outside the browser are marked.

    The workload is a stack from the Stacks page: postgres:16-alpine with a named volume called pgdata, and a second container that inserts a row into a table every 5 seconds so there is something to lose. It was 26 rows when I broke things. I used the Docker runtime, not Podman, and the compose file went in as plain text.

    Stacks page with a two service compose file: a postgres db with a named volume and a ticker service
    The stack. The password in it is a throwaway for this VM.

    The backup

    Backups page, pick the container, mode snapshot, zstd, a note that says “db before I break it”, Back up now. It was done inside the 12 seconds I recorded and wrote a 102.8 MiB archive. Then Verify, which said “verified OK (2 file(s) checked)”.

    Backing up the database container. 13 seconds, real time.
    Backups page showing one archive marked OK after verification
    Verified OK.

    Then I looked inside the archive, which is a thing I should have done before the video. It holds three files: a manifest, inspect.json, and rootfs.tar, about 297 MB uncompressed. That is the container’s file system as docker export writes it. In the tar, /var/lib/postgresql/data/ is an empty directory. On the live container that directory was 9.3 MB. Verify checks the checksums of what is in the archive, so it passed. The data was never in it.

    Breaking it

    I removed the stack from the Stacks page. The confirm text says it “stops and deletes every container in it”, and that’s accurate. The pgdata volume survived, which is Docker’s normal behaviour. Then I went to the Volumes page and removed the leftovers, the way you tidy up when you think a project is gone.

    Removing the stack and then the volume. 16 seconds, real time.
    Volumes page listing pgdata and an anonymous volume, with the Actions column off screen to the right
    The Volumes page at 1440 pixels wide. The Remove buttons are past the right edge, so I clicked them with a script. A person would scroll sideways.

    Restoring

    Backups page, Restore on the archive, original id, start after restore. It failed:

    Red banner: Restore failed, HTTP 500, network notes_default not found
    The first restore attempt.

    The stack’s network, notes_default, went away with the stack, and the container’s config in the backup still points at it. What the failure left behind was a container in the Created state and a brand new empty pgdata volume. I made the network again on the Container Networks page, pressed Start on the Containers page, and it ran. The image is a new one, horcrux-restore/notes_db_9405c03c:94a20893, imported from the tar.

    The failed restore, the network, and starting the container. 39 seconds, real time.
    Containers page with the restored notes_db container, stopped, image horcrux-restore/notes_db
    Restored and stopped, before I pressed Start.

    Then I asked the database. The notes database exists, because the restored config still has POSTGRES_DB=notes and the Postgres image creates it on first start. It has no tables. The 26 rows are gone, and so is the table they were in. Nothing on any page warned me before or after.

    Terminal output: restored notes_db container up, database list including notes, no relations found, relation readings does not exist
    From a root shell on the node (the one other thing I did outside the browser): the list of databases, then “Did not find any relations”.

    Getting the data back by hand

    /var/lib/docker is its own ZFS dataset on a Horcrux install, so a ZFS snapshot of it contains every Docker volume. I tried that on the restored database: made a table with 1000 rows, took rpool/var/lib/docker@hand-before-drop (0 bytes used when it was taken), dropped the table, stopped the container, emptied the volume directory, copied pgdata back out of the snapshot’s .zfs/snapshot directory, and started it. Postgres logged “redo done” and “ready to accept connections”, and select count(*) said 1000.

    Terminal session: zfs snapshot, drop table, copy from the snapshot directory, redo done, count 1000
    The commands and the output, from the node.

    This isn’t a Horcrux feature. The Snapshots page only knows about VMs. It also worked once, on an idle database of one table, and a snapshot taken under write load only gives you crash recovery. For a database you care about, run pg_dump on a schedule. The file system layout just makes the snapshot trick possible.

    What doesn’t work (yet)

    • Container backups don’t include named volumes. This one matters most. I already had it in my QA notes from the Thursday before, with a fix on a branch that adds the volume data to the archive. I checked main again this morning, a week later, and that branch still isn’t merged, so a fresh daily image won’t have it either.
    • Restore only found out the network was gone at the start step. A failed restore leaves a half-made container and an empty volume behind. It should fail before it creates anything, or it should create the network.
    • The Volumes and Networks lists don’t refresh after you remove or create something with Docker selected. I watched the Networks list for 30 seconds after creating one and it never appeared. A reload showed it. Same on the Volumes page after removing pgdata: it was gone from disk and still on screen.
    • On the Volumes page at 1440 pixels the Actions column is off the right edge. On a 390 pixel phone the backup archive table is 887 pixels wide, so the Restore and Verify buttons sit behind a sideways scroll.
    • The times don’t agree. The Backups page shows 10:16:27 -08:00, the Containers page shows the creation time as 18:19:38 UTC, and the node’s own logs are in UTC.
    • Every container row carries the same warning that CRIU isn’t installed, so state can’t be saved. The warning is accurate, and it appears on every row.
    • The UI listens on port 8006 and not 443, and the certificate is self-signed, so the browser stops you at a warning first. I told the browser to ignore it.
    Phone-width Backups page with the archive table cut off after the Size column
    Backup archives on a 390 pixel wide screen. Time and Size fit, the buttons don’t.

    Design decisions

    The backup code calls itself a vzdump equivalent, and it follows Proxmox’s behaviour on purpose: a catalog of archives with SHA-256 checksums, Verify that re-reads them, retention per guest, restore into the same or a new id. Its header comment says a no-pause snapshot, a copy-before-write block job, isn’t implemented, so in snapshot mode a running container is frozen for the copy and then resumed. The restore form says the archive is verified first and that a corrupt one never touches the existing guest, and that part I believe, because the UI states it and the verify step exists.

    Containers go in with docker export, which is a file system and nothing else. The code has a comment saying so next to the function that puts the image config back by hand. I haven’t found anything written down about why volumes were left out, and I’m not going to invent a reason. My QA notes file it as a bug, not as a decision.

    ZFS is under all of this for the reason I gave in the last post: recovery and bit rot protection. The separate dataset for Docker’s data comes from the same layout that keeps the root file system rollbackable on its own. That layout is why the snapshot trick above works at all.

    Where it stands

    Backups work for containers that store their state inside the container. They don’t work for containers that use a volume, and that includes the usual way to run Postgres. The fix exists and isn’t merged yet. Until it is, I wouldn’t trust a container backup from this build to hold a database.

    Next: get that branch merged, then run this same test again on the build that has it, with a database big enough to take more than a second to copy. I haven’t re-run any of this on a newer image than the one from last Saturday, so the other items above are as of that build.

    Horcrux lives at horcrux.errant.solutions.

  • Linux privilege escalation hygiene: the SUID bits, capabilities and sudo rules that quietly hand out root

    Linux privilege escalation hygiene: the SUID bits, capabilities and sudo rules that quietly hand out root

    Most local privilege escalation I run into on real systems isn’t a kernel exploit. It’s a configuration someone added three years ago to make a deploy script work, and nobody has looked at since. A binary with a stray setuid bit, a capability granted to an interpreter, a sudoers line with a wildcard in it. Each one is a perfectly legitimate way for an unprivileged user to become root, and the system is doing exactly what it was told.

    This post is about auditing those three places and tightening them. It’s defensive: run these on boxes you own.

    SUID and SGID binaries

    Before and after diagram. Before: an unprivileged user reaches root through a stray SUID binary, a cap_setuid interpreter and a sudo tee wildcard rule. After: nosuid mounts with baseline diff, AmbientCapabilities in the unit file and a validated wrapper script close those paths, leaving one narrow logged route.

    The diagram compares the three paths above before and after the controls described in this post.

    A file with the setuid bit runs with the owner’s UID instead of the caller’s. That is how passwd can write to /etc/shadow. It also means every bug in that binary is a root bug, and the bug can be reached by any user who can execute it, through arguments, environment variables, and files it opens.

    The history is bad. CVE-2021-4034 (PwnKit) was an out-of-bounds read and write in pkexec, a SUID-root binary shipped on essentially every mainstream distribution, and it sat there for about twelve years. CVE-2023-4911 (Looney Tunables) was a buffer overflow in glibc’s dynamic loader, triggered through the GLIBC_TUNABLES environment variable, which made every SUID binary on affected systems a way in. Neither needed a misconfiguration. The attack surface was just there.

    So the first job is an inventory, and a diff against it over time:

    find / -xdev -perm -4000 -type f 2>/dev/null | sort > suid.now
    find / -xdev -perm -2000 -type f 2>/dev/null | sort > sgid.now
    diff suid.baseline suid.now

    On a stock Ubuntu 24.04 container image the SUID list is short: chfn, chsh, gpasswd, mount, newgrp, passwd, su, umount. A full server install has more. Anything that isn’t in your baseline needs an owner and a reason.

    Three habits remove most of the risk. Mount /tmp, /var/tmp, /home and /dev/shm with nosuid,nodev, so a SUID file dropped by an attacker or a user is inert there. Remove the bit from binaries you don’t use (chfn and chsh are good candidates on a server with no local logins). And alert on new SUID files at creation time. With auditd, a rule on the chmod family catches the bit being set (04000 is 0x800):

    -a always,exit -F arch=b64 -S chmod,fchmod -F a1&0x800 -F auid>=1000 -F auid!=unset -k suid_set
    -a always,exit -F arch=b64 -S fchmodat -F a2&0x800 -F auid>=1000 -F auid!=unset -k suid_set

    That doesn’t catch a SUID file arriving inside a tarball extracted as root, so the periodic find-and-diff stays.

    File capabilities

    Capabilities split root into pieces, which sounds like a safe improvement. In practice, some of those pieces are root under another name. CAP_SETUID lets a process become any UID, including 0. CAP_DAC_READ_SEARCH bypasses file read permission checks, so it reads /etc/shadow and SSH host keys. CAP_SYS_ADMIN is so broad that the capabilities man page itself describes it as overloaded. CAP_SYS_PTRACE lets you inject into other processes.

    The classic mistake is giving a capability to something that can run arbitrary code. I reproduced it in a throwaway container for this post: copy the Python interpreter, give it cap_setuid, and an ordinary user can become root.

    Terminal output from a disposable Ubuntu 24.04 container: the SUID file list, getcap showing cap_setuid=ep on a copied python3 binary, and user alice (uid 1001) running it to get uid=0(root).

    The screenshot is a real run in a disposable Ubuntu 24.04 container, with the output rendered to an image. The user alice has UID 1001 until she calls os.setuid(0) through the capable interpreter. Nothing in that sequence is a vulnerability. The capability does what it says.

    To find these on a host:

    getcap -r / 2>/dev/null

    Expect a few legitimate entries, for example cap_net_bind_service on a web server binary or cap_net_raw on ping on distributions that use capabilities instead of SUID for it. Any capability on a shell, an interpreter, find, tar, cp, vim or an editor is a finding. Check these against GTFOBins, which lists which common binaries turn each capability into a shell or a file write.

    For services, don’t set file capabilities at all. Use AmbientCapabilities=CAP_NET_BIND_SERVICE and CapabilityBoundingSet= in the unit file, which scopes the grant to that service and leaves no tagged binary on disk for someone else to execute. I covered the systemd side in the sandboxing post earlier in this blog.

    Sudo rules

    Sudo is where I find the most variety. The pattern is always the same: a rule meant to allow one narrow action that allows a general one instead.

    Anything that can spawn a shell or write arbitrary files is root. NOPASSWD: /usr/bin/vim, less, find, awk, tar, git, man, any interpreter. A user runs the allowed program, then escapes to a shell from inside it, and the shell keeps root. The NOEXEC tag blocks some of these by intercepting execve through LD_PRELOAD, but the sudoers manual is clear that it’s not a defence against a determined user, so I don’t count on it.

    Wildcards are the other classic. In sudoers, * matches any characters including slashes and spaces. This rule looks like it restricts writes to a log directory:

    deploy ALL=(root) NOPASSWD: /usr/bin/tee /var/log/app/*

    It allows sudo tee /var/log/app/../../../etc/sudoers.d/x, and it allows extra arguments after the first path, so a second file can be named too. The fix is a wrapper script that validates its input, or better, a design that doesn’t need root for it, like a group-writable log directory.

    Sudo itself has had its moments. CVE-2021-3156 (Baron Samedit) was a heap overflow in sudo’s argument handling, exploitable by any local user without being in sudoers, affecting 1.8.2 through 1.8.31p2 and 1.9.0 through 1.9.5p1. CVE-2023-22809 let a user with sudoedit access edit extra files by smuggling them into the EDITOR variable after a --. Keeping sudo patched matters, and so does keeping the number of people with sudo rights small, because those bugs are only reachable by whoever can run it.

    Audit with these:

    sudo -l -U deploy
    grep -rEn 'NOPASSWD|\*|!|env_keep|SETENV' /etc/sudoers /etc/sudoers.d/
    visudo -c

    Things I’d rather see in a sudoers file: full paths only, sudoedit instead of a bare editor, no SETENV tag, Defaults use_pty and Defaults logfile= or shipped logs, and a Cmnd_Alias per task so a review can read intent. If a rule needs a wildcard, treat it as code and review it like code.

    Making it stick

    A one-time cleanup decays in a quarter. What has worked for me is boring: put the SUID and capability baselines into configuration management so the expected state is declared, run the find and getcap diffs on a schedule, and ship sudo’s logs and the auditd suid_set key to wherever you already alert. Lynis and OpenSCAP both check parts of this if you’d rather start from a tool than from scripts. Tools like linPEAS are worth running against your own hosts once, because they show you the same list an attacker’s first script sees.

    The rule I apply to every entry on these three lists is the same one: if you can’t say who needs it and why, it goes.