自修改程序执行完SearchAndDestroy头擦除函数后触发SEGFAULT排查
自修改程序擦除ELF头后触发SEGFAULT问题
在调试自编辑程序头的自修改程序时,SearchAndDestroy()头擦除函数执行完成后程序触发SEGFAULT,GDB持续报错:在SearchAndDestroy()之后调用的第一个外部函数位置提示“../elf/dl-runtime.c:73 找不到文件”。
核心实现代码
#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #define ELFHeaderLength 0x40 #define ProgramHeaderLength 0x38 #define SectionHeaderLength 0x40 #define AddressLength 12 #define SecondAddressOffset (AddressLength + 1) #define FileLineBuff 150 typedef int WORD; int SearchAndDestroy(void) { FILE *filePointer; char line[FileLineBuff]; char lastLine[FileLineBuff]; char addressStr[AddressLength + 1]; long int addressInt; WORD *start; WORD *end; // open /proc/self/maps file filePointer = fopen("/proc/self/maps", "r"); if (filePointer == NULL) { return 2; } // read the first address from first line from /proc/self/maps into address array fgets(line, FileLineBuff * sizeof(char), filePointer); memcpy(addressStr, line, AddressLength); addressStr[AddressLength] = 0x00; // make hex then make pointer addressInt = strtol(addressStr, NULL, 16); start = (WORD *) addressInt; // trace through until the last line is found for (; (strstr(line, "MangleS.elf")) != NULL; fgets(line, FileLineBuff * sizeof(char), filePointer)) { memcpy(lastLine, line, FileLineBuff); } memcpy(addressStr, &lastLine[SecondAddressOffset], AddressLength); addressStr[AddressLength] = 0x00; // make hex then make pointer addressInt = strtol(addressStr, NULL, 16); end = (WORD *) addressInt; // close file stream fclose(filePointer); // allow write to header spaces with mprotect mprotect(start, ELFHeaderLength + ProgramHeaderLength, PROT_WRITE); // clear ELF & Program Headers for (int i = 0; i < (ELFHeaderLength + ProgramHeaderLength); i++) { *(start + i) = 0; } // disallow write & allow SectionHeader write mprotect(start, ELFHeaderLength + ProgramHeaderLength, PROT_READ); mprotect(end - SectionHeaderLength, SectionHeaderLength, PROT_WRITE); // clear Section Header for (int i = 0; i < SectionHeaderLength; i++) { *(end - SectionHeaderLength + i) = 0; } mprotect(end - SectionHeaderLength, SectionHeaderLength, PROT_READ); return 0; }
已观测到的异常表现
- Valgrind检测出程序运行临近结束位置存在4字节无效写错误
- 打印语句验证显示,该问题不会在常规执行流程中直接触发
- GDB将崩溃点定位到其他函数内的一处if判断语句,但常规执行流程中本该在该if语句前输出的打印信息并未正常显示
内容的提问来源于stack exchange,提问作者BraffZacklin
相关产品推荐
相关产品推荐

