hi, I’m following the post on the elf crypter, everything works, except when it uses the encryption function, in my case I tried xor and aes, with both it doesn’t work (when i try to run the binary it print seg fault), while if I use your rc4 algorithm it works, I don’t understand why, this is my code.
I’m still stuck at the first document ( Programming for Wanabes XIII. Crypters part I) because I’m trying to modify your crypter and add something, also to understand how the elf headers work.
I’m pretty sure there’s something wrong with the encryption stage.
static uint32_t table_key = 0xcafebabe;
int main (int argc, char *argv[])
{
if (argc != 2)
{
fprintf (stderr, "Invalid number of parameters\n");
fprintf (stderr, "Usage: crypter <binary>\n");
exit(-1);
}
int fd = -1;
if((fd = open(argv[1], O_RDWR)) == -1)
exit(-1);
struct stat _st;
if((fstat (fd, &_st)) == -1)
exit(-1);
unsigned char *p;
if ((p = mmap (0, _st.st_size, PROT_READ | PROT_WRITE,
MAP_SHARED, fd, 0)) == MAP_FAILED)
{
fprintf (stderr, "Error mapping the binary\n");
exit(-1);
}
Elf64_Ehdr *elf_header = (Elf64_Ehdr*)p;
printf("Magic Bytes: %02x %c %c %c\n", elf_header->e_ident[0], elf_header->e_ident[1], elf_header->e_ident[2], elf_header->e_ident[3]);
if (memcmp(elf_header->e_ident, ELFMAG, SELFMAG) != 0)
{
fprintf(stderr, "Invalid file format\n");
fprintf(stderr, "Elf Required!\n");
munmap(p, _st.st_size);
close(fd);
exit(-1);
}
if(elf_header->e_type != ET_DYN)
{
fprintf (stderr, "File is not an executable\n");
munmap(p, _st.st_size);
close(fd);
exit(-1);
}
printf ("Section Table located at : %ld\n", elf_header->e_shoff);
printf ("Section Table entry size : %hu\n", elf_header->e_shentsize);
printf ("Section Table entries : %hu\n", elf_header->e_shnum);
Elf64_Shdr *sh = (Elf64_Shdr*)(p + elf_header->e_shoff);
unsigned char *s_name = p + sh[elf_header->e_shstrndx].sh_offset;
unsigned char *name = NULL;
//char *key ="0x00Sec!\0";
for (size_t i = 0; i < elf_header->e_shnum; i++)
{
name = s_name + sh[i].sh_name;
if (!strcmp((const char *)name, ".text") || !strcmp ((const char *)name, ".rodata"))
{
printf ("Section %02zu [%s]: Type: %d Flags: %lx Off: %lx Size: %lx => ",i, name,sh[i].sh_type, sh[i].sh_flags,sh[i].sh_offset, sh[i].sh_size);
if (sh[i].sh_offset + sh[i].sh_size > _st.st_size)
{
fprintf(stderr, "Error: Attempting to XOR beyond the end of the file.\n");
munmap(p, _st.st_size);
close(fd);
exit(-1);
}
//rc4(p + sh[i].sh_offset, sh[i].sh_size, (unsigned char*)key, strlen (key));
xor(p + sh[i].sh_offset, sh[i].sh_size);
puts(" - Crypted!");
}
}
munmap(p, _st.st_size);
close(fd);
return 0;
}
static void xor(unsigned char *data, size_t data_len)
{
uint8_t k1 = table_key & 0xff, k2 = (table_key >> 8) & 0xff, k3 = (table_key >> 16) & 0xff, k4 = (table_key >> 24) & 0xff;
uint32_t cnt = 0;
for (size_t i = 0; i < data_len; i++)
{
data[i] ^= k1;
data[i] ^= k2;
data[i] ^= k3;
data[i] ^= k4;
++cnt;
}
printf(" [%d bytes encoded]", cnt);
}