Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Standard C usage of getenv and safe practices

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?

like image 741
user1944224 Avatar asked Feb 22 '13 23:02

user1944224


Video Answer


2 Answers

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.

Security concerns

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.

like image 178
Dietrich Epp Avatar answered Sep 25 '22 06:09

Dietrich Epp


#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
like image 23
loganaayahee Avatar answered Sep 26 '22 06:09

loganaayahee