Commands.page Logo

Understanding env_keep in Ubuntu Sudo Configuration

This article explains the env_keep option within the sudo configuration file on Ubuntu systems. It details how environment variables are handled during privilege escalation, why certain variables are preserved by default, and how administrators can safely customize this setting to maintain security while ensuring necessary tools function correctly.

How Sudo Handles Environment Variables

By default, the sudo command resets the environment before executing a command as another user, typically root. This security measure prevents users from injecting malicious environment variables that could alter the behavior of privileged programs. However, some variables are necessary for specific tasks, such as displaying graphical applications or maintaining specific path configurations. The env_keep option allows administrators to whitelist specific variables that should survive this reset.

Configuring env_keep in the Sudoers File

To modify this setting, you must edit the /etc/sudoers file. Never edit this file directly with a standard text editor, as syntax errors can lock you out of sudo access. Instead, use the visudo command, which checks for syntax errors before saving changes.

To add a variable to the keep list, use the following syntax within the visudo interface:

Defaults env_keep += "VAR_NAME"

You can keep multiple variables by listing them within the quotes, separated by spaces. For example, to preserve both the HOME and DISPLAY variables, the configuration would look like this:

Defaults env_keep += "HOME DISPLAY"

Security Best Practices

While env_keep is useful, it should be used sparingly. Keeping unnecessary variables increases the attack surface. Never preserve variables related to dynamic linking or library loading, such as LD_PRELOAD, LD_LIBRARY_PATH, or IFS. These variables can be exploited to force privileged programs to load malicious code. Only whitelist variables that are strictly required for the specific commands being executed.