SolvedConverting C++ Injection Code To C#

Posts 1–14 of 14 · Page 1 of 1
Converting C++ Injection Code To C#
Hey everyone.

I compiled it in C++ awhile back and have been injecting it lately with Winject... Works great and is amazing. BUT now I decided to create an injector in C# and inject the DLL from there... This is where the problems begin. The injector seems to work great, its just the DLLmain from the C++ code isnt getting called or something, as It doesent work when injected from the C# injector. Here is the injector source (C#):

Code:
using System.Diagnostics;
using System;
using System.Xml.Linq;
using System.Windows.Forms;
using System.Collections;
using System.Drawing;
using Microsoft.VisualBasic;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;


namespace injectortest
{
    public partial class Form1 : Form
    {
        public Form1()
        {


            InitializeComponent();


        }

        [DllImport("kernel32")]
        public static extern IntPtr CreateRemoteThread(
          IntPtr hProcess,
          IntPtr lpThreadAttributes,
          uint dwStackSize,
          UIntPtr lpStartAddress, // raw Pointer into remote process
          IntPtr lpParameter,
          uint dwCreationFlags,
          out IntPtr lpThreadId
        );

        [DllImport("kernel32.dll")]
        public static extern IntPtr OpenProcess(
            UInt32 dwDesiredAccess,
            Int32 bInheritHandle,
            Int32 dwProcessId
            );

        [DllImport("kernel32.dll")]
        public static extern Int32 CloseHandle(
        IntPtr hObject
        );

        [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
        static extern bool VirtualFreeEx(
            IntPtr hProcess,
            IntPtr lpAddress,
            UIntPtr dwSize,
            uint dwFreeType
            );

        [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)]
        public static extern UIntPtr GetProcAddress(
            IntPtr hModule,
            string procName
            );

        [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
        static extern IntPtr VirtualAllocEx(
            IntPtr hProcess,
            IntPtr lpAddress,
            uint dwSize,
            uint flAllocationType,
            uint flProtect
            );

        [DllImport("kernel32.dll")]
        static extern bool WriteProcessMemory(
            IntPtr hProcess,
            IntPtr lpBaseAddress,
            string lpBuffer,
            UIntPtr nSize,
            out IntPtr lpNumberOfBytesWritten
        );

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public static extern IntPtr GetModuleHandle(
            string lpModuleName
            );

        [DllImport("kernel32", SetLastError = true, ExactSpelling = true)]
        internal static extern Int32 WaitForSingleObject(
            IntPtr handle,
            Int32 milliseconds
            );

        public Int32 GetProcessId(String proc)
        {
            Process[] ProcList;
            ProcList = Process.GetProcessesByName(proc);
            return ProcList[0].Id;
        }

        public void InjectDLL(IntPtr hProcess, String strDLLName)
        {


                IntPtr bytesout;

                // Length of string containing the DLL file name +1 byte padding
                Int32 LenWrite = strDLLName.Length + 1;
                // Allocate memory within the virtual address space of the target process
                IntPtr AllocMem = (IntPtr)VirtualAllocEx(hProcess, (IntPtr)null, (uint)LenWrite, 0x1000, 0x40); //allocation pour WriteProcessMemory

                // Write DLL file name to allocated memory in target process
                WriteProcessMemory(hProcess, AllocMem, strDLLName, (UIntPtr)LenWrite, out bytesout);
                // Function pointer "Injector"
                UIntPtr Injector = (UIntPtr)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");

                if (Injector == null)
                {
                    MessageBox.Show(" Injector Error! \n ");
                    // return failed
                    return;
                }

                // Create thread in target process, and store handle in hThread
                IntPtr hThread = (IntPtr)CreateRemoteThread(hProcess, (IntPtr)null, 0, Injector, AllocMem, 0, out bytesout);
                // Make sure thread handle is valid
                if (hThread == null)
                {
                    //incorrect thread handle ... return failed
                    MessageBox.Show(" hThread [ 1 ] Error! \n ");
                    return;
                }
                // Time-out is 10 seconds...
                int Result = WaitForSingleObject(hThread, 10 * 1000);
                // Check whether thread timed out...
                if (Result == 0x00000080L || Result == 0x00000102L || Result == 0xFFFFFFFF)
                {
                    /* Thread timed out... */
                    MessageBox.Show(" hThread [ 2 ] Error! \n ");
                    // Make sure thread handle is valid before closing... prevents crashes.
                    if (hThread != null)
                    {
                        //Close thread in target process
                        CloseHandle(hThread);
                    }
                    return;
                }
                // Sleep thread for 1 second
                Thread.Sleep(1000);
                // Clear up allocated space ( Allocmem )
                VirtualFreeEx(hProcess, AllocMem, (UIntPtr)0, 0x8000);
                // Make sure thread handle is valid before closing... prevents crashes.
                if (hThread != null)
                {
                    MessageBox.Show("Success");
                    //Close thread in target process
                    CloseHandle(hThread);
                }
                // return succeeded
                return;
            
            
        }

        public void nject10n()
        {
            String dllnaem = "hacks.dll"; 
            String pr0c3ssname = "iw3mp";

            Int32 ProcID = GetProcessId(pr0c3ssname);
            if (ProcID >= 0)
            {
                IntPtr hProcess = (IntPtr)OpenProcess(0x1F0FFF, 1,ProcID);
                if (hProcess == null)
                {
                    MessageBox.Show("OpenProcess() Failed!");
                    return;
                }
                else
                    InjectDLL(hProcess, dllnaem);
            }
    }

        private void button1_Click(object sender, EventArgs e)
        {
            nject10n();
        }
    }
}
And the DLL Code

Code:
/*COD4 Chams Hack
Copyright (C) 2012 SystemFiles 

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.*/

// #include "check.cpp"
#include "Headers.h"

LONG WINAPI ExceptionHandler( EXCEPTION_POINTERS* ExceptionInfo ); 
BYTE OriginalBytes[5];

VOID SetBreakpoints()
{
	AddVectoredExceptionHandler( rand() % 0xFFFFFF, ExceptionHandler ); 
	CONTEXT Context = { CONTEXT_DEBUG_REGISTERS };

	Context.Dr0 = Engine::DrawXModelSkinnedCachedOffset;
	Context.Dr7 = 0x1;

	SetThreadContext( GetCurrentThread(), &Context );
}

VOID MyDrawXModelSkinnedCached( INT a1, INT a2, INT a3 )
{
	CHAR* ModelName;

	_asm PUSHAD;
	_asm MOV EBX, [EDI + 0xB8];
	_asm MOV EAX, [EBX];
	_asm MOV ModelName, EAX;

	static BOOL bRemove = FALSE;

	if( !bRemove )
	{
		DWORD Protect = 0x0;
		VirtualProtect( ( VOID* )Engine::DrawXModelSkinnedCachedOffset, 5, PAGE_EXECUTE_READWRITE, &Protect );
		
		for( INT i = 0; i < 5; i++ )
			*( BYTE* )( Engine::DrawXModelSkinnedCachedOffset + i ) = OriginalBytes[i];

		VirtualProtect( ( VOID* )Engine::DrawXModelSkinnedCachedOffset, 5, Protect, &Protect );

		SetBreakpoints();

		bRemove = TRUE;
	}

	if( Engine::D3DDevice != NULL && Engine::D3DDevice != NULL )
	{
		if( Tools::RedTexture == NULL || Tools::YellowTexture == NULL || Tools::SkyBlueTexture == NULL || Tools::GreenTexture == NULL )
		{
			Tools::GenerateTexture( Engine::D3DDevice, &Tools::RedTexture, D3DCOLOR_RGBA( 255, 0, 0, 255 ) );
			Tools::GenerateTexture( Engine::D3DDevice, &Tools::YellowTexture, D3DCOLOR_RGBA( 255, 255, 0, 255 ) );
			Tools::GenerateTexture( Engine::D3DDevice, &Tools::SkyBlueTexture, D3DCOLOR_RGBA( 0, 170, 255, 255 ) );
			Tools::GenerateTexture( Engine::D3DDevice, &Tools::GreenTexture, D3DCOLOR_RGBA( 0, 255, 0, 255 ) );
		}

		if( !strstr( ModelName, "mi24p" ) && !strstr( ModelName, "weapon" ) && !strstr( ModelName, "cobra" ) )
		{
			if( strstr( ModelName, "sas" ) || strstr( ModelName, "usmc" ) )
			{
				Engine::D3DDevice->SetRenderState( D3DRS_ZENABLE, D3DZB_FALSE );
				Engine::D3DDevice->SetTexture( 0, Tools::YellowTexture );
				Engine::DrawXModelSkinnedCached( a1, a2, a3 );
				Engine::D3DDevice->SetRenderState( D3DRS_ZENABLE, D3DZB_TRUE );
				Engine::D3DDevice->SetTexture( 0, Tools::RedTexture );
			}
			else if( strstr( ModelName, "opforce" ) || strstr( ModelName, "arab" ) || strstr( ModelName, "head_suren" ) )
			{
				Engine::D3DDevice->SetRenderState( D3DRS_ZENABLE, D3DZB_FALSE );
				Engine::D3DDevice->SetTexture( 0, Tools::GreenTexture );
				Engine::DrawXModelSkinnedCached( a1, a2, a3 );
				Engine::D3DDevice->SetRenderState( D3DRS_ZENABLE, D3DZB_TRUE );
				Engine::D3DDevice->SetTexture( 0, Tools::SkyBlueTexture );
			}
		}
	}

	_asm POPAD;

	Engine::DrawXModelSkinnedCached( a1, a2, a3 );
}

LONG WINAPI ExceptionHandler( EXCEPTION_POINTERS* ExceptionInfo )
{
	if( ExceptionInfo->ExceptionRecord->ExceptionCode == EXCEPTION_SINGLE_STEP && ( DWORD )ExceptionInfo->ExceptionRecord->ExceptionAddress == Engine::DrawXModelSkinnedCachedOffset )
	{
		ExceptionInfo->ContextRecord->Eip = ( DWORD )MyDrawXModelSkinnedCached;
		return EXCEPTION_CONTINUE_EXECUTION;
	} 

	return EXCEPTION_CONTINUE_SEARCH;
}

DWORD WINAPI HookThread( VOID* Arguments )
{
	for( INT i = 0; i < 5; i++ )
		OriginalBytes[i] = *( BYTE* )( Engine::DrawXModelSkinnedCachedOffset + i );

	Engine::DrawXModelSkinnedCached = ( Engine::tDrawXModelSkinnedCached )Tools::JMPHook( ( BYTE* )Engine::DrawXModelSkinnedCachedOffset, ( BYTE* )MyDrawXModelSkinnedCached, 5 );

	return 0; 
}

//BOOL WINAPI DLLMAIN( HMODULE hModule, DWORD Reason, VOID* Reserved )
//
//
//	CreateThread( NULL, 0, ( LPTHREAD_START_ROUTINE )HookThread, NULL, 0x0, NULL );
//	return TRUE;
//}

BOOL WINAPI DllMain( HMODULE hModule, DWORD Reason, VOID* Reserved )
{	
	if( Reason == DLL_PROCESS_ATTACH )
	{
		CreateThread( NULL, 0, ( LPTHREAD_START_ROUTINE )HookThread, NULL, 0x0, NULL );
	}
	//if( Reason == DLL_THREAD_ATTACH )
	//{
	//	CreateThread( NULL, 0, ( LPTHREAD_START_ROUTINE )HookThread, NULL, 0x0, NULL );
	//}
//as you can see i was playing around with the thread calling after i got frustrated... it didnt work! :(
	return TRUE;
}
Im pretty sure thats working great, Its just the DLL never activates. Do I need to create a pipe to the DLL and call DLLMain? Why isnt the DLLmain being executed at all?

Im a bit confused, and I have looked all around the net and havent found much information on this. Its hard to put into words to search for the problem like this, so thats why I finally decided to post here as a last resort. If theres a keyword name/search for this please let me know... I just dont know how to put my problem into words.

TL;DR
1. C++ DLL Successfully Works when injected with Winject
2. Doesent work with C# Injector, But No Errors Received from C# Injector

PS: I did an injector in Visual Basics similiar to the C# one and it injects fine also, just no chams... No Errors or anything.

Thanks! Any help would be greatly appreciated.
Quote Originally Posted by Synkro View Post
Hey everyone.

I compiled it in C++ awhile back and have been injecting it lately with Winject... Works great and is amazing. BUT now I decided to create an injector in C# and inject the DLL from there... This is where the problems begin. The injector seems to work great, its just the DLLmain from the C++ code isnt getting called or something, as It doesent work when injected from the C# injector. Here is the injector source (C#):

Code:
using System.Diagnostics;
using System;
using System.Xml.Linq;
using System.Windows.Forms;
using System.Collections;
using System.Drawing;
using Microsoft.VisualBasic;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;


namespace injectortest
{
    public partial class Form1 : Form
    {
        public Form1()
        {


            InitializeComponent();


        }

