[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M71F0AJ9AY3VBXR48P9XNVXK":3,"skill-same:01M71F0AJ9AY3VBXR48P9XNVXK":63},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":31,"linkOnly":32,"markdownContent":33,"markdownBody":34,"frontMatter":35,"refName":36,"commitSha":37,"skillDirectory":38,"forksCount":14,"repositoryHtmlUrl":39,"repositoryHomepageUrl":6,"ownerHtmlUrl":40,"ownerBlogUrl":6,"ownerDescription":41,"updatedAt":42,"install":43,"resources":56},"01M71F0AJ9AY3VBXR48P9XNVXK","malware-obfuscation-psobfuscation-parse",null,"- [MITRE ATT&CK T1059.001 - PowerShell](https:\u002F\u002Fattack.","DCx7C5\u002Fai-marketplace","DCx7C5","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F42419559?v=4","01M71C01G2AZV3NTNGWAWSHJPP","DC","01M71C01GQW6G50S2BYMS7PP3E",0,"MIT","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fmalware-obfuscation-psobfuscation-parse\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30],"parse","malware obfuscation psobfuscation parse","obfuscation","malware","T1059.001","powershell","ATT&CK","t1059","cybersecurity","https","ck","attack","2026-11-10 10:12:30",false,"---\nname: malware-obfuscation-psobfuscation-parse\ndescription: \"- [MITRE ATT&CK T1059.001 - PowerShell](https:\u002F\u002Fattack.\"\ndomain: cybersecurity\n---\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## 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\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\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\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\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\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## 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\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\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\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\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\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,"domain":27,"description":7},"main","a91f1293287ffa9f4f1b8f486cd6e835a1568c84","skills\u002Fmalware-obfuscation-psobfuscation-parse","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace","https:\u002F\u002Fgithub.com\u002FDCx7C5","#Python","2026-09-01 11:21:00",{"source":8,"skillName":5,"commands":44,"prompt":54,"zipAvailable":55},[45,48,51],{"tool":46,"command":47},"npx","npx skills add DCx7C5\u002Fai-marketplace --skill malware-obfuscation-psobfuscation-parse",{"tool":49,"command":50},"bunx","bunx skills add DCx7C5\u002Fai-marketplace --skill malware-obfuscation-psobfuscation-parse",{"tool":52,"command":53},"pnpm","pnpm dlx skills add DCx7C5\u002Fai-marketplace --skill malware-obfuscation-psobfuscation-parse","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fmalware-obfuscation-psobfuscation-parse\u002FSKILL.md",true,[57],{"path":58,"resourceType":59,"resourceTypeDesc":60,"sizeBytes":61,"sourceHtmlUrl":62},"index.json","REFERENCE","参考文档",571,"https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fmalware-obfuscation-psobfuscation-parse\u002Findex.json",[64,89,112,134,156,172],{"skillNo":65,"name":66,"nameZh":6,"description":67,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":31},"01M71HAPZ01KQ30RKTB0FFSQ05","services-wmi-persistence-detect","Detect WMI event subscription persistence by enumerating ActiveScriptEventConsumer, CommandLineEventConsumer, and permanent subscriptions in the WMI repository.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fservices\u002Fwmi\u002Fpersistence\u002Fdetect\u002FSKILL.md",[],[71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,27,88],"services","detect","services wmi persistence detect","wmi","persistence","de","cm","process","activescript","event","subscriptions","commandline-consumer","repository","subscription","event-subscription","t1546.003","forensics","process-forensics",{"skillNo":90,"name":91,"nameZh":6,"description":92,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":93,"categories":94,"keywords":95,"publishedAt":31},"01M71HAK6JTTTS229T17WJMMCG","services-wmi-exec-exploit","Perform lateral movement across Windows networks using WMI-based remote execution techniques including Impacket wmiexec.py, CrackMapExec, and native WMI commands for stealthy post-exploitation during red team engagements.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fservices\u002Fwmi\u002Fexec\u002Fexploit\u002FSKILL.md",[],[96,71,97,74,98,99,100,27,101,102,103,104,105,106,76,107,108,109,110,111],"exploit","services wmi exec exploit","exec","remote","traffic","Bash","analysis","team","across","crackmapexec","native","command","lateral movement","read","lateral-movement","Impacket",{"skillNo":113,"name":114,"nameZh":6,"description":115,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":116,"categories":117,"keywords":118,"publishedAt":31},"01M71HAG6MHKNQV8KDZKMT4886","registry-artifact-extract","Extract and analyze Windows Registry hives to uncover user activity, installed software, autostart entries, and evidence of system compromise.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fregistry\u002Fartifact\u002Fextract\u002FSKILL.md",[],[119,120,121,122,123,124,27,101,125,102,126,127,76,109,128,129,130,131,132,133],"artifact","registry","registry artifact extract","extract","evidence-collection","artifact-analysis","collection","analyze","uncover","software","activity","digital-forensics","windows-registry","regripper","sonnet",{"skillNo":135,"name":136,"nameZh":6,"description":137,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":138,"categories":139,"keywords":140,"publishedAt":31},"01M71HACR4A8XTWTTSXK4124AA","processes-token-impersonate-detect","Detect Windows token impersonation and privilege abuse including SeImpersonatePrivilege exploitation via Potato attacks and token stealing techniques.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fprocesses\u002Ftoken\u002Fimpersonate\u002Fdetect\u002FSKILL.md",[],[72,141,142,143,144,145,146,77,147,27,88,148,149,150,151,152,153,154,155,76],"processes token impersonate detect","token","processes","attacks","windows","escalation","techniques","privilege-escalation","seimpersonate","token-impersonation","printspoofer","exploitation","potato","impersonation","via",{"skillNo":157,"name":158,"nameZh":6,"description":159,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":160,"categories":161,"keywords":162,"publishedAt":31},"01M71HAABSB4Z6QFSXEG00R4RK","processes-thread-injection-detect","Detect Windows thread injection techniques including CreateRemoteThread, QueueUserAPC, NtCreateThreadEx, and thread hijacking via process memory analysis.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fprocesses\u002Fthread\u002Finjection\u002Fdetect\u002FSKILL.md",[],[163,164,72,165,143,145,166,77,167,147,27,88,102,168,169,170,171,155,76,78],"thread","processes thread injection detect","injection","memory","process-injection","api","apc-injection","thread-injection","nt-api",{"skillNo":173,"name":174,"nameZh":6,"description":175,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":176,"categories":177,"keywords":178,"publishedAt":31},"01M71HA7H311V5G14WMX58HQSS","processes-hollow-technique-detect","Detect process hollowing (RunPE) by identifying processes with mismatched image paths between PEB and VAD tree, or unmapped PE headers in memory.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fprocesses\u002Fhollow\u002Ftechnique\u002Fdetect\u002FSKILL.md",[],[179,72,143,180,166,77,181,182,27,88,183,184,185,186,187,188,76,78,189,190],"processes hollow technique detect","tree","memory-forensics","process-hollow","peb","runpe","image","pe-header","in memory","with","mismatched","headers"]