/* Public function to determine the linkage of an ELF. */ ElfType get_elf_linkage(const char *path) { ElfType ret = ELFERROR; FILE *elf_file = NULL; uint8_t pHeader[HEADERSIZE] = ""; elf_file = fopen(path, "r"); if (elf_file) { if (fread(pHeader, 1, HEADERSIZE, elf_file) == HEADERSIZE) { if (is_elf_magic(pHeader)) { if ((pHeader[EI_DATA] == ELFDATA2LSB) && (pHeader[EI_CLASS] == ELFCLASS64)) { /* 64 bit little endian */ ret = parseElf64(elf_file, pHeader, 1); } else if ((pHeader[EI_DATA] == ELFDATA2MSB) && (pHeader[EI_CLASS] == ELFCLASS64)) { /* 64 bit big endian */ ret = parseElf64(elf_file, pHeader, 0); } else if ((pHeader[EI_DATA] == ELFDATA2LSB) && (pHeader[EI_CLASS] == ELFCLASS32)) { /* 32 bit little endian */ ret = parseElf32(elf_file, pHeader, 1); } else if ((pHeader[EI_DATA] == ELFDATA2MSB) && (pHeader[EI_CLASS] == ELFCLASS32)) { /* 32 bit big endian */ ret = parseElf32(elf_file, pHeader, 0); } } else { /* * The binary is not an ELF. We assume it's a * script. We should parse the #! line and * check the interpreter to guard against * static interpreters escaping the sandbox. * As minijail is only called from rootfs * it was deemed not necessary to check this. * So we will just let execve decided if this * is valid. */ ret = ELFDYNAMIC; } } else { /* * The file is smaller than |HEADERSIZE| bytes. * We assume it's a short script. See above for * reasoning on scripts. */ ret = ELFDYNAMIC; } fclose(elf_file); } return ret; }
void parseElf(FILE* fp, long fileSize) { // ELF Header unsigned char* buffer = (unsigned char*)malloc(0x05); fread(buffer, sizeof(unsigned char), 0x05, fp); if (buffer[4] == 1) { printf("Determined 32-bit.\n\n"); if (fseek(fp, 0l, SEEK_SET) != 0) { printf("[ELF] Error seeking back to zero (parse).\n"); } free(buffer); parseElf32(fp, fileSize); } else if (buffer[4] == 2) { printf("Determined 64-bit.\n"); if (fseek(fp, 0l, SEEK_SET) != 0) { printf("[ELF] Error seeking back to zero (parse).\n"); } free(buffer); parseElf64(fp, fileSize); } else { printf("Failed to determine 32-bit or 64-bit.\n"); return; } }