        [DllImport("kernel32")]
        public static extern IntPtr CreateRemoteThread(
          IntPtr hProcess,
          IntPtr lpThreadAttributes,
          uint dwStackSize,
          UIntPtr lpStartAddress, // raw Pointer into remote process
          IntPtr lpParameter,
          uint dwCreationFlags,
          out IntPtr lpThreadId
        );

        [DllImport("kernel32.dll")]
        public static extern IntPtr OpenProcess(
            UInt32 dwDesiredAccess,
            Int32 bInheritHandle,
            Int32 dwProcessId
            );

        [DllImport("kernel32.dll")]
        public static extern Int32 CloseHandle(
        IntPtr hObject
        );

        [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
        static extern bool VirtualFreeEx(
            IntPtr hProcess,
            IntPtr lpAddress,
            UIntPtr dwSize,
            uint dwFreeType
            );

        [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)]
        public static extern UIntPtr GetProcAddress(
            IntPtr hModule,
            string procName
            );

        [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
        static extern IntPtr VirtualAllocEx(
            IntPtr hProcess,
            IntPtr lpAddress,
            uint dwSize,
            uint flAllocationType,
            uint flProtect
            );

        [DllImport("kernel32.dll")]
        static extern bool WriteProcessMemory(
            IntPtr hProcess,
            IntPtr lpBaseAddress,
            string lpBuffer,
            UIntPtr nSize,
            out IntPtr lpNumberOfBytesWritten
        );

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public static extern IntPtr GetModuleHandle(
            string lpModuleName
            );

        [DllImport("kernel32", SetLastError = true, ExactSpelling = true)]
        internal static extern Int32 WaitForSingleObject(
            IntPtr handle,
            Int32 milliseconds
            );

        public Int32 GetProcessId(String proc)
        {
            Process[] ProcList;
            ProcList = Process.GetProcessesByName(proc);
            return ProcList[0].Id;
        }

        public void InjectDLL(IntPtr hProcess, String strDLLName)
        {


                IntPtr bytesout;

                // Length of string containing the DLL file name +1 byte padding
                Int32 LenWrite = strDLLName.Length + 1;
                // Allocate memory within the virtual address space of the target process
                IntPtr AllocMem = (IntPtr)VirtualAllocEx(hProcess, (IntPtr)null, (uint)LenWrite, 0x1000, 0x40); //allocation pour WriteProcessMemory

                // Write DLL file name to allocated memory in target process
                WriteProcessMemory(hProcess, AllocMem, strDLLName, (UIntPtr)LenWrite, out bytesout);
                // Function pointer "Injector"
                UIntPtr Injector = (UIntPtr)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");

                if (Injector == null)
                {
                    MessageBox.Show(" Injector Error! \n ");
                    // return failed
                    return;
                }

                // Create thread in target process, and store handle in hThread
                IntPtr hThread = (IntPtr)CreateRemoteThread(hProcess, (IntPtr)null, 0, Injector, AllocMem, 0, out bytesout);
                // Make sure thread handle is valid
                if (hThread == null)
                {
                    //incorrect thread handle ... return failed
                    MessageBox.Show(" hThread [ 1 ] Error! \n ");
                    return;
                }
                // Time-out is 10 seconds...
                int Result = WaitForSingleObject(hThread, 10 * 1000);
                // Check whether thread timed out...
                if (Result == 0x00000080L || Result == 0x00000102L || Result == 0xFFFFFFFF)
                {
                    /* Thread timed out... */
                    MessageBox.Show(" hThread [ 2 ] Error! \n ");
                    // Make sure thread handle is valid before closing... prevents crashes.
                    if (hThread != null)
                    {
                        //Close thread in target process
                        CloseHandle(hThread);
                    }
                    return;
                }
                // Sleep thread for 1 second
                Thread.Sleep(1000);
                // Clear up allocated space ( Allocmem )
                VirtualFreeEx(hProcess, AllocMem, (UIntPtr)0, 0x8000);
                // Make sure thread handle is valid before closing... prevents crashes.
                if (hThread != null)
                {
                    MessageBox.Show("Success");
                    //Close thread in target process
                    CloseHandle(hThread);
                }
                // return succeeded
                return;
            
            
        }

        public void nject10n()
        {
            String dllnaem = "hacks.dll"; 
            String pr0c3ssname = "iw3mp";

            Int32 ProcID = GetProcessId(pr0c3ssname);
            if (ProcID >= 0)
            {
                IntPtr hProcess = (IntPtr)OpenProcess(0x1F0FFF, 1,ProcID);
                if (hProcess == null)
                {
                    MessageBox.Show("OpenProcess() Failed!");
                    return;
                }
                else
                    InjectDLL(hProcess, dllnaem);
            }
    }

        private void button1_Click(object sender, EventArgs e)
        {
            nject10n();
        }
    }
}
And the DLL Code

Code:
/*COD4 Chams Hack
Copyright (C) 2012 SystemFiles 

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.*/

// #include "check.cpp"
#include "Headers.h"

LONG WINAPI ExceptionHandler( EXCEPTION_POINTERS* ExceptionInfo ); 
BYTE OriginalBytes[5];

VOID SetBreakpoints()
{
	AddVectoredExceptionHandler( rand() % 0xFFFFFF, ExceptionHandler ); 
	CONTEXT Context = { CONTEXT_DEBUG_REGISTERS };

	Context.Dr0 = Engine::DrawXModelSkinnedCachedOffset;
	Context.Dr7 = 0x1;

	SetThreadContext( GetCurrentThread(), &Context );
}

VOID MyDrawXModelSkinnedCached( INT a1, INT a2, INT a3 )
{
	CHAR* ModelName;

	_asm PUSHAD;
	_asm MOV EBX, [EDI + 0xB8];
	_asm MOV EAX, [EBX];
	_asm MOV ModelName, EAX;

	static BOOL bRemove = FALSE;

	if( !bRemove )
	{
		DWORD Protect = 0x0;
		VirtualProtect( ( VOID* )Engine::DrawXModelSkinnedCachedOffset, 5, PAGE_EXECUTE_READWRITE, &Protect );
		
		for( INT i = 0; i < 5; i++ )
			*( BYTE* )( Engine::DrawXModelSkinnedCachedOffset + i ) = OriginalBytes[i];

		VirtualProtect( ( VOID* )Engine::DrawXModelSkinnedCachedOffset, 5, Protect, &Protect );

		SetBreakpoints();

		bRemove = TRUE;
	}

	if( Engine::D3DDevice != NULL && Engine::D3DDevice != NULL )
	{
		if( Tools::RedTexture == NULL || Tools::YellowTexture == NULL || Tools::SkyBlueTexture == NULL || Tools::GreenTexture == NULL )
		{
			Tools::GenerateTexture( Engine::D3DDevice, &Tools::RedTexture, D3DCOLOR_RGBA( 255, 0, 0, 255 ) );
			Tools::GenerateTexture( Engine::D3DDevice, &Tools::YellowTexture, D3DCOLOR_RGBA( 255, 255, 0, 255 ) );
			Tools::GenerateTexture( Engine::D3DDevice, &Tools::SkyBlueTexture, D3DCOLOR_RGBA( 0, 170, 255, 255 ) );
			Tools::GenerateTexture( Engine::D3DDevice, &Tools::GreenTexture, D3DCOLOR_RGBA( 0, 255, 0, 255 ) );
		}

		if( !strstr( ModelName, "mi24p" ) && !strstr( ModelName, "weapon" ) && !strstr( ModelName, "cobra" ) )
		{
			if( strstr( ModelName, "sas" ) || strstr( ModelName, "usmc" ) )
			{
				Engine::D3DDevice->SetRenderState( D3DRS_ZENABLE, D3DZB_FALSE );
				Engine::D3DDevice->SetTexture( 0, Tools::YellowTexture );
				Engine::DrawXModelSkinnedCached( a1, a2, a3 );
				Engine::D3DDevice->SetRenderState( D3DRS_ZENABLE, D3DZB_TRUE );
				Engine::D3DDevice->SetTexture( 0, Tools::RedTexture );
			}
			else if( strstr( ModelName, "opforce" ) || strstr( ModelName, "arab" ) || strstr( ModelName, "head_suren" ) )
			{
				Engine::D3DDevice->SetRenderState( D3DRS_ZENABLE, D3DZB_FALSE );
				Engine::D3DDevice->SetTexture( 0, Tools::GreenTexture );
				Engine::DrawXModelSkinnedCached( a1, a2, a3 );
				Engine::D3DDevice->SetRenderState( D3DRS_ZENABLE, D3DZB_TRUE );
				Engine::D3DDevice->SetTexture( 0, Tools::SkyBlueTexture );
			}
		}
	}

	_asm POPAD;

	Engine::DrawXModelSkinnedCached( a1, a2, a3 );
}

LONG WINAPI ExceptionHandler( EXCEPTION_POINTERS* ExceptionInfo )
{
	if( ExceptionInfo->ExceptionRecord->ExceptionCode == EXCEPTION_SINGLE_STEP && ( DWORD )ExceptionInfo->ExceptionRecord->ExceptionAddress == Engine::DrawXModelSkinnedCachedOffset )
	{
		ExceptionInfo->ContextRecord->Eip = ( DWORD )MyDrawXModelSkinnedCached;
		return EXCEPTION_CONTINUE_EXECUTION;
	} 

	return EXCEPTION_CONTINUE_SEARCH;
}

DWORD WINAPI HookThread( VOID* Arguments )
{
	for( INT i = 0; i < 5; i++ )
		OriginalBytes[i] = *( BYTE* )( Engine::DrawXModelSkinnedCachedOffset + i );

	Engine::DrawXModelSkinnedCached = ( Engine::tDrawXModelSkinnedCached )Tools::JMPHook( ( BYTE* )Engine::DrawXModelSkinnedCachedOffset, ( BYTE* )MyDrawXModelSkinnedCached, 5 );

	return 0; 
}

//BOOL WINAPI DLLMAIN( HMODULE hModule, DWORD Reason, VOID* Reserved )
//
//
//	CreateThread( NULL, 0, ( LPTHREAD_START_ROUTINE )HookThread, NULL, 0x0, NULL );
//	return TRUE;
//}

BOOL WINAPI DllMain( HMODULE hModule, DWORD Reason, VOID* Reserved )
{	
	if( Reason == DLL_PROCESS_ATTACH )
	{
		CreateThread( NULL, 0, ( LPTHREAD_START_ROUTINE )HookThread, NULL, 0x0, NULL );
	}
	//if( Reason == DLL_THREAD_ATTACH )
	//{
	//	CreateThread( NULL, 0, ( LPTHREAD_START_ROUTINE )HookThread, NULL, 0x0, NULL );
	//}
//as you can see i was playing around with the thread calling after i got frustrated... it didnt work! :(
	return TRUE;
}
Im pretty sure thats working great, Its just the DLL never activates. Do I need to create a pipe to the DLL and call DLLMain? Why isnt the DLLmain being executed at all?

Im a bit confused, and I have looked all around the net and havent found much information on this. Its hard to put into words to search for the problem like this, so thats why I finally decided to post here as a last resort. If theres a keyword name/search for this please let me know... I just dont know how to put my problem into words.

TL;DR
1. C++ DLL Successfully Works when injected with Winject
2. Doesent work with C# Injector, But No Errors Received from C# Injector

PS: I did an injector in Visual Basics similiar to the C# one and it injects fine also, just no chams... No Errors or anything.

Thanks! Any help would be greatly appreciated.
It's because your error checking in C# is wrong. Look up the documentation for most of your WinAPI function calls and see how many actually return NULL. First, change your GetModuleHandle Pinvoke to GetModuleHandleA (as you're using an ascii string, not a multi-byte unicode string) and then try it out. You should be checking most for "== IntPtr.Zero" not "== null" for failures though. If that doesn't resolve it, I have a source in the VB.NET section stickied that you can take the WinAPI declarations from and convert to C# easily.
Thanks for your help Jason. I added your changes and now when injecting the game crashes. I actually moved to the C# crypter because i was having troubles with the VB.net crypter i had made before it. The VB.net source i was using was giving me an error while injecting saying: "Unable to find an entry point named 'CloseHandleA' in DLL 'kernel32'. I found a fix (after a LONG search) saying to remove the "A" from closehandle.
Heres the exact code:
From
Code:
    Private Declare Function CloseHandle Lib "kernel32" Alias "CloseHandleA" ( _
    ByVal hObject As Integer) As Integer
To
Code:
    Private Declare Function CloseHandle Lib "kernel32" Alias "CloseHandle" ( _
    ByVal hObject As Integer) As Integer
After doing this the injection never returned the error and completely went to the end of the injection sub with no errors... But the chams were still not showing... Heres the source i WAS using until i removed the A from closehandleA. I think it might be your source that your talking about. I forgot where i leeched it from exactly.

Code:
    
