Tricking a program with more privileges to do something that the owner of the program didn't intend is called privilege escalation.
When a privileged program reads data from the outside, it should verify that this data is harmless. This is called data sanitization. For example, a setuid program that executes an external program should verify that the program it's executing is the intended one. In this case the program depends both on the comamnd string ls -la /dir
and on the value of the PATH
environment variable¹. The only safe values for PATH
are those such that the first entry for ls
and any other command that the program might execute is the intended one; in practice that means completely ignoring the external information (the value of PATH
in the environment) and setting PATH
to a known safe value.
Sudo removes most environment variables, including PATH
which it sets to a safe default. This makes it easier to write safe privileged components by using sudo rather than a custom setuid program for privilege elevation. A program run through sudo
starts up with a safe value for PATH
. You can still get things wrong, of course. For example allowing a user to run sudo ./example
allows them to run whatever they want since they can create an executable called example
in the directory of their choice.
¹ And LD_xxx
variables used by the dynamic linker, but the dynamic linker of the setuid program wipes those when it sees that the program it's linking is setuid.