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.

Discussion<br />

For the code presented in this recipe, we’ll be using RC4 to perform our encryption.<br />

We’ve chosen to use RC4 because it is fast and easy to implement. You will need to<br />

use the RC4 implementation from Recipe 5.23 or an alternative implementation<br />

from somewhere else to use the code we will be presenting.<br />

The actual code to decrypt and replace the code in memory is minimal. The complexity<br />

arises from having to obtain the code to be encrypted, encrypting it, and making<br />

it accessible to the code that will be decrypting and executing it. A set of macros<br />

provides the means to mark replaceable code, and a single function, spc_smc_<br />

decrypt( ), performs the decryption of the code. Because we’re using RC4, encryption<br />

and decryption are performed in exactly the same way, so spc_smc_decrypt( )<br />

can also be used for encryption, which we’ll do later on.<br />

#include <br />

#include <br />

#include <br />

#include <br />

#include <br />

#define SPC_SMC_START_BLOCK(label) void label(void) { }<br />

#define SPC_SMC_END_BLOCK(label) void _##label(void) { }<br />

#define SPC_SMC_BLOCK_LEN(label) (int)_##label - (int)label<br />

#define SPC_SMC_BLOCK_ADDR(label) (unsigned char *)label<br />

#define SPC_SMC_START_KEY(label) void key_##label(void) { }<br />

#define SPC_SMC_END_KEY(label) void _key_##label(void) { }<br />

#define SPC_SMC_KEY_LEN(label) (int)_key_##label - (int)key_##label<br />

#define SPC_SMC_KEY_ADDR(label) (unsigned char *)key_##label<br />

#define SPC_SMC_OFFSET(label) (long)label - (long)_start<br />

extern void _start(void);<br />

/* returns number of bytes encoded */<br />

int spc_smc_decrypt(unsigned char *buf, int buf_len, unsigned char *key, int key_len)<br />

{<br />

RC4_CTX ctx;<br />

RC4_set_key(&ctx, key_len, key);<br />

/* NOTE: most code segments have read-only permissions, and so must be modified<br />

* to allow writing to the buffer<br />

*/<br />

if (mprotect(buf, buf_len, PROT_WRITE | PROT_READ | PROT_EXEC)) {<br />

fprintf(stderr, "mprotect: %s\n", strerror(errno));<br />

return(0);<br />

}<br />

/* decrypt the buffer */<br />

RC4(&ctx, buf_len, buf, buf);<br />

/* restore the original memory permissions */<br />

694 | Chapter 12: Anti-Tampering<br />

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

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.

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

Saved successfully!

Ooh no, something went wrong!