    Private TargetProcessHandle As Integer
    Private pfnStartAddr As Integer
    Private pszLibFileRemote As String
    Private TargetBufferSize As Integer

    Public Const PROCESS_VM_READ = &H10
    Public Const TH32CS_SNAPPROCESS = &H2
    Public Const MEM_COMMIT = 4096
    Public Const PAGE_READWRITE = 4
    Public Const PROCESS_CREATE_THREAD = (&H2)
    Public Const PROCESS_VM_OPERATION = (&H8)
    Public Const PROCESS_VM_WRITE = (&H20)
    Dim DLLFileName As String
    Public Declare Function ReadProcessMemory Lib "kernel32" ( _
    ByVal hProcess As Integer, _
    ByVal lpBaseAddress As Integer, _
    ByVal lpBuffer As String, _
    ByVal nSize As Integer, _
    ByRef lpNumberOfBytesWritten As Integer) As Integer

    Public Declare Function LoadLibrary Lib "kernel32" Alias "LoadLibraryA" ( _
    ByVal lpLibFileName As String) As Integer

    Public Declare Function VirtualAllocEx Lib "kernel32" ( _
    ByVal hProcess As Integer, _
    ByVal lpAddress As Integer, _
    ByVal dwSize As Integer, _
    ByVal flAllocationType As Integer, _
    ByVal flProtect As Integer) As Integer

