flawopen.com/Teardowns/CVE-2021-3156 Sudo Baron Samedit

CVE-2021-3156: Sudo Baron Samedit Heap Overflow

Critical 7.8 CWE-122 Patch Teardown
ELI5 — The Trailing Backslash Trick

Imagine a sign-painter who turns escaped letters like '\n' into new lines. Whenever he sees a backslash '\', he skips it and copies the next letter. But a prankster ends a word with a single backslash right at the end of the sign. The painter sees the backslash, skips it, and copies the letter after it—which is the empty blank wall beyond the sign! He keeps writing all over the wall, destroying the house's master deeds. In Sudo, a trailing backslash allowed an unprivileged user to overwrite root authentication structures in heap memory.

Target: Sudo utility on Unix/Linux operating systems
Vector: Invoking sudoedit -s '\' with unescaped backslashes
Impact: Local privilege escalation to root without password
Remediation: Verifying character existence before skipping backslashes in loop

The Mechanism & Root Cause

When sudo executed in shell mode (-s or sudoedit -s), it concatenated command line arguments with escaping backslashes. It then called set_cmnd() to unescape the string. If an argument ended with an unescaped backslash, the copy loop incremented past the null terminator (from[1] != '\0'), copying out-of-bounds heap data and overflowing destination buffers.

plugins/sudoers/sudoers.c (Vulnerable)Vulnerable
/* VULNERABLE: Unescape loop skips past string termination null byte */
for (to = user_args, from = NewArgv[0]; *from != '\0'; from++) {
    if (from[0] == '\\' && !isspace((unsigned char)from[1]))
        from++; /* BUG: If from[1] == '\0', loop skips past null terminator! */
    *to++ = *from;
}
*to = '\0'; /* Corrupts adjacent heap chunks with root auth structures */
plugins/sudoers/sudoers.c (Patched)Hardened
/* FIXED: Explicitly check that from[1] is neither space nor the null byte */
for (to = user_args, from = NewArgv[0]; *from != '\0'; from++) {
    if (from[0] == '\\' && from[1] != '\0' && !isspace((unsigned char)from[1]))
        from++;
    *to++ = *from;
}
*to = '\0';

The Attack & Exploit Sequence

Defensive Engineering & Prevention Rules

Explore related security topics and post-mortems: Complete Security Directory →