forked from kg/shootblues
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RPCChannel.cs
242 lines (203 loc) · 8.51 KB
/
RPCChannel.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
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Squared.Task;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
namespace ShootBlues {
public enum RPCMessageType : uint {
Run = 0,
AddModule = 1,
RemoveModule = 2,
ReloadModules = 3,
CallFunction = 4
}
public struct RPCMessage {
public RPCMessageType Type;
public string ModuleName;
public string FunctionName;
public string Text;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct TransportRPCMessage {
public RPCMessageType Type;
public UInt32 MessageId;
public UInt32 ModuleName;
public UInt32 FunctionName;
public UInt32 Text;
}
public class RPCResponseChannel : NativeWindow, IDisposable {
protected int WM_RPC_MESSAGE;
private const int WS_EX_NOACTIVATE = 0x08000000;
protected Process _Process;
protected Dictionary<UInt32, Future<byte[]>> _AwaitingResponses = new Dictionary<uint, Future<byte[]>>();
protected BlockingQueue<byte[]> _Messages = new BlockingQueue<byte[]>();
protected Random _Random = new Random();
public UInt32 RemoteThreadId = 0;
public RPCResponseChannel (Process process)
: base() {
_Process = process;
WM_RPC_MESSAGE = Win32.RegisterWindowMessage("ShootBlues.RPCMessage");
var cp = new CreateParams {
Caption = "ShootBlues.RPCChannel",
X = 0,
Y = 0,
Width = 0,
Height = 0,
Style = 0,
ExStyle = WS_EX_NOACTIVATE,
Parent = new IntPtr(-3)
};
CreateHandle(cp);
try {
if (!Win32.ChangeWindowMessageFilterEx(
this.Handle, WM_RPC_MESSAGE, MessageFilterFlag.AllowMessage, IntPtr.Zero
)) {
var error = Win32.GetLastError();
throw new Exception(String.Format("Error changing window message filter: {0:x8}", error));
}
} catch (EntryPointNotFoundException) {
try {
if (!Win32.ChangeWindowMessageFilter(
WM_RPC_MESSAGE, MessageFilterFlag.AllowMessage
)) {
var error = Win32.GetLastError();
throw new Exception(String.Format("Error changing window message filter: {0:x8}", error));
}
} catch (EntryPointNotFoundException) {
}
}
}
protected unsafe byte[] ReadRemoteData (RemoteMemoryRegion region, out UInt32 messageId) {
using (var handle = region.OpenHandle(ProcessAccessFlags.VMRead)) {
messageId = BitConverter.ToUInt32(
region.ReadBytes(handle, 0, 4), 0
);
return region.ReadBytes(handle, 4, region.Size - 4);
}
}
protected override void WndProc (ref Message m) {
if (m.Msg == WM_RPC_MESSAGE) {
byte[] messageData = null;
UInt32 messageID = 0;
if ((m.WParam != IntPtr.Zero) && (m.LParam != IntPtr.Zero))
using (var region = RemoteMemoryRegion.Existing(_Process, m.WParam, (uint)m.LParam.ToInt64()))
messageData = ReadRemoteData(region, out messageID);
Future<byte[]> fResult;
Monitor.Enter(_AwaitingResponses);
if (_AwaitingResponses.TryGetValue(messageID, out fResult)) {
_AwaitingResponses.Remove(messageID);
Monitor.Exit(_AwaitingResponses);
fResult.SetResult(messageData, null);
} else {
Debug.Assert(messageID == 0);
Monitor.Exit(_AwaitingResponses);
_Messages.Enqueue(messageData);
}
} else {
base.WndProc(ref m);
}
}
public Future<byte[]> Receive () {
return _Messages.Dequeue();
}
public UInt32 GetMessageID () {
var buf = new byte[4];
_Random.NextBytes(buf);
return BitConverter.ToUInt32(buf, 0);
}
public Future<byte[]> WaitForMessage (UInt32 messageID) {
Future<byte[]> result;
lock (_AwaitingResponses) {
if (!_AwaitingResponses.TryGetValue(messageID, out result))
_AwaitingResponses[messageID] = result = new Future<byte[]>();
}
return result;
}
public UInt32 ChannelID {
get {
return (UInt32)Handle.ToInt64();
}
}
public void Dispose () {
foreach (var f in _AwaitingResponses.Values)
f.Dispose();
_AwaitingResponses.Clear();
DestroyHandle();
}
}
public class RPCChannel : RPCResponseChannel {
public RPCChannel (Process process)
: base(process) {
}
private UInt32 TransportStringSize (string text) {
if (text == null)
return 0;
return (UInt32)Encoding.ASCII.GetByteCount(text) + 1;
}
private UInt32 WriteTransportString (string text, byte[] buffer, UInt32 offset, IntPtr baseAddress) {
if (text == null)
return 0;
int chars = Encoding.ASCII.GetBytes(text, 0, text.Length, buffer, (int)offset);
buffer[offset + chars] = 0;
return (UInt32)(baseAddress.ToInt64() + offset);
}
public void Send (RPCMessage message) {
Send(message, false);
}
public unsafe Future<byte[]> Send (RPCMessage message, bool wantResponse) {
if (_Process == null)
throw new Exception("No remote process");
if (RemoteThreadId == 0)
throw new Exception("No remote thread");
UInt32 messageSize = (UInt32)Marshal.SizeOf(typeof(TransportRPCMessage));
UInt32 moduleNameSize = TransportStringSize(message.ModuleName);
UInt32 functionNameSize = TransportStringSize(message.FunctionName);
UInt32 textSize = TransportStringSize(message.Text);
Future<byte[]> result = null;
UInt32 messageID = 0;
if (wantResponse) {
messageID = GetMessageID();
result = new Future<byte[]>();
_AwaitingResponses[messageID] = result;
}
using (var handle = Win32.OpenProcessHandle(ProcessAccessFlags.VMWrite | ProcessAccessFlags.VMOperation, false, _Process.Id)) {
RemoteMemoryRegion region;
var regionSize = messageSize + moduleNameSize + textSize + functionNameSize;
var buffer = new byte[regionSize];
// leaked on purpose
region = RemoteMemoryRegion.Allocate(
_Process, handle, regionSize
);
object transportMessage = new TransportRPCMessage {
Type = message.Type,
MessageId = messageID,
Text = WriteTransportString(message.Text, buffer, messageSize, region.Address),
FunctionName = WriteTransportString(message.FunctionName, buffer, messageSize + textSize, region.Address),
ModuleName = WriteTransportString(message.ModuleName, buffer, messageSize + textSize + functionNameSize, region.Address)
};
fixed (byte* pBuffer = buffer) {
Marshal.StructureToPtr(transportMessage, new IntPtr(pBuffer), false);
try {
region.Write(handle, 0, regionSize, pBuffer);
} catch {
try {
region.Dispose();
} catch {
}
throw;
}
}
if (!Win32.PostThreadMessage(RemoteThreadId, WM_RPC_MESSAGE, region.Address, region.Size)) {
var error = Win32.GetLastError();
region.Dispose();
throw new Exception(String.Format("Error posting thread message: {0:x8}", error));
}
}
return result;
}
}
}