    Public Declare Function WriteProcessMemory Lib "kernel32" ( _
    ByVal hProcess As Integer, _
    ByVal lpBaseAddress As Integer, _
    ByVal lpBuffer As String, _
    ByVal nSize As Integer, _
    ByRef lpNumberOfBytesWritten As Integer) As Integer

    Public Declare Function GetProcAddress Lib "kernel32" ( _
    ByVal hModule As Integer, ByVal lpProcName As String) As Integer

    Private Declare Function GetModuleHandle Lib "Kernel32" Alias "GetModuleHandleA" ( _
    ByVal lpModuleName As String) As Integer

    Public Declare Function CreateRemoteThread Lib "kernel32" ( _
    ByVal hProcess As Integer, _
    ByVal lpThreadAttributes As Integer, _
    ByVal dwStackSize As Integer, _
    ByVal lpStartAddress As Integer, _
    ByVal lpParameter As Integer, _
    ByVal dwCreationFlags As Integer, _
    ByRef lpThreadId As Integer) As Integer

    Public Declare Function OpenProcess Lib "kernel32" ( _
    ByVal dwDesiredAccess As Integer, _
    ByVal bInheritHandle As Integer, _
    ByVal dwProcessId As Integer) As Integer

    Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" ( _
    ByVal lpClassName As String, _
    ByVal lpWindowName As String) As Integer

    Private Declare Function CloseHandle Lib "kernel32" Alias "CloseHandleA" ( _
    ByVal hObject As Integer) As Integer


    Dim ExeName As String = IO.Path.GetFileNameWithoutExtension(Application.ExecutablePath)

    Private Sub Inject()
        Try
            Dim TargetProcess As Process() = Process.GetProcessesByName("iw3mp")
            TargetProcessHandle = OpenProcess(PROCESS_CREATE_THREAD Or PROCESS_VM_OPERATION Or PROCESS_VM_WRITE, False,     TargetProcess(0).Id)
            pszLibFileRemote = "hacks.dll"
            pfnStartAddr = GetProcAddress(GetModuleHandle("Kernel32"), "LoadLibraryA")
            TargetBufferSize = 1 + Len(pszLibFileRemote)
            Dim Rtn As Integer
            Dim LoadLibParamAdr As Integer
            LoadLibParamAdr = VirtualAllocEx(TargetProcessHandle, 0, TargetBufferSize, MEM_COMMIT, PAGE_READWRITE)
            Rtn = WriteProcessMemory(TargetProcessHandle, LoadLibParamAdr, pszLibFileRemote, TargetBufferSize, 0)
            CreateRemoteThread(TargetProcessHandle, 0, 0, pfnStartAddr, LoadLibParamAdr, 0, 0)
            CloseHandle(TargetProcessHandle)

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
 

    Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
        Call Inject()
    End Sub
End Class
Thanks for the help again.
Quote Originally Posted by Synkro View Post
Thanks for your help Jason. I added your changes and now when injecting the game crashes. I actually moved to the C# crypter because i was having troubles with the VB.net crypter i had made before it. The VB.net source i was using was giving me an error while injecting saying: "Unable to find an entry point named 'CloseHandleA' in DLL 'kernel32'. I found a fix (after a LONG search) saying to remove the "A" from closehandle.
Heres the exact code:
From
Code:
    Private Declare Function CloseHandle Lib "kernel32" Alias "CloseHandleA" ( _
    ByVal hObject As Integer) As Integer
To
Code:
    Private Declare Function CloseHandle Lib "kernel32" Alias "CloseHandle" ( _
    ByVal hObject As Integer) As Integer
After doing this the injection never returned the error and completely went to the end of the injection sub with no errors... But the chams were still not showing... Heres the source i WAS using until i removed the A from closehandleA. I think it might be your source that your talking about. I forgot where i leeched it from exactly.

