C - Executing Bash Commands with Execvp

elmazzun picture elmazzun · Jan 3, 2013 · Viewed 32.1k times · Source

I want to write a program Shellcode.c that accepts in input a text file, which contains bash commands separeted by newline, and executes every commands in the text file: for example, the text file will contain:

echo Hello World
mkdir goofy   
ls

I tried this one (just to begin practicing with one of the exec functions):

#include <stdio.h>
#include <unistd.h>

void main() {
    char *name[3];

    name[0] = "echo";
    name[1] = "Hello World";
    name[2] = NULL;
    execvp("/bin/sh", name);
}

I get, in return,

echo: Can't open Hello World

I'm stuck with the execvp function, where did I go wrong?

Answer

unwind picture unwind · Jan 3, 2013

You're doing it wrong.

The first array index is the name of the program, as explained in the docs:

The execv(), execvp(), and execvpe() functions provide an array of pointers to null-terminated strings that represent the argument list available to the new program. The first argument, by convention, should point to the filename associated with the file being executed. The array of pointers must be terminated by a NULL pointer.

Also, bash doesn't expect free-form argument like that, you need to tell it you're going to pass commands using the -c option:

So, you need:

name[0] = "sh";
name[1] = "-c";
name[2] = "echo hello world";
name[3] = NULL;