zParik commited on
Commit
d0d28ff
·
verified ·
1 Parent(s): 298ca51

Create Generator.py

Browse files
Files changed (1) hide show
  1. Generator.py +820 -0
Generator.py ADDED
@@ -0,0 +1,820 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Turns PE binaries into 6-channel 3D tensors for a CNN.
3
+
4
+ Each channel encodes a different semantic signal so the model isn't just
5
+ memorizing raw byte patterns:
6
+ 0 - raw byte values (normalized)
7
+ 1 - local entropy (high = encrypted/compressed/packed)
8
+ 2 - executable section mask (where the actual code lives)
9
+ 3 - import density (proximity to import tables, behavioral signal)
10
+ 4 - string density (ASCII-heavy regions = function names, strings, etc.)
11
+ 5 - data presence mask (1 where we have real bytes, 0 where it's padding)
12
+
13
+ Bytes get folded into 3D via a Morton/Z-order curve so spatially nearby
14
+ bytes stay nearby in the volume. This preserves locality better than
15
+ naive reshape.
16
+
17
+ Usage:
18
+ python malware_3d_multichannel.py -i ./samples -o ./tensors_5ch
19
+ """
20
+
21
+ import os
22
+ import argparse
23
+ import numpy as np
24
+ import matplotlib.pyplot as plt
25
+ from pathlib import Path
26
+ from tqdm import tqdm
27
+ import json
28
+ import struct
29
+ import math
30
+ from collections import defaultdict
31
+
32
+
33
+ class PEParserExtended:
34
+ """
35
+ Rips apart PE headers and sections to get the bytes we actually care about,
36
+ plus metadata about what lives where (code vs imports vs data).
37
+
38
+ We skip resource/reloc/debug sections since they're mostly noise for
39
+ malware classification. .text, .rdata, .idata, .data are what matter.
40
+ """
41
+
42
+ RELEVANT_SECTIONS = {
43
+ b'.text', b'.code', b'CODE', b'.TEXT',
44
+ b'.rdata', b'.rodata', b'.idata',
45
+ b'.data', b'.DATA',
46
+ b'.edata',
47
+ }
48
+
49
+ SKIP_SECTIONS = {
50
+ b'.rsrc', b'.reloc', b'.pdata', b'.tls',
51
+ b'.debug', b'.didat', b'.sxdata',
52
+ }
53
+
54
+ CODE_SECTIONS = {b'.text', b'.code', b'CODE', b'.TEXT'}
55
+
56
+ IMAGE_DIRECTORY_ENTRY_EXPORT = 0
57
+ IMAGE_DIRECTORY_ENTRY_IMPORT = 1
58
+ IMAGE_DIRECTORY_ENTRY_IAT = 12
59
+
60
+ def __init__(self, filepath: str):
61
+ self.filepath = filepath
62
+ self.valid = False
63
+ self.headers = b''
64
+ self.sections = {}
65
+ self.section_info = []
66
+ self.data_directories = []
67
+ self.import_ranges = []
68
+ self._parse()
69
+
70
+ def _parse(self):
71
+ try:
72
+ with open(self.filepath, 'rb') as f:
73
+ if not self._validate_pe(f):
74
+ return
75
+
76
+ self._parse_data_directories(f)
77
+ self._find_import_ranges(f)
78
+
79
+ f.seek(0)
80
+ self.headers = f.read(self.pe_header_end)
81
+ self._parse_sections(f)
82
+ self.valid = True
83
+
84
+ except (IOError, OSError, struct.error):
85
+ self.valid = False
86
+
87
+ def _validate_pe(self, f) -> bool:
88
+ f.seek(0, 2)
89
+ self.file_size = f.tell()
90
+ if self.file_size < 64:
91
+ return False
92
+
93
+ f.seek(0)
94
+ if f.read(2) != b'MZ':
95
+ return False
96
+
97
+ f.seek(0x3C)
98
+ pe_offset = struct.unpack('<I', f.read(4))[0]
99
+
100
+ if pe_offset + 4 > self.file_size:
101
+ return False
102
+
103
+ f.seek(pe_offset)
104
+ if f.read(4) != b'PE\x00\x00':
105
+ return False
106
+
107
+ self.pe_offset = pe_offset
108
+
109
+ self.machine = struct.unpack('<H', f.read(2))[0]
110
+ self.num_sections = struct.unpack('<H', f.read(2))[0]
111
+ f.read(12) # skip timestamp, symbol table ptr, symbol count
112
+ self.optional_header_size = struct.unpack('<H', f.read(2))[0]
113
+ self.characteristics = struct.unpack('<H', f.read(2))[0]
114
+
115
+ self.optional_header_offset = pe_offset + 24
116
+ self.section_table_offset = pe_offset + 24 + self.optional_header_size
117
+ self.pe_header_end = self.section_table_offset + (self.num_sections * 40)
118
+
119
+ return True
120
+
121
+ def _parse_data_directories(self, f):
122
+ """Grab the data directory entries so we can find import/export tables."""
123
+ f.seek(self.optional_header_offset)
124
+ magic = struct.unpack('<H', f.read(2))[0]
125
+
126
+ # PE32 vs PE32+ have the data dirs at different offsets
127
+ if magic == 0x10b:
128
+ f.seek(self.optional_header_offset + 92)
129
+ elif magic == 0x20b:
130
+ f.seek(self.optional_header_offset + 108)
131
+ else:
132
+ return
133
+
134
+ num_data_dirs = struct.unpack('<I', f.read(4))[0]
135
+ num_data_dirs = min(num_data_dirs, 16)
136
+
137
+ for i in range(num_data_dirs):
138
+ rva = struct.unpack('<I', f.read(4))[0]
139
+ size = struct.unpack('<I', f.read(4))[0]
140
+ self.data_directories.append((rva, size))
141
+
142
+ def _rva_to_file_offset(self, rva, f):
143
+ """Walk the section table to figure out where an RVA lands on disk."""
144
+ f.seek(self.section_table_offset)
145
+
146
+ for i in range(self.num_sections):
147
+ section_header = f.read(40)
148
+ if len(section_header) < 40:
149
+ break
150
+
151
+ virtual_size = struct.unpack('<I', section_header[8:12])[0]
152
+ virtual_addr = struct.unpack('<I', section_header[12:16])[0]
153
+ raw_size = struct.unpack('<I', section_header[16:20])[0]
154
+ raw_offset = struct.unpack('<I', section_header[20:24])[0]
155
+
156
+ if virtual_addr <= rva < virtual_addr + max(virtual_size, raw_size):
157
+ return raw_offset + (rva - virtual_addr)
158
+
159
+ return None
160
+
161
+ def _find_import_ranges(self, f):
162
+ """Use the actual data directory entries to locate import data on disk."""
163
+ self.import_ranges = []
164
+
165
+ if len(self.data_directories) > self.IMAGE_DIRECTORY_ENTRY_IMPORT:
166
+ rva, size = self.data_directories[self.IMAGE_DIRECTORY_ENTRY_IMPORT]
167
+ if rva > 0 and size > 0:
168
+ offset = self._rva_to_file_offset(rva, f)
169
+ if offset is not None:
170
+ self.import_ranges.append((offset, size))
171
+ self._parse_import_descriptors(f, offset, rva)
172
+
173
+ # IAT is separate from the import directory
174
+ if len(self.data_directories) > self.IMAGE_DIRECTORY_ENTRY_IAT:
175
+ rva, size = self.data_directories[self.IMAGE_DIRECTORY_ENTRY_IAT]
176
+ if rva > 0 and size > 0:
177
+ offset = self._rva_to_file_offset(rva, f)
178
+ if offset is not None:
179
+ self.import_ranges.append((offset, size))
180
+
181
+ def _parse_import_descriptors(self, f, import_dir_offset, import_dir_rva):
182
+ """
183
+ Chase the import descriptors to find DLL name strings and thunk arrays.
184
+ These are the regions that tell us what APIs the binary calls.
185
+ """
186
+ try:
187
+ f.seek(import_dir_offset)
188
+ max_descriptors = 1000 # way beyond any legit PE, just a safety net
189
+
190
+ for _ in range(max_descriptors):
191
+ desc = f.read(20)
192
+ if len(desc) < 20:
193
+ break
194
+
195
+ original_first_thunk = struct.unpack('<I', desc[0:4])[0]
196
+ name_rva = struct.unpack('<I', desc[12:16])[0]
197
+ first_thunk = struct.unpack('<I', desc[16:20])[0]
198
+
199
+ # null terminator = end of import descriptors
200
+ if name_rva == 0 and first_thunk == 0 and original_first_thunk == 0:
201
+ break
202
+
203
+ if name_rva > self.file_size or first_thunk > self.file_size:
204
+ break
205
+
206
+ # grab the DLL name string region
207
+ if name_rva > 0 and len(self.import_ranges) < 500:
208
+ name_offset = self._rva_to_file_offset(name_rva, f)
209
+ if name_offset is not None and name_offset < self.file_size:
210
+ self.import_ranges.append((name_offset, min(256, self.file_size - name_offset)))
211
+
212
+ # grab the thunk array (function name hints / ordinals)
213
+ thunk_rva = original_first_thunk if original_first_thunk else first_thunk
214
+ if thunk_rva > 0 and len(self.import_ranges) < 500:
215
+ thunk_offset = self._rva_to_file_offset(thunk_rva, f)
216
+ if thunk_offset is not None and thunk_offset < self.file_size:
217
+ self.import_ranges.append((thunk_offset, min(512, self.file_size - thunk_offset)))
218
+
219
+ except:
220
+ pass # malware loves corrupt import tables, just bail
221
+
222
+ def _parse_sections(self, f):
223
+ f.seek(self.section_table_offset)
224
+ current_offset = len(self.headers)
225
+
226
+ for i in range(self.num_sections):
227
+ section_header = f.read(40)
228
+ if len(section_header) < 40:
229
+ break
230
+
231
+ name = section_header[0:8].rstrip(b'\x00')
232
+ virtual_size = struct.unpack('<I', section_header[8:12])[0]
233
+ virtual_addr = struct.unpack('<I', section_header[12:16])[0]
234
+ raw_size = struct.unpack('<I', section_header[16:20])[0]
235
+ raw_offset = struct.unpack('<I', section_header[20:24])[0]
236
+ characteristics = struct.unpack('<I', section_header[36:40])[0]
237
+
238
+ is_code = (characteristics & 0x20000000) != 0 # IMAGE_SCN_MEM_EXECUTE
239
+
240
+ info = {
241
+ 'name': name,
242
+ 'name_str': name.decode('utf-8', errors='replace'),
243
+ 'virtual_size': virtual_size,
244
+ 'virtual_addr': virtual_addr,
245
+ 'raw_size': raw_size,
246
+ 'raw_offset': raw_offset,
247
+ 'characteristics': characteristics,
248
+ 'is_code': is_code or name in self.CODE_SECTIONS,
249
+ 'extracted': False,
250
+ 'output_start': None,
251
+ 'output_end': None,
252
+ }
253
+
254
+ is_relevant = name in self.RELEVANT_SECTIONS
255
+ is_skip = name in self.SKIP_SECTIONS
256
+
257
+ if (is_relevant or is_code) and not is_skip:
258
+ if raw_size > 0 and raw_offset + raw_size <= self.file_size:
259
+ current_pos = f.tell()
260
+ f.seek(raw_offset)
261
+ section_data = f.read(raw_size)
262
+ f.seek(current_pos)
263
+
264
+ self.sections[name] = section_data
265
+ info['extracted'] = True
266
+ info['output_start'] = current_offset
267
+ info['output_end'] = current_offset + len(section_data)
268
+ current_offset += len(section_data)
269
+
270
+ self.section_info.append(info)
271
+
272
+ def get_relevant_bytes(self) -> bytes:
273
+ if not self.valid:
274
+ return b''
275
+
276
+ result = bytearray(self.headers)
277
+
278
+ # deterministic ordering: code first, then read-only data, then writable
279
+ section_order = [
280
+ b'.text', b'.code', b'CODE', b'.TEXT',
281
+ b'.rdata', b'.rodata',
282
+ b'.idata',
283
+ b'.data', b'.DATA',
284
+ b'.edata',
285
+ ]
286
+
287
+ for name in section_order:
288
+ if name in self.sections:
289
+ result.extend(self.sections[name])
290
+
291
+ # anything we didn't explicitly order goes at the end
292
+ for name, data in self.sections.items():
293
+ if name not in section_order:
294
+ result.extend(data)
295
+
296
+ return bytes(result)
297
+
298
+ def get_section_masks(self, total_length: int) -> dict:
299
+ """
300
+ Build per-byte masks that say "this byte is code" or "this byte is
301
+ import-related". We need these as channels for the CNN.
302
+
303
+ Uses range-based mapping instead of a byte-by-byte dict because
304
+ that was absurdly slow on large binaries.
305
+ """
306
+ code_mask = np.zeros(total_length, dtype=np.float32)
307
+ import_mask = np.zeros(total_length, dtype=np.float32)
308
+
309
+ header_len = len(self.headers)
310
+
311
+ section_order = [
312
+ b'.text', b'.code', b'CODE', b'.TEXT',
313
+ b'.rdata', b'.rodata',
314
+ b'.idata',
315
+ b'.data', b'.DATA',
316
+ b'.edata',
317
+ ]
318
+
319
+ # we need to track the mapping from original file offsets to our
320
+ # rearranged output offsets so we can place import ranges correctly
321
+ offset_mappings = []
322
+ offset_mappings.append((0, 0, min(header_len, total_length)))
323
+
324
+ output_offset = header_len
325
+
326
+ for name in section_order:
327
+ if name in self.sections and output_offset < total_length:
328
+ section_len = len(self.sections[name])
329
+
330
+ for info in self.section_info:
331
+ if info['name'] == name and info['extracted']:
332
+ file_offset = info['raw_offset']
333
+ usable_len = min(section_len, total_length - output_offset)
334
+ offset_mappings.append((file_offset, output_offset, usable_len))
335
+
336
+ if info['is_code']:
337
+ end = min(output_offset + section_len, total_length)
338
+ code_mask[output_offset:end] = 1.0
339
+
340
+ break
341
+
342
+ output_offset += section_len
343
+
344
+ for name, data in self.sections.items():
345
+ if name not in section_order and output_offset < total_length:
346
+ section_len = len(data)
347
+
348
+ for info in self.section_info:
349
+ if info['name'] == name and info['extracted']:
350
+ file_offset = info['raw_offset']
351
+ usable_len = min(section_len, total_length - output_offset)
352
+ offset_mappings.append((file_offset, output_offset, usable_len))
353
+
354
+ if info['is_code']:
355
+ end = min(output_offset + section_len, total_length)
356
+ code_mask[output_offset:end] = 1.0
357
+
358
+ break
359
+
360
+ output_offset += section_len
361
+
362
+ # now project the import ranges (which are in original file coords)
363
+ # into our rearranged output coords
364
+ for import_file_offset, import_size in self.import_ranges:
365
+ for file_start, out_start, length in offset_mappings:
366
+ file_end = file_start + length
367
+
368
+ if import_file_offset < file_end and import_file_offset + import_size > file_start:
369
+ overlap_start = max(import_file_offset, file_start)
370
+ overlap_end = min(import_file_offset + import_size, file_end)
371
+
372
+ out_overlap_start = out_start + (overlap_start - file_start)
373
+ out_overlap_end = out_start + (overlap_end - file_start)
374
+
375
+ out_overlap_start = max(0, min(out_overlap_start, total_length))
376
+ out_overlap_end = max(0, min(out_overlap_end, total_length))
377
+
378
+ if out_overlap_end > out_overlap_start:
379
+ import_mask[out_overlap_start:out_overlap_end] = 1.0
380
+
381
+ return {
382
+ 'code': code_mask,
383
+ 'import': import_mask
384
+ }
385
+
386
+ def get_stats(self) -> dict:
387
+ extracted_size = len(self.headers) + sum(len(d) for d in self.sections.values())
388
+
389
+ return {
390
+ 'file_size': self.file_size,
391
+ 'extracted_size': extracted_size,
392
+ 'compression_ratio': extracted_size / self.file_size if self.file_size > 0 else 0,
393
+ 'num_sections': self.num_sections,
394
+ 'extracted_sections': [s['name_str'] for s in self.section_info if s['extracted']],
395
+ 'skipped_sections': [s['name_str'] for s in self.section_info if not s['extracted']],
396
+ 'import_ranges_found': len(self.import_ranges),
397
+ }
398
+
399
+
400
+ # --- Feature extraction ---
401
+ # Each of these produces a 1D float32 array the same length as the input,
402
+ # which later gets folded into the 3D volume as a separate channel.
403
+
404
+ def compute_block_entropy(data: np.ndarray, block_size: int = 256) -> np.ndarray:
405
+ """
406
+ Shannon entropy per fixed-size block, upsampled back to full resolution.
407
+ Using blocks instead of a sliding window keeps this O(n) and avoids
408
+ the weird edge artifacts you get with windowed approaches.
409
+ """
410
+ n = len(data)
411
+ if n == 0:
412
+ return np.zeros(0, dtype=np.float32)
413
+
414
+ n_blocks = max(1, (n + block_size - 1) // block_size)
415
+ block_entropies = np.zeros(n_blocks, dtype=np.float32)
416
+
417
+ for i in range(n_blocks):
418
+ start = i * block_size
419
+ end = min(start + block_size, n)
420
+ block = data[start:end]
421
+
422
+ if len(block) == 0:
423
+ continue
424
+
425
+ counts = np.bincount(block, minlength=256)
426
+ probs = counts[counts > 0] / len(block)
427
+ block_entropies[i] = -np.sum(probs * np.log2(probs)) / 8.0 # normalize to [0,1]
428
+
429
+ entropy = np.repeat(block_entropies, block_size)[:n]
430
+ return entropy.astype(np.float32)
431
+
432
+
433
+ def compute_string_density(data: np.ndarray, window_size: int = 64) -> np.ndarray:
434
+ """
435
+ Sliding window ratio of printable ASCII bytes. Regions with high density
436
+ are likely string tables, function names, debug info. stuff that's
437
+ semantically meaningful even if it's not code.
438
+ """
439
+ n = len(data)
440
+ if n == 0:
441
+ return np.zeros(n, dtype=np.float32)
442
+
443
+ is_printable = ((data >= 32) & (data <= 126)).astype(np.float32)
444
+ kernel = np.ones(window_size) / window_size
445
+ density = np.convolve(is_printable, kernel, mode='same').astype(np.float32)
446
+ return density
447
+
448
+
449
+ def compute_import_density(data: np.ndarray, import_mask: np.ndarray,
450
+ window_size: int = 128) -> np.ndarray:
451
+ """
452
+ Spread the binary import mask with a gaussian kernel so nearby bytes
453
+ also get some import signal. The idea is that the bytes surrounding
454
+ import tables are contextually related even if they're not literally
455
+ inside the directory entry.
456
+ """
457
+ n = len(data)
458
+ if n == 0:
459
+ return np.zeros(n, dtype=np.float32)
460
+
461
+ kernel = np.exp(-np.linspace(-2, 2, window_size)**2)
462
+ kernel = kernel / kernel.sum()
463
+
464
+ density = np.convolve(import_mask, kernel, mode='same').astype(np.float32)
465
+
466
+ if density.max() > 0:
467
+ density = density / density.max()
468
+
469
+ return density
470
+
471
+
472
+ # --- Space-filling curve ---
473
+
474
+ class SpaceFillingCurve:
475
+ """
476
+ Morton / Z-order curve: maps a linear byte index to (x, y, z) coords
477
+ by interleaving bits. This keeps bytes that are close in the file close
478
+ in 3D space, which matters for conv filters.
479
+ """
480
+
481
+ def __init__(self, order: int):
482
+ self.order = order
483
+ self.size = 2 ** order
484
+ self.total_points = self.size ** 3
485
+ self._build_lookup_table()
486
+
487
+ def _build_lookup_table(self):
488
+ print(f"Building space-filling curve lookup table ({self.size}³ = {self.total_points:,} points)...")
489
+ self.lookup = np.zeros((self.total_points, 3), dtype=np.int32)
490
+
491
+ for d in tqdm(range(self.total_points), desc="Building lookup", leave=False):
492
+ x = y = z = 0
493
+ for i in range(self.order):
494
+ x |= ((d >> (3 * i)) & 1) << i
495
+ y |= ((d >> (3 * i + 1)) & 1) << i
496
+ z |= ((d >> (3 * i + 2)) & 1) << i
497
+ self.lookup[d] = (x, y, z)
498
+
499
+ def get_all_coords(self) -> np.ndarray:
500
+ return self.lookup
501
+
502
+
503
+ # --- Core conversion: PE file -> 6-channel 3D tensor ---
504
+
505
+ def pe_to_multichannel_3d(
506
+ filepath: str,
507
+ order: int = 6,
508
+ curve: SpaceFillingCurve = None,
509
+ entropy_block_size: int = 256,
510
+ string_window: int = 64,
511
+ import_window: int = 128,
512
+ ) -> tuple:
513
+ """
514
+ The main pipeline. Parses the PE, extracts relevant sections, computes
515
+ all the per-byte features, then folds everything into a 3D volume via
516
+ the Morton curve.
517
+
518
+ Returns (tensor [6, D, H, W], stats_dict).
519
+ """
520
+ if curve is None:
521
+ curve = SpaceFillingCurve(order)
522
+
523
+ pe = PEParserExtended(filepath)
524
+
525
+ if not pe.valid:
526
+ raise ValueError(f"Invalid PE file: {filepath}")
527
+
528
+ relevant_bytes = pe.get_relevant_bytes()
529
+ stats = pe.get_stats()
530
+
531
+ # truncate to what fits in the volume (or pad with zeros implicitly)
532
+ max_bytes = curve.total_points
533
+ bytes_array = np.frombuffer(relevant_bytes[:max_bytes], dtype=np.uint8)
534
+ num_bytes = len(bytes_array)
535
+
536
+ masks = pe.get_section_masks(num_bytes)
537
+
538
+ # compute all 1D feature channels
539
+ raw_normalized = bytes_array.astype(np.float32) / 255.0
540
+ entropy = compute_block_entropy(bytes_array, block_size=entropy_block_size)
541
+ code_mask = masks['code']
542
+ import_density = compute_import_density(bytes_array, masks['import'], window_size=import_window)
543
+ string_density = compute_string_density(bytes_array, window_size=string_window)
544
+
545
+ # scatter 1D features into the 3D volume along the curve
546
+ tensor = np.zeros((6, curve.size, curve.size, curve.size), dtype=np.float32)
547
+ coords = curve.get_all_coords()[:num_bytes]
548
+
549
+ tensor[0, coords[:, 0], coords[:, 1], coords[:, 2]] = raw_normalized
550
+ tensor[1, coords[:, 0], coords[:, 1], coords[:, 2]] = entropy
551
+ tensor[2, coords[:, 0], coords[:, 1], coords[:, 2]] = code_mask
552
+ tensor[3, coords[:, 0], coords[:, 1], coords[:, 2]] = import_density
553
+ tensor[4, coords[:, 0], coords[:, 1], coords[:, 2]] = string_density
554
+ tensor[5, coords[:, 0], coords[:, 1], coords[:, 2]] = 1.0 # data presence mask
555
+
556
+ fill_ratio = num_bytes / curve.total_points
557
+
558
+ stats['bytes_mapped'] = num_bytes
559
+ stats['fill_ratio'] = fill_ratio
560
+ stats['channels'] = ['raw_bytes', 'entropy', 'code_mask', 'import_density', 'string_density', 'data_mask']
561
+ stats['channel_stats'] = {
562
+ 'raw_bytes_mean': float(np.mean(raw_normalized)),
563
+ 'entropy_mean': float(np.mean(entropy)),
564
+ 'code_fraction': float(np.mean(code_mask)),
565
+ 'import_fraction': float(np.mean(masks['import'])),
566
+ 'string_density_mean': float(np.mean(string_density)),
567
+ }
568
+
569
+ return tensor, stats
570
+
571
+
572
+ # --- File discovery and batch processing ---
573
+
574
+ def is_valid_pe(filepath: str) -> bool:
575
+ """Quick sniff test: MZ magic + valid PE offset + PE signature."""
576
+ try:
577
+ with open(filepath, 'rb') as f:
578
+ f.seek(0, 2)
579
+ if f.tell() < 64:
580
+ return False
581
+
582
+ f.seek(0)
583
+ if f.read(2) != b'MZ':
584
+ return False
585
+
586
+ f.seek(0x3C)
587
+ pe_offset = struct.unpack('<I', f.read(4))[0]
588
+
589
+ f.seek(0, 2)
590
+ if pe_offset + 4 > f.tell():
591
+ return False
592
+
593
+ f.seek(pe_offset)
594
+ if f.read(4) != b'PE\x00\x00':
595
+ return False
596
+
597
+ return True
598
+ except:
599
+ return False
600
+
601
+
602
+ def find_pe_files(input_dir: str, min_size: int = 10*1024, max_size: int = 50*1024*1024) -> list:
603
+ input_path = Path(input_dir)
604
+
605
+ if not input_path.exists():
606
+ raise ValueError(f"Input directory does not exist: {input_dir}")
607
+
608
+ pe_files = []
609
+ all_files = list(input_path.rglob('*'))
610
+
611
+ skipped_small = 0
612
+ skipped_large = 0
613
+ skipped_invalid = 0
614
+
615
+ print(f"Scanning {len(all_files)} items for valid PE files...")
616
+ print(f"Size filter: {min_size/1024:.1f}KB - {max_size/1024/1024:.1f}MB")
617
+
618
+ for filepath in tqdm(all_files, desc="Validating PE files"):
619
+ if not filepath.is_file():
620
+ continue
621
+
622
+ try:
623
+ file_size = filepath.stat().st_size
624
+ except OSError:
625
+ continue
626
+
627
+ if file_size < min_size:
628
+ skipped_small += 1
629
+ continue
630
+
631
+ if file_size > max_size:
632
+ skipped_large += 1
633
+ continue
634
+
635
+ if is_valid_pe(str(filepath)):
636
+ pe_files.append(filepath)
637
+ else:
638
+ skipped_invalid += 1
639
+
640
+ print(f"\nFiltering results:")
641
+ print(f" Valid PE files: {len(pe_files)}")
642
+ print(f" Too small (<{min_size/1024:.0f}KB): {skipped_small}")
643
+ print(f" Too large (>{max_size/1024/1024:.0f}MB): {skipped_large}")
644
+ print(f" Invalid PE: {skipped_invalid}")
645
+
646
+ return pe_files
647
+
648
+
649
+ def process_pe_files(pe_files: list, output_dir: str, order: int = 6) -> dict:
650
+ output_path = Path(output_dir)
651
+ output_path.mkdir(parents=True, exist_ok=True)
652
+
653
+ curve = SpaceFillingCurve(order)
654
+
655
+ metadata = {
656
+ 'order': order,
657
+ 'grid_size': curve.size,
658
+ 'max_bytes': curve.total_points,
659
+ 'channels': 6,
660
+ 'channel_names': ['raw_bytes', 'entropy', 'code_mask', 'import_density', 'string_density', 'data_mask'],
661
+ 'extraction_mode': 'multichannel_semantic',
662
+ 'files': {}
663
+ }
664
+
665
+ print(f"\nProcessing {len(pe_files)} PE files...")
666
+ print(f"Grid size: {curve.size}³ = {curve.total_points:,} voxels")
667
+ print(f"Output channels: 6 (raw, entropy, code, import, strings, data_mask)\n")
668
+
669
+ for filepath in tqdm(pe_files, desc="Converting to 6ch 3D tensors"):
670
+ try:
671
+ tensor, stats = pe_to_multichannel_3d(str(filepath), order, curve)
672
+
673
+ safe_name = "".join(c if c.isalnum() or c in '._-' else '_' for c in filepath.name)
674
+ output_name = f"{safe_name}.npy"
675
+ output_file = output_path / output_name
676
+
677
+ # handle filename collisions
678
+ counter = 1
679
+ base_safe_name = safe_name
680
+ while output_file.exists():
681
+ safe_name = f"{base_safe_name}_{counter}"
682
+ output_name = f"{safe_name}.npy"
683
+ output_file = output_path / output_name
684
+ counter += 1
685
+
686
+ np.save(output_file, tensor)
687
+
688
+ metadata['files'][str(filepath)] = {
689
+ 'output': str(output_file.name),
690
+ 'original_size': stats['file_size'],
691
+ 'extracted_size': stats['extracted_size'],
692
+ 'compression_ratio': stats['compression_ratio'],
693
+ 'bytes_mapped': stats['bytes_mapped'],
694
+ 'fill_ratio': stats['fill_ratio'],
695
+ 'extracted_sections': stats['extracted_sections'],
696
+ 'skipped_sections': stats['skipped_sections'],
697
+ 'import_ranges_found': stats.get('import_ranges_found', 0),
698
+ }
699
+
700
+ except Exception as e:
701
+ tqdm.write(f"Error processing {filepath.name}: {e}")
702
+ metadata['files'][str(filepath)] = {'error': str(e)}
703
+
704
+ metadata_file = output_path / 'metadata.json'
705
+ with open(metadata_file, 'w') as f:
706
+ json.dump(metadata, f, indent=2)
707
+
708
+ return metadata
709
+
710
+
711
+ def print_dataset_stats(metadata: dict):
712
+ """Dump fill ratio distribution. important to check before training
713
+ since fill ratio can be a spurious feature if it correlates with labels."""
714
+ files_data = [v for v in metadata['files'].values() if 'error' not in v]
715
+
716
+ if not files_data:
717
+ print("No successfully processed files!")
718
+ return
719
+
720
+ fill_ratios = [f['fill_ratio'] for f in files_data]
721
+
722
+ print("\n" + "=" * 60)
723
+ print("DATASET STATISTICS")
724
+ print("=" * 60)
725
+ print(f"Files processed: {len(files_data)}")
726
+ print(f"Grid size: {metadata['grid_size']}³")
727
+ print(f"Channels: {metadata['channels']} ({', '.join(metadata['channel_names'])})")
728
+
729
+ print(f"\nFILL RATIO DISTRIBUTION:")
730
+ print(f" Min: {min(fill_ratios):.4f} ({min(fill_ratios)*100:.1f}%)")
731
+ print(f" Max: {max(fill_ratios):.4f} ({max(fill_ratios)*100:.1f}%)")
732
+ print(f" Mean: {np.mean(fill_ratios):.4f} ({np.mean(fill_ratios)*100:.1f}%)")
733
+ print(f" Std: {np.std(fill_ratios):.4f}")
734
+ print(f" Median: {np.median(fill_ratios):.4f}")
735
+
736
+ buckets = [0, 0.1, 0.25, 0.5, 0.75, 1.0]
737
+ print(f"\n Distribution:")
738
+ for i in range(len(buckets)-1):
739
+ count = sum(1 for r in fill_ratios if buckets[i] <= r < buckets[i+1])
740
+ pct = count / len(fill_ratios) * 100
741
+ bar = "█" * int(pct / 5)
742
+ print(f" {buckets[i]:.2f}-{buckets[i+1]:.2f}: {count:4d} ({pct:5.1f}%) {bar}")
743
+
744
+ full_count = sum(1 for r in fill_ratios if r >= 0.99)
745
+ print(f"\n Tensors at 100% fill: {full_count} ({full_count/len(fill_ratios)*100:.1f}%)")
746
+ if full_count < len(fill_ratios) * 0.5:
747
+ print(" WARNING: Fill ratio varies significantly!")
748
+ print(" Check correlation with labels before training, this can be a confound.")
749
+
750
+
751
+ def save_fill_ratio_report(metadata: dict, output_path: Path):
752
+ files_data = [(k, v) for k, v in metadata['files'].items() if 'error' not in v]
753
+
754
+ report = {
755
+ 'total_files': len(files_data),
756
+ 'fill_ratios': {k: v['fill_ratio'] for k, v in files_data},
757
+ 'statistics': {
758
+ 'min': min(v['fill_ratio'] for _, v in files_data),
759
+ 'max': max(v['fill_ratio'] for _, v in files_data),
760
+ 'mean': float(np.mean([v['fill_ratio'] for _, v in files_data])),
761
+ 'std': float(np.std([v['fill_ratio'] for _, v in files_data])),
762
+ 'median': float(np.median([v['fill_ratio'] for _, v in files_data])),
763
+ }
764
+ }
765
+
766
+ with open(output_path / 'fill_ratio_report.json', 'w') as f:
767
+ json.dump(report, f, indent=2)
768
+
769
+ print(f"Fill ratio report saved to {output_path / 'fill_ratio_report.json'}")
770
+
771
+
772
+ def main():
773
+ parser = argparse.ArgumentParser(
774
+ description='Convert PE files to 6-channel 3D tensors with semantic features'
775
+ )
776
+ parser.add_argument('--input_dir', '-i', type=str, required=True,
777
+ help='Input directory containing PE files')
778
+ parser.add_argument('--output_dir', '-o', type=str, required=True,
779
+ help='Output directory for tensor files')
780
+ parser.add_argument('--order', type=int, default=6, choices=[4, 5, 6, 7],
781
+ help='Curve order. Grid = 2^order. 6=64³. Default: 6')
782
+ parser.add_argument('--min_size', type=int, default=10,
783
+ help='Minimum file size in KB (default: 10)')
784
+ parser.add_argument('--max_size', type=int, default=50,
785
+ help='Maximum file size in MB (default: 50)')
786
+
787
+ args = parser.parse_args()
788
+
789
+ print("=" * 60)
790
+ print("PE -> 6-CHANNEL 3D TENSOR CONVERTER")
791
+ print("=" * 60)
792
+ print("Channels: raw bytes | entropy | code mask | import density | string density | data mask")
793
+ print("=" * 60)
794
+
795
+ min_bytes = args.min_size * 1024
796
+ max_bytes = args.max_size * 1024 * 1024
797
+ pe_files = find_pe_files(args.input_dir, min_size=min_bytes, max_size=max_bytes)
798
+
799
+ if not pe_files:
800
+ print("\nNo valid PE files found.")
801
+ return
802
+
803
+ print(f"\nFound {len(pe_files)} valid PE files")
804
+
805
+ metadata = process_pe_files(pe_files, args.output_dir, order=args.order)
806
+
807
+ successful = sum(1 for v in metadata['files'].values() if 'error' not in v)
808
+ failed = len(metadata['files']) - successful
809
+
810
+ print(f"\nDone. {successful}/{len(pe_files)} succeeded.")
811
+ if failed > 0:
812
+ print(f" Failed: {failed}")
813
+ print(f" Output: {args.output_dir}")
814
+
815
+ print_dataset_stats(metadata)
816
+ save_fill_ratio_report(metadata, Path(args.output_dir))
817
+
818
+
819
+ if __name__ == '__main__':
820
+ main()