Code:
    
    Private TargetProcessHandle As Integer
    Private pfnStartAddr As Integer
    Private pszLibFileRemote As String
    Private TargetBufferSize As Integer

    Public Const PROCESS_VM_READ = &H10
    Public Const TH32CS_SNAPPROCESS = &H2
    Public Const MEM_COMMIT = 4096
    Public Const PAGE_READWRITE = 4
    Public Const PROCESS_CREATE_THREAD = (&H2)
    Public Const PROCESS_VM_OPERATION = (&H8)
    Public Const PROCESS_VM_WRITE = (&H20)
    Dim DLLFileName As String
    Public Declare Function ReadProcessMemory Lib "kernel32" ( _
    ByVal hProcess As Integer, _
    ByVal lpBaseAddress As Integer, _
    ByVal lpBuffer As String, _
    ByVal nSize As Integer, _
    ByRef lpNumberOfBytesWritten As Integer) As Integer

    Public Declare Function LoadLibrary Lib "kernel32" Alias "LoadLibraryA" ( _
    ByVal lpLibFileName As String) As Integer

    Public Declare Function VirtualAllocEx Lib "kernel32" ( _
    ByVal hProcess As Integer, _
    ByVal lpAddress As Integer, _
    ByVal dwSize As Integer, _
    ByVal flAllocationType As Integer, _
    ByVal flProtect As Integer) As Integer

    Public Declare Function WriteProcessMemory Lib "kernel32" ( _
    ByVal hProcess As Integer, _
    ByVal lpBaseAddress As Integer, _
    ByVal lpBuffer As String, _
    ByVal nSize As Integer, _
    ByRef lpNumberOfBytesWritten As Integer) As Integer

    Public Declare Function GetProcAddress Lib "kernel32" ( _
    ByVal hModule As Integer, ByVal lpProcName As String) As Integer

    Private Declare Function GetModuleHandle Lib "Kernel32" Alias "GetModuleHandleA" ( _
    ByVal lpModuleName As String) As Integer

    Public Declare Function CreateRemoteThread Lib "kernel32" ( _
    ByVal hProcess As Integer, _
    ByVal lpThreadAttributes As Integer, _
    ByVal dwStackSize As Integer, _
    ByVal lpStartAddress As Integer, _
    ByVal lpParameter As Integer, _
    ByVal dwCreationFlags As Integer, _
    ByRef lpThreadId As Integer) As Integer

    Public Declare Function OpenProcess Lib "kernel32" ( _
    ByVal dwDesiredAccess As Integer, _
    ByVal bInheritHandle As Integer, _
    ByVal dwProcessId As Integer) As Integer

    Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" ( _
    ByVal lpClassName As String, _
    ByVal lpWindowName As String) As Integer

    Private Declare Function CloseHandle Lib "kernel32" Alias "CloseHandleA" ( _
    ByVal hObject As Integer) As Integer


    Dim ExeName As String = IO.Path.GetFileNameWithoutExtension(Application.ExecutablePath)

    Private Sub Inject()
        Try
            Dim TargetProcess As Process() = Process.GetProcessesByName("iw3mp")
            TargetProcessHandle = OpenProcess(PROCESS_CREATE_THREAD Or PROCESS_VM_OPERATION Or PROCESS_VM_WRITE, False,     TargetProcess(0).Id)
            pszLibFileRemote = "hacks.dll"
            pfnStartAddr = GetProcAddress(GetModuleHandle("Kernel32"), "LoadLibraryA")
            TargetBufferSize = 1 + Len(pszLibFileRemote)
            Dim Rtn As Integer
            Dim LoadLibParamAdr As Integer
            LoadLibParamAdr = VirtualAllocEx(TargetProcessHandle, 0, TargetBufferSize, MEM_COMMIT, PAGE_READWRITE)
            Rtn = WriteProcessMemory(TargetProcessHandle, LoadLibParamAdr, pszLibFileRemote, TargetBufferSize, 0)
            CreateRemoteThread(TargetProcessHandle, 0, 0, pfnStartAddr, LoadLibParamAdr, 0, 0)
            CloseHandle(TargetProcessHandle)

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
 

    Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
        Call Inject()
    End Sub
End Class
Thanks for the help again.
I hate that injection source. I'll quickly write up a working one in C# if you give me 10 minutes. I'll edit this post when I'm done. (Might take longer than 10 mins, I'm at work atm and don't have an IDE, so I'll just write it from memory.)
Wow, your a GOD. Thanks so much man. I'll be waiting for the source. Leave your paypal email too please. Ill drop $5 in it.
Quote Originally Posted by Synkro View Post
Wow, your a GOD. Thanks so much man. I'll be waiting for the source. Leave your paypal email too please. Ill drop $5 in it.
Hahaha don't worry about it.


---------- Post added at 08:41 PM ---------- Previous post was at 07:50 PM ----------

Lol took longer than I expected. Having no IDE is a real pain in the ass. If there's any syntax errors when you paste this into VC# let me know and I'll resolve them

Code:
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Text;
using System;

namespace BasicInjection
{
    public class Injection
    {
        #region WinAPI
        /**** [API DECLARATIONS ****/
        [DllImport("kernel32.dll")]
        private static extern int OpenProcess(int access, bool inherit, int pid);

        [DllImport("kernel32.dll")]
        private static extern uint VirtualAllocEx(int hprocess, uint address, int size, uint type, uint prot);

        [DllImport("kernel32.dll")]
        private static extern uint GetModuleHandleA(string module);

        [DllImport("kernel32.dll")]
        private static extern uint GetProcAddress(uint hmodule, string name);

        [DllImport("kernel32.dll")]
        private static extern bool WriteProcessMemory(int hprocess, uint address, byte[] pdata, int szdata, int byteswritten);

        [DllImport("kernel32.dll")]
        public static extern int CreateRemoteThread(int hProcess, int lpThreadAttributes, int dwStackSize, uint lpStartAddress, uint lpParameter, int dwCreationFlags, int lpThreadId);

        [DllImport("kernel32.dll")]
        private static extern int WaitForSingleObject(int hThread, uint timeout);

        [DllImport("kernel32.dll")]
        private static extern bool GetExitCodeThread(int hThread, out uint exit);

        [DllImport("kernel32.dll")]
        private static extern bool VirtualFreeEx(int hprocess, uint address, int size, uint type);

        [DllImport("kernel32.dll")]
        private static extern bool CloseHandle(int handle);
        #endregion

        //The Error Log for the Injection Class
        private static StringBuilder ErrorLog;

        /**** [ERROR LOG FUNCTIONS] ****/
        private static void AddError(string err)
        {
            Injection.ErrorLog.AppendLine(err);
        }

        private static void AddError(string err, int hproc, uint alloc)
        {
            Injection.ErrorLog.AppendLine(err);
            VirtualFreeEx(hproc, alloc, 0, 0x8000);
        }

        public static string GetErrors()
        {
            return Injection.ErrorLog.ToString();
        }

        private static void ResetErrors()
        {
            if (Injection.ErrorLog == null)
                Injection.ErrorLog = new StringBuilder();
            else
                Injection.ErrorLog.Remove(0, Injection.ErrorLog.Length);
        }
        /**** [END ERROR LOG FUNCTIONS] ****/

        /**** [INJECTOR OVERLOAD FUNCTIONS] ****/
        public static uint Inject(int hProcess, string dll, bool destroyHwnd)
        {
            Injection.ResetErrors();
            uint hModule = 0;
            int hThread = 0;
            if (hProcess > 0)
            {
                byte[] pData = Encoding.ASCII.GetBytes(dll + "\0");
                uint lla = GetProcAddress(GetModuleHandleA("kernel32.dll"), "LoadLibraryA");
                uint dAlloc = VirtualAllocEx(hProcess, 0, pData.Length, 0x1000 | 0x2000, 0x40);

                if (dAlloc > 0)
                {
                    if (WriteProcessMemory(hProcess, dAlloc, pData, pData.Length, 0))
                    {
                        hThread = CreateRemoteThread(hProcess, 0, 0, lla, dAlloc, 0, 0);
                        if (hThread > 0 && WaitForSingleObject(hThread, 5000) == 0x0L)
                        {
                            GetExitCodeThread(hThread, out hModule);
                            VirtualFreeEx(hProcess, dAlloc, 0, 0x8000);
                        }
                        else { AddError("Error occured in creating or executing the remote thread."); }
                    }
                    else { AddError("Unable to write memory to the process.", hProcess, dAlloc); }
                }
                else { AddError("Unable to allocate memory in the remote process."); }
            }
            else { AddError("Invalid process handle."); }

            CloseHandle(hThread);
            if (destroyHwnd)
                CloseHandle(hProcess);

            return hModule;
        }

        public static uint Inject(int pId, string dll)
        {
            int hProc = OpenProcess(0x43A, false, pId);
            return Injection.Inject(hProc, dll, true);
        }

        public static uint Inject(string process, string dll)
        {
            Process[] procs = Process.GetProcessesByName(process);
            uint hModule = (uint)(procs.Length > 0 ? Inject(procs[0].Id, dll) : 0);
            return hModule;
        }
        /**** [END INJECTOR OVERLOAD FUNCTIONS] ****/
    }
}
Thanks so much for your help but after editing out the errors IT STILL DOESENT WORK! Im not getting any errors or anything BUT the same DLl im attempting to inject with your injector works when injected with winject... Heres the source that Im using after editing yours (all I did was add some System.Conversions, change it to work with my form, and possibly some other little edit):

Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System;


