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.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *hai;
printf("The current User name is\n");
hai="USER";
printf("%s\n",getenv(hai));
printf("The current User Directory is\n");
char *hai1="PWD";
printf("%s\n",getenv(hai1));
exit(0);
}
This program is passing the argument of the getenv() function its valid means get the output
Output:
The current User name is
loganaayahee
The current User Directory is
/home/loganaayahee/AdvanceUnix/
(or)
This is not the Environment variable means getenv() function return NULL.
hai="HELLO";
if(getenv(hai)==NULL)
printf("This is not Env\n");
else
printf("%s\n",getenv(hai));
Output:
This is Not Env
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With