21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

mprotect(buf, buf_len, PROT_READ | PROT_EXEC);<br />

return(buf_len);<br />

}<br />

The use of mprotect( ), or an equivalent operating system routine for modifying the<br />

permissions of a page of memory, is required on most modern operating systems to<br />

write to the code segment. This is an inherent weakness of the self-modifying code<br />

technique: the call to mprotect( ) is suspicious, and it is trivial to write a utility that<br />

searches the disassembly of a program for calls to mprotect( ) that enable write<br />

access or take an address in the code segment as the first parameter. The use of<br />

mprotect( ) should be obfuscated (see Recipes 12.3 and 12.9).<br />

Once the binary has been compiled, the protected code will have to be encrypted<br />

before it can be executed. The following code demonstrates a utility for encrypting a<br />

portion of an ELF executable file based on the contents of another portion of the file.<br />

The usage is:<br />

smc_encrypt filename code_offset code_len key_offset key_len<br />

In the command, code_offset and code_len are the location in the file of the code to<br />

be encrypted and the code’s length, and key_offset and key_len are the location in<br />

the file of the key with which to encode the code and the key’s length.<br />

#include <br />

#include <br />

#include <br />

#include <br />

#include <br />

#include <br />

#include <br />

#include <br />

#include <br />

#include <br />

/* ELF-specific stuff */<br />

#define ELF_ENTRY_OFFSET 24 /* e_hdr e_entry field offset */<br />

#define ELF_PHOFF_OFFSET 28 /* e_hdr e_phoff field offset */<br />

#define ELF_PHESZ_OFFSET 42 /* e_hdr e_phentsize field offset */<br />

#define ELF_PHNUM_OFFSET 44 /* e_hdr e_phnum field offset */<br />

#define ELF_PH_OFFSET_OFF 4 /* p_hdr p_offset field offset */<br />

#define ELF_PH_VADDR_OFF 8 /* p_hdr p_vaddr field offset */<br />

#define ELF_PH_FILESZ_OFF 16 /* p_hdr p_size field offset */<br />

static unsigned long elf_get_entry(unsigned char *buf) {<br />

unsigned long entry, p_vaddr, p_filesz, p_offset;<br />

unsigned int i, phoff;<br />

unsigned short phnum, phsz;<br />

unsigned char *phdr;<br />

entry = *(unsigned long *) &buf[ELF_ENTRY_OFFSET];<br />

phoff = *(unsigned int *) &buf[ELF_PHOFF_OFFSET];<br />

phnum = *(unsigned short *) &buf[ELF_PHNUM_OFFSET];<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.<br />

Using Self-Modifying Code | 695

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!