namespace BasicInjection
{
    public partial class Form1 : Form
    {

        #region WinAPI
        /**** [API DECLARATIONS ****/
        [DllImport("kernel32.dll")]
        private static extern int OpenProcess(int access, bool inherit, int pid);

        [DllImport("kernel32.dll")]
        private static extern uint VirtualAllocEx(int hprocess, uint address, int size, uint type, uint prot);

        [DllImport("kernel32.dll")]
        private static extern uint GetModuleHandleA(string module);

        [DllImport("kernel32.dll")]
        private static extern uint GetProcAddress(uint hmodule, string name);

        [DllImport("kernel32.dll")]
        private static extern bool WriteProcessMemory(int hprocess, uint address, byte[] pdata, int szdata, int byteswritten);

        [DllImport("kernel32.dll")]
        private static extern int CreateRemoteThread(int hprocess, int attr, int stack, uint address, uint param, uint flags, uint threadid);

        [DllImport("kernel32.dll")]
        private static extern int WaitForSingleObject(int hThread, uint timeout);

        [DllImport("kernel32.dll")]
        private static extern bool GetExitCodeThread(int hThread, out uint exit);

        [DllImport("kernel32.dll")]
        private static extern bool VirtualFreeEx(int hprocess, uint address, int size, uint type);

        [DllImport("kernel32.dll")]
        private static extern bool CloseHandle(int handle);
        #endregion

        //The Error Log for the Injection Class
        private static StringBuilder ErrorLog;

        /**** [ERROR LOG FUNCTIONS] ****/
        private static void AddError(string err)
        {
            ErrorLog.AppendLine(err);
        }

        private static void AddError(string err, int hproc, int alloc)
        {
            ErrorLog.AppendLine(err);
          //  VirtualFreeEx(System.Convert.ToInt32(hproc), System.Convert.ToInt32(alloc), System.Convert.ToInt32(0), System.Convert.ToUInt32(0x8000));
            VirtualFreeEx(System.Convert.ToInt32(hproc), System.Convert.ToUInt32(alloc), System.Convert.ToInt32(0), System.Convert.ToUInt32(0x800));
        }

        public static string GetErrors()
        {
            return ErrorLog.ToString();
        }

        private static bool ResetErrors()
        {
            if (ErrorLog == null)
            {
                ErrorLog = new StringBuilder();
                return true;
            }
            else
            {
                ErrorLog.Clear();
                return true;
            }
        }
        /**** [END ERROR LOG FUNCTIONS] ****/


        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }



        		/**** [INJECTOR OVERLOAD FUNCTIONS] ****/
		public static uint Inject(int hProcess, string dll, bool destroyHwnd)
		{			
			ResetErrors();
			uint hModule = 0;
			int hThread = 0;
			if (hProcess > 0)
			{
				byte[] pData = Encoding.ASCII.GetBytes(dll + "\0");
				uint lla = GetProcAddress(GetModuleHandleA("kernel32.dll"), "LoadLibraryA");
				uint dAlloc = VirtualAllocEx(hProcess, 0, pData.Length, 0x1000 | 0x2000, 0x40);
				
				if (dAlloc > 0)
				{
					if (WriteProcessMemory(hProcess, dAlloc, pData, pData.Length, 0))
					{
						hThread = CreateRemoteThread(hProcess, 0, 0, lla, dAlloc, 0, 0);
						if (hThread > 0 && WaitForSingleObject(hThread, 5000) == 0x0L)
						{
							GetExitCodeThread(hThread, out hModule);
							VirtualFreeEx(hProcess, dAlloc, 0, 0x8000);
						}
						//else { AddError("Thread creation failed or was terminated unexpectedly.", System.Convert.ToInt32(hProcess), System.Convert.ToUInt32(dAlloc)); }
                        else { AddError("Thread creation failed or was terminated unexpectedly.", System.Convert.ToInt32(hProcess), System.Convert.ToInt32(dAlloc)); }
					}
					else { AddError("Unable to write memory to the process.", System.Convert.ToInt32(hProcess), System.Convert.ToInt32(dAlloc)); }
				}
				else { AddError("Unable to allocate memory in the remote process."); }
			}
			else {  AddError("Invalid process handle."); }
			
			CloseHandle(hThread);
			if (destroyHwnd)
				CloseHandle(hProcess);
			
			return hModule;
		}
		
		public static uint Inject(int pId, string dll)
		{
            int hProc = OpenProcess(System.Convert.ToInt32(0x43A), System.Convert.ToBoolean(0), pId);
			return Inject(hProc, dll, true);
		}
		
		public static uint Inject(string process, string dll)
		{
			Process[] procs = Process.GetProcessesByName(process);
			uint hModule = (uint)(procs.Length > 0 ? Inject(procs[0].Id, dll) : 0);
			return hModule;
		}

        private void button1_Click(object sender, System.EventArgs e)
        {
            Inject("iw3mp", "hacks.dll");
        }
		/**** [END INJECTOR OVERLOAD FUNCTIONS] ****/
	}



    }
Thanks again for all your help.
Quote Originally Posted by Synkro View Post
Thanks so much for your help but after editing out the errors IT STILL DOESENT WORK! Im not getting any errors or anything BUT the same DLl im attempting to inject with your injector works when injected with winject... Heres the source that Im using after editing yours (all I did was add some System.Conversions, change it to work with my form, and possibly some other little edit):

Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System;


namespace BasicInjection
{
    public partial class Form1 : Form
    {

        #region WinAPI
        /**** [API DECLARATIONS ****/
        [DllImport("kernel32.dll")]
        private static extern int OpenProcess(int access, bool inherit, int pid);

        [DllImport("kernel32.dll")]
        private static extern uint VirtualAllocEx(int hprocess, uint address, int size, uint type, uint prot);

        [DllImport("kernel32.dll")]
        private static extern uint GetModuleHandleA(string module);

        [DllImport("kernel32.dll")]
        private static extern uint GetProcAddress(uint hmodule, string name);

        [DllImport("kernel32.dll")]
        private static extern bool WriteProcessMemory(int hprocess, uint address, byte[] pdata, int szdata, int byteswritten);

        [DllImport("kernel32.dll")]
        private static extern int CreateRemoteThread(int hprocess, int attr, int stack, uint address, uint param, uint flags, uint threadid);

        [DllImport("kernel32.dll")]
        private static extern int WaitForSingleObject(int hThread, uint timeout);

        [DllImport("kernel32.dll")]
        private static extern bool GetExitCodeThread(int hThread, out uint exit);

        [DllImport("kernel32.dll")]
        private static extern bool VirtualFreeEx(int hprocess, uint address, int size, uint type);

        [DllImport("kernel32.dll")]
        private static extern bool CloseHandle(int handle);
        #endregion

        //The Error Log for the Injection Class
        private static StringBuilder ErrorLog;

        /**** [ERROR LOG FUNCTIONS] ****/
        private static void AddError(string err)
        {
            ErrorLog.AppendLine(err);
        }

        private static void AddError(string err, int hproc, int alloc)
        {
            ErrorLog.AppendLine(err);
          //  VirtualFreeEx(System.Convert.ToInt32(hproc), System.Convert.ToInt32(alloc), System.Convert.ToInt32(0), System.Convert.ToUInt32(0x8000));
            VirtualFreeEx(System.Convert.ToInt32(hproc), System.Convert.ToUInt32(alloc), System.Convert.ToInt32(0), System.Convert.ToUInt32(0x800));
        }

        public static string GetErrors()
        {
            return ErrorLog.ToString();
        }

        private static bool ResetErrors()
        {
            if (ErrorLog == null)
            {
                ErrorLog = new StringBuilder();
                return true;
            }
            else
            {
                ErrorLog.Clear();
                return true;
            }
        }
        /**** [END ERROR LOG FUNCTIONS] ****/


        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }



