-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathProgram.cs
303 lines (264 loc) · 11.7 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
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
using System;
using System.Linq;
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Reflection;
using CoreHook.BinaryInjection.RemoteInjection;
using CoreHook.BinaryInjection.ProcessUtils;
using CoreHook.BinaryInjection.RemoteInjection.Configuration;
using CoreHook.FileMonitor.Service;
using CoreHook.IPC.Platform;
using CoreHook.Memory.Processes;
namespace CoreHook.Uwp.FileMonitor
{
class Program
{
/// <summary>
/// The pipe name the FileMonitor RPC service communicates over between processes.
/// </summary>
private const string CoreHookPipeName = "UwpCoreHook";
/// <summary>
/// The directory containing the CoreHook modules to be loaded in the target process.
/// </summary>
private const string HookLibraryDirName = "Hook";
/// <summary>
/// The library to be injected into the target process and executed
/// using it's 'Run' Method.
/// </summary>
private const string HookLibraryName = "CoreHook.Uwp.FileMonitor.Hook.dll";
/// <summary>
/// The name of the pipe used for notifying the host process
/// if the hooking plugin has been loaded successfully in
/// the target process or if loading failed.
/// </summary>
private const string InjectionPipeName = "UwpCoreHookInjection";
/// <summary>
/// Enable verbose logging to the console for the CoreCLR native host module.
/// </summary>
private const bool HostVerboseLog = false;
/// <summary>
/// Class that handles creating a named pipe server for communicating with the target process.
/// </summary>
private static readonly IPipePlatform PipePlatform = new Pipe.PipePlatform();
/// <summary>
/// Security Identifier representing ALL_APPLICATION_PACKAGES permission.
/// </summary>
private static readonly SecurityIdentifier AllAppPackagesSid = new SecurityIdentifier("S-1-15-2-1");
private static void Main(string[] args)
{
int targetProcessId = 0;
string targetApp = string.Empty;
// Get the process to hook by Application User Model Id for launching or process id for attaching.
while ((args.Length != 1) || !int.TryParse(args[0], out targetProcessId))
{
if (targetProcessId > 0)
{
break;
}
if (args.Length != 1)
{
Console.WriteLine();
Console.WriteLine("Usage: FileMonitor %PID%");
Console.WriteLine(" or: FileMonitor AppUserModelId");
Console.WriteLine();
Console.Write("Please enter a process Id or the App Id to launch: ");
args = new string[]
{
Console.ReadLine()
};
if (string.IsNullOrWhiteSpace(args[0]))
{
return;
}
}
else
{
targetApp = args[0];
break;
}
}
var currentDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string injectionLibrary = Path.Combine(currentDir, HookLibraryDirName, HookLibraryName);
if (!File.Exists(injectionLibrary))
{
Console.WriteLine("Cannot find FileMonitor injection dll");
return;
}
// Grant read+execute permissions on the binary files
// we are injecting into the UWP application.
GrantAllAppPackagesAccessToDir(currentDir);
GrantAllAppPackagesAccessToDir(Path.GetDirectoryName(injectionLibrary));
// Start the target application and begin plugin loading.
if (!string.IsNullOrEmpty(targetApp))
{
targetProcessId = LaunchAppxPackage(targetApp);
}
// Inject the FileMonitor.Hook dll into the process.
InjectDllIntoTarget(targetProcessId, injectionLibrary);
// Start the RPC server for handling requests from the hooked app.
StartListener();
}
/// <summary>
/// Inject and load the CoreHook hooking module <paramref name="injectionLibrary"/>
/// in the existing created process referenced by <paramref name="processId"/>.
/// </summary>
/// <param name="processId">The target process ID to inject and load plugin into.</param>
/// <param name="injectionLibrary">The path of the plugin that is loaded into the target process.</param>
/// <param name="injectionPipeName">The pipe name which receives messages during the plugin initialization stage.</param>
private static void InjectDllIntoTarget(
int processId,
string injectionLibrary,
string injectionPipeName = InjectionPipeName)
{
if (Examples.Common.ModulesPathHelper.GetCoreLoadPaths(
ProcessHelper.GetProcessById(processId).Is64Bit(),
out NativeModulesConfiguration nativeConfig) &&
Examples.Common.ModulesPathHelper.GetCoreLoadModulePath(
out string coreLoadLibrary))
{
// Make sure the native dll modules can be accessed by the UWP application
GrantAllAppPackagesAccessToFile(nativeConfig.HostLibrary);
GrantAllAppPackagesAccessToFile(nativeConfig.DetourLibrary);
RemoteInjector.Inject(
processId,
new RemoteInjectorConfiguration(nativeConfig)
{
InjectionPipeName = injectionPipeName,
ClrBootstrapLibrary = coreLoadLibrary,
PayloadLibrary = injectionLibrary,
VerboseLog = HostVerboseLog
},
PipePlatform,
CoreHookPipeName);
}
}
/// <summary>
/// Create an RPC server that is called by the RPC client started in a target process.
/// </summary>
private static void StartListener()
{
var session = new FileMonitorSessionFeature();
Examples.Common.RpcService.CreateRpcService(
CoreHookPipeName,
PipePlatform,
session,
typeof(FileMonitorService),
async (context, next) =>
{
Console.WriteLine("> {0}", context.Request);
await next();
Console.WriteLine("< {0}", context.Response);
});
Console.WriteLine("Press Enter to quit.");
Console.ReadLine();
session.StopServer();
}
/// <summary>
/// Grant ALL_APPLICATION_PACKAGES permissions to binary
/// and configuration files in <paramref name="directoryPath"/>.
/// </summary>
/// <param name="directoryPath">Directory containing application files.</param>
private static void GrantAllAppPackagesAccessToDir(string directoryPath)
{
if (!Directory.Exists(directoryPath))
{
return;
}
GrantAllAppPackagesAccessToFolder(directoryPath);
foreach (var filePath in Directory.GetFiles(directoryPath, "*.*", SearchOption.AllDirectories)
.Where(name => name.EndsWith(".json") || name.EndsWith(".dll") || name.EndsWith(".pdb")))
{
GrantFolderRecursive(filePath, directoryPath);
GrantAllAppPackagesAccessToFile(filePath);
}
}
/// <summary>
/// Grant ALL_APPLICATION_PACKAGES permissions to the Symbol Cache directory <paramref name="directoryPath"/>.
/// </summary>
/// <param name="directoryPath">A directory containing Windows symbols (.PDB files).</param>
private static void GrantAllAppPackagesAccessToSymCacheDir(string directoryPath)
{
if (!Directory.Exists(directoryPath))
{
return;
}
GrantAllAppPackagesAccessToFolder(directoryPath);
foreach (var filePath in Directory.GetFiles(directoryPath, "*.*", SearchOption.AllDirectories)
.Where(name => name.EndsWith(".pdb")))
{
GrantFolderRecursive(filePath, directoryPath);
GrantAllAppPackagesAccessToFile(filePath);
}
}
/// <summary>
/// Grant ALL_APPLICATION_PACKAGES permissions to a directory and its subdirectories.
/// </summary>
/// <param name="path">The path of the directory to grant permissions to.</param>
/// <param name="rootDirectory">The root marking when to stop granting permissions if reached.</param>
private static void GrantFolderRecursive(string path, string rootDirectory)
{
while ((path = Path.GetDirectoryName(path)) != rootDirectory)
{
GrantAllAppPackagesAccessToFolder(path);
}
}
/// <summary>
/// Grant ALL_APPLICATION_PACKAGES permissions to a file at <paramref name="fileName"/>.
/// </summary>
/// <param name="fileName">The file to be granted ALL_APPLICATION_PACKAGES permissions.</param>
private static void GrantAllAppPackagesAccessToFile(string fileName)
{
try
{
var fileInfo = new FileInfo(fileName);
FileSecurity acl = fileInfo.GetAccessControl();
var rule = new FileSystemAccessRule(AllAppPackagesSid,
FileSystemRights.ReadAndExecute, AccessControlType.Allow);
acl.SetAccessRule(rule);
fileInfo.SetAccessControl(acl);
}
catch
{
}
}
/// <summary>
/// Grant ALL_APPLICATION_PACKAGES permissions to a directory at <paramref name="folderPath"/>.
/// </summary>
/// <param name="folderPath">The directory to be granted ALL_APPLICATION_PACKAGES permissions.</param>
private static void GrantAllAppPackagesAccessToFolder(string folderPath)
{
try
{
var dirInfo = new DirectoryInfo(folderPath);
DirectorySecurity acl = dirInfo.GetAccessControl(AccessControlSections.Access);
var rule = new FileSystemAccessRule(AllAppPackagesSid,
FileSystemRights.ReadAndExecute, AccessControlType.Allow);
acl.SetAccessRule(rule);
dirInfo.SetAccessControl(acl);
}
catch
{
}
}
/// <summary>
/// Launch a Universal Windows Platform (UWP) application on Windows 10.
/// </summary>
/// <param name="appName">The Application User Model Id (AUMID) to start.</param>
/// <returns>The process ID of the application started or 0 if launching failed.</returns>
private static int LaunchAppxPackage(string appName)
{
var appActiveManager = new ApplicationActivationManager();
try
{
// PackageFamilyName + {Applications.Application.Id}, inside AppxManifest.xml
appActiveManager.ActivateApplication(appName, null, ActivateOptions.None, out var processId);
return (int)processId;
}
catch
{
return 0;
}
}
}
}