21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

eturn 4;<br />

}<br />

/* get entry point : here we assume ELF example */<br />

entry = elf_get_entry(buf);<br />

if (!entry) {<br />

fprintf(stderr, "Invalid ELF header\n");<br />

munmap(buf, sb.st_size);<br />

close(fd);<br />

return 5;<br />

}<br />

/* these are offsets from the entry point */<br />

offset += entry;<br />

key_offset += entry;<br />

printf("Encrypting %d bytes at 0x%X with %d bytes at 0x%X\n",<br />

len, offset, key_len, key_offset);<br />

/* Because we're using RC4, encryption and decryption are the same operation */<br />

spc_smc_decrypt(buf + offset, len, buf + key_offset, key_len);<br />

/* mem-unmap the file */<br />

msync(buf, sb.st_size, MS_SYNC);<br />

munmap(buf, sb.st_size);<br />

close(fd);<br />

return 0;<br />

}<br />

This program incorporates an ELF file-header parser in the elf_get_entry( ) routine.<br />

The program header table entries of the ELF header are searched for the loadable<br />

segment containing the entry point. This is done to translate the entry point<br />

virtual address into an offset from the start of the file. This is necessary because the<br />

offsets generated by the SPC_SMC_OFFSET macro are relative to the program entry point<br />

(_start).<br />

The following code provides an example of using the code we’ve presented in this<br />

recipe. The program decrypts itself at runtime, using bogus_routine( ) as a key for<br />

decrypting test_routine( ).<br />

#include <br />

#include <br />

SPC_SMC_START_BLOCK(test)<br />

int test_routine(void) {<br />

int x;<br />

for (x = 0; x < 10; x++) printf("decrpyted!\n");<br />

return x;<br />

}<br />

SPC_SMC_END_BLOCK(test)<br />

SPC_SMC_START_KEY(test)<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 | 697

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

Saved successfully!

Ooh no, something went wrong!