""" EMBER Feature Extraction Service Ported from elastic/ember for Python 3.12+ compatibility Extracts 2381 features from PE (Portable Executable) files for malware detection. Based on EMBER 2018 v2 feature format. Original source: https://github.com/elastic/ember """ import re import hashlib import logging import numpy as np from typing import Dict, List, Any, Optional, Tuple logger = logging.getLogger(__name__) # Try to import lief - required for PE parsing try: import lief LIEF_AVAILABLE = True LIEF_MAJOR, LIEF_MINOR, *_ = lief.__version__.split('.') LIEF_MAJOR = int(LIEF_MAJOR) LIEF_MINOR = int(LIEF_MINOR) LIEF_EXPORT_OBJECT = LIEF_MAJOR > 0 or (LIEF_MAJOR == 0 and LIEF_MINOR >= 10) LIEF_HAS_SIGNATURE = LIEF_MAJOR > 0 or (LIEF_MAJOR == 0 and LIEF_MINOR >= 11) logger.info(f"LIEF version {lief.__version__} loaded successfully") except ImportError: LIEF_AVAILABLE = False LIEF_MAJOR = LIEF_MINOR = 0 LIEF_EXPORT_OBJECT = False LIEF_HAS_SIGNATURE = False logger.warning("LIEF library not available. PE feature extraction disabled.") # Try to import sklearn FeatureHasher try: from sklearn.feature_extraction import FeatureHasher SKLEARN_AVAILABLE = True except ImportError: SKLEARN_AVAILABLE = False logger.warning("sklearn not available. Feature hashing disabled.") class FeatureType: """Base class for feature extractors.""" name = '' dim = 0 def __repr__(self): return f'{self.name}({self.dim})' def raw_features(self, bytez: bytes, lief_binary) -> Any: """Generate JSON-able representation of the file.""" raise NotImplementedError def process_raw_features(self, raw_obj: Any) -> np.ndarray: """Generate a feature vector from raw features.""" raise NotImplementedError def feature_vector(self, bytez: bytes, lief_binary) -> np.ndarray: """Calculate feature vector directly from sample.""" return self.process_raw_features(self.raw_features(bytez, lief_binary)) class ByteHistogram(FeatureType): """Byte histogram (normalized) over the entire binary file.""" name = 'histogram' dim = 256 def raw_features(self, bytez: bytes, lief_binary) -> List[int]: counts = np.bincount(np.frombuffer(bytez, dtype=np.uint8), minlength=256) return counts.tolist() def process_raw_features(self, raw_obj: List[int]) -> np.ndarray: counts = np.array(raw_obj, dtype=np.float32) total = counts.sum() if total > 0: normalized = counts / total else: normalized = counts return normalized class ByteEntropyHistogram(FeatureType): """ 2D byte/entropy histogram based on Saxe and Berlin, 2015. Approximates the joint probability of byte value and local entropy. """ name = 'byteentropy' dim = 256 def __init__(self, step: int = 1024, window: int = 2048): self.window = window self.step = step def _entropy_bin_counts(self, block: np.ndarray) -> Tuple[int, np.ndarray]: """Calculate entropy bin and coarse histogram.""" # Coarse histogram, 16 bytes per bin c = np.bincount(block >> 4, minlength=16) p = c.astype(np.float32) / self.window wh = np.where(c)[0] if len(wh) > 0: H = np.sum(-p[wh] * np.log2(p[wh])) * 2 else: H = 0.0 Hbin = int(H * 2) # Up to 16 bins (max entropy is 8 bits) if Hbin == 16: Hbin = 15 return Hbin, c def raw_features(self, bytez: bytes, lief_binary) -> List[int]: output = np.zeros((16, 16), dtype=np.int64) a = np.frombuffer(bytez, dtype=np.uint8) if a.shape[0] < self.window: Hbin, c = self._entropy_bin_counts(a) output[Hbin, :] += c else: # Strided trick for efficiency shape = a.shape[:-1] + (a.shape[-1] - self.window + 1, self.window) strides = a.strides + (a.strides[-1],) blocks = np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)[::self.step, :] for block in blocks: Hbin, c = self._entropy_bin_counts(block) output[Hbin, :] += c return output.flatten().tolist() def process_raw_features(self, raw_obj: List[int]) -> np.ndarray: counts = np.array(raw_obj, dtype=np.float32) total = counts.sum() if total > 0: normalized = counts / total else: normalized = counts return normalized class StringExtractor(FeatureType): """Extract string-based features from raw byte stream.""" name = 'strings' dim = 104 # 1 + 1 + 1 + 96 + 1 + 1 + 1 + 1 + 1 def __init__(self): # All consecutive runs of printable ASCII (0x20-0x7f) that are 5+ chars self._allstrings = re.compile(b'[\x20-\x7f]{5,}') # Occurrences of 'C:\' self._paths = re.compile(b'c:\\\\', re.IGNORECASE) # Occurrences of http:// or https:// self._urls = re.compile(b'https?://', re.IGNORECASE) # Occurrences of HKEY_ self._registry = re.compile(b'HKEY_') # Evidence of MZ header (dropper?) self._mz = re.compile(b'MZ') def raw_features(self, bytez: bytes, lief_binary) -> Dict: allstrings = self._allstrings.findall(bytez) if allstrings: string_lengths = [len(s) for s in allstrings] avlength = sum(string_lengths) / len(string_lengths) # Map printable characters 0x20-0x7f to int array 0-95 as_shifted_string = [b - ord(b'\x20') for b in b''.join(allstrings)] c = np.bincount(as_shifted_string, minlength=96) csum = c.sum() p = c.astype(np.float32) / csum if csum > 0 else c.astype(np.float32) wh = np.where(c)[0] H = np.sum(-p[wh] * np.log2(p[wh])) if len(wh) > 0 else 0.0 else: avlength = 0 c = np.zeros((96,), dtype=np.float32) H = 0 csum = 0 return { 'numstrings': len(allstrings), 'avlength': avlength, 'printabledist': c.tolist(), 'printables': int(csum), 'entropy': float(H), 'paths': len(self._paths.findall(bytez)), 'urls': len(self._urls.findall(bytez)), 'registry': len(self._registry.findall(bytez)), 'MZ': len(self._mz.findall(bytez)) } def process_raw_features(self, raw_obj: Dict) -> np.ndarray: hist_divisor = float(raw_obj['printables']) if raw_obj['printables'] > 0 else 1.0 return np.hstack([ raw_obj['numstrings'], raw_obj['avlength'], raw_obj['printables'], np.asarray(raw_obj['printabledist']) / hist_divisor, raw_obj['entropy'], raw_obj['paths'], raw_obj['urls'], raw_obj['registry'], raw_obj['MZ'] ]).astype(np.float32) class GeneralFileInfo(FeatureType): """General information about the PE file.""" name = 'general' dim = 10 def raw_features(self, bytez: bytes, lief_binary) -> Dict: if lief_binary is None: return { 'size': len(bytez), 'vsize': 0, 'has_debug': 0, 'exports': 0, 'imports': 0, 'has_relocations': 0, 'has_resources': 0, 'has_signature': 0, 'has_tls': 0, 'symbols': 0 } return { 'size': len(bytez), 'vsize': lief_binary.virtual_size, 'has_debug': int(lief_binary.has_debug), 'exports': len(lief_binary.exported_functions), 'imports': len(lief_binary.imported_functions), 'has_relocations': int(lief_binary.has_relocations), 'has_resources': int(lief_binary.has_resources), 'has_signature': int(lief_binary.has_signatures) if LIEF_HAS_SIGNATURE else int(lief_binary.has_signature), 'has_tls': int(lief_binary.has_tls), 'symbols': len(lief_binary.symbols), } def process_raw_features(self, raw_obj: Dict) -> np.ndarray: return np.asarray([ raw_obj['size'], raw_obj['vsize'], raw_obj['has_debug'], raw_obj['exports'], raw_obj['imports'], raw_obj['has_relocations'], raw_obj['has_resources'], raw_obj['has_signature'], raw_obj['has_tls'], raw_obj['symbols'] ], dtype=np.float32) class HeaderFileInfo(FeatureType): """Machine, architecture, OS, linker and other header information.""" name = 'header' dim = 62 def raw_features(self, bytez: bytes, lief_binary) -> Dict: raw_obj = { 'coff': {'timestamp': 0, 'machine': "", 'characteristics': []}, 'optional': { 'subsystem': "", 'dll_characteristics': [], 'magic': "", 'major_image_version': 0, 'minor_image_version': 0, 'major_linker_version': 0, 'minor_linker_version': 0, 'major_operating_system_version': 0, 'minor_operating_system_version': 0, 'major_subsystem_version': 0, 'minor_subsystem_version': 0, 'sizeof_code': 0, 'sizeof_headers': 0, 'sizeof_heap_commit': 0 } } if lief_binary is None: return raw_obj raw_obj['coff']['timestamp'] = lief_binary.header.time_date_stamps raw_obj['coff']['machine'] = str(lief_binary.header.machine).split('.')[-1] raw_obj['coff']['characteristics'] = [ str(c).split('.')[-1] for c in lief_binary.header.characteristics_list ] raw_obj['optional']['subsystem'] = str(lief_binary.optional_header.subsystem).split('.')[-1] raw_obj['optional']['dll_characteristics'] = [ str(c).split('.')[-1] for c in lief_binary.optional_header.dll_characteristics_lists ] raw_obj['optional']['magic'] = str(lief_binary.optional_header.magic).split('.')[-1] raw_obj['optional']['major_image_version'] = lief_binary.optional_header.major_image_version raw_obj['optional']['minor_image_version'] = lief_binary.optional_header.minor_image_version raw_obj['optional']['major_linker_version'] = lief_binary.optional_header.major_linker_version raw_obj['optional']['minor_linker_version'] = lief_binary.optional_header.minor_linker_version raw_obj['optional']['major_operating_system_version'] = lief_binary.optional_header.major_operating_system_version raw_obj['optional']['minor_operating_system_version'] = lief_binary.optional_header.minor_operating_system_version raw_obj['optional']['major_subsystem_version'] = lief_binary.optional_header.major_subsystem_version raw_obj['optional']['minor_subsystem_version'] = lief_binary.optional_header.minor_subsystem_version raw_obj['optional']['sizeof_code'] = lief_binary.optional_header.sizeof_code raw_obj['optional']['sizeof_headers'] = lief_binary.optional_header.sizeof_headers raw_obj['optional']['sizeof_heap_commit'] = lief_binary.optional_header.sizeof_heap_commit return raw_obj def process_raw_features(self, raw_obj: Dict) -> np.ndarray: return np.hstack([ raw_obj['coff']['timestamp'], FeatureHasher(10, input_type="string").transform([[raw_obj['coff']['machine']]]).toarray()[0], FeatureHasher(10, input_type="string").transform([raw_obj['coff']['characteristics']]).toarray()[0], FeatureHasher(10, input_type="string").transform([[raw_obj['optional']['subsystem']]]).toarray()[0], FeatureHasher(10, input_type="string").transform([raw_obj['optional']['dll_characteristics']]).toarray()[0], FeatureHasher(10, input_type="string").transform([[raw_obj['optional']['magic']]]).toarray()[0], raw_obj['optional']['major_image_version'], raw_obj['optional']['minor_image_version'], raw_obj['optional']['major_linker_version'], raw_obj['optional']['minor_linker_version'], raw_obj['optional']['major_operating_system_version'], raw_obj['optional']['minor_operating_system_version'], raw_obj['optional']['major_subsystem_version'], raw_obj['optional']['minor_subsystem_version'], raw_obj['optional']['sizeof_code'], raw_obj['optional']['sizeof_headers'], raw_obj['optional']['sizeof_heap_commit'], ]).astype(np.float32) class SectionInfo(FeatureType): """Information about section names, sizes and entropy.""" name = 'section' dim = 255 # 5 + 50 + 50 + 50 + 50 + 50 @staticmethod def _properties(s) -> List[str]: return [str(c).split('.')[-1] for c in s.characteristics_lists] def raw_features(self, bytez: bytes, lief_binary) -> Dict: if lief_binary is None: return {"entry": "", "sections": []} # Find entry section try: if LIEF_MAJOR > 0 or (LIEF_MAJOR == 0 and LIEF_MINOR >= 12): section = lief_binary.section_from_rva( lief_binary.entrypoint - lief_binary.imagebase ) if section is None: raise lief.not_found entry_section = section.name else: entry_section = lief_binary.section_from_offset(lief_binary.entrypoint).name except: # Bad entry point, find first executable section entry_section = "" for s in lief_binary.sections: if lief.PE.SECTION_CHARACTERISTICS.MEM_EXECUTE in s.characteristics_lists: entry_section = s.name break raw_obj = {"entry": entry_section} raw_obj["sections"] = [{ 'name': s.name, 'size': s.size, 'entropy': s.entropy, 'vsize': s.virtual_size, 'props': self._properties(s) } for s in lief_binary.sections] return raw_obj def process_raw_features(self, raw_obj: Dict) -> np.ndarray: sections = raw_obj['sections'] general = [ len(sections), sum(1 for s in sections if s['size'] == 0), sum(1 for s in sections if s['name'] == ""), sum(1 for s in sections if 'MEM_READ' in s['props'] and 'MEM_EXECUTE' in s['props']), sum(1 for s in sections if 'MEM_WRITE' in s['props']) ] # Section characteristics hashed section_sizes = [(s['name'], s['size']) for s in sections] section_sizes_hashed = FeatureHasher(50, input_type="pair").transform([section_sizes]).toarray()[0] section_entropy = [(s['name'], s['entropy']) for s in sections] section_entropy_hashed = FeatureHasher(50, input_type="pair").transform([section_entropy]).toarray()[0] section_vsize = [(s['name'], s['vsize']) for s in sections] section_vsize_hashed = FeatureHasher(50, input_type="pair").transform([section_vsize]).toarray()[0] entry_name_hashed = FeatureHasher(50, input_type="string").transform([[raw_obj['entry']]]).toarray()[0] characteristics = [p for s in sections for p in s['props'] if s['name'] == raw_obj['entry']] characteristics_hashed = FeatureHasher(50, input_type="string").transform([characteristics]).toarray()[0] return np.hstack([ general, section_sizes_hashed, section_entropy_hashed, section_vsize_hashed, entry_name_hashed, characteristics_hashed ]).astype(np.float32) class ImportsInfo(FeatureType): """Information about imported libraries and functions.""" name = 'imports' dim = 1280 def raw_features(self, bytez: bytes, lief_binary) -> Dict[str, List[str]]: imports = {} if lief_binary is None: return imports for lib in lief_binary.imports: if lib.name not in imports: imports[lib.name] = [] for entry in lib.entries: if entry.is_ordinal: imports[lib.name].append("ordinal" + str(entry.ordinal)) else: imports[lib.name].append(entry.name[:10000]) return imports def process_raw_features(self, raw_obj: Dict[str, List[str]]) -> np.ndarray: # Unique libraries libraries = list(set([l.lower() for l in raw_obj.keys()])) libraries_hashed = FeatureHasher(256, input_type="string").transform([libraries]).toarray()[0] # Fully qualified import names imports = [lib.lower() + ':' + e for lib, elist in raw_obj.items() for e in elist] imports_hashed = FeatureHasher(1024, input_type="string").transform([imports]).toarray()[0] return np.hstack([libraries_hashed, imports_hashed]).astype(np.float32) class ExportsInfo(FeatureType): """Information about exported functions.""" name = 'exports' dim = 128 def raw_features(self, bytez: bytes, lief_binary) -> List[str]: if lief_binary is None: return [] if LIEF_EXPORT_OBJECT: clipped_exports = [export.name[:10000] for export in lief_binary.exported_functions] else: clipped_exports = [export[:10000] for export in lief_binary.exported_functions] return clipped_exports def process_raw_features(self, raw_obj: List[str]) -> np.ndarray: exports_hashed = FeatureHasher(128, input_type="string").transform([raw_obj]).toarray()[0] return exports_hashed.astype(np.float32) class DataDirectories(FeatureType): """Size and virtual address of the first 15 data directories.""" name = 'datadirectories' dim = 30 # 15 * 2 def __init__(self): self._name_order = [ "EXPORT_TABLE", "IMPORT_TABLE", "RESOURCE_TABLE", "EXCEPTION_TABLE", "CERTIFICATE_TABLE", "BASE_RELOCATION_TABLE", "DEBUG", "ARCHITECTURE", "GLOBAL_PTR", "TLS_TABLE", "LOAD_CONFIG_TABLE", "BOUND_IMPORT", "IAT", "DELAY_IMPORT_DESCRIPTOR", "CLR_RUNTIME_HEADER" ] def raw_features(self, bytez: bytes, lief_binary) -> List[Dict]: output = [] if lief_binary is None: return output for data_directory in lief_binary.data_directories: output.append({ "name": str(data_directory.type).replace("DATA_DIRECTORY.", ""), "size": data_directory.size, "virtual_address": data_directory.rva }) return output def process_raw_features(self, raw_obj: List[Dict]) -> np.ndarray: features = np.zeros(2 * len(self._name_order), dtype=np.float32) for i in range(len(self._name_order)): if i < len(raw_obj): features[2 * i] = raw_obj[i]["size"] features[2 * i + 1] = raw_obj[i]["virtual_address"] return features class PEFeatureExtractor: """ Extract 2381 features from a PE file (EMBER 2018 v2 format). Usage: extractor = PEFeatureExtractor() with open("sample.exe", "rb") as f: features = extractor.feature_vector(f.read()) # features is now a numpy array of 2381 float values """ def __init__(self, feature_version: int = 2): if not LIEF_AVAILABLE: raise ImportError("LIEF library is required for PE feature extraction. Install with: pip install lief") if not SKLEARN_AVAILABLE: raise ImportError("scikit-learn is required for feature hashing. Install with: pip install scikit-learn") self.features = [ ByteHistogram(), ByteEntropyHistogram(), StringExtractor(), GeneralFileInfo(), HeaderFileInfo(), SectionInfo(), ImportsInfo(), ExportsInfo(), ] if feature_version == 2: self.features.append(DataDirectories()) self.dim = sum([fe.dim for fe in self.features]) logger.info(f"PEFeatureExtractor initialized with {self.dim} features (version {feature_version})") def raw_features(self, bytez: bytes) -> Dict[str, Any]: """Extract raw features from PE bytes.""" lief_binary = None try: lief_binary = lief.PE.parse(list(bytez)) except Exception as e: logger.warning(f"LIEF parsing error: {e}") lief_binary = None features = {"sha256": hashlib.sha256(bytez).hexdigest()} features.update({fe.name: fe.raw_features(bytez, lief_binary) for fe in self.features}) return features def process_raw_features(self, raw_obj: Dict[str, Any]) -> np.ndarray: """Process raw features into a feature vector.""" feature_vectors = [fe.process_raw_features(raw_obj[fe.name]) for fe in self.features] return np.hstack(feature_vectors).astype(np.float32) def feature_vector(self, bytez: bytes) -> np.ndarray: """ Extract feature vector directly from PE file bytes. Args: bytez: Raw bytes of the PE file Returns: numpy array of 2381 float32 features """ return self.process_raw_features(self.raw_features(bytez)) def extract_with_hash(self, bytez: bytes) -> Tuple[np.ndarray, str]: """ Extract features and return SHA256 hash. Args: bytez: Raw bytes of the PE file Returns: Tuple of (feature_vector, sha256_hash) """ raw = self.raw_features(bytez) return self.process_raw_features(raw), raw["sha256"] # Singleton instance _extractor_instance: Optional[PEFeatureExtractor] = None def get_feature_extractor() -> PEFeatureExtractor: """Get or create the singleton feature extractor.""" global _extractor_instance if _extractor_instance is None: _extractor_instance = PEFeatureExtractor() return _extractor_instance def extract_features_from_file(file_path: str) -> Tuple[np.ndarray, str]: """ Extract EMBER features from a PE file. Args: file_path: Path to the PE file Returns: Tuple of (feature_vector, sha256_hash) """ with open(file_path, 'rb') as f: bytez = f.read() extractor = get_feature_extractor() return extractor.extract_with_hash(bytez) def extract_features_from_bytes(bytez: bytes) -> Tuple[np.ndarray, str]: """ Extract EMBER features from PE file bytes. Args: bytez: Raw bytes of the PE file Returns: Tuple of (feature_vector, sha256_hash) """ extractor = get_feature_extractor() return extractor.extract_with_hash(bytez) def extract_features_and_lief(bytez: bytes) -> Tuple[np.ndarray, str, any]: """ Extract EMBER features and return LIEF binary for additional analysis. Args: bytez: Raw bytes of the PE file Returns: Tuple of (feature_vector, sha256_hash, lief_binary) """ if not LIEF_AVAILABLE: raise ImportError("LIEF is not available") extractor = get_feature_extractor() features, sha256 = extractor.extract_with_hash(bytez) # Parse with LIEF for additional analysis try: lief_binary = lief.PE.parse(list(bytez)) except Exception: lief_binary = None return features, sha256, lief_binary