(转)linux so的init.array字段添加代码
原文地址:http://0nly3nd.sinaapp.com/?p=642
0×1
so文件是一个elf格式的文件
通过对elf文件格式的了解。so在被加载之前,会执行init段的代码。在结束的时候,会执行fini段的代码。
上次分析过360的加固,他们采用的就是在init中执行代码的解密函数。(这也是为什么在jni_onload中无需解密的原因)
今天就展示一下怎么将自己的函数放入init段,并执行。
0×2
so代码
s.c
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
#include <stdio.h>
void my_init(void) __attribute__((constructor)); //告诉gcc把这个函数扔到init section
void my_fini(void) __attribute__((destructor)); //告诉gcc把这个函数扔到fini section
void out_msg(const char *m)
{
printf(" Our_Func \n");
}
void my_init(void)
{
printf("\n Init \n");
}
void my_fini(void)
{
printf(" Fini \n");
}
|
编译生成so:
|
1
2
|
gcc -fPIC -g -c s.c -o libs.o
gcc -g -shared -Wl,-soname,libs.so -o libs.so libs.o -lc
|
0×3
调用so
ts.c
|
1
2
3
4
5
6
7
8
9
10
11
12
|
#include <stdio.h>
#include "s.h"
int main(int argc, char** argv)
{
printf(" Main Start \n");
out_msg("main");
printf(" Main Quit \n");
}
|
s.h
|
1
2
3
4
|
#ifndef _MY_SO_HEADER_
#define _MY_SO_HEADER_
void out_msg(const char *m);
#endif
|
编译生成可执行文件:
|
1
|
gcc -g ts.c -o ts -L. -ls
|
0×4
指定程序加载so的路径
新建名为e的文件:
|
1
2
3
|
#!/bin/sh
export LD_LIBRARY_PATH=${pwd}:${LD_LIBRARY_PATH}
./ts
|
0×5
运行
终端中输入:./e &
|
1
2
3
4
5
6
7
8
9
10
11
|
xxx@xxx-ubuntu:~/桌面/test$ gcc -fPIC -g -c s.c -o libs.o
xxx@xxx-ubuntu:~/桌面/test$ gcc -g -shared -Wl,-soname,libs.so -o libs.so libs.o -lc
xxx@xxx-ubuntu:~/桌面/test$ gcc -g ts.c -o ts -L. -ls
xxx@xxx-ubuntu:~/桌面/test$ ./e &
[2] 5756
xxx@xxx-ubuntu:~/桌面/test$
Init
Main Start
Our_Func
Main Quit
Fini
|
可以看出,最新执行的是Init,最后执行的是Fini。
今天了解到一种动态调试手法,据说能够断在init中,明天再来试试。

浙公网安备 33010602011771号