Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't find the env passed into execve function

Tags:

c

execve

I would like to see if the environment variable I have passed in the execve() function has really been passed, so I made this code (Main.c):

int main(){

    char PATH[4];
    strcpy(PATH, "bin");
    char * newargv[] = {"./get","", (char*)0};
    char * newenviron[] = {PATH};
    execve("./get", newargv, newenviron);
    perror("execve");
    return 0;
}

(get.c):

int main()
{
    const char* s = getenv("PATH");
    printf("PATH :%s\n",s);

}

But, when I execute the binary issued by Main.c, I get this output:

PATH :(null)

whereas I want to see

PATH: bin

Do you have any explanation?

like image 514
juRioqs75 Avatar asked Jan 04 '23 11:01

juRioqs75


2 Answers

Environment strings must be in the format of VARIABLE_NAME=value of the variable.

Your PATH variable (the C variable, not the environment variable) should be a string with the contents PATH=bin.

Also, you need to end it with an extra null (along with the null that comes with the last string, of course) to indicate that there are no more strings in the environment.

From the execve(2) manpage (emphasis mine):

The argument envp is also a pointer to a null-terminated array of character pointers to null-terminated strings. A pointer to this array is normally stored in the global variable environ. These strings pass information to the new process that is not directly an argument to the command (see environ(7)).

and from the environ(7) manpage:

An array of strings called the environment is made available by execve(2) when a process begins. By convention these strings have the form ``name=value''.

like image 165
Qix - MONICA WAS MISTREATED Avatar answered Jan 07 '23 00:01

Qix - MONICA WAS MISTREATED


  1. Your string buffer PATH is not large enough for the string you're trying to put into it.

  2. The environment string needs to be "PATH=bin", not just "bin".

  3. As the other answer indicates, you need to end your list of environment strings with a null pointer, i.e. char *newenviron[] = {PATH, 0};.

You might try examining the environment structure that's passed to your program before modifying it, to see the necessary format. Here's an example of how to do this: http://nibot-lab.livejournal.com/115837.html

like image 29
nibot Avatar answered Jan 06 '23 23:01

nibot