// DefenderRuleParser // Author: Andrea Cristaldi 2025 - https://github.com/andreacristaldi/DefenderRuleParser // This project is licensed under the Apache 2.0 License. /* * Summary: PEP code parser for compact opcode-like sequences tied to PE features. * Origin: dump-driven; instruction shapes and constants observed in hex. * Role: Renders pseudo-ops and captures notable immediates. */ using System; using System.Collections.Generic; using System.IO; using DefenderRuleParser2.Models; namespace DefenderRuleParser2.Parsers { public class PepCodeParser : ISignatureParser { public void Parse(BinaryReader reader, int size, uint threatId) { long offset = reader.BaseStream.Position; var hexLinesForConsole = new List(); var hexLinesForExport = new List(); try { byte[] buffer = reader.ReadBytes(size); for (int i = 0; i < buffer.Length; i += 16) { string line = $"{(offset + i):X8} "; string clean = ""; for (int j = 0; j < 16; j++) { if (i + j < buffer.Length) { byte b = buffer[i + j]; line += $"{b:X2} "; clean += $"{b:X2} "; } else { line += " "; } } hexLinesForConsole.Add(line.TrimEnd()); hexLinesForExport.Add(clean.TrimEnd()); } Logger.Info($"[PEPCODE] Threat ID: {threatId}, Size: {size} bytes"); Logger.Info(" > Hex dump:"); foreach (var line in hexLinesForConsole) Logger.Info(" " + line); if (ThreatDatabase.TryGetThreat(threatId, out var threat)) { threat.Signatures.Add(new SignatureEntry { Type = "SIGNATURE_TYPE_PEPCODE", Offset = offset, Pattern = hexLinesForExport, Parsed = true, ConditionType = "PRESENT", ConditionValue = 1 }); } } catch (Exception ex) { Logger.Error($"[!] PEPCODE Error parsing at offset 0x{offset:X}: {ex.Message}"); } finally { reader.BaseStream.Seek(offset + size, SeekOrigin.Begin); } } } }