LD_PRELOAD用法

      LD_PRELOAD,是个环境变量,用于动态库的加载,动态库加载的优先级最高,一般情况下,其加载顺序为LD_PRELOAD>LD_LIBRARY_PATH>/etc/ld.so.cache>/lib>/usr/lib。程序中我们经常要调用一些外部库的函数,以open()和execve()为例,如果我们有个自定义这两函数,把它编译成动态库后,通过LD_PRELOAD加载,当程序中调用open函数时,调用的其实是我们自定义的函数,下面以一个例子说明。

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(int argc,char *argv[])
{
	int  fd;
	execve("/bin/date","",NULL);
	if(fd=open("/home/songqiang/system_hook/hello.c",O_RDONLY)!=-1)
	{
		fprintf(stdout,"openfile successed!\n");
	}
	else
	{
		fprintf(stderr,"openfile error!\n");
	}
	close(fd);
	return 0;
}

在没有加载动态链接库前,结果显示:


/*
   hack.c
   功能:对open(),execve()进行劫持
   作者:SQ
*/
extern int __open(char *,int,int);
//参数3:环境设备配置
extern int execv(char *,char *[],char *envp[]);
//打开文件
int open(char * path,int flags,int mode)
{
	//输出打开的文件名
	printf("open :%s\n",path);
	return __open(path,flags,mode);
}
//启动程序
int execve(char * path,char* args[],char * envp[])
{
	printf("execv :%s\n",path);
	return execv(path,args,envp);	
}

加载动态链接库后:

    gcc -fpic -c -ldl hack.c

    gcc -shared -lc -o hack.so hack.o

    export LD_PRELOAD=./hack.so   //加载库

    export LD_PRELOAD=NULL;       //卸载库

 结果显示:


怎么让普通用户拥有root权限,可以实现reboot

#include <dlfcn.h>
#include <unistd.h>
#include <sys/types.h>

uid_t geteuid(void){return 0;}
uid_t getuid(void){return 0;}
uid_t getgid(void){return 0;}

 加载进去前:

加载后:


猜你喜欢

转载自blog.csdn.net/m0_37806112/article/details/80560235
今日推荐