Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Executing Bash Commands with Execvp

Tags:

c

bash

execvp

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?

like image 488
elmazzun Avatar asked Jan 03 '13 14:01

elmazzun


People also ask

Why does Execvp return?

execvp() returns a negative value if the execution fails (e.g., the request file does not exist).

Is Execvp a system call?

execvp : Using this command, the created child process does not have to run the same program as the parent process does. The exec type system calls allow a process to run any program files, which include a binary executable or a shell script .

What should I pass to Execvp?

the parameter(s) passed to execvp() are: 1) path/name of file to execute 2) the number of entries in the passed third parameter 3) a ppointer to an array of pointers to C strings, with the last entry being NULL.

What does the Execvp () command do?

The execvp function is most commonly used to overlay a process image that has been created by a call to the fork function. identifies the location of the new process image within the hierarchical file system (HFS).


1 Answers

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;
like image 136
unwind Avatar answered Sep 30 '22 00:09

unwind