|
| 1 | +import pefile |
| 2 | +import pandas as pd |
| 3 | +import math |
| 4 | + |
| 5 | +# Function to calculate entropy of a section |
| 6 | +def calculate_entropy(data): |
| 7 | + if not data: |
| 8 | + return 0 |
| 9 | + entropy = 0 |
| 10 | + for x in range(256): |
| 11 | + p_x = float(data.count(bytes([x]))) / len(data) |
| 12 | + if p_x > 0: |
| 13 | + entropy += - p_x * math.log(p_x, 2) |
| 14 | + return entropy |
| 15 | + |
| 16 | +def extract_features(file_path): |
| 17 | + pe = pefile.PE(file_path) |
| 18 | + |
| 19 | + # Extract the specified 23 features in the given order |
| 20 | + features = { |
| 21 | + 'MajorLinkerVersion': pe.OPTIONAL_HEADER.MajorLinkerVersion, |
| 22 | + 'MinorOperatingSystemVersion': pe.OPTIONAL_HEADER.MinorOperatingSystemVersion, |
| 23 | + 'MajorSubsystemVersion': pe.OPTIONAL_HEADER.MajorSubsystemVersion, |
| 24 | + 'SizeOfStackReserve': pe.OPTIONAL_HEADER.SizeOfStackReserve, |
| 25 | + 'TimeDateStamp': pe.FILE_HEADER.TimeDateStamp, |
| 26 | + 'MajorOperatingSystemVersion': pe.OPTIONAL_HEADER.MajorOperatingSystemVersion, |
| 27 | + 'Characteristics': pe.FILE_HEADER.Characteristics, |
| 28 | + 'ImageBase': pe.OPTIONAL_HEADER.ImageBase, |
| 29 | + 'Subsystem': pe.OPTIONAL_HEADER.Subsystem, |
| 30 | + 'MinorImageVersion': pe.OPTIONAL_HEADER.MinorImageVersion, |
| 31 | + 'MinorSubsystemVersion': pe.OPTIONAL_HEADER.MinorSubsystemVersion, |
| 32 | + 'SizeOfInitializedData': pe.OPTIONAL_HEADER.SizeOfInitializedData, |
| 33 | + 'DllCharacteristics': pe.OPTIONAL_HEADER.DllCharacteristics, |
| 34 | + 'DirectoryEntryExport': 1 if hasattr(pe, 'DIRECTORY_ENTRY_EXPORT') else 0, |
| 35 | + 'ImageDirectoryEntryExport': pe.OPTIONAL_HEADER.DATA_DIRECTORY[0].Size if hasattr(pe, 'DIRECTORY_ENTRY_EXPORT') else 0, |
| 36 | + 'CheckSum': pe.OPTIONAL_HEADER.CheckSum, |
| 37 | + 'DirectoryEntryImportSize': pe.OPTIONAL_HEADER.DATA_DIRECTORY[1].Size if hasattr(pe, 'DIRECTORY_ENTRY_IMPORT') else 0, |
| 38 | + 'SectionMaxChar': len(pe.sections), # Example calculation for demonstration |
| 39 | + 'MajorImageVersion': pe.OPTIONAL_HEADER.MajorImageVersion, |
| 40 | + 'AddressOfEntryPoint': pe.OPTIONAL_HEADER.AddressOfEntryPoint, |
| 41 | + 'SectionMinEntropy': None, # Placeholder, will be calculated |
| 42 | + 'SizeOfHeaders': pe.OPTIONAL_HEADER.SizeOfHeaders, |
| 43 | + 'SectionMinVirtualsize': None # Placeholder, will be calculated |
| 44 | + } |
| 45 | + |
| 46 | + # Calculate SectionMinEntropy |
| 47 | + entropies = [] |
| 48 | + for section in pe.sections: |
| 49 | + entropy = calculate_entropy(section.get_data()) |
| 50 | + entropies.append(entropy) |
| 51 | + |
| 52 | + if entropies: |
| 53 | + features['SectionMinEntropy'] = min(entropies) |
| 54 | + |
| 55 | + # Calculate SectionMinVirtualsize (example calculation) |
| 56 | + features['SectionMinVirtualsize'] = min(section.Misc_VirtualSize for section in pe.sections) |
| 57 | + |
| 58 | + return pd.DataFrame([features]) |
0 commit comments