forked from mkaring/ConfuserEx
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathProgram.cs
More file actions
345 lines (297 loc) · 11.2 KB
/
Copy pathProgram.cs
File metadata and controls
345 lines (297 loc) · 11.2 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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Xml;
using Confuser.Core;
using Confuser.Core.Diagnostics;
using Confuser.Core.Project;
using Microsoft.Extensions.Logging;
using NDesk.Options;
using Serilog;
using Serilog.Events;
namespace Confuser.CLI {
internal class Program {
static int Main(string[] args) {
ConsoleColor original = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.White;
string originalTitle = null;
if (OperatingSystem.IsWindows()) {
originalTitle = Console.Title;
Console.Title = "ConfuserEx";
}
try {
bool noPause = false;
bool debug = false;
bool quiet = false;
bool dumpRequested = false;
string dumpPath = null;
string inputMap = null;
int verbosity = 0;
string outDir = null;
string snKeyPath = null;
string snKeyPass = null;
List<string> probePaths = new List<string>();
List<string> plugins = new List<string>();
var p = new OptionSet {
{
"n|nopause", "no pause after finishing protection.",
value => { noPause = (value != null); }
}, {
"o|out=", "specifies output directory.",
value => { outDir = value; }
}, {
"probe=", "specifies probe directory.",
value => { probePaths.Add(value); }
}, {
"plugin=", "specifies plugin path.",
value => { plugins.Add(value); }
}, {
"debug", "specifies debug symbol generation.",
value => { debug = (value != null); }
}, {
"snkey=", "specifies strong name key file path.",
value => { snKeyPath = value; }
}, {
"snkeypass=", "specifies strong name key password.",
value => { snKeyPass = value; }
}, {
"v|verbose", "increase verbosity (repeat for more: -v, -vv, -vvv).",
value => { verbosity++; }
}, {
"q|quiet", "only show warnings and errors.",
value => { quiet = (value != null); }
}, {
"dump:", "write a diagnostic report (optionally to the given file).",
value => { dumpRequested = true; if (!string.IsNullOrEmpty(value)) dumpPath = value; }
}, {
"map=", "reuse names from a previous symbol map for consistent re-obfuscation.",
value => { inputMap = value; }
}
};
List<string> files;
try {
files = p.Parse(args);
if (files.Count == 0)
throw new ArgumentException("No input files specified.");
}
catch (Exception ex) {
Console.Write("ConfuserEx.CLI: ");
Console.WriteLine(ex.Message);
PrintUsage();
return -1;
}
var parameters = new ConfuserParameters();
if (files.Count == 1 && Path.GetExtension(files[0]) == ".crproj") {
var proj = new ConfuserProject();
try {
var xmlDoc = new XmlDocument();
xmlDoc.Load(files[0]);
proj.Load(xmlDoc, Path.GetDirectoryName(Path.GetFullPath(files[0])));
proj.OutputDirectory = Path.GetFullPath(Path.Combine(proj.BaseDirectory, proj.OutputDirectory));
}
catch (Exception ex) {
WriteLineWithColor(ConsoleColor.Red, "Failed to load project:");
WriteLineWithColor(ConsoleColor.Red, ex.ToString());
return -1;
}
parameters.Project = proj;
}
else {
if (string.IsNullOrEmpty(outDir)) {
Console.WriteLine("ConfuserEx.CLI: No output directory specified.");
PrintUsage();
return -1;
}
var proj = new ConfuserProject();
var templateModules = new List<ProjectModule>();
if (Path.GetExtension(files[files.Count - 1]) == ".crproj") {
LoadTemplateProject(files[files.Count - 1], proj, templateModules);
files.RemoveAt(files.Count - 1);
}
// Generate a ConfuserProject for input modules
// Assuming first file = main module
proj.BaseDirectory = Path.GetDirectoryName(files[0]);
if (string.IsNullOrWhiteSpace(proj.BaseDirectory)) {
WriteLineWithColor(ConsoleColor.Red, "Failed to identify base directory for main assembly.");
PrintUsage();
return -1;
}
foreach (var input in files) {
string modulePath = input;
if (modulePath.StartsWith(proj.BaseDirectory, StringComparison.OrdinalIgnoreCase)) {
modulePath = modulePath.Substring(proj.BaseDirectory.Length + 1);
}
if (TryMatchTemplateProject(templateModules, proj.BaseDirectory, modulePath, out var matchedModule)) {
if (snKeyPath != null) matchedModule.SNKeyPath = snKeyPath;
if (snKeyPass != null) matchedModule.SNKeyPassword = snKeyPass;
proj.Add(matchedModule);
}
else
proj.Add(new ProjectModule { Path = modulePath, SNKeyPath = snKeyPath, SNKeyPassword = snKeyPass });
}
proj.OutputDirectory = outDir;
foreach (var path in probePaths)
proj.ProbePaths.Add(path);
foreach (var path in plugins)
proj.PluginPaths.Add(path);
proj.Debug = debug;
parameters.Project = proj;
}
if (inputMap != null && parameters.Project != null)
parameters.Project.InputSymbolMap = inputMap;
int retVal = RunProject(parameters, quiet, verbosity, dumpRequested, dumpPath);
if (NeedPause() && !noPause) {
Console.WriteLine("Press any key to continue...");
Console.ReadKey(true);
}
return retVal;
}
finally {
Console.ForegroundColor = original;
if (OperatingSystem.IsWindows() && originalTitle != null)
Console.Title = originalTitle;
}
}
static bool TryMatchTemplateProject(List<ProjectModule> templateModules, string baseDirectory, string modulePath, out ProjectModule matchedModule) {
var matchedToTemplate = false;
matchedModule = null;
foreach (var templateModule in templateModules) {
var templatePath = templateModule.Path;
if (templatePath.StartsWith(@".\", StringComparison.Ordinal))
templatePath = templatePath.Substring(2);
if (modulePath.Equals(templatePath, StringComparison.OrdinalIgnoreCase))
matchedToTemplate = true;
if (modulePath.Equals(Path.Combine(baseDirectory, templatePath), StringComparison.OrdinalIgnoreCase))
matchedToTemplate = true;
if (matchedToTemplate)
matchedModule = templateModule;
}
return matchedToTemplate;
}
static void LoadTemplateProject(string templatePath, ConfuserProject proj, List<ProjectModule> templateModules) {
var templateProj = new ConfuserProject();
var xmlDoc = new XmlDocument();
xmlDoc.Load(templatePath);
templateProj.Load(xmlDoc);
foreach (var rule in templateProj.Rules)
proj.Rules.Add(rule);
proj.Packer = templateProj.Packer;
foreach (string pluginPath in templateProj.PluginPaths)
proj.PluginPaths.Add(pluginPath);
foreach (string probePath in templateProj.ProbePaths)
proj.ProbePaths.Add(probePath);
foreach (var templateModule in templateProj)
if (templateModule.IsExternal)
proj.Add(templateModule);
else
templateModules.Add(templateModule);
}
static int RunProject(ConfuserParameters parameters, bool quiet, int verbosity, bool dumpRequested, string dumpPath) {
var levelSwitch = quiet
? LogEventLevel.Warning
: verbosity >= 3 ? LogEventLevel.Verbose
: verbosity >= 2 ? LogEventLevel.Verbose
: verbosity >= 1 ? LogEventLevel.Debug
: LogEventLevel.Information;
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Is(levelSwitch)
.WriteTo.Console(
outputTemplate: "[{Level:u4}] {Message:lj}{NewLine}{Exception}")
.CreateLogger();
using var loggerFactory = LoggerFactory.Create(builder =>
builder.AddSerilog(dispose: false));
var melLogger = loggerFactory.CreateLogger("ConfuserEx");
var progressReporter = new ConsoleProgressReporter();
// When a diagnostic report is requested, wrap both the logger and the progress reporter
// with a collector so the report captures the full transcript, timing and outcome even
// when the run fails.
DiagnosticCollector collector = null;
if (dumpRequested) {
collector = new DiagnosticCollector(melLogger, progressReporter) { Project = parameters.Project };
parameters.Logger = collector;
parameters.ProgressReporter = collector;
}
else {
parameters.Logger = melLogger;
parameters.ProgressReporter = progressReporter;
}
if (OperatingSystem.IsWindows())
Console.Title = "ConfuserEx - Running...";
ConfuserEngine.Run(parameters).GetAwaiter().GetResult();
Log.CloseAndFlush();
if (collector != null)
WriteDiagnosticReport(collector, dumpPath);
return progressReporter.ReturnValue;
}
static void WriteDiagnosticReport(DiagnosticCollector collector, string dumpPath) {
string path = string.IsNullOrEmpty(dumpPath) ? "confuser-diagnostic-report.md" : dumpPath;
try {
File.WriteAllText(path, collector.GenerateReport());
WriteLineWithColor(ConsoleColor.Cyan, "Diagnostic report written to: " + Path.GetFullPath(path));
}
catch (Exception ex) {
WriteLineWithColor(ConsoleColor.Red, "Failed to write diagnostic report: " + ex.Message);
}
}
static bool NeedPause() {
return Debugger.IsAttached || string.IsNullOrEmpty(Environment.GetEnvironmentVariable("PROMPT"));
}
static void PrintUsage() {
WriteLine("Usage:");
WriteLine("Confuser.CLI -n|noPause <project configuration>");
WriteLine("Confuser.CLI -n|noPause -o|out=<output directory> <modules>");
WriteLine(" -n|noPause : no pause after finishing protection.");
WriteLine(" -o|out : specifies output directory.");
WriteLine(" -probe : specifies probe directory.");
WriteLine(" -plugin : specifies plugin path.");
WriteLine(" -debug : specifies debug symbol generation.");
WriteLine(" -snkey : specifies strong name key file path.");
WriteLine(" -snkeypass : specifies strong name key password.");
WriteLine(" -v|verbose : increase verbosity (-v debug, -vv trace).");
WriteLine(" -q|quiet : only show warnings and errors.");
WriteLine(" -dump : write a diagnostic report (-dump=<file> for a custom path).");
WriteLine(" -map : reuse names from a previous symbol map for consistent re-obfuscation.");
}
static void WriteLineWithColor(ConsoleColor color, string txt) {
ConsoleColor original = Console.ForegroundColor;
Console.ForegroundColor = color;
Console.WriteLine(txt);
Console.ForegroundColor = original;
}
static void WriteLine(string txt) {
Console.WriteLine(txt);
}
static void WriteLine() {
Console.WriteLine();
}
class ConsoleProgressReporter : IProgressReporter {
readonly DateTime begin;
public ConsoleProgressReporter() {
begin = DateTime.Now;
}
public int ReturnValue { get; private set; }
public void Progress(int progress, int overall) { }
public void EndProgress() { }
public void Finish(bool successful) {
DateTime now = DateTime.Now;
string timeString = string.Format(
"at {0}, {1}:{2:d2} elapsed.",
now.ToShortTimeString(),
(int)now.Subtract(begin).TotalMinutes,
now.Subtract(begin).Seconds);
if (successful) {
Console.Title = "ConfuserEx - Success";
WriteLineWithColor(ConsoleColor.Green, "Finished " + timeString);
ReturnValue = 0;
}
else {
Console.Title = "ConfuserEx - Fail";
WriteLineWithColor(ConsoleColor.Red, "Failed " + timeString);
ReturnValue = 1;
}
}
}
}
}