Course contentsShow
← Linux
Lesson 30 of 1,8191. Shell Architecture and Process EnvironmentFree lesson

Security Risks in Variable Injection

Mitigate command injection risks caused by the unsanitized expansion of environment variables.

In this lesson, you will learn how environment variables can be manipulated to hijack the behavior of programs through unintended command injection.

The Danger of Untrusted Input

Because environment variables are inherited by child processes, they represent a "hidden" communication channel between the shell and the programs it runs. When a script or binary uses an environment variable to define what it should execute or where it should look for files, it trusts that the environment hasn't been tampered with. If an attacker can inject malicious text into those variables, they can trick the program into performing unauthorized actions.

A Concrete Illustration: Path Hijacking

Imagine you have a script that runs a command using a relative path, relying on the environment variable PATH to find the binary. If an attacker gains control over your environment, they can prepend a directory they control to your PATH.

Consider this logic in a script:

# The script runs 'ls' based on the system PATH
ls -l

If an attacker executes:

export PATH="/tmp/malicious_folder:$PATH"

Now, if the attacker creates a file named ls inside /tmp/malicious_folder containing a script like rm -rf /, the original script will execute the attacker’s malicious code instead of the legitimate ls utility. Because the shell resolves the binary location using the variable provided in the environment block, the process follows the attacker's instructions unknowingly.

Mitigating the Risk

The primary risk stems from the fact that processes often assume the inherited environment is "clean" or standard. To mitigate this, robust programs should never blindly trust environment variables to dictate logic flow. Instead of relying on variables for critical pathing or configuration, secure programs explicitly define absolute paths or sanitize the variables they read before passing them to execution functions like execve. By validating the content of variables—ensuring they don't contain unexpected characters or malicious strings—you prevent the shell from tokenizing or executing unintended logic.

Key Takeaway: Never treat environment variables as trusted data, as they are easily modified by users and can be leveraged to hijack the execution path of your processes.