[TOC]
引言
如何对so文件中的核心代码进行保护?
通过将核心代码写到自定义节中,并且对该节使用加密工具进行加密,在so文件执行时,利用attribute((constructor));属性,先于main执行解密函数,作用类似于java中的构造函数
实现流程
确定好自定义节的名称
开始加密流程遍历所有节头,根据节头名来定位需要加密的节
获取节头中节的起始位置和大小,对节头指向的数据进行加密
编写解密代码用属性: attribute((constructor));声明解密函数
在native层编写解密函数
代码实现
加密流程
#include
#include
#include
#include
#include
int main(int argc, char** argv)
{
int fd;
Elf32_Ehdr ehdr;
Elf32_Shdr shdr;
char * section_name_table;
int i;
unsigned int base, length;
char *content;
//参数验证
if(argc != 3)
{
printf("Encrypt section of elf file\n\nUsage:\n\t%s \n", *argv);
goto _error;
}
if((fd = open(argv[1], O_RDWR, 0777)) == -1)
{
perror("open");
goto _error;
}
if(read(fd, &ehdr, sizeof(Elf32_Ehdr)) != sizeof(Elf32_Ehdr))
{
perror("read elf header");
goto _error;
}
//读取节头字符串表
printf("[+] Begining find section %s\n", argv[2]);
lseek(fd, ehdr.e_shoff+sizeof(Elf32_Shdr)*ehdr.e_shstrndx, SEEK_SET);
if(read(fd, &shdr, sizeof(Elf32_Shdr)) != sizeof(Elf32_Shdr))
{
perror("read elf section header which contain string table");
goto _error;
}
if((section_name_table = (char*) malloc(shdr.sh_size)) == NULL)
{
perror("malloc for SHT_STRTAB");
goto _error;
}
lseek(fd, shdr.sh_offset, SEEK_SET);
if(read(fd, section_name_table, shdr.sh_size) != shdr.sh_size)
{
perror("read string table");
goto _error;
}
lseek(fd, ehdr.e_shoff, SEEK_SET);
//根据节头名来定位需要加密的节头
for(i=0; i
{
if(read(fd, &shdr, sizeof(Elf32_Shdr)) != sizeof(Elf32_Shdr))
{
perror("read section");
goto _error;
}
if(strcmp(section_name_table+shdr.sh_name, argv[2]) =