Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Want the excutable run by execve() to use my preloaded library

Tags:

c

linux

fork

I am executing a program say A from another by first fork-ing followed by execve(). Now the problem is I would want A to use my library that I would generaly do by using LD_PRELOAD. How do I do it within execve().

Thanks

like image 787
Lipika Deka Avatar asked May 16 '11 07:05

Lipika Deka


People also ask

How use execve command in Linux?

Write a C code inside it having an exec() function. In the main program, while introducing the arguments, we call the file's name we have created “EXEC. c.” Then, by making a function call of execve(), use that call as an argument. And then print a statement 'ending…'.

What is the purpose of the execve function?

The execve function is most commonly used to overlay a process image that has been created by a call to the fork function. is the filename of the file that contains the executable image of the new process. is a pointer to an array of pointers to null-terminated character strings.

What is the LD_PRELOAD trick?

The LD_PRELOAD trick is a useful technique to influence the linkage of shared libraries and the resolution of symbols (functions) at runtime. To explain LD_PRELOAD, let's first discuss a bit about libraries in the Linux system. In brief, a library is a collection of compiled functions.

What does execve stand for?

execve() is a POSIX (and UNIX systems in general) function of the family of the exec*() functions that replace the current process image. The v comes from the fact that it takes an argument argv to the vector of arguments to the program (the same way the main function of a C program may take it).


1 Answers

you can pass the LD_PRELOAD in envp execve's argument:

the program that gets execved, named "run":

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

int main(int argc, char **argv) 
{

    printf("%s\n",getenv("LD_PRELOAD"));
}

the program that does the execve, named "ex":

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


int main(int argc, char **argv)
{
    char *const args[] = {"./run",NULL};
    char *const envs[] = {"LD_PRELOAD=caca",NULL};
    execve("./run",args,envs);
}

running it:

root@pinkpony:~# ./ex
ERROR: ld.so: object 'caca' from LD_PRELOAD cannot be preloaded: ignored.
caca

EDIT: the error shown gets thrown because "caca" lib can't be preloaded for run, so it works. (I skipped the fork() part for clarity but the usage is the same)

EDIT: doing something like:

LD_PRELOAD=caca ./ex

will not automagically preload caca lib when execve()-ing run if you're not passing it via envp execve()'s argument

like image 138
user237419 Avatar answered Oct 21 '22 06:10

user237419