-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathProgram.cs
213 lines (175 loc) · 10.5 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
using Binarysharp.Assemblers.Fasm;
using System;
using System.CodeDom;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
using Process.NET;
using Process.NET.Memory;
using Process.NET.Native.Types;
using Process = System.Diagnostics.Process;
namespace CSharp_Inline_Assembly
{
/// <summary>
/// This program demonstrates how to use inline x86 assembly from C#
/// </summary>
class Program
{
private static IProcess _currentProcess;
static void Main(string[] args)
{
_currentProcess = new ProcessSharp(System.Diagnostics.Process.GetCurrentProcess(), MemoryType.Local);
Example1();
Example2();
Example3();
Example4();
Example5();
//Wait for any key to exit
Console.ReadKey(true);
}
// Example 1: Function Returning Constant Value
[SuppressUnmanagedCodeSecurity] // disable security checks for better performance
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] // cdecl - let caller (.NET CLR) clean the stack
private delegate int AssemblyConstantValueFunction();
private static void Example1()
{
const int valueToReturn = 1;
FasmNet fasmNet = new FasmNet();
fasmNet.AddLine("use32"); //Tell FASM.Net to use x86 (32bit) mode
fasmNet.AddLine("mov eax, {0}", valueToReturn); // copy "1" to eax
fasmNet.AddLine("ret"); // in cdecl calling convention, return value is stored in eax; so this will return 1
byte[] assembledCode = fasmNet.Assemble();
var allocatedCodeMemory = _currentProcess.MemoryFactory.Allocate(
name: "Example1", // only used for debugging; not really needed
size: assembledCode.Length,
protection: MemoryProtectionFlags.ExecuteReadWrite /* It is important to mark the memory as executeable or we will get exceptions from DEP */
);
allocatedCodeMemory.Write(0, assembledCode);
var myAssemblyFunction = Marshal.GetDelegateForFunctionPointer<AssemblyConstantValueFunction>(allocatedCodeMemory.BaseAddress);
var returnValue = myAssemblyFunction();
// Warning: Potential memory leak!
// Do not forget to dispose the allocated code memory after usage.
allocatedCodeMemory.Dispose();
Console.WriteLine($"Example1 return value: {returnValue}, expected: {valueToReturn}"); // Prints 1
}
// Example 2: Function Reading Registers
[SuppressUnmanagedCodeSecurity] // disable security checks for better performance
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] // cdecl - let caller (.NET CLR) clean the stack
private delegate IntPtr AssemblyReadRegistersFunction();
private static void Example2()
{
FasmNet fasmNet = new FasmNet();
fasmNet.AddLine("use32"); //Tell FASM.Net to use x86 (32bit) mode
fasmNet.AddLine("mov eax, [ebp+4]"); // Set return value to ebp+4 (return address)
fasmNet.AddLine("ret"); // in cdecl calling convention, return value is stored in eax; so this will return the return address
byte[] assembledCode = fasmNet.Assemble();
var allocatedCodeMemory = _currentProcess.MemoryFactory.Allocate(
name: "Example2", // only used for debugging; not really needed
size: assembledCode.Length,
protection: MemoryProtectionFlags.ExecuteReadWrite /* It is important to mark the memory as executeable or we will get exceptions from DEP */
);
allocatedCodeMemory.Write(0, assembledCode);
var myAssemblyFunction = Marshal.GetDelegateForFunctionPointer<AssemblyReadRegistersFunction>(allocatedCodeMemory.BaseAddress);
var returnValue = myAssemblyFunction();
// Warning: Potential memory leak!
// Do not forget to dispose the allocated code memory after usage.
allocatedCodeMemory.Dispose();
Console.WriteLine($"Example2 return value: 0x{returnValue.ToInt32():X}"); // Prints this methods JIT'ed address
}
// Example 3: Add Function With Parameters
[SuppressUnmanagedCodeSecurity] // disable security checks for better performance
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] // cdecl - let caller (.NET CLR) clean the stack
private delegate int AssemblyAddFunction(int x, int y);
private static void Example3()
{
FasmNet fasmNet = new FasmNet();
fasmNet.AddLine("use32"); //Tell FASM.Net to use x86 (32bit) mode
fasmNet.AddLine("push ebp"); // init stack frame
fasmNet.AddLine("mov eax, [ebp+8]"); // set eax to second param (remember, in cdecl calling convention, params are pushed right-to-left)
fasmNet.AddLine("mov edx, [ebp+12]"); // set edx to first param
fasmNet.AddLine("add eax, edx"); //add edx (first param) to eax (second param)
fasmNet.AddLine("pop ebp"); // leave stack frame
fasmNet.AddLine("ret"); // in cdecl calling convention, return value is stored in eax; so this will return both params added up
byte[] assembledCode = fasmNet.Assemble();
var allocatedCodeMemory = _currentProcess.MemoryFactory.Allocate(
name: "Example3", // only used for debugging; not really needed
size: assembledCode.Length,
protection: MemoryProtectionFlags.ExecuteReadWrite /* It is important to mark the memory as executeable or we will get exceptions from DEP */
);
allocatedCodeMemory.Write(0, assembledCode);
var myAssemblyFunction = Marshal.GetDelegateForFunctionPointer<AssemblyAddFunction>(allocatedCodeMemory.BaseAddress);
var returnValue = myAssemblyFunction(10, -15);
// Warning: Potential memory leak!
// Do not forget to dispose the allocated code memory after usage.
allocatedCodeMemory.Dispose();
Console.WriteLine($"Example3 return value: {returnValue}, expected: -5"); // Prints -5
}
// Example 4: Add Function With Parameters (Without Fasm.NET)
private static void Example4()
{
//You can use any x86 assembler
//For this example I have used https://defuse.ca/online-x86-assembler.htm
// Without FASM.Net I strongly suggest you to comment each instruction (e.g. "0 push ebp")
byte[] assembledCode =
{
0x55, // 0 push ebp ; init stack frame
0x8B, 0x45, 0x08, // 1 mov eax, [ebp+8] ; set eax to second param (remember, in cdecl calling convention, params are pushed right-to-left)
0x8B, 0x55, 0x0C, // 4 mov edx, [ebp+12] ; set edx to first param
0x01, 0xD0, // 7 add eax, edx ; add edx (first param) to eax (second param)
0x5D, // 9 pop ebp ; leave stack frame
0xC3 // A ret ; in cdecl calling convention, return value is stored in eax; so this will return both params added up
};
var allocatedCodeMemory = _currentProcess.MemoryFactory.Allocate(
name: "Example4", // only used for debugging; not really needed
size: assembledCode.Length,
protection: MemoryProtectionFlags.ExecuteReadWrite /* It is important to mark the memory as executeable or we will get exceptions from DEP */
);
allocatedCodeMemory.Write(0, assembledCode);
var myAssemblyFunction = Marshal.GetDelegateForFunctionPointer<AssemblyAddFunction>(allocatedCodeMemory.BaseAddress);
var returnValue = myAssemblyFunction(10, -15);
// Warning: Potential memory leak!
// Do not forget to dispose the allocated code memory after usage.
allocatedCodeMemory.Dispose();
Console.WriteLine($"Example3 (no Fasm.NET) return value: {returnValue}, expected: -5"); // Prints -5
}
//Example 5: Add Function With Parameters (Without any dependencies)
[DllImport("kernel32.dll")]
private static extern bool VirtualProtectEx(IntPtr hProcess, IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect);
private static void Example5()
{
var process = System.Diagnostics.Process.GetCurrentProcess();
//You can use any x86 assembler
//For this example I have used https://defuse.ca/online-x86-assembler.htm
// Without FASM.Net I strongly suggest you to comment each instruction (e.g. "0 push ebp")
byte[] assembledCode =
{
0x55, // 0 push ebp ; init stack frame
0x8B, 0x45, 0x08, // 1 mov eax, [ebp+8] ; set eax to second param (remember, in cdecl calling convention, params are pushed right-to-left)
0x8B, 0x55, 0x0C, // 4 mov edx, [ebp+12] ; set edx to first param
0x01, 0xD0, // 7 add eax, edx ; add edx (first param) to eax (second param)
0x5D, // 9 pop ebp ; leave stack frame
0xC3 // A ret ; in cdecl calling convention, return value is stored in eax; so this will return both params added up
};
int returnValue;
unsafe
{
fixed (byte* ptr = assembledCode)
{
var memoryAddress = (IntPtr) ptr;
// Mark memory as EXECUTE_READWRITE to prevent DEP exceptions
if (!VirtualProtectEx(process.Handle, memoryAddress,
(UIntPtr) assembledCode.Length, 0x40 /* EXECUTE_READWRITE */, out uint _))
{
throw new Win32Exception();
}
var myAssemblyFunction = Marshal.GetDelegateForFunctionPointer<AssemblyAddFunction>(memoryAddress);
returnValue = myAssemblyFunction(10, -15);
}
}
// Note: We do not have to dispose memory ourself; the CLR will handle this.
Console.WriteLine($"Example3 (no dependencies) return value: {returnValue}, expected: -5"); // Prints -5
}
}
}