Safeguard
Application Security•

CWE-272 Least Privilege Violation: Drop Rights After chroot

CWE-272 means keeping elevated privilege longer than needed. Learn the drop-after-use pattern for chroot and other privileged calls, with code in C.

Safeguard Security Team
2 min read

CWE-272, Least Privilege Violation, states that the elevated privilege required to perform operations such as chroot() should be dropped immediately after the operation is performed.

It applies to any daemon, installer, or setuid program that starts with more rights than it needs for its main work.

How it happens

A program starts as root to bind a port, call chroot(), or open a protected file. Then it carries on running as root through the rest of its life, including the parts that parse untrusted input. Any bug in those parts now runs with full rights.

// Vulnerable pattern: stays root after the privileged step
chroot("/var/app/jail");
chdir("/");
// ... continues serving requests as root

What an attacker gains

MITRE lists access to resources with the elevated privilege that the attacker's own account could not reach, including reading application data, files, or directories. A small flaw elsewhere in the program becomes a big one.

How to find it

MITRE's detection notes cite several approaches, each with partial coverage:

  • Source code weakness analyzers and context configured analysis.
  • Manual source code review, rated highly cost effective for this weakness.
  • Binary or bytecode analysis comparing the binary to the application's design.
  • Host based vulnerability scanning, run against the running system.

A quick manual check: run the process and inspect its user.

ps -o user,pid,cmd -C myservice

How to fix it

Do the privileged work first, then drop rights permanently and verify that the drop worked.

if (chroot("/var/app/jail") != 0 || chdir("/") != 0) {
    exit(EXIT_FAILURE);
}
if (setgid(app_gid) != 0 || setuid(app_uid) != 0) {
    exit(EXIT_FAILURE);
}
// confirm we cannot get root back
if (setuid(0) == 0) {
    exit(EXIT_FAILURE);
}

Drop the group before the user, since changing groups needs root. Check every return value, which is the subject of CWE-273.

Quick check

Why drop the group ID before the user ID?

After the user ID is lowered, the process may no longer have the right to change its group, so the group change would fail or be skipped.

Sources

Never miss an update

Weekly insights on software supply chain security, delivered to your inbox.

Self-healing security runs on Safeguard.

Your first fix PR is minutes away.

No sales call required, even your agent can complete the purchase over MCP.