View Single Post
Re: Storing an array of function calls, and their params.....
Old
  (#15)
Lazy
Member
 
Lazy's Avatar
 
Status: Offline
Posts: 236
Join Date: Jan 2004
Location: Toronto, Ontario, Canada
Default Re: Storing an array of function calls, and their params..... - 16-05-2005

WARNING: Disgusting, hacked up code!

Code:
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <tlhelp32.h>
#include <conio.h>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include "remotemodule.h"

#define FUNCTION_SIZE 18
// Dynamically generated function
// ------
// push ( b )		5 bytes
// push ( a )		5 bytes
// call ( pfnAdd )   5 bytes
// pop ( eax )	   1 byte
// pop ( eax )	   1 byte
// ret			   1 byte

int Add( int iA, int iB ) {
   return printf( "%d\n", iA + iB );
}

typedef int ( __cdecl* tAdd ) ( int, int );

struct function_s {
   tAdd pfnAdd; // Adds two numbers
} 
gFunctionlist[ 4 ];

BYTE* CreateAddFunction( int iA, int iB ) {
   BYTE* pMemory = NULL;

   // Use this instead of malloc so this area in memory can run code
   pMemory = ( BYTE* ) VirtualAlloc( NULL, FUNCTION_SIZE, MEM_COMMIT, PAGE_EXECUTE_READWRITE );

   if ( pMemory ) {
	  pMemory[ 0 ] = 0x68;
	  pMemory[ 1 ] = LOBYTE( LOWORD( iB ) );
	  pMemory[ 2 ] = HIBYTE( LOWORD( iB ) );
	  pMemory[ 3 ] = LOBYTE( HIWORD( iB ) );
	  pMemory[ 4 ] = HIBYTE( HIWORD( iB ) );

	  pMemory[ 5 ] = 0x68;
	  pMemory[ 6 ] = LOBYTE( LOWORD( iA ) );
	  pMemory[ 7 ] = HIBYTE( LOWORD( iA ) );
	  pMemory[ 8 ] = LOBYTE( HIWORD( iA ) );
	  pMemory[ 9 ] = HIBYTE( HIWORD( iA ) );

	  int a = ( ( int ) Add - ( int ) &pMemory[ 10 ] ) - 5;

	  pMemory[ 10 ] = 0xE8;
	  pMemory[ 11 ] = LOBYTE( LOWORD( a ) );
	  pMemory[ 12 ] = HIBYTE( LOWORD( a ) );
	  pMemory[ 13 ] = LOBYTE( HIWORD( a ) );
	  pMemory[ 14 ] = HIBYTE( HIWORD( a ) );

	  pMemory[ 15 ] = 0x58;
	  pMemory[ 16 ] = 0x58;

	  pMemory[ 17 ] = 0xC3;
   }

   return pMemory;
}

int main( void ) {
   int i = 0;

   for ( i = 0; i < 4; i++ ) {
	  gFunctionlist[ i ].pfnAdd = ( tAdd ) CreateAddFunction( i, 5 );

	  if ( gFunctionlist[ i ].pfnAdd ) {
		 ( gFunctionlist[ i ].pfnAdd ) ( 0, 0 );
		 VirtualFree( gFunctionlist[ i ].pfnAdd, FUNCTION_SIZE, MEM_RELEASE );
	  }
   }

   return 0;
}
Note that the call to pfnAdd has zeros as parameters but it always comes out as what the call to CreateAddFunction says.
  
Reply With Quote