Search code examples
csystemsetuidexecve

What's the difference between system() and execve()


I use linux and c.

First, I soft link bin/zsh to sh

Second, I login as root the run the following program.

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
 char *v[3];
 if(argc < 2) {
  printf("Please type a file name.\n");
  return 1;
 }
 v[0] = "/bin/cat"; v[1] = argv[1]; v[2] = 0;
 /* Set q = 0 for system(), and q = 1 for execve */
 int q = 0;
 if (q == 0){
   char *command = malloc(strlen(v[0]) + strlen(v[1]) + 2);
   sprintf(command, "%s %s", v[0], v[1]);
   system(command);
 }
 else execve(v[0], v, 0);
 return 0 ; 
}

Third, I login as a normal user(not root). Now, I can remove or rewrite a file which I don't have write privilege by using the execute file of this program.

Like this:

./a.out text;\`echo \”Not right\”>text\`”

Now I can write "Not right" into the file "text". I only have read privilege of this file

enter image description here

The read and write privilege of these files. enter image description here

Fourth, I change q to 1. That means, this time I use execve instead.

And do the same thing as above. But this time I cannot change the content of the file.

Why? I google in the internet, but I can not find the different between system and execve.


Solution

  • system invokes a shell to parse the string and handle quoting and variable interpolations and stuff. execve does none of this. It replaces the program with the called program and passes the argument strings exactly as specified; ie. it will not interpret quotes.