Detect Junk Code Insertion in Microsoft Sentinel
Adversaries may insert junk code or dead code into malware to obfuscate its functionality, hinder static analysis, and evade signature-based detections. Junk code includes NOP (No-Operation) sleds, dummy API calls, excessive mathematical operations, infinite loops that are never reached, and random garbage instructions interspersed between legitimate code. Unlike Binary Padding (T1027.001), which changes file size/hash, junk code insertion specifically targets analyst workflow and automated analysis engines. Real-world actors including Maze ransomware, FIN7, Gamaredon Group, APT32, Kimsuky, and StrelaStealer have employed this technique.
MITRE ATT&CK
- Tactic
- Defense Evasion
- Technique
- T1027 Obfuscated Files or Information
- Sub-technique
- T1027.016 Junk Code Insertion
- Canonical reference
- https://attack.mitre.org/techniques/T1027/016/
KQL Detection Query
// T1027.016 - Junk Code Insertion Detection
// Detects behavioral and artifact indicators of binaries using junk code obfuscation
// Primary signals: high entropy PE files, unusual section characteristics, sandbox evasion patterns
let SuspiciousParents = dynamic(["winword.exe", "excel.exe", "powerpnt.exe", "outlook.exe", "mshta.exe", "wscript.exe", "cscript.exe", "cmd.exe", "rundll32.exe", "regsvr32.exe"]);
let KnownPackerSections = dynamic([".ndata", ".MPRESS", ".petite", ".pec", "UPX0", "UPX1", ".rsrc"]);
// Signal 1: Newly created executables with suspicious section names written by Office or script interpreters
let NewExecutablesFromSuspiciousParents = DeviceFileEvents
| where Timestamp > ago(24h)
| where ActionType in ("FileCreated", "FileModified")
| where FileName endswith ".exe" or FileName endswith ".dll" or FileName endswith ".scr"
| where InitiatingProcessFileName has_any (SuspiciousParents)
| project Timestamp, DeviceName, AccountName, FolderPath, FileName,
InitiatingProcessFileName, InitiatingProcessCommandLine,
SHA256, FileSize, Signal="NewExeFromSuspiciousParent";
// Signal 2: Processes with very high CPU usage and low network/file activity (junk computation loops)
let HighCPULowIO = DeviceProcessEvents
| where Timestamp > ago(24h)
| where ProcessVersionInfoCompanyName == "" or isnull(ProcessVersionInfoCompanyName)
| where ProcessVersionInfoProductName == "" or isnull(ProcessVersionInfoProductName)
| where not (FolderPath has_any (@"C:\Windows\System32", @"C:\Windows\SysWOW64", @"C:\Program Files", @"C:\Program Files (x86)"))
| where FileName endswith ".exe" or FileName endswith ".scr"
| project Timestamp, DeviceName, AccountName, FolderPath, FileName,
ProcessCommandLine, InitiatingProcessFileName,
InitiatingProcessCommandLine, SHA256, ProcessId,
Signal="UnsignedBinaryNoVersionInfo";
// Signal 3: Script files with excessive concatenation/padding patterns indicating junk string insertion
let SuspiciousScriptExecution = DeviceProcessEvents
| where Timestamp > ago(24h)
| where FileName in~ ("powershell.exe", "pwsh.exe", "wscript.exe", "cscript.exe", "cmd.exe")
| where ProcessCommandLine matches regex @"(\+\s*['"][a-zA-Z0-9]{1,3}['"]\s*){5,}"
or ProcessCommandLine matches regex @"([Cc]hr\([0-9]+\)\s*[&\+]\s*){5,}"
or ProcessCommandLine matches regex @"(String\.Concat|\[string\]::join).*(['"][a-zA-Z]{1,2}['"].*){10,}"
| project Timestamp, DeviceName, AccountName, FileName, ProcessCommandLine,
InitiatingProcessFileName, InitiatingProcessCommandLine,
SHA256, Signal="ExcessiveStringConcatenation";
// Signal 4: Execution from temp/user directories with no digital signature indicators
let TempDirExecution = DeviceProcessEvents
| where Timestamp > ago(24h)
| where FolderPath has_any (@"\Temp\\", @"\AppData\Local\\", @"\AppData\Roaming\\", @"\Downloads\\", @"\Users\Public\")
| where FileName endswith ".exe" or FileName endswith ".scr" or FileName endswith ".com"
| where ProcessVersionInfoCompanyName == "" or isnull(ProcessVersionInfoCompanyName)
| where InitiatingProcessFileName has_any (SuspiciousParents)
| project Timestamp, DeviceName, AccountName, FolderPath, FileName,
ProcessCommandLine, InitiatingProcessFileName,
InitiatingProcessCommandLine, SHA256, Signal="UnsignedTempDirExecution";
// Combine all signals
NewExecutablesFromSuspiciousParents
| union HighCPULowIO
| union SuspiciousScriptExecution
| union TempDirExecution
| summarize Signals=make_set(Signal), AlertCount=count(),
EarliestActivity=min(Timestamp), LatestActivity=max(Timestamp),
CommandLines=make_set(ProcessCommandLine, 5),
Hashes=make_set(SHA256, 5)
by DeviceName, AccountName, FileName, FolderPath, InitiatingProcessFileName
| extend SignalCount = array_length(Signals)
| where SignalCount >= 1
| sort by SignalCount desc, AlertCount desc Detects behavioral indicators associated with binaries or scripts employing junk code insertion techniques. Since junk code itself is a static binary characteristic not directly observable through standard event telemetry, this detection focuses on correlated behavioral signals: executables dropped by suspicious parent processes with no version info (commonly seen in packed/obfuscated malware), excessive string concatenation in scripts (Kimsuky/FIN7 pattern), and unsigned binaries executing from user-writable directories. The query unions four signal types and summarizes by host/file to highlight multi-signal events for prioritization.
Data Sources
Required Tables
False Positives & Tuning
- Legitimate software installers that extract temporary executables to %TEMP% directories during installation (e.g., NSIS, Inno Setup installers)
- Developer tools and build systems (MSBuild, Roslyn compilers) generating intermediate binaries without version metadata in temp directories
- Scripting automation tools using heavy string concatenation for legitimate data manipulation or template generation
- Third-party software lacking version information metadata (many open-source or legacy applications omit this field)
- Security testing tools and penetration testing frameworks that intentionally lack signatures
Other platforms for T1027.016
Testing Methodology
Validate this detection against 4 adversary techniques from Atomic Red Team. Each test below lists the behaviour to exercise and the telemetry you should expect to see. Executable commands and cleanup steps are available with Pro.
- Test 1PowerShell Script with Excessive String Concatenation Junk Code
Expected signal: Sysmon Event ID 1: Process Create with Image=powershell.exe, CommandLine containing excessive variable concatenation. PowerShell ScriptBlock Log Event ID 4104 will show full script with dead variable assignments and Invoke-Expression. The final executed command 'whoami' will also appear in script block logs.
- Test 2VBScript with Dead Code Padding (chr() Concatenation Pattern)
Expected signal: Sysmon Event ID 11: File Create for %TEMP%\junktest.vbs (created by cmd.exe). Sysmon Event ID 1: Process Create for cscript.exe executing junktest.vbs. Sysmon Event ID 1: Child process cmd.exe spawned by cscript.exe with whoami command. Sysmon Event ID 11: File Create for %TEMP%\vbsout.txt.
- Test 3Compile and Execute Binary with NOP Sled Simulation via Inline Assembly
Expected signal: Sysmon Event ID 1: PowerShell.exe process with Add-Type command. Sysmon Event ID 11: File Create for %TEMP%\junkcode_test.exe compiled by csc.exe (invoked by Add-Type). Sysmon Event ID 1: Execution of junkcode_test.exe from %TEMP% directory. PowerShell ScriptBlock Log Event ID 4104 showing the source code with NOP-equivalent patterns.
- Test 4Batch File with Dead Code Branches and Junk Variable Inflation
Expected signal: Sysmon Event ID 11: File Create for %TEMP%\junkbatch.bat. Sysmon Event ID 1: cmd.exe executing junkbatch.bat from %TEMP%. Sysmon Event ID 1: Child cmd.exe process executing whoami. Sysmon Event ID 11: File Create for %TEMP%\batchout.txt. Security Event ID 4688 (if process creation auditing enabled) for all cmd.exe instances.
References (12)
- https://attack.mitre.org/techniques/T1027/016/
- https://cyberpedia.reasonlabs.com/EN/dead%20code%20insertion.html
- https://cyberpedia.reasonlabs.com/EN/junk%20code.html
- https://www.mcafee.com/blogs/other-blogs/mcafee-labs/maze-ransomware-no-promised-decryption-key-after-ransom-payment/
- https://www.welivesecurity.com/2016/10/25/lifting-lid-sednit-closer-look-group/
- https://www.mandiant.com/resources/blog/fin7-shim-databases-persistence
- https://www.welivesecurity.com/2020/06/11/gamaredon-group-grows-its-game/
- https://research.nccgroup.com/2020/06/23/wastedlocker-a-new-ransomware-variant-developed-by-the-evil-corp-group/
- https://www.cybereason.com/blog/operation-cobalt-kitty-apt
- https://github.com/redcanaryco/atomic-red-team/blob/master/atomics/T1027/T1027.md
- https://github.com/SigmaHQ/sigma/tree/master/rules/windows
- https://docs.microsoft.com/en-us/windows/security/threat-protection/windows-defender-application-control/microsoft-recommended-block-rules
Unlock Pro Content
Get the full detection package for T1027.016 including response playbook, investigation guide, and atomic red team tests.