1
+ using System ;
2
+ using System . Text ;
3
+ using System . Diagnostics ;
4
+ using System . Runtime . InteropServices ;
5
+
6
+
1
7
namespace DLLoad
2
8
{
3
9
internal static class Program
@@ -14,4 +20,51 @@ static void Main()
14
20
Application . Run ( new MainForm ( ) ) ;
15
21
}
16
22
}
23
+
24
+
25
+ public class BasicInject
26
+ {
27
+ [ DllImport ( "kernel32.dll" ) ]
28
+ public static extern IntPtr OpenProcess ( int dwDesiredAccess , bool bInheritHandle , int dwProcessId ) ;
29
+
30
+ [ DllImport ( "kernel32.dll" , CharSet = CharSet . Auto ) ]
31
+ public static extern IntPtr GetModuleHandle ( string lpModuleName ) ;
32
+
33
+ [ DllImport ( "kernel32" , CharSet = CharSet . Ansi , ExactSpelling = true , SetLastError = true ) ]
34
+ static extern IntPtr GetProcAddress ( IntPtr hModule , string procName ) ;
35
+
36
+ [ DllImport ( "kernel32.dll" , SetLastError = true , ExactSpelling = true ) ]
37
+ static extern IntPtr VirtualAllocEx ( IntPtr hProcess , IntPtr lpAddress , uint dwSize , uint flAllocationType , uint flProtect ) ;
38
+
39
+ [ DllImport ( "kernel32.dll" , SetLastError = true ) ]
40
+ static extern bool WriteProcessMemory ( IntPtr hProcess , IntPtr lpBaseAddress , byte [ ] lpBuffer , uint nSize , out UIntPtr lpNumberOfBytesWritten ) ;
41
+
42
+ [ DllImport ( "kernel32.dll" ) ]
43
+ static extern IntPtr CreateRemoteThread ( IntPtr hProcess , IntPtr lpThreadAttributes , uint dwStackSize , IntPtr lpStartAddress , IntPtr lpParameter , uint dwCreationFlags , IntPtr lpThreadId ) ;
44
+
45
+ // privileges
46
+ const int PROCESS_CREATE_THREAD = 0x0002 ;
47
+ const int PROCESS_QUERY_INFORMATION = 0x0400 ;
48
+ const int PROCESS_VM_OPERATION = 0x0008 ;
49
+ const int PROCESS_VM_WRITE = 0x0020 ;
50
+ const int PROCESS_VM_READ = 0x0010 ;
51
+
52
+ // used for memory allocation
53
+ const uint MEM_COMMIT = 0x00001000 ;
54
+ const uint MEM_RESERVE = 0x00002000 ;
55
+ const uint PAGE_READWRITE = 4 ;
56
+
57
+ public static int Inject ( Process targetProcess , string dllPath )
58
+ {
59
+ IntPtr procHandle = OpenProcess ( PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ , false , targetProcess . Id ) ;
60
+ IntPtr loadLibraryAddr = GetProcAddress ( GetModuleHandle ( "kernel32.dll" ) , "LoadLibraryA" ) ;
61
+ IntPtr allocMemAddress = VirtualAllocEx ( procHandle , IntPtr . Zero , ( uint ) ( ( dllPath . Length + 1 ) * Marshal . SizeOf ( typeof ( char ) ) ) , MEM_COMMIT | MEM_RESERVE , PAGE_READWRITE ) ;
62
+
63
+ UIntPtr bytesWritten ;
64
+ WriteProcessMemory ( procHandle , allocMemAddress , Encoding . Default . GetBytes ( dllPath ) , ( uint ) ( ( dllPath . Length + 1 ) * Marshal . SizeOf ( typeof ( char ) ) ) , out bytesWritten ) ;
65
+ CreateRemoteThread ( procHandle , IntPtr . Zero , 0 , loadLibraryAddr , allocMemAddress , 0 , IntPtr . Zero ) ;
66
+
67
+ return 0 ;
68
+ }
69
+ }
17
70
}
0 commit comments