-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathProcessC.cs
More file actions
580 lines (477 loc) · 16.7 KB
/
ProcessC.cs
File metadata and controls
580 lines (477 loc) · 16.7 KB
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
using System;
//using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Runtime.Serialization;
namespace eflayMH_WPF
{
/// <summary>
/// Description of dllinject.
/// </summary>
public unsafe class ProcessC
{
public ProcessC(int _pid)
{
Pid = _pid;
//bool ttladj;
//RtlAdjustPrivilege(20, true, 0, out ttladj);
try
{
pname = Process.GetProcessById(Pid);
hwnd = pname.Handle;
}
catch (Exception error)
{ //当标示pid的进程不存在时发生异常;
throw new ProcessCException("找不到进程," + error);
}
}
public ProcessC(Process proc)
{
Pid = proc.Id;
pname = proc;
hwnd = pname.Handle;
//bool ttladj;
//RtlAdjustPrivilege(20, true, 0, out ttladj);
}
//public static void enterDebugPrivilege()
//{
// bool ttladj;
// RtlAdjustPrivilege(20, true, 0, out ttladj);
//}
[DllImport("kernel32.dll")]
static extern int VirtualAllocEx(IntPtr hwnd, int lpaddress, int size, int type, Int32 tect);
[DllImport("kernel32.dll")]
static extern Boolean WriteProcessMemory(IntPtr hwnd, int baseaddress, string buffer, int nsize,out int filewriten);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool WriteProcessMemory(IntPtr hProcess, int lpBaseAddress, Byte[] lpBuffer, int nSize, out int lpNumberOfBytesWritten);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool WriteProcessMemory(IntPtr hProcess, int lpBaseAddress, char[] lpBuffer, int nSize, out int lpNumberOfBytesWritten);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool WriteProcessMemory(IntPtr hProcess, int lpBaseAddress, byte* lpBuffer, int nSize, out int lpNumberOfBytesWritten);
[DllImport("kernel32.dll")]
static extern bool WriteProcessMemory(IntPtr hProcess, int lpBaseAddress, int lpBuffer,
int nSize, out int lpNumberOfBytesWritten);
[DllImport("kernel32.dll", SetLastError = true, PreserveSig = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress,void* lpBuffer, int nSize, out int lpNumberOfBytesRead);
[DllImport("kernel32.dll", SetLastError = true, PreserveSig = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, [Out] byte[] Buffer, int nSize, out int lpNumberOfBytesRead);
[DllImport("kernel32.dll")]
static extern int GetProcAddress(int hwnd, string lpname);
[DllImport("kernel32.dll")]
static extern int GetModuleHandleA(string name);
[DllImport("kernel32.dll")]
static extern IntPtr CreateRemoteThread(IntPtr hwnd, int attrib, int size, int address, int par, int flags, int threadid);
[DllImport("kernel32.dll")]
static extern Int32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds);
//[DllImport("kernel32.dll")]
//static extern Boolean VirtualFree(IntPtr lpAddress, Int32 dwSize, Int32 dwFreeType);
[DllImport("kernel32", SetLastError = true)]
static extern IntPtr LoadLibrary(string lpFileName);
[Flags]
public enum FreeType
{
Decommit = 0x4000,
Release = 0x8000,
}
[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
static extern bool VirtualFreeEx(IntPtr hProcess, IntPtr lpAddress,
int dwSize, FreeType dwFreeType);
/// <summary>
///
/// </summary>
/// <param name="v1">enum imformation ,Process Token & Privilege</param>
/// <param name="v2">是否打开权限</param>
/// <param name="v3">仅当前线程?否则当前进程,adjustPrivilegeType</param>
/// <param name="v4">此权限原来的状态</param>
/// <returns></returns>
//[DllImport("ntdll.dll", CharSet = CharSet.Unicode, SetLastError = true)]
//public static extern int RtlAdjustPrivilege(int v1, bool v2, int v3, out bool v4);
[DllImport("kernel32.dll")]
static extern bool VirtualProtectEx(IntPtr hProcess, int lpAddress,
uint dwSize, uint flNewProtect, ref uint lpflOldProtect);
public enum Protection
{
PAGE_NOACCESS = 0x01,
PAGE_READONLY = 0x02,
PAGE_READWRITE = 0x04,
PAGE_WRITECOPY = 0x08,
PAGE_EXECUTE = 0x10,
PAGE_EXECUTE_READ = 0x20,
PAGE_EXECUTE_READWRITE = 0x40,
PAGE_EXECUTE_WRITECOPY = 0x80,
PAGE_GUARD = 0x100,
PAGE_NOCACHE = 0x200,
PAGE_WRITECOMBINE = 0x400
}
//[StructLayout(LayoutKind.Sequential)]
//public struct UNICODE_STRING : IDisposable
//{
// public ushort Length;
// public ushort MaximumLength;
// private IntPtr buffer;
// public UNICODE_STRING(string s)
// {
// Length = (ushort)(s.Length * 2);
// MaximumLength = (ushort)(Length + 2);
// buffer = Marshal.StringToHGlobalUni(s);
// }
// public void Dispose()
// {
// Marshal.FreeHGlobal(buffer);
// buffer = IntPtr.Zero;
// }
// public override string ToString()
// {
// return Marshal.PtrToStringUni(buffer);
// }
//}
//[StructLayout(LayoutKind.Sequential)]
//struct PEB_LDR_DATA
//{
// public int Length;
// public uint Initialized;
// public IntPtr SsHandle;
// public LIST_ENTRY InLoadOrderModuleList;
// public LIST_ENTRY InMemoryOrderModuleList;
// public LIST_ENTRY InInitializationOrderModuleList;
//}
[StructLayout(LayoutKind.Sequential)]
unsafe struct LIST_ENTRY
{
public LIST_ENTRY* Flink;
public LIST_ENTRY* Blink;
}
//[StructLayout(LayoutKind.Sequential)]
//unsafe struct LDR_MODULE
//{
// public LIST_ENTRY InLoadOrderModuleList; //+0x00
// public LIST_ENTRY InMemoryOrderModuleList; //+0x08
// public LIST_ENTRY InInitializationOrderModuleList; //+0x10
// public void* BaseAddress; //+0x18
// public void* EntryPoint; //+0x1c
// public ULONG SizeOfImage;
// public UNICODE_STRING FullDllName;
// public UNICODE_STRING BaseDllName;
// public ULONG Flags;
// public SHORT LoadCount;
// public SHORT TlsIndex;
// public IntPtr SectionHandle;
// public uint CheckSum;
// public uint TimeDateStamp;
//}
//[StructLayout(LayoutKind.Sequential)]
//private struct ProcessBasicInformation
//{
// public int ExitStatus;
// public int PebBaseAddress;
// public int AffinityMask;
// public int BasePriority;
// public uint UniqueProcessId;
// public uint InheritedFromUniqueProcessId;
//}
//[DllImport("ntdll.dll")]
//private static extern int NtQueryInformationProcess(
// IntPtr hProcess,
// int processInformationClass /* 0 */,
// ref ProcessBasicInformation processBasicInformation,
// uint processInformationLength,
// out uint returnLength
//);
//public static int VarPtr(object e)
//{
// System.Runtime.InteropServices.GCHandle gh = System.Runtime.InteropServices.GCHandle.Alloc(e, System.Runtime.InteropServices.GCHandleType.Pinned);
// int gc = gh.AddrOfPinnedObject().ToInt32();
// gh.Free();
// return gc;
//}
public Process pname;
const UInt32 INFINITE = 0xFFFFFFFF;
const Int32 PAGE_EXECUTE_READWRITE = 0x40;
const Int32 MEM_COMMIT = 0x1000;
const Int32 MEM_RESERVE = 0x2000;
const Int32 MEM_RELEASE = 0x8000;
Int32 AllocBaseAddress;
public IntPtr hwnd;
string dllname;
public Int32 Pid;
Boolean ok;
Int32 loadaddr;
IntPtr ThreadHwnd;
public int DllBaseAddress;
public string Version;
Module[] modules;
public Module[] Modules
{
get
{
if (modules == null)
modules = GetModules();
return modules;
}
set
{
modules = value;
}
}
public bool WriteMemory(int baseAddress, byte[] lpbuffer, int Size, out int RealSize)
{
return WriteProcessMemory(hwnd, baseAddress, lpbuffer, Size, out RealSize);
}
public bool WriteMemory(int baseAddress, byte[] lpbuffer, int Size)
{
int RealSize;
bool result = WriteProcessMemory(hwnd, baseAddress, lpbuffer, Size, out RealSize);
if (result == false)
{
throw new ProcessCException("内存写错误");
}
return result;
}
public bool WriteMemory(int baseAddress, int lpbuffer, int Size)
{
int RealSize;
bool result = WriteProcessMemory(hwnd, baseAddress, lpbuffer, Size, out RealSize);
if (result == false)
{
throw new ProcessCException("内存写错误");
}
return result;
}
/// <summary>
/// 包含去除内存保护
/// </summary>
/// <param name="baseAddress"></param>
/// <param name="lpbuffer"></param>
/// <param name="Size"></param>
/// <returns></returns>
public bool WriteMemoryVP(int baseAddress, byte[] lpbuffer)
{
int RealSize;
uint Size = (uint)lpbuffer.Length;
uint oldProtect = 0;
VirtualProtectEx(this.hwnd, baseAddress, Size, (uint)Protection.PAGE_READWRITE, ref oldProtect);
bool result = WriteProcessMemory(hwnd, baseAddress, lpbuffer, (int)Size, out RealSize);
VirtualProtectEx(hwnd, baseAddress, Size, oldProtect, ref oldProtect);
if (result == false)
{
throw new ProcessCException("内存写错误");
}
return result;
}
public void WriteBytes(int BaseAddress, byte[] Buffer)
{
int oi;
WriteBytes(BaseAddress, Buffer, Buffer.Length,out oi);
}
public void WriteBytes(int BaseAddress, byte[] Buffer, int Size, out int BytesWriten)
{
if (hwnd == IntPtr.Zero)
BytesWriten = 0;
else
WriteProcessMemory(hwnd, BaseAddress, Buffer, Size, out BytesWriten);
}
/// <summary>
/// 写内存地址加上指定Dll基址
/// </summary>
/// <param name="BaseAddress"></param>
/// <param name="Buffer"></param>
/// <param name="Size"></param>
public void patch(int BaseAddress,params byte[] Buffer)
{
int RealSize;
bool result = WriteProcessMemory(hwnd, BaseAddress + DllBaseAddress, Buffer, Buffer.Length, out RealSize);
if (result == false)
{
throw new ProcessCException("内存写错误");
}
//return result;
}
public bool VirtualProtectEx(int Address, uint Size, Protection Prot, ref uint oldProtect)
{
return VirtualProtectEx(this.hwnd, Address, Size, (uint)Prot, ref oldProtect);
}
public bool ReadMemory(IntPtr baseAddress, void* lpbuffer, int Size, out int RealSize)
{
bool result = ReadProcessMemory(hwnd, baseAddress, lpbuffer, Size, out RealSize);
return result;
}
public bool ReadMemory(IntPtr baseAddress, void* lpbuffer, int Size)
{
int RealSize;
return ReadProcessMemory(hwnd, baseAddress, lpbuffer, Size, out RealSize);
}
public bool ReadMemory(IntPtr baseAddress, byte[] buffer,int Size)
{
int RealSize;
return ReadProcessMemory(hwnd, baseAddress, buffer, Size, out RealSize);
}
public int VirtualAllocEx(int lpaddress, int size)
{
return VirtualAllocEx(this.hwnd, lpaddress, size, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
}
public bool VirtualFreeEx(int pladdress)
{
return VirtualFreeEx(hwnd, new IntPtr(pladdress), 0, FreeType.Release);
}
public bool VirtualFreeEx(int pladdress, int Size)
{
return VirtualFreeEx(hwnd, new IntPtr(pladdress), Size, FreeType.Decommit);
}
public Module[] GetModules()
{
return Module.GetModules(this.hwnd);
}
/// <summary>
/// 更新模块信息
/// </summary>
public void reflesh()
{
this.modules = this.GetModules();
}
public bool inject(string _dllname, bool hidedll)
{
dllname = _dllname;
int umstrcnt = System.Text.Encoding.Default.GetByteCount(dllname);
if (Pid < 0)
{
throw new NullReferenceException("pid错误");
}
if (string.IsNullOrEmpty(dllname))
{
throw new ProcessCException("模块名为空");
}
AllocBaseAddress = VirtualAllocEx(hwnd, 0, umstrcnt, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
if (AllocBaseAddress == 0)
{
throw new ProcessCException("virtualallocex fail");
}
//ok=WriteProcessMemory(hwnd, AllocBaseAddress, dllname, dllname.Length + 2,0);
IntPtr AddrWM = Marshal.StringToHGlobalAnsi(dllname);
ok = WriteMemory(AllocBaseAddress, (int)AddrWM, umstrcnt);
Marshal.FreeHGlobal(AddrWM);
if (!ok)
{
throw new ProcessCException("writeprocessmemory fail");
}
loadaddr = GetProcAddress(GetModuleHandleA("kernel32.dll"), "LoadLibraryA");
if (loadaddr == 0)
{ //取得LoadLibraryA的地址失败时返回
throw new ProcessCException("get loadlibraryA fail");
}
ThreadHwnd = CreateRemoteThread(hwnd, 0, 0, loadaddr, AllocBaseAddress, 0, 0);
if (ThreadHwnd == IntPtr.Zero)
{
throw new ProcessCException("createremotethread fail");
}
//MessageBox.Show("ok ,you can check now!!!");
WaitForSingleObject(ThreadHwnd, INFINITE);
if (hidedll == true)
{
}
return true;
}
private bool disposed = false;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
// 释放托管资源
this.pname.Dispose();
}
// 释放非托管资源,如果disposing为false,
// 只有非托管资源被释放
hwnd = IntPtr.Zero;
AllocBaseAddress = 0;
Pid = 0;loadaddr=0;ThreadHwnd = IntPtr.Zero;DllBaseAddress = 0;
// 注意这里不是线程安全的
}
disposed = true;
}
}
[Serializable]
public class ProcessCException : Exception
{
private readonly int errorCode;
/// <summary>
/// Initializes a new instance of the <see cref="ProcessCException"/> class.
/// </summary>
public ProcessCException()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ProcessCException"/> class.
/// </summary>
/// <param name="errorCode">The error code.</param>
public ProcessCException(int errorCode)
{
this.errorCode = errorCode;
}
/// <summary>
/// Initializes a new instance of the <see cref="ProcessCException"/> class.
/// </summary>
/// <param name="message">The message.</param>
public ProcessCException(string message)
: base(message)
{
errorCode = Marshal.GetLastWin32Error();
}
/// <summary>
/// Initializes a new instance of the <see cref="ProcessCException"/> class.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="errorCode">The error code.</param>
public ProcessCException(string message, int errorCode)
: base(message)
{
this.errorCode = errorCode;
}
/// <summary>
/// Initializes a new instance of the <see cref="ProcessCException"/> class.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="innerException">The inner exception.</param>
public ProcessCException(string message, Exception innerException)
: base(message, innerException)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ProcessCException"/> class.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info"/> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult"/> is zero (0). </exception>
public ProcessCException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
/// <summary>
/// Gets the error code.
/// </summary>
public int ErrorCode
{
get { return errorCode; }
}
/// <summary>
/// Gets a message that describes the current exception.
/// </summary>
/// <returns>The error message that explains the reason for the exception, or an empty string("").</returns>
public override string Message
{
get
{
return base.Message + " Error Code: " + errorCode;
}
}
}//end of public class ProcessCException : Exception
}