[MUSIC]
Now let's look at some of the implicit assumptions that programs make, these
are ones that are not explicitly stated in the code, and they can really bite you.
Implicit, if you call system or popen, you're using PATH,
the environment variable PATH.
Interestingly, there are a couple of version of the exec family, execlp and
execvp, those spawn subcommands.
But when they look for
the subcommand to spawn, they use the PATH variable to find this.
So if I can play games with PATH here,
then I can cause your programs to execute the wrong thing.
And the environment also is inherited through execs, unless you reset it.
Moral of the story, always reset it.
That brings us to rule number one on the next slide.
Don't trust environment variables.
The only time you should use them is when they don't affect the security of
the program.
If they do affect the security of the program and you still need to use them,
make sure they are set to a known and safe value.
If they already is defined, check for validity.
But the bottom line is, if you can clean out the environment variable list and
create your own, one you know is trusted, that's much better.
In practice, what is this mean?
The next slide show, some of it.
Don't add them to the environment variable list without
being sure that it is not already defined.
So, remember how multiple definitions are handled?
Here's an example of an environment variable list
with PATH defined in two ways.
And you'll notice, the first one ends with usr/etc and
the second one begins with a dot.
Which PATH is actually used for the search path by the command interpreter?
It varies, but it's usually going to be the second, the last one.
But what happens if you essentially delete PATH, or replace PATH with something else?
It's the first one that's going to be deleted or replaced.
So in other words,
if I can load that second PATH into your environment in some way, and
then delete the first one or get you to delete the first one, I'm in business.
In order to do things right, you need to clean out the environment variable list
every time you spawn a subcommand.
And that's what execve does.
Set envp to a new array of environment variables,
an array of string with names and values.
The names being the variable names and the values being the variable values.
And then pass in through execve.
Now, if anyone tried to do anything untoward to you
by manipulating the previous environment, it's wiped out, so you're fine.
The second tip is never use system, or popen, or indeed anything that spawns
a subs command unless you clean out your own environment first.
Personally, I wouldn't even do it then, I don't like those functions.
But you can use them safely, providing you know the environment is cleaned out.