I am trying to write C code which makes use of some ENV variables in a UNIX environment. The question is: Could reading variables (for example getenv()) cause buffer overflow? Moreover, how can I find the limit of the env variable size for my platform ? For example which header file?
Finally, what are the safest code practices in reading environment supplied variables?
Reading an environment variable with getenv()
will not cause a buffer overflow.
On Linux, inherited environment variables and their values are stored in the process address space by the kernel during exec()
. The getenv()
function just returns a pointer to this existing data. Since it does not copy any data, there is no buffer, and there can be no buffer overflow.
If you try to pass too many environment variables to a new process, exec()
will signal the E2BIG
error.
There aren't really any buffer overflow concerns with environment variables.
The security concerns center around the fact that you shouldn't trust the contents of the environment. If your program is run setuid (or setgid, etc.) then the environment is an attack vector. The user can set PATH
or LD_PRELOAD
or other variables in malicious ways.
However, it's rare to write setuid programs. This is a good thing, since there are so many reasons why it's difficult to make setuid programs secure.