        		/**** [INJECTOR OVERLOAD FUNCTIONS] ****/
		public static uint Inject(int hProcess, string dll, bool destroyHwnd)
		{			
			ResetErrors();
			uint hModule = 0;
			int hThread = 0;
			if (hProcess > 0)
			{
				byte[] pData = Encoding.ASCII.GetBytes(dll + "\0");
				uint lla = GetProcAddress(GetModuleHandleA("kernel32.dll"), "LoadLibraryA");
				uint dAlloc = VirtualAllocEx(hProcess, 0, pData.Length, 0x1000 | 0x2000, 0x40);
				
				if (dAlloc > 0)
				{
					if (WriteProcessMemory(hProcess, dAlloc, pData, pData.Length, 0))
					{
						hThread = CreateRemoteThread(hProcess, 0, 0, lla, dAlloc, 0, 0);
						if (hThread > 0 && WaitForSingleObject(hThread, 5000) == 0x0L)
						{
							GetExitCodeThread(hThread, out hModule);
							VirtualFreeEx(hProcess, dAlloc, 0, 0x8000);
						}
						//else { AddError("Thread creation failed or was terminated unexpectedly.", System.Convert.ToInt32(hProcess), System.Convert.ToUInt32(dAlloc)); }
                        else { AddError("Thread creation failed or was terminated unexpectedly.", System.Convert.ToInt32(hProcess), System.Convert.ToInt32(dAlloc)); }
					}
					else { AddError("Unable to write memory to the process.", System.Convert.ToInt32(hProcess), System.Convert.ToInt32(dAlloc)); }
				}
				else { AddError("Unable to allocate memory in the remote process."); }
			}
			else {  AddError("Invalid process handle."); }
			
			CloseHandle(hThread);
			if (destroyHwnd)
				CloseHandle(hProcess);
			
			return hModule;
		}
		
		public static uint Inject(int pId, string dll)
		{
            int hProc = OpenProcess(System.Convert.ToInt32(0x43A), System.Convert.ToBoolean(0), pId);
			return Inject(hProc, dll, true);
		}
		
		public static uint Inject(string process, string dll)
		{
			Process[] procs = Process.GetProcessesByName(process);
			uint hModule = (uint)(procs.Length > 0 ? Inject(procs[0].Id, dll) : 0);
			return hModule;
		}

        private void button1_Click(object sender, System.EventArgs e)
        {
            Inject("iw3mp", "hacks.dll");
        }
		/**** [END INJECTOR OVERLOAD FUNCTIONS] ****/
	}



    }
Thanks again for all your help.
Go to C#, say Project -> Add item choose code file (should have the .cs extension), name it whatever. C# should then open up the new file, highlight everything (CTRL + A) and hit delete. You should now have an empty file. Copy and paste my code from the previous post into this file.

Now, in your main .cs file, add the following namespace import (at the top of the codefile)
Code:
using BasicInjection;
Then to call,
Code:
uint hMod = Injection.Inject("iw3mp", "hacks.dll");
if (hMod == 0)
    MessageBox.Show(Injection.GetErrors());
Make sure "hacks.dll" is located in your executable path, otherwise put the absolute path in

Oh yeah, I forgot. Make sure you compile your application as x86 not 'any cpu'.
Did everything you just said... Still doesent work.... Sighh. Anyways, no errors returned for your code, but when injecting i get a blank error message... Like a message box pops up but says nothing... Is that supposed to happen? I cant tell by your code. A VB.net Code would be just find if you know a working injection one for VB.net.... Just to clarify again, the hacks ARE working with Winject.... Just not with your injection code. Its sooo odd.... (and yes, i am building on x86). And the hacks.dll are in my directoy. I assure you I am doing everything correctly, I just don't know why its not working!

Thanks
Quote Originally Posted by Synkro View Post
Did everything you just said... Still doesent work.... Sighh. Anyways, no errors returned for your code, but when injecting i get a blank error message... Like a message box pops up but says nothing... Is that supposed to happen? I cant tell by your code. A VB.net Code would be just find if you know a working injection one for VB.net.... Just to clarify again, the hacks ARE working with Winject.... Just not with your injection code. Its sooo odd.... (and yes, i am building on x86). And the hacks.dll are in my directoy. I assure you I am doing everything correctly, I just don't know why its not working!

Thanks
I think it would help him if you can post all of your code here.
Quote Originally Posted by Synkro View Post
Did everything you just said... Still doesent work.... Sighh. Anyways, no errors returned for your code, but when injecting i get a blank error message... Like a message box pops up but says nothing... Is that supposed to happen? I cant tell by your code. A VB.net Code would be just find if you know a working injection one for VB.net.... Just to clarify again, the hacks ARE working with Winject.... Just not with your injection code. Its sooo odd.... (and yes, i am building on x86). And the hacks.dll are in my directoy. I assure you I am doing everything correctly, I just don't know why its not working!

Thanks
I had the same thing when I got home and tested it. Changing to x86 fixed the problem though. Here's the exact code I used.

Code:
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Text;
using System;

namespace BasicInjection
{
    public class Injection
    {
        #region WinAPI
        /**** [API DECLARATIONS ****/
        [DllImport("kernel32.dll")]
        private static extern int OpenProcess(int access, bool inherit, int pid);

        [DllImport("kernel32.dll")]
        private static extern uint VirtualAllocEx(int hprocess, uint address, int size, uint type, uint prot);

        [DllImport("kernel32.dll")]
        private static extern uint GetModuleHandleA(string module);

        [DllImport("kernel32.dll")]
        private static extern uint GetProcAddress(uint hmodule, string name);

        [DllImport("kernel32.dll")]
        private static extern bool WriteProcessMemory(int hprocess, uint address, byte[] pdata, int szdata, out int byteswritten);

        [DllImport("kernel32.dll")]
        public static extern int CreateRemoteThread(int hProcess, int lpThreadAttributes, int dwStackSize, uint lpStartAddress, uint lpParameter, int dwCreationFlags, int lpThreadId);

        [DllImport("kernel32.dll")]
        private static extern int WaitForSingleObject(int hThread, uint timeout);

        [DllImport("kernel32.dll")]
        private static extern bool GetExitCodeThread(int hThread, out uint exit);

        [DllImport("kernel32.dll")]
        private static extern bool VirtualFreeEx(int hprocess, uint address, int size, uint type);

        [DllImport("kernel32.dll")]
        private static extern bool CloseHandle(int handle);
        #endregion

        //The Error Log for the Injection Class
        private static StringBuilder ErrorLog;

        /**** [ERROR LOG FUNCTIONS] ****/
        private static void AddError(string err)
        {
            Injection.ErrorLog.AppendLine(err);
        }

        private static void AddError(string err, int hproc, uint alloc)
        {
            Injection.ErrorLog.AppendLine(err);
            VirtualFreeEx(hproc, alloc, 0, 0x8000);
        }

        public static string GetErrors()
        {
            return Injection.ErrorLog.ToString();
        }

        private static void ResetErrors()
        {
            if (Injection.ErrorLog == null)
                Injection.ErrorLog = new StringBuilder();
            else
                Injection.ErrorLog.Remove(0, Injection.ErrorLog.Length);
        }
        /**** [END ERROR LOG FUNCTIONS] ****/

        /**** [INJECTOR OVERLOAD FUNCTIONS] ****/
        public static uint Inject(int hProcess, string dll, bool destroyHwnd)
        {
            Injection.ResetErrors();
            uint hModule = 0;
            int hThread = 0;
  
            if (hProcess > 0 && IntPtr.Size == 4)
            {
                byte[] pData = Encoding.ASCII.GetBytes(dll + "\0");
                uint lla = GetProcAddress(GetModuleHandleA("kernel32.dll"), "LoadLibraryA");
                uint dAlloc = VirtualAllocEx(hProcess, 0, pData.Length, 0x1000 | 0x2000, 0x40);
                int bytes = 0;

                if (dAlloc > 0)
                {
                    if (WriteProcessMemory(hProcess, dAlloc, pData, pData.Length, out bytes) && bytes == pData.Length)
                    {
                        hThread = CreateRemoteThread(hProcess, 0, 0, lla, dAlloc, 0, 0);
                        if (hThread > 0 && WaitForSingleObject(hThread, 5000) == 0x0L)
                        {
                            GetExitCodeThread(hThread, out hModule);
                            VirtualFreeEx(hProcess, dAlloc, 0, 0x8000);
                        }
                        else { AddError("Error occured in creating or executing the remote thread."); }
                    }
                    else { AddError("Unable to write memory to the process.", hProcess, dAlloc); }
                }
                else { AddError("Unable to allocate memory in the remote process."); }
            }
            else { AddError("Invalid process handle or not compiled in x86 mode."); }

            CloseHandle(hThread);
            if (destroyHwnd)
                CloseHandle(hProcess);

            return hModule;
        }

