作者: net66 原创
本文网址:http://www.cnblogs.com/net66/p/5609026.html
发布日期:2015 年 06月 22日
一、LD_PRELOAD是什么
二、程序调用流图
- LA_PRELOAD替换前
- LA_PRELOAD替换后
三、演示程序代码
- 主程序
// myverifypasswd.c
#include <stdio.h>
#include <string.h>
#include "mystrcmp.h"
void main(int argc,char **argv) {
char passwd[] = "password";
if (argc < 2) {
printf("usage: %s <password>\n",argv[0]);
return;
}
if (!mystrcmp(passwd,argv[1])) {
printf("Correct Password!\n");
return;
}
printf("Invalid Password!\n");
}
- 调用库
// mystrcmp.h
#include <stdio.h>
int mystrcmp(const char *s1, const char *s2);
// mystrcmp.c
#include <stdio.h>
#include <string.h>
#include "mystrcmp.h"
int mystrcmp(const char *s1, const char *s2)
{
return strcmp(s1,s2); //正常字串比较
}
四、程序编译与试验
演示流程图
编译、设置指令
gcc mystrcmp.c -fPIC -shared -o libmystrcmp.so #编译动态链接库
gcc myverifypasswd.c -L. -lmystrcmp -o myverifypasswd #编译主程序
export LD_LIBRARY_PATH=/home/n6/桌面/LD_PRELOAD #指定动态链接库所在目录位置
ldd myverifypasswd #显示、确认依赖关系
./myverifypasswd #运行主程序myverifypasswd
- 终端运行结果
n6@X240s:~/桌面/LD_PRELOAD$ gcc mystrcmp.c -fPIC -shared -o libmystrcmp.so
n6@X240s:~/桌面/LD_PRELOAD$ gcc myverifypasswd.c -L. -lmystrcmp -o myverifypasswd
n6@X240s:~/桌面/LD_PRELOAD$ export LD_LIBRARY_PATH=/home/n6/桌面/LD_PRELOAD
n6@X240s:~/桌面/LD_PRELOAD$ ldd myverifypasswd
linux-vdso.so.1 => (0x00007ffedc1bd000)
libmystrcmp.so => /home/n6/桌面/LD_PRELOAD/libmystrcmp.so (0x00007eff99a7f000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007eff99698000)
/lib64/ld-linux-x86-64.so.2 (0x000056269aba4000)
n6@X240s:~/桌面/LD_PRELOAD$ ./myverifypasswd
usage: ./myverifypasswd <password>
n6@X240s:~/桌面/LD_PRELOAD$ ./myverifypasswd abc
Invalid Password!
n6@X240s:~/桌面/LD_PRELOAD$ ./myverifypasswd password
Correct Password!
五、替换库代码
// myhack.c
#include <stdio.h>
#include <string.h>
int mystrcmp(const char *s1, const char *s2)
{
printf("hack function invoked. s1=<%s> s2=<%s>\n", s1, s2);
// always return 0, which means s1 equals to s2--总是相等
return 0;
}
六、替换并测试运行
替换流程图
编译、设置指令
gcc myhack.c -fPIC -shared -o myhack.so #编译替换库
export LD_PRELOAD="./myhack.so" #设置LD_PRELOAD环境变量,库中的同名函数在程序运行时优先调用
./myverifypasswd #运行主程序
- 终端运行结果
n6@X240s:~/桌面/LD_PRELOAD$ gcc myhack.c -fPIC -shared -o myhack.so
n6@X240s:~/桌面/LD_PRELOAD$ export LD_PRELOAD="./myhack.so"
n6@X240s:~/桌面/LD_PRELOAD$ ./myverifypasswd
usage: ./myverifypasswd <password>
n6@X240s:~/桌面/LD_PRELOAD$ ./myverifypasswd abc
hack function invoked. s1=<password> s2=<abc>
Correct Password!
n6@X240s:~/桌面/LD_PRELOAD$ ./myverifypasswd password
hack function invoked. s1=<password> s2=<password>
Correct Password!
n6@X240s:~/桌面/LD_PRELOAD$ unset LD_PRELOAD