[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6GXASFTSH559NES6XG4046H":3,"skill-same:01M6GXASFTSH559NES6XG4046H":102},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":38,"linkOnly":39,"markdownContent":40,"markdownBody":41,"frontMatter":42,"refName":46,"commitSha":47,"skillDirectory":48,"forksCount":49,"repositoryHtmlUrl":50,"repositoryHomepageUrl":6,"ownerHtmlUrl":51,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":52,"install":53,"resources":66},"01M6GXASFTSH559NES6XG4046H","deobfuscating-powershell-obfuscated-malware",null,"Systematically deobfuscate multi-layer PowerShell malware using AST analysis, dynamic tracing, and tools like PSDecode and PowerDecode to reveal hidden payloads and C2 infrastructure.","micsapp\u002Fmicstec-skills","micsapp","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F82411001?v=4","01M6GWCFQ6D3PV8EHNY62NN5VW","01M6GWCFVE1PA5HG0DKC7AMFJ3",4,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002F_universal\u002Fcybersecurity-skills\u002Fskills\u002Fdeobfuscating-powershell-obfuscated-malware\u002FSKILL.md",[],[18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37],"malware","powershell","deobfuscating powershell obfuscated malware","obfuscation","layer","multi","incident","payloads","ast","analysis","Tools","ast-analysis","cybersecurity","scripting","deobfuscation","incident-response","malware-analysis","c2","tracing","infrastructure","2026-11-10 10:12:30",false,"---\nname: deobfuscating-powershell-obfuscated-malware\ndescription: Systematically deobfuscate multi-layer PowerShell malware using AST analysis, dynamic tracing, and tools like PSDecode and PowerDecode to reveal hidden payloads and C2 infrastructure.\ndomain: cybersecurity\nsubdomain: malware-analysis\ntags: [powershell, deobfuscation, malware-analysis, scripting, obfuscation, ast-analysis, incident-response]\nversion: \"1.0\"\nauthor: mahipal\nlicense: Apache-2.0\n---\n# Deobfuscating PowerShell Obfuscated Malware\n\n## Overview\n\nPowerShell is heavily abused by malware authors due to its deep Windows integration and powerful scripting capabilities. Obfuscation techniques include string concatenation, Base64 encoding, character substitution, Invoke-Expression layering, SecureString abuse, environment variable manipulation, and tick-mark insertion. Modern malware uses multiple obfuscation layers requiring iterative deobfuscation. Tools like PSDecode, PowerDecode, and PowerPeeler automate much of this process, while manual AST (Abstract Syntax Tree) analysis handles custom obfuscation. PowerPeeler achieves a 95% deobfuscation correctness rate using instruction-level dynamic analysis of expression-related AST nodes.\n\n\n## When to Use\n\n- When performing authorized security testing that involves deobfuscating powershell obfuscated malware\n- When analyzing malware samples or attack artifacts in a controlled environment\n- When conducting red team exercises or penetration testing engagements\n- When building detection capabilities based on offensive technique understanding\n\n## Prerequisites\n\n- Python 3.9+ with `base64`, `re`, `subprocess` modules\n- PowerShell 5.1+ or PowerShell 7+ (for AST access)\n- PSDecode (`Install-Module PSDecode`)\n- PowerDecode (https:\u002F\u002Fgithub.com\u002FMalandrone\u002FPowerDecode)\n- Isolated VM or sandbox for safe script execution\n- CyberChef for manual encoding transformations\n- Understanding of PowerShell AST and Invoke-Expression patterns\n\n## Key Concepts\n\n### Common Obfuscation Techniques\n\nPowerShell malware employs layered obfuscation to evade static detection. String concatenation splits commands across variables (`$a='In'+'voke'`). Base64 encoding wraps entire scripts in `-EncodedCommand` parameters. Character code arrays use `[char]` casting (`[char[]](73,69,88)|%{$r+=$_}`). Environment variable abuse reads substrings from `$env:` paths. Tick-mark insertion adds backticks between characters that PowerShell ignores (`I`nv`oke-Exp`ression`). SecureString conversion encrypts strings using ConvertTo-SecureString with embedded keys.\n\n### AST-Based Deobfuscation\n\nPowerShell's Abstract Syntax Tree exposes the parsed structure of scripts regardless of surface-level obfuscation. By walking the AST and evaluating expression nodes, analysts can resolve concatenated strings, decode encoded values, and reconstruct the original commands. PowerPeeler uses this approach at the instruction level, monitoring the execution process to correlate AST nodes with their evaluated results.\n\n### Dynamic Execution Tracing\n\nBy replacing `Invoke-Expression` (IEX) with `Write-Output`, analysts can safely capture the deobfuscated script content that would normally be executed. This technique works across multiple layers by iteratively replacing IEX calls until the final payload is revealed.\n\n## Workflow\n\n### Step 1: Identify Obfuscation Layers\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"Identify and classify PowerShell obfuscation techniques.\"\"\"\nimport re\nimport base64\nimport sys\n\n\ndef analyze_obfuscation(script_content):\n    \"\"\"Identify obfuscation techniques used in PowerShell script.\"\"\"\n    techniques = []\n\n    # Check for Base64 encoded command\n    b64_pattern = re.compile(\n        r'-[Ee](?:nc(?:odedcommand)?)\\s+([A-Za-z0-9+\u002F=]{20,})',\n        re.IGNORECASE\n    )\n    if b64_pattern.search(script_content):\n        techniques.append(\"Base64 EncodedCommand\")\n\n    # Check for FromBase64String\n    if re.search(r'\\[Convert\\]::FromBase64String', script_content, re.IGNORECASE):\n        techniques.append(\"Base64 FromBase64String\")\n\n    # Check for string concatenation\n    concat_count = script_content.count(\"'+'\") + script_content.count('\"+\"')\n    if concat_count > 3:\n        techniques.append(f\"String Concatenation ({concat_count} joins)\")\n\n    # Check for char array construction\n    if re.search(r'\\[char\\]\\s*\\d+', script_content, re.IGNORECASE):\n        techniques.append(\"Character Code Array\")\n\n    # Check for Invoke-Expression variants\n    iex_patterns = [\n        r'Invoke-Expression',\n        r'\\bIEX\\b',\n        r'\\.\\s*\\(\\s*\\$',\n        r'&\\s*\\(\\s*\\$',\n        r'\\|\\s*IEX',\n        r'\\|\\s*Invoke-Expression',\n    ]\n    for pattern in iex_patterns:\n        if re.search(pattern, script_content, re.IGNORECASE):\n            techniques.append(f\"Invoke-Expression variant: {pattern}\")\n\n    # Check for tick-mark obfuscation\n    tick_count = script_content.count('`')\n    if tick_count > 5:\n        techniques.append(f\"Tick-mark Insertion ({tick_count} backticks)\")\n\n    # Check for environment variable abuse\n    if re.search(r'\\$env:', script_content, re.IGNORECASE):\n        env_refs = re.findall(r'\\$env:\\w+', script_content, re.IGNORECASE)\n        if len(env_refs) > 2:\n            techniques.append(f\"Environment Variable Abuse ({len(env_refs)} refs)\")\n\n    # Check for SecureString\n    if re.search(r'ConvertTo-SecureString', script_content, re.IGNORECASE):\n        techniques.append(\"SecureString Encryption\")\n\n    # Check for compression\n    if re.search(r'IO\\.Compression|DeflateStream|GZipStream',\n                 script_content, re.IGNORECASE):\n        techniques.append(\"Compression (Deflate\u002FGZip)\")\n\n    # Check for XOR encoding\n    if re.search(r'-bxor\\s+\\d+', script_content, re.IGNORECASE):\n        techniques.append(\"XOR Encoding\")\n\n    # Check for Replace chain\n    replace_count = len(re.findall(r'\\.Replace\\(', script_content))\n    if replace_count > 2:\n        techniques.append(f\"Replace Chain ({replace_count} replacements)\")\n\n    return techniques\n\n\ndef decode_base64_command(script_content):\n    \"\"\"Extract and decode Base64 encoded commands.\"\"\"\n    b64_match = re.search(\n        r'-[Ee](?:nc(?:odedcommand)?)\\s+([A-Za-z0-9+\u002F=]{20,})',\n        script_content, re.IGNORECASE\n    )\n    if b64_match:\n        encoded = b64_match.group(1)\n        try:\n            decoded = base64.b64decode(encoded).decode('utf-16-le')\n            return decoded\n        except Exception:\n            return None\n    return None\n\n\ndef remove_tick_marks(script_content):\n    \"\"\"Remove PowerShell tick-mark obfuscation.\"\"\"\n    # Remove backticks that are not escape sequences\n    escape_chars = {'`n', '`r', '`t', '`a', '`b', '`f', '`v', '`0', '``'}\n    result = []\n    i = 0\n    while i \u003C len(script_content):\n        if script_content[i] == '`' and i + 1 \u003C len(script_content):\n            pair = script_content[i:i+2]\n            if pair in escape_chars:\n                result.append(pair)\n                i += 2\n            else:\n                # Skip the backtick, keep the next char\n                result.append(script_content[i+1])\n                i += 2\n        else:\n            result.append(script_content[i])\n            i += 1\n    return ''.join(result)\n\n\ndef resolve_string_concat(script_content):\n    \"\"\"Resolve simple string concatenation patterns.\"\"\"\n    # Pattern: 'str1' + 'str2'\n    pattern = re.compile(r\"'([^']*)'\\s*\\+\\s*'([^']*)'\")\n    while pattern.search(script_content):\n        script_content = pattern.sub(lambda m: f\"'{m.group(1)}{m.group(2)}'\",\n                                      script_content)\n    # Pattern: \"str1\" + \"str2\"\n    pattern = re.compile(r'\"([^\"]*)\"\\s*\\+\\s*\"([^\"]*)\"')\n    while pattern.search(script_content):\n        script_content = pattern.sub(lambda m: f'\"{m.group(1)}{m.group(2)}\"',\n                                      script_content)\n    return script_content\n\n\nif __name__ == \"__main__\":\n    if len(sys.argv) \u003C 2:\n        print(f\"Usage: {sys.argv[0]} \u003Cpowershell_script>\")\n        sys.exit(1)\n\n    with open(sys.argv[1], 'r', errors='replace') as f:\n        content = f.read()\n\n    print(\"[+] Obfuscation Analysis\")\n    print(\"=\" * 60)\n    techniques = analyze_obfuscation(content)\n    for t in techniques:\n        print(f\"  - {t}\")\n\n    # Attempt automatic deobfuscation\n    print(\"\\n[+] Attempting Deobfuscation\")\n    print(\"=\" * 60)\n\n    # Layer 1: Remove tick marks\n    deobfuscated = remove_tick_marks(content)\n\n    # Layer 2: Resolve string concatenation\n    deobfuscated = resolve_string_concat(deobfuscated)\n\n    # Layer 3: Decode Base64\n    b64_decoded = decode_base64_command(deobfuscated)\n    if b64_decoded:\n        print(\"[+] Base64 decoded content:\")\n        print(b64_decoded[:2000])\n        deobfuscated = b64_decoded\n\n    print(f\"\\n[+] Deobfuscated script length: {len(deobfuscated)} chars\")\n    output_file = sys.argv[1] + \".deobfuscated.ps1\"\n    with open(output_file, 'w') as f:\n        f.write(deobfuscated)\n    print(f\"[+] Saved to {output_file}\")\n```\n\n### Step 2: Multi-Layer IEX Replacement\n\n```python\nimport subprocess\nimport tempfile\nimport os\n\ndef iex_replacement_deobfuscate(script_content, max_layers=10):\n    \"\"\"Iteratively replace IEX with Write-Output to unwrap layers.\"\"\"\n    # IEX replacement patterns\n    replacements = [\n        (r'\\bInvoke-Expression\\b', 'Write-Output'),\n        (r'\\bIEX\\b', 'Write-Output'),\n        (r'\\|\\s*IEX\\b', '| Write-Output'),\n    ]\n\n    current = script_content\n    layers = []\n\n    for layer_num in range(max_layers):\n        # Apply IEX replacements\n        modified = current\n        for pattern, replacement in replacements:\n            modified = re.sub(pattern, replacement, modified, flags=re.IGNORECASE)\n\n        if modified == current and layer_num > 0:\n            print(f\"  [+] No more IEX layers found at layer {layer_num}\")\n            break\n\n        # Write to temp file and execute in constrained PowerShell\n        with tempfile.NamedTemporaryFile(mode='w', suffix='.ps1',\n                                          delete=False) as tmp:\n            tmp.write(modified)\n            tmp_path = tmp.name\n\n        try:\n            result = subprocess.run(\n                ['powershell', '-NoProfile', '-ExecutionPolicy', 'Bypass',\n                 '-File', tmp_path],\n                capture_output=True, text=True, timeout=30\n            )\n\n            output = result.stdout.strip()\n            if output and output != current:\n                print(f\"  [+] Layer {layer_num + 1}: Unwrapped \"\n                      f\"{len(output)} chars\")\n                layers.append({\n                    \"layer\": layer_num + 1,\n                    \"technique\": \"IEX replacement\",\n                    \"content_length\": len(output),\n                })\n                current = output\n            else:\n                break\n\n        except subprocess.TimeoutExpired:\n            print(f\"  [!] Layer {layer_num + 1}: Execution timeout\")\n            break\n        finally:\n            os.unlink(tmp_path)\n\n    return current, layers\n```\n\n### Step 3: Extract IOCs from Deobfuscated Script\n\n```python\ndef extract_iocs_from_script(deobfuscated_content):\n    \"\"\"Extract indicators of compromise from deobfuscated PowerShell.\"\"\"\n    iocs = {\n        \"urls\": [],\n        \"ips\": [],\n        \"domains\": [],\n        \"file_paths\": [],\n        \"registry_keys\": [],\n        \"commands\": [],\n        \"base64_blobs\": [],\n    }\n\n    # URLs\n    url_pattern = re.compile(\n        r'https?:\u002F\u002F[^\\s\\'\"\u003C>)\\]]+', re.IGNORECASE\n    )\n    iocs[\"urls\"] = list(set(url_pattern.findall(deobfuscated_content)))\n\n    # IP addresses\n    ip_pattern = re.compile(\n        r'\\b(?:\\d{1,3}\\.){3}\\d{1,3}\\b'\n    )\n    iocs[\"ips\"] = list(set(ip_pattern.findall(deobfuscated_content)))\n\n    # File paths\n    path_pattern = re.compile(\n        r'[A-Za-z]:\\\\[^\\s\\'\"\u003C>|]+|'\n        r'\\\\\\\\[^\\s\\'\"\u003C>|]+|'\n        r'%(?:APPDATA|TEMP|USERPROFILE|PROGRAMFILES)%[^\\s\\'\"\u003C>|]*',\n        re.IGNORECASE\n    )\n    iocs[\"file_paths\"] = list(set(path_pattern.findall(deobfuscated_content)))\n\n    # Registry keys\n    reg_pattern = re.compile(\n        r'(?:HKLM|HKCU|HKCR|HKU|HKCC)(?:\\\\[^\\s\\'\"\u003C>|]+)+',\n        re.IGNORECASE\n    )\n    iocs[\"registry_keys\"] = list(set(reg_pattern.findall(deobfuscated_content)))\n\n    # Suspicious commands\n    suspicious_cmds = [\n        'New-Object Net.WebClient',\n        'DownloadString', 'DownloadFile', 'DownloadData',\n        'Start-Process', 'Invoke-WebRequest',\n        'New-Object IO.MemoryStream',\n        'Reflection.Assembly',\n        'Add-MpPreference -ExclusionPath',\n        'Set-MpPreference -DisableRealtimeMonitoring',\n        'New-ScheduledTask', 'Register-ScheduledTask',\n    ]\n    for cmd in suspicious_cmds:\n        if cmd.lower() in deobfuscated_content.lower():\n            iocs[\"commands\"].append(cmd)\n\n    return iocs\n```\n\n## Validation Criteria\n\n- All obfuscation layers identified and classified correctly\n- Base64 encoded commands decoded to readable PowerShell\n- Tick-mark and string concatenation obfuscation resolved\n- IEX replacement reveals next-stage payloads\n- URLs, IPs, and file paths extracted from final deobfuscated stage\n- Deobfuscated script matches observed malware behavior in sandbox\n\n## References\n\n- [PSDecode - PowerShell Deobfuscation](https:\u002F\u002Fgithub.com\u002FR3MRUM\u002FPSDecode)\n- [PowerDecode - Multi-layer Deobfuscation](https:\u002F\u002Fgithub.com\u002FMalandrone\u002FPowerDecode)\n- [PowerPeeler - Instruction-level Deobfuscation](https:\u002F\u002Farxiv.org\u002Fhtml\u002F2406.04027v2)\n- [SentinelOne - Deconstructing PowerShell Obfuscation](https:\u002F\u002Fwww.sentinelone.com\u002Fblog\u002Fdeconstructing-powershell-obfuscation-in-malspam-campaigns\u002F)\n- [MITRE ATT&CK T1059.001 - PowerShell](https:\u002F\u002Fattack.mitre.org\u002Ftechniques\u002FT1059\u002F001\u002F)\n","# Deobfuscating PowerShell Obfuscated Malware\n\n## Overview\n\nPowerShell is heavily abused by malware authors due to its deep Windows integration and powerful scripting capabilities. Obfuscation techniques include string concatenation, Base64 encoding, character substitution, Invoke-Expression layering, SecureString abuse, environment variable manipulation, and tick-mark insertion. Modern malware uses multiple obfuscation layers requiring iterative deobfuscation. Tools like PSDecode, PowerDecode, and PowerPeeler automate much of this process, while manual AST (Abstract Syntax Tree) analysis handles custom obfuscation. PowerPeeler achieves a 95% deobfuscation correctness rate using instruction-level dynamic analysis of expression-related AST nodes.\n\n\n## When to Use\n\n- When performing authorized security testing that involves deobfuscating powershell obfuscated malware\n- When analyzing malware samples or attack artifacts in a controlled environment\n- When conducting red team exercises or penetration testing engagements\n- When building detection capabilities based on offensive technique understanding\n\n## Prerequisites\n\n- Python 3.9+ with `base64`, `re`, `subprocess` modules\n- PowerShell 5.1+ or PowerShell 7+ (for AST access)\n- PSDecode (`Install-Module PSDecode`)\n- PowerDecode (https:\u002F\u002Fgithub.com\u002FMalandrone\u002FPowerDecode)\n- Isolated VM or sandbox for safe script execution\n- CyberChef for manual encoding transformations\n- Understanding of PowerShell AST and Invoke-Expression patterns\n\n## Key Concepts\n\n### Common Obfuscation Techniques\n\nPowerShell malware employs layered obfuscation to evade static detection. String concatenation splits commands across variables (`$a='In'+'voke'`). Base64 encoding wraps entire scripts in `-EncodedCommand` parameters. Character code arrays use `[char]` casting (`[char[]](73,69,88)|%{$r+=$_}`). Environment variable abuse reads substrings from `$env:` paths. Tick-mark insertion adds backticks between characters that PowerShell ignores (`I`nv`oke-Exp`ression`). SecureString conversion encrypts strings using ConvertTo-SecureString with embedded keys.\n\n### AST-Based Deobfuscation\n\nPowerShell's Abstract Syntax Tree exposes the parsed structure of scripts regardless of surface-level obfuscation. By walking the AST and evaluating expression nodes, analysts can resolve concatenated strings, decode encoded values, and reconstruct the original commands. PowerPeeler uses this approach at the instruction level, monitoring the execution process to correlate AST nodes with their evaluated results.\n\n### Dynamic Execution Tracing\n\nBy replacing `Invoke-Expression` (IEX) with `Write-Output`, analysts can safely capture the deobfuscated script content that would normally be executed. This technique works across multiple layers by iteratively replacing IEX calls until the final payload is revealed.\n\n## Workflow\n\n### Step 1: Identify Obfuscation Layers\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"Identify and classify PowerShell obfuscation techniques.\"\"\"\nimport re\nimport base64\nimport sys\n\n\ndef analyze_obfuscation(script_content):\n    \"\"\"Identify obfuscation techniques used in PowerShell script.\"\"\"\n    techniques = []\n\n    # Check for Base64 encoded command\n    b64_pattern = re.compile(\n        r'-[Ee](?:nc(?:odedcommand)?)\\s+([A-Za-z0-9+\u002F=]{20,})',\n        re.IGNORECASE\n    )\n    if b64_pattern.search(script_content):\n        techniques.append(\"Base64 EncodedCommand\")\n\n    # Check for FromBase64String\n    if re.search(r'\\[Convert\\]::FromBase64String', script_content, re.IGNORECASE):\n        techniques.append(\"Base64 FromBase64String\")\n\n    # Check for string concatenation\n    concat_count = script_content.count(\"'+'\") + script_content.count('\"+\"')\n    if concat_count > 3:\n        techniques.append(f\"String Concatenation ({concat_count} joins)\")\n\n    # Check for char array construction\n    if re.search(r'\\[char\\]\\s*\\d+', script_content, re.IGNORECASE):\n        techniques.append(\"Character Code Array\")\n\n    # Check for Invoke-Expression variants\n    iex_patterns = [\n        r'Invoke-Expression',\n        r'\\bIEX\\b',\n        r'\\.\\s*\\(\\s*\\$',\n        r'&\\s*\\(\\s*\\$',\n        r'\\|\\s*IEX',\n        r'\\|\\s*Invoke-Expression',\n    ]\n    for pattern in iex_patterns:\n        if re.search(pattern, script_content, re.IGNORECASE):\n            techniques.append(f\"Invoke-Expression variant: {pattern}\")\n\n    # Check for tick-mark obfuscation\n    tick_count = script_content.count('`')\n    if tick_count > 5:\n        techniques.append(f\"Tick-mark Insertion ({tick_count} backticks)\")\n\n    # Check for environment variable abuse\n    if re.search(r'\\$env:', script_content, re.IGNORECASE):\n        env_refs = re.findall(r'\\$env:\\w+', script_content, re.IGNORECASE)\n        if len(env_refs) > 2:\n            techniques.append(f\"Environment Variable Abuse ({len(env_refs)} refs)\")\n\n    # Check for SecureString\n    if re.search(r'ConvertTo-SecureString', script_content, re.IGNORECASE):\n        techniques.append(\"SecureString Encryption\")\n\n    # Check for compression\n    if re.search(r'IO\\.Compression|DeflateStream|GZipStream',\n                 script_content, re.IGNORECASE):\n        techniques.append(\"Compression (Deflate\u002FGZip)\")\n\n    # Check for XOR encoding\n    if re.search(r'-bxor\\s+\\d+', script_content, re.IGNORECASE):\n        techniques.append(\"XOR Encoding\")\n\n    # Check for Replace chain\n    replace_count = len(re.findall(r'\\.Replace\\(', script_content))\n    if replace_count > 2:\n        techniques.append(f\"Replace Chain ({replace_count} replacements)\")\n\n    return techniques\n\n\ndef decode_base64_command(script_content):\n    \"\"\"Extract and decode Base64 encoded commands.\"\"\"\n    b64_match = re.search(\n        r'-[Ee](?:nc(?:odedcommand)?)\\s+([A-Za-z0-9+\u002F=]{20,})',\n        script_content, re.IGNORECASE\n    )\n    if b64_match:\n        encoded = b64_match.group(1)\n        try:\n            decoded = base64.b64decode(encoded).decode('utf-16-le')\n            return decoded\n        except Exception:\n            return None\n    return None\n\n\ndef remove_tick_marks(script_content):\n    \"\"\"Remove PowerShell tick-mark obfuscation.\"\"\"\n    # Remove backticks that are not escape sequences\n    escape_chars = {'`n', '`r', '`t', '`a', '`b', '`f', '`v', '`0', '``'}\n    result = []\n    i = 0\n    while i \u003C len(script_content):\n        if script_content[i] == '`' and i + 1 \u003C len(script_content):\n            pair = script_content[i:i+2]\n            if pair in escape_chars:\n                result.append(pair)\n                i += 2\n            else:\n                # Skip the backtick, keep the next char\n                result.append(script_content[i+1])\n                i += 2\n        else:\n            result.append(script_content[i])\n            i += 1\n    return ''.join(result)\n\n\ndef resolve_string_concat(script_content):\n    \"\"\"Resolve simple string concatenation patterns.\"\"\"\n    # Pattern: 'str1' + 'str2'\n    pattern = re.compile(r\"'([^']*)'\\s*\\+\\s*'([^']*)'\")\n    while pattern.search(script_content):\n        script_content = pattern.sub(lambda m: f\"'{m.group(1)}{m.group(2)}'\",\n                                      script_content)\n    # Pattern: \"str1\" + \"str2\"\n    pattern = re.compile(r'\"([^\"]*)\"\\s*\\+\\s*\"([^\"]*)\"')\n    while pattern.search(script_content):\n        script_content = pattern.sub(lambda m: f'\"{m.group(1)}{m.group(2)}\"',\n                                      script_content)\n    return script_content\n\n\nif __name__ == \"__main__\":\n    if len(sys.argv) \u003C 2:\n        print(f\"Usage: {sys.argv[0]} \u003Cpowershell_script>\")\n        sys.exit(1)\n\n    with open(sys.argv[1], 'r', errors='replace') as f:\n        content = f.read()\n\n    print(\"[+] Obfuscation Analysis\")\n    print(\"=\" * 60)\n    techniques = analyze_obfuscation(content)\n    for t in techniques:\n        print(f\"  - {t}\")\n\n    # Attempt automatic deobfuscation\n    print(\"\\n[+] Attempting Deobfuscation\")\n    print(\"=\" * 60)\n\n    # Layer 1: Remove tick marks\n    deobfuscated = remove_tick_marks(content)\n\n    # Layer 2: Resolve string concatenation\n    deobfuscated = resolve_string_concat(deobfuscated)\n\n    # Layer 3: Decode Base64\n    b64_decoded = decode_base64_command(deobfuscated)\n    if b64_decoded:\n        print(\"[+] Base64 decoded content:\")\n        print(b64_decoded[:2000])\n        deobfuscated = b64_decoded\n\n    print(f\"\\n[+] Deobfuscated script length: {len(deobfuscated)} chars\")\n    output_file = sys.argv[1] + \".deobfuscated.ps1\"\n    with open(output_file, 'w') as f:\n        f.write(deobfuscated)\n    print(f\"[+] Saved to {output_file}\")\n```\n\n### Step 2: Multi-Layer IEX Replacement\n\n```python\nimport subprocess\nimport tempfile\nimport os\n\ndef iex_replacement_deobfuscate(script_content, max_layers=10):\n    \"\"\"Iteratively replace IEX with Write-Output to unwrap layers.\"\"\"\n    # IEX replacement patterns\n    replacements = [\n        (r'\\bInvoke-Expression\\b', 'Write-Output'),\n        (r'\\bIEX\\b', 'Write-Output'),\n        (r'\\|\\s*IEX\\b', '| Write-Output'),\n    ]\n\n    current = script_content\n    layers = []\n\n    for layer_num in range(max_layers):\n        # Apply IEX replacements\n        modified = current\n        for pattern, replacement in replacements:\n            modified = re.sub(pattern, replacement, modified, flags=re.IGNORECASE)\n\n        if modified == current and layer_num > 0:\n            print(f\"  [+] No more IEX layers found at layer {layer_num}\")\n            break\n\n        # Write to temp file and execute in constrained PowerShell\n        with tempfile.NamedTemporaryFile(mode='w', suffix='.ps1',\n                                          delete=False) as tmp:\n            tmp.write(modified)\n            tmp_path = tmp.name\n\n        try:\n            result = subprocess.run(\n                ['powershell', '-NoProfile', '-ExecutionPolicy', 'Bypass',\n                 '-File', tmp_path],\n                capture_output=True, text=True, timeout=30\n            )\n\n            output = result.stdout.strip()\n            if output and output != current:\n                print(f\"  [+] Layer {layer_num + 1}: Unwrapped \"\n                      f\"{len(output)} chars\")\n                layers.append({\n                    \"layer\": layer_num + 1,\n                    \"technique\": \"IEX replacement\",\n                    \"content_length\": len(output),\n                })\n                current = output\n            else:\n                break\n\n        except subprocess.TimeoutExpired:\n            print(f\"  [!] Layer {layer_num + 1}: Execution timeout\")\n            break\n        finally:\n            os.unlink(tmp_path)\n\n    return current, layers\n```\n\n### Step 3: Extract IOCs from Deobfuscated Script\n\n```python\ndef extract_iocs_from_script(deobfuscated_content):\n    \"\"\"Extract indicators of compromise from deobfuscated PowerShell.\"\"\"\n    iocs = {\n        \"urls\": [],\n        \"ips\": [],\n        \"domains\": [],\n        \"file_paths\": [],\n        \"registry_keys\": [],\n        \"commands\": [],\n        \"base64_blobs\": [],\n    }\n\n    # URLs\n    url_pattern = re.compile(\n        r'https?:\u002F\u002F[^\\s\\'\"\u003C>)\\]]+', re.IGNORECASE\n    )\n    iocs[\"urls\"] = list(set(url_pattern.findall(deobfuscated_content)))\n\n    # IP addresses\n    ip_pattern = re.compile(\n        r'\\b(?:\\d{1,3}\\.){3}\\d{1,3}\\b'\n    )\n    iocs[\"ips\"] = list(set(ip_pattern.findall(deobfuscated_content)))\n\n    # File paths\n    path_pattern = re.compile(\n        r'[A-Za-z]:\\\\[^\\s\\'\"\u003C>|]+|'\n        r'\\\\\\\\[^\\s\\'\"\u003C>|]+|'\n        r'%(?:APPDATA|TEMP|USERPROFILE|PROGRAMFILES)%[^\\s\\'\"\u003C>|]*',\n        re.IGNORECASE\n    )\n    iocs[\"file_paths\"] = list(set(path_pattern.findall(deobfuscated_content)))\n\n    # Registry keys\n    reg_pattern = re.compile(\n        r'(?:HKLM|HKCU|HKCR|HKU|HKCC)(?:\\\\[^\\s\\'\"\u003C>|]+)+',\n        re.IGNORECASE\n    )\n    iocs[\"registry_keys\"] = list(set(reg_pattern.findall(deobfuscated_content)))\n\n    # Suspicious commands\n    suspicious_cmds = [\n        'New-Object Net.WebClient',\n        'DownloadString', 'DownloadFile', 'DownloadData',\n        'Start-Process', 'Invoke-WebRequest',\n        'New-Object IO.MemoryStream',\n        'Reflection.Assembly',\n        'Add-MpPreference -ExclusionPath',\n        'Set-MpPreference -DisableRealtimeMonitoring',\n        'New-ScheduledTask', 'Register-ScheduledTask',\n    ]\n    for cmd in suspicious_cmds:\n        if cmd.lower() in deobfuscated_content.lower():\n            iocs[\"commands\"].append(cmd)\n\n    return iocs\n```\n\n## Validation Criteria\n\n- All obfuscation layers identified and classified correctly\n- Base64 encoded commands decoded to readable PowerShell\n- Tick-mark and string concatenation obfuscation resolved\n- IEX replacement reveals next-stage payloads\n- URLs, IPs, and file paths extracted from final deobfuscated stage\n- Deobfuscated script matches observed malware behavior in sandbox\n\n## References\n\n- [PSDecode - PowerShell Deobfuscation](https:\u002F\u002Fgithub.com\u002FR3MRUM\u002FPSDecode)\n- [PowerDecode - Multi-layer Deobfuscation](https:\u002F\u002Fgithub.com\u002FMalandrone\u002FPowerDecode)\n- [PowerPeeler - Instruction-level Deobfuscation](https:\u002F\u002Farxiv.org\u002Fhtml\u002F2406.04027v2)\n- [SentinelOne - Deconstructing PowerShell Obfuscation](https:\u002F\u002Fwww.sentinelone.com\u002Fblog\u002Fdeconstructing-powershell-obfuscation-in-malspam-campaigns\u002F)\n- [MITRE ATT&CK T1059.001 - PowerShell](https:\u002F\u002Fattack.mitre.org\u002Ftechniques\u002FT1059\u002F001\u002F)\n",{"name":5,"tags":43,"author":44,"domain":30,"license":14,"version":45,"subdomain":34,"description":7},[19,32,34,31,21,29,33],"mahipal","1.0","master","3f5d983eb4ef375b749adcd6b07ec03bd82ae8a8","_universal\u002Fcybersecurity-skills\u002Fskills\u002Fdeobfuscating-powershell-obfuscated-malware",0,"https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills","https:\u002F\u002Fgithub.com\u002Fmicsapp","2026-03-20 11:24:18",{"source":8,"skillName":5,"commands":54,"prompt":64,"zipAvailable":65},[55,58,61],{"tool":56,"command":57},"npx","npx skills add micsapp\u002Fmicstec-skills --skill deobfuscating-powershell-obfuscated-malware",{"tool":59,"command":60},"bunx","bunx skills add micsapp\u002Fmicstec-skills --skill deobfuscating-powershell-obfuscated-malware",{"tool":62,"command":63},"pnpm","pnpm dlx skills add micsapp\u002Fmicstec-skills --skill deobfuscating-powershell-obfuscated-malware","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002F_universal\u002Fcybersecurity-skills\u002Fskills\u002Fdeobfuscating-powershell-obfuscated-malware\u002FSKILL.md",true,[67,73,78,84,88,92,98],{"path":68,"resourceType":69,"resourceTypeDesc":70,"sizeBytes":71,"sourceHtmlUrl":72},"assets\u002Ftemplate.md","ASSET","资产文件",1353,"https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002F_universal\u002Fcybersecurity-skills\u002Fskills\u002Fdeobfuscating-powershell-obfuscated-malware\u002Fassets\u002Ftemplate.md",{"path":74,"resourceType":74,"resourceTypeDesc":75,"sizeBytes":76,"sourceHtmlUrl":77},"LICENSE","许可证",11255,"https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002F_universal\u002Fcybersecurity-skills\u002Fskills\u002Fdeobfuscating-powershell-obfuscated-malware\u002FLICENSE",{"path":79,"resourceType":80,"resourceTypeDesc":81,"sizeBytes":82,"sourceHtmlUrl":83},"references\u002Fapi-reference.md","REFERENCE","参考文档",1425,"https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002F_universal\u002Fcybersecurity-skills\u002Fskills\u002Fdeobfuscating-powershell-obfuscated-malware\u002Freferences\u002Fapi-reference.md",{"path":85,"resourceType":80,"resourceTypeDesc":81,"sizeBytes":86,"sourceHtmlUrl":87},"references\u002Fstandards.md",1907,"https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002F_universal\u002Fcybersecurity-skills\u002Fskills\u002Fdeobfuscating-powershell-obfuscated-malware\u002Freferences\u002Fstandards.md",{"path":89,"resourceType":80,"resourceTypeDesc":81,"sizeBytes":90,"sourceHtmlUrl":91},"references\u002Fworkflows.md",2348,"https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002F_universal\u002Fcybersecurity-skills\u002Fskills\u002Fdeobfuscating-powershell-obfuscated-malware\u002Freferences\u002Fworkflows.md",{"path":93,"resourceType":94,"resourceTypeDesc":95,"sizeBytes":96,"sourceHtmlUrl":97},"scripts\u002Fagent.py","SCRIPT","脚本",5229,"https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002F_universal\u002Fcybersecurity-skills\u002Fskills\u002Fdeobfuscating-powershell-obfuscated-malware\u002Fscripts\u002Fagent.py",{"path":99,"resourceType":94,"resourceTypeDesc":95,"sizeBytes":100,"sourceHtmlUrl":101},"scripts\u002Fprocess.py",10939,"https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002F_universal\u002Fcybersecurity-skills\u002Fskills\u002Fdeobfuscating-powershell-obfuscated-malware\u002Fscripts\u002Fprocess.py",[103,141,170,191,211,236],{"skillNo":104,"name":105,"nameZh":6,"description":106,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":107,"licenseFileUrl":6,"sourceHtmlUrl":108,"categories":109,"keywords":120,"publishedAt":38},"01M6HBTJ02FXBFG9NYEHHYAP52","azure-apim-architecture","Analyzes and explains Azure API Management architecture decisions for enterprise API marketplace implementations using VNet Internal mode, Front Door, hybrid authentication, and multi-environment strategies. Use when discussing APIM component selection, network topology, cost optimization, or comparing alternatives like workspaces vs instances, VNet Internal vs External mode, or Front Door vs Application Gateway.","MIT","https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002Fcopilot-cli\u002Fcopilot-agent-skills\u002F.github\u002Fskills\u002Fazure-apim-architecture\u002FSKILL.md",[110,115],{"categoryNo":111,"categoryName":112,"taxonomyType":113,"taxonomyTypeDesc":114},"01JBSEEDCAT000000000000010","后端与接口","SCENARIO","使用场景",{"categoryNo":116,"categoryName":117,"taxonomyType":118,"taxonomyTypeDesc":119},"01JBSEEDCAT000000000000030","开发工程师","PROFESSION","适用职业",[121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140],"architecture","azure","azure apim architecture","component","authentication","gateway","topology","Optimization","network","api","team","environment","multi-environment","workspaces","instances","selection","strategies","azure api management","mode","for",{"skillNo":142,"name":143,"nameZh":6,"description":144,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":107,"licenseFileUrl":6,"sourceHtmlUrl":145,"categories":146,"keywords":155,"publishedAt":38},"01M6HBT7J4H082JEEA670B3EQ9","apiops-deployment","Guides deployment of Azure API Management infrastructure using Infrastructure as Code (Bicep\u002FTerraform), CI\u002FCD pipelines (GitHub Actions\u002FAzure DevOps), and APIOps workflows. Use when deploying APIM, creating pipelines, or implementing dev→test→prod promotion strategies.","https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002Fcopilot-cli\u002Fcopilot-agent-skills\u002F.github\u002Fskills\u002Fapiops-deployment\u002FSKILL.md",[147,148,151,154],{"categoryNo":111,"categoryName":112,"taxonomyType":113,"taxonomyTypeDesc":114},{"categoryNo":149,"categoryName":150,"taxonomyType":113,"taxonomyTypeDesc":114},"01JBSEEDCAT000000000000011","运维与部署",{"categoryNo":152,"categoryName":153,"taxonomyType":113,"taxonomyTypeDesc":114},"01JBSEEDCAT000000000000023","Skill与智能体开发",{"categoryNo":116,"categoryName":117,"taxonomyType":118,"taxonomyTypeDesc":119},[156,157,158,159,122,37,160,161,162,163,164,165,130,131,137,166,167,138,168,169],"deployment","apiops deployment","workflows","azure devops","code","infrastructure as code","actions","ci","github actions","github-actions","as","guides","CI\u002FCD","implementing",{"skillNo":171,"name":172,"nameZh":6,"description":173,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":107,"licenseFileUrl":6,"sourceHtmlUrl":174,"categories":175,"keywords":177,"publishedAt":38},"01M6HBT2HEA23THNE9E00GYQBE","apim-policy-authoring","Creates production-ready Azure API Management policy XML for authentication (OAuth 2.0, JWT validation, subscription keys), rate limiting, CORS configuration, error handling, and API transformations. Use when implementing API security, access control, or request\u002Fresponse processing logic.","https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002Fcopilot-cli\u002Fcopilot-agent-skills\u002F.github\u002Fskills\u002Fapim-policy-authoring\u002FSKILL.md",[176],{"categoryNo":111,"categoryName":112,"taxonomyType":113,"taxonomyTypeDesc":114},[178,179,180,181,122,125,130,131,182,183,184,185,186,187,188,138,189,190,169,140],"policy","authoring","apim policy authoring","security","access","use","ready","api security","Access Control","error","processing","cors configuration","production-ready",{"skillNo":192,"name":193,"nameZh":6,"description":194,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":107,"licenseFileUrl":6,"sourceHtmlUrl":195,"categories":196,"keywords":199,"publishedAt":38},"01M6HBSY65SB29J9WE9KYD0K6T","api-security-review","Reviews Azure API Management configurations for security vulnerabilities, OWASP API Security Top 10 compliance, VNet Internal mode validation, Private Link verification, and Azure Security Benchmark alignment. Use when performing security audits, pre-deployment validation, or compliance reviews.","https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002Fcopilot-cli\u002Fcopilot-agent-skills\u002F.github\u002Fskills\u002Fapi-security-review\u002FSKILL.md",[197,198],{"categoryNo":111,"categoryName":112,"taxonomyType":113,"taxonomyTypeDesc":114},{"categoryNo":116,"categoryName":117,"taxonomyType":118,"taxonomyTypeDesc":119},[200,181,201,130,185,202,122,156,203,204,205,206,131,207,138,208,209,210,139,140],"review","security review","api security review","benchmark","verification","owasp","owasp-api","alignment","azure security","reviews","top",{"skillNo":212,"name":213,"nameZh":6,"description":214,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":107,"licenseFileUrl":6,"sourceHtmlUrl":215,"categories":216,"keywords":217,"publishedAt":38},"01M6HBSRW4PDFE6K4F8JYPZQ05","jira-cli","Interact with Jira from the command line to create, list, view, edit, and transition issues, manage sprints and epics, and perform common Jira workflows. Use when the user asks about Jira tasks, tickets, issues, sprints, or needs to manage project work items.","https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002Fcopilot-cli\u002Fawesome-copilot-agents\u002Fskills\u002Fjira-cli\u002FSKILL.md",[],[218,219,220,158,221,222,223,224,130,225,226,227,228,229,230,231,232,233,234,235],"cli","jira","jira cli","init","tasks","create","issues","common","work","command","edit","list","view","project","project work","token","line","sprints",{"skillNo":237,"name":238,"nameZh":6,"description":239,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":107,"licenseFileUrl":6,"sourceHtmlUrl":240,"categories":241,"keywords":242,"publishedAt":38},"01M6HBSNS3JHMW603G47TWE31H","calculator","Performs arbitrary-precision arithmetic calculations including addition, subtraction, multiplication, division, and exponents. Use when the user asks to calculate, compute, or evaluate math expressions, or when precise decimal arithmetic is needed to avoid floating-point errors.","https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002Fcopilot-cli\u002Fawesome-copilot-agents\u002Fskills\u002Fcalculator\u002FSKILL.md",[],[238,243,244,245,246,247,248,183,249,250],"npm","js","calculate","node","math","user","compute","errors"]