        public static uint Inject(int pId, string dll)
        {
            int hProc = OpenProcess(0x43A, false, pId);
            return Injection.Inject(hProc, dll, true);
        }

        public static uint Inject(string process, string dll)
        {
            Process[] procs = Process.GetProcessesByName(process);
            uint hModule = 0;
            if (procs.Length > 0)
                hModule = Inject(procs[0].Id, dll);
            else
                AddError("Target process is not running.");
            return hModule;
        }
        /**** [END INJECTOR OVERLOAD FUNCTIONS] ****/
    }
}
And for the injection:
Code:
        private void button1_Click(object sender, EventArgs e)
        {
            uint hmod = BasicInjection.Injection.Inject("bf2", @"C:\Users\Jason\Documents\Visual Studio 2008\Projects\BF2Hack\Release\BF2Hack.dll");
            if (hmod == 0)
                MessageBox.Show(BasicInjection.Injection.GetErrors());
        }
Quote Originally Posted by Jason View Post


I had the same thing when I got home and tested it. Changing to x86 fixed the problem though. Here's the exact code I used.

Code:
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Text;
using System;

namespace BasicInjection
{
    public class Injection
    {
        #region WinAPI
        /**** [API DECLARATIONS ****/
        [DllImport("kernel32.dll")]
        private static extern int OpenProcess(int access, bool inherit, int pid);

        [DllImport("kernel32.dll")]
        private static extern uint VirtualAllocEx(int hprocess, uint address, int size, uint type, uint prot);

        [DllImport("kernel32.dll")]
        private static extern uint GetModuleHandleA(string module);

        [DllImport("kernel32.dll")]
        private static extern uint GetProcAddress(uint hmodule, string name);

        [DllImport("kernel32.dll")]
        private static extern bool WriteProcessMemory(int hprocess, uint address, byte[] pdata, int szdata, out int byteswritten);

        [DllImport("kernel32.dll")]
        public static extern int CreateRemoteThread(int hProcess, int lpThreadAttributes, int dwStackSize, uint lpStartAddress, uint lpParameter, int dwCreationFlags, int lpThreadId);

        [DllImport("kernel32.dll")]
        private static extern int WaitForSingleObject(int hThread, uint timeout);

        [DllImport("kernel32.dll")]
        private static extern bool GetExitCodeThread(int hThread, out uint exit);

        [DllImport("kernel32.dll")]
        private static extern bool VirtualFreeEx(int hprocess, uint address, int size, uint type);

        [DllImport("kernel32.dll")]
        private static extern bool CloseHandle(int handle);
        #endregion

        //The Error Log for the Injection Class
        private static StringBuilder ErrorLog;

        /**** [ERROR LOG FUNCTIONS] ****/
        private static void AddError(string err)
        {
            Injection.ErrorLog.AppendLine(err);
        }

        private static void AddError(string err, int hproc, uint alloc)
        {
            Injection.ErrorLog.AppendLine(err);
            VirtualFreeEx(hproc, alloc, 0, 0x8000);
        }

        public static string GetErrors()
        {
            return Injection.ErrorLog.ToString();
        }

        private static void ResetErrors()
        {
            if (Injection.ErrorLog == null)
                Injection.ErrorLog = new StringBuilder();
            else
                Injection.ErrorLog.Remove(0, Injection.ErrorLog.Length);
        }
        /**** [END ERROR LOG FUNCTIONS] ****/

        /**** [INJECTOR OVERLOAD FUNCTIONS] ****/
        public static uint Inject(int hProcess, string dll, bool destroyHwnd)
        {
            Injection.ResetErrors();
            uint hModule = 0;
            int hThread = 0;
  
            if (hProcess > 0 && IntPtr.Size == 4)
            {
                byte[] pData = Encoding.ASCII.GetBytes(dll + "\0");
                uint lla = GetProcAddress(GetModuleHandleA("kernel32.dll"), "LoadLibraryA");
                uint dAlloc = VirtualAllocEx(hProcess, 0, pData.Length, 0x1000 | 0x2000, 0x40);
                int bytes = 0;

                if (dAlloc > 0)
                {
                    if (WriteProcessMemory(hProcess, dAlloc, pData, pData.Length, out bytes) && bytes == pData.Length)
                    {
                        hThread = CreateRemoteThread(hProcess, 0, 0, lla, dAlloc, 0, 0);
                        if (hThread > 0 && WaitForSingleObject(hThread, 5000) == 0x0L)
                        {
                            GetExitCodeThread(hThread, out hModule);
                            VirtualFreeEx(hProcess, dAlloc, 0, 0x8000);
                        }
                        else { AddError("Error occured in creating or executing the remote thread."); }
                    }
                    else { AddError("Unable to write memory to the process.", hProcess, dAlloc); }
                }
                else { AddError("Unable to allocate memory in the remote process."); }
            }
            else { AddError("Invalid process handle or not compiled in x86 mode."); }

            CloseHandle(hThread);
            if (destroyHwnd)
                CloseHandle(hProcess);

            return hModule;
        }

        public static uint Inject(int pId, string dll)
        {
            int hProc = OpenProcess(0x43A, false, pId);
            return Injection.Inject(hProc, dll, true);
        }

        public static uint Inject(string process, string dll)
        {
            Process[] procs = Process.GetProcessesByName(process);
            uint hModule = 0;
            if (procs.Length > 0)
                hModule = Inject(procs[0].Id, dll);
            else
                AddError("Target process is not running.");
            return hModule;
        }
        /**** [END INJECTOR OVERLOAD FUNCTIONS] ****/
    }
}
And for the injection:
Code:
        private void button1_Click(object sender, EventArgs e)
        {
            uint hmod = BasicInjection.Injection.Inject("bf2", @"C:\Users\Jason\Documents\Visual Studio 2008\Projects\BF2Hack\Release\BF2Hack.dll");
            if (hmod == 0)
                MessageBox.Show(BasicInjection.Injection.GetErrors());
        }
Wow jason... You are AMAZING. I can not thank you enough. PLEASE put your paypal down... I seriously feel like i owe you something! Why do you do this for free?!?! And whats your job? It better be something with programming! I will be helping out around these forums with other peoples problems to pay off my debt I now owe to this forum! Haha. Seriously though, thanks man. It works flawlessly now. If you want it would be great if you had a vb.net injector too (if thats not to much to ask, haha it probably is considering how much you've already done for me)... But if not Ill just have the two communicate via tcpconnections with my vb.net application.

Thanks again Jason!
-Synkro
Quote Originally Posted by Synkro View Post
Wow jason... You are AMAZING. I can not thank you enough. PLEASE put your paypal down... I seriously feel like i owe you something! Why do you do this for free?!?! And whats your job? It better be something with programming! I will be helping out around these forums with other peoples problems to pay off my debt I now owe to this forum! Haha. Seriously though, thanks man. It works flawlessly now. If you want it would be great if you had a vb.net injector too (if thats not to much to ask, haha it probably is considering how much you've already done for me)... But if not Ill just have the two communicate via tcpconnections with my vb.net application.

Thanks again Jason!
-Synkro
My VB.NET injector is stickied in the Visual Basic section.

I work as a web developer for a University.
Lol, marked solved
Posts 1–14 of 14 · Page 1 of 1

Post a Reply

Similar Threads

Tags for this Thread

None

Talk with us