2021.05.10 - [1인 1프로젝트] - 코딩 시작
이전에 했던 코딩에 이어서 GOT 정보를 얻어오는 함수를 구현하여 최종적으로 ELF의 정보들을 얻어오는 함수 및 구조체를 만들었다. 또한 해킹하고자 하는 프로그램이 사용한는 libc파일을 자동으로 얻어오는 함수를 구현했다.
unsigned long long getGOT(GOT * got, char * target){
if(__glibc_unlikely(got == 0)) return 0;
for(int i = 0; (got + i) -> addr != 0 || (got + i) -> name != 0; i++){
if(!(strcmp((got + i) -> name, target))) return (got + i) -> addr;
}
return 0;
}
SYM * findSYM(int fd, Section section){
int i;
Elf64_Shdr * dynsymSection = getSectionInfo(section, ".dynsym");
Elf64_Shdr * dynstrSection = getSectionInfo(section, ".dynstr");
Elf64_Sym * dynsym = malloc(dynsymSection -> sh_size);
char * dynstr = malloc(dynstrSection -> sh_size);
int SymbolCnt = (dynsymSection -> sh_size) / sizeof(Elf64_Sym);
SYM * symbol = malloc(sizeof(SYM) * (SymbolCnt + 1)); //SymbolCnt + 1 : NULL 구조체 추가
char * t;
int NameOffset;
lseek(fd, dynsymSection -> sh_offset, SEEK_SET);
read(fd, dynsym, dynsymSection -> sh_size);
lseek(fd, dynstrSection -> sh_offset, SEEK_SET);
read(fd, dynstr, dynstrSection -> sh_size);
int idx;
for(i = 0; i < SymbolCnt; i++){
if(((dynsym + i) -> st_value) != 0){
(symbol + idx) -> value = (dynsym + i) -> st_value;
NameOffset = (dynsym + i) -> st_name;
(symbol + idx) -> name = dynstr + NameOffset;
idx++;
}
}
(symbol + i) -> value = 0;
(symbol + i) -> name = 0;
return symbol;
}
unsigned long long getSYM(SYM * sym, char * target){
if(__glibc_unlikely(sym == 0)) return 0;
for(int i = 0; (sym + i) -> value != 0 || (sym + i) -> name != 0; i++){
if(!(strcmp((sym + i) -> name, target)))return (sym + i) -> value;
}
return 0;
}
ELFInfo ELF(char * path){
int fd = open(path, O_RDONLY);
ELFInfo elf;
elf.fd = fd;
elf.filename = path;
elf.section = findSectionHeader(fd);
elf.got = findGOTInfo(fd, elf.section);
elf.sym = findSYM(fd, elf.section);
return elf;
}
ELFInfo getLibcELF(ELFInfo elf){
char * LibcPath = malloc(1024);
char * command = malloc(1024);
int fd = open(".result.txt", O_RDWR | O_CREAT | O_TRUNC, 0644);
ELFInfo LibcELF;
char tmp;
int i;
sprintf(command, "ldd %s >> .result.txt", elf.filename);
if(system(command) == -1){
printf("system() error");
exit(0);
}
for(int i = 0; i < 2; i++){
while(1){
read(fd, &tmp, 1);
if(tmp == '>') break;
}
}
for(int i = 0; i< 2; i++){
i = 0;
while(1){
read(fd, &tmp, 1);
if(tmp == ' ') break;
*(LibcPath + i) = tmp;
i++;
}
}
LibcELF = ELF(LibcPath);
return LibcELF;
}