using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
class Program
{
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr OpenProcess(uint processAccess, bool bInheritHandle, int processId);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint size, out int lpNumberOfBytesWritten);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, out IntPtr lpThreadId);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool CloseHandle(IntPtr hObject);
private const uint PROCESS_ALL_ACCESS = 0x1F0FFF;
private const uint MEM_COMMIT = 0x1000;
private const uint MEM_RESERVE = 0x2000;
private const uint PAGE_READWRITE = 0x04;
static void Main(string[] args)
{
if (args.Length < 2)
{
Console.WriteLine("Usage: Injector <ProcessId> <PathToDll>");
return;
}
int processId = int.Parse(args[0]);
string dllPath = args[1];
IntPtr hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, processId);
if (hProcess == IntPtr.Zero)
{
Console.WriteLine("Failed to open process.");
return;
}
IntPtr allocMemAddress = VirtualAllocEx(hProcess, IntPtr.Zero, (uint)((dllPath.Length + 1) * Marshal.SizeOf(typeof(char))), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (allocMemAddress == IntPtr.Zero)
{
Console.WriteLine("Failed to allocate memory in target process.");
CloseHandle(hProcess);
return;
}
byte[] dllPathBytes = System.Text.Encoding.ASCII.GetBytes(dllPath);
if (!WriteProcessMemory(hProcess, allocMemAddress, dllPathBytes, (uint)dllPathBytes.Length, out _))
{
Console.WriteLine("Failed to write to process memory.");
CloseHandle(hProcess);
return;
}
IntPtr loadLibraryAddress = GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");
CreateRemoteThread(hProcess, IntPtr.Zero, 0, loadLibraryAddress, allocMemAddress, 0, out _);
CloseHandle(hProcess);
Console.WriteLine("DLL injected successfully.");
}
[DllImport("kernel32.dll")]
private static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
[DllImport("kernel32.dll")]
private static extern IntPtr GetModuleHandle(string lpModuleName);
}