Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

system() vs execve()

Both system() and execve() can be used to execute another command inside a program. Why in set-UID programs, system() is dangerous, while execve() is safe ?

like image 599
Jake Avatar asked Dec 12 '14 10:12

Jake


People also ask

How is system different from execv?

The system( ) function works differently from the exec*( ) functions; instead of replacing the currently executing program, it creates a new process with fork( ) . The new process executes the shell with execve( ) while the original process waits for the new process to terminate.

Why is system () unsafe while execve () is safe?

Why is system() unsafe while execve() is safe? If the external program is decided by external factors, such as user input, since system() uses /bin/sh internally, the user can input a dummy program, followed by a ; and include potentially malicious commands after that, and they'll be executed too.

Is execve a system call?

execve() - Unix, Linux System Call.

What is the difference between system and exec?

system() will execute the supplied command in a child process that it spawns. exec() will replace the current process with the invocation of the new executable that you specify. If you want to spawn a child process using exec , you'll have to fork() your process beforehand.


1 Answers

system will call the shell (sh) to execute the command sent as an argument. The problem with system because the shell behavior depends on the user who run the command. A small example:

Creating a file test.c:

#include <stdio.h>

int main(void) {
    if (system ("ls") != 0)
        printf("Error!");
    return 0;
}

Then:

$ gcc test.c -o test

$ sudo chown root:root test

$ sudo chmod +s test

$ ls -l test
-rwsr-sr-x 1 root root 6900 Dec 12 17:53 test

Creating a script called ls in your current directory:

$ cat > ls
#!/bin/sh

/bin/sh

$ chmod +x ls

Now:

$ PATH=. ./test
# /usr/bin/id
uid=1000(cuonglm) gid=1000(cuonglm) euid=0(root) egid=0(root) groups=0(root),
24(cdrom),25(floppy),29(audio),30(dip),44(video),46(plugdev),105(scanner),
110(bluetooth),111(netdev),999(docker),1000(cuonglm)
# /usr/bin/whoami
root

Oops, you got a shell with root privileges.

execve does not call a shell. It executes the program that passed to it as first argument. The program must be a binary executable or a script start with shebang line.

like image 77
cuonglm Avatar answered Sep 18 '22 05:09

cuonglm