-
Notifications
You must be signed in to change notification settings - Fork 398
Expand file tree
/
Copy pathDumper.cs
More file actions
83 lines (64 loc) · 2.34 KB
/
Dumper.cs
File metadata and controls
83 lines (64 loc) · 2.34 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
using System;
using System.Diagnostics.Contracts;
using System.IO;
namespace ReClassNET.Memory
{
public class Dumper
{
private readonly RemoteProcess process;
public Dumper(RemoteProcess process)
{
Contract.Requires(process != null);
Contract.Ensures(this.process != null);
this.process = process;
}
/// <summary>Dumps a section to the given stream.</summary>
/// <param name="address">The begin of the section.</param>
/// <param name="size">The size of the section.</param>
/// <param name="stream">The stream to dump to.</param>
public void DumpSection(IntPtr address, int size, Stream stream)
{
Contract.Requires(size >= 0);
Contract.Requires(stream != null);
var data = process.ReadRemoteMemory(address, size);
stream.Write(data, 0, data.Length);
}
/// <summary>Dumps a module to the given stream. The section headers of the pe header get fixed to make a valid pe file.</summary>
/// <param name="address">The begin of the module.</param>
/// <param name="size">The size of the module.</param>
/// <param name="stream">The stream to dump to.</param>
public void DumpModule(IntPtr address, int size, Stream stream)
{
Contract.Requires(size >= 0);
Contract.Requires(stream != null);
var data = process.ReadRemoteMemory(address, size);
var pe = new SimplePeHeader(data);
// Fix the section headers.
using (var bw = new BinaryWriter(new MemoryStream(data)))
{
for (var i = 0; i < pe.NumberOfSections; ++i)
{
var offset = pe.SectionOffset(i);
bw.Seek(offset + 16, SeekOrigin.Begin);
bw.Write(BitConverter.ToUInt32(data, offset + 8)); // SizeOfRawData = VirtualSize
bw.Write(BitConverter.ToUInt32(data, offset + 12)); // PointerToRawData = VirtualAddress
}
}
stream.Write(data, 0, data.Length);
}
private class SimplePeHeader
{
private readonly byte[] data;
private int e_lfanew => BitConverter.ToInt32(data, 60);
private int FileHeader => e_lfanew + 4;
public int NumberOfSections => BitConverter.ToInt16(data, FileHeader + 2);
private int SizeOfOptionalHeader => BitConverter.ToInt16(data, FileHeader + 16);
private int FirstSectionOffset => e_lfanew + 24 + SizeOfOptionalHeader;
public int SectionOffset(int index) => FirstSectionOffset + index * 40;
public SimplePeHeader(byte[] data)
{
this.data = data;
}
}
}
}