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.

12.9 Using Function Pointers<br />

<strong>Problem</strong><br />

By knowing which functions are called—either directly or indirectly—a programmer<br />

can understand the operation of a compiled program without resorting to runtime<br />

analysis.<br />

Solution<br />

The address of a function will always be visible in memory before it is called; however,<br />

by storing an obfuscated version of the function pointer, disassemblers and<br />

cross-reference analysis tools will fail to recognize the stored pointer as a code<br />

address. Note that this technique will not work with function pointers that require<br />

relocation, such as the addresses of functions in shared libraries.<br />

Discussion<br />

Function pointers can be handled like other variables. Because they are essentially<br />

compile-time constants, it is best to use a technique that obfuscates them at compile<br />

time. It is important that the functions created using the SET_FN_PTR macro presented<br />

below be inlined by the compiler so that they do not appear in the resulting<br />

executable’s symbol table; otherwise, they will be obvious tip-offs to a cracker that<br />

something is not as it should be.<br />

#define SET_FN_PTR(func, num) \<br />

static inline void *get_##func(void) { \<br />

int i, j = num / 4; \<br />

long ptr = (long)func + num; \<br />

for (i = 0; i < 2; i++) ptr -= j; \<br />

return (void *)(ptr - (j * 2)); \<br />

}<br />

#define GET_FN_PTR(func) get_##func( )<br />

With the SET_FN_PTR macro, the pointer to a function is returned by a routine that<br />

stores the function pointer modified by a programmer-supplied value. The GET_FN_<br />

PTR macro calls this routine, which performs a mathematical transformation on the<br />

stored pointer and returns the real function address. The following example demonstrates<br />

the usage of the macros:<br />

#include <br />

void my_func(void) {<br />

printf("my_func( ) called!\n");<br />

}<br />

SET_FN_PTR(my_func, 0x01301100); /* 0x01301100 is some arbitrary value */<br />

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

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

Using Function Pointers | 671

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

Saved successfully!

Ooh no, something went wrong!