deobfuscating-powershell-obfuscated-malware

mukul975/Anthropic-Cybersecurity-Skills · updated May 25, 2026

MDX-style export adds YAML metadata + attribution linking explainx.ai and this canonical listing URL.

$npx skills install mukul975/Anthropic-Cybersecurity-Skills/deobfuscating-powershell-obfuscated-malware
0 commentsdiscussion
summary

Systematically deobfuscate multi-layer PowerShell malware using AST analysis, dynamic tracing, and tools like PSDecode and PowerDecode to reveal hidden payloads and C2 infrastructure.

skill.md
name
deobfuscating-powershell-obfuscated-malware
description
Systematically deobfuscate multi-layer PowerShell malware using AST analysis, dynamic tracing, and tools like PSDecode and PowerDecode to reveal hidden payloads and C2 infrastructure.
domain
cybersecurity
subdomain
malware-analysis
tags
- powershell - deobfuscation - malware-analysis - scripting - obfuscation - ast-analysis - incident-response
mitre_attack
- T1059.001 - T1027 - T1140
version
'1.0'
author
mahipal
license
Apache-2.0
d3fend_techniques
- Executable Denylisting - Execution Isolation - File Metadata Consistency Validation - Content Format Conversion - File Content Analysis
nist_csf
- DE.AE-02 - RS.AN-03 - ID.RA-01 - DE.CM-01

Deobfuscating PowerShell Obfuscated Malware

Overview

PowerShell 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.

When to Use

  • When performing authorized security testing that involves deobfuscating powershell obfuscated malware
  • When analyzing malware samples or attack artifacts in a controlled environment
  • When conducting red team exercises or penetration testing engagements
  • When building detection capabilities based on offensive technique understanding

Prerequisites

  • Python 3.9+ with base64, re, subprocess modules
  • PowerShell 5.1+ or PowerShell 7+ (for AST access)
  • PSDecode (Install-Module PSDecode)
  • PowerDecode (https://github.com/Malandrone/PowerDecode)
  • Isolated VM or sandbox for safe script execution
  • CyberChef for manual encoding transformations
  • Understanding of PowerShell AST and Invoke-Expression patterns

Key Concepts

Common Obfuscation Techniques

PowerShell 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 (Invoke-Expression`). SecureString conversion encrypts strings using ConvertTo-SecureString with embedded keys.

AST-Based Deobfuscation

PowerShell'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.

Dynamic Execution Tracing

By 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.

Workflow

Step 1: Identify Obfuscation Layers

#!/usr/bin/env python3
"""Identify and classify PowerShell obfuscation techniques."""
import re
import base64
import sys


def analyze_obfuscation(script_content):
    """Identify obfuscation techniques used in PowerShell script."""
    techniques = []

    # Check for Base64 encoded command
    b64_pattern = re.compile(
        r'-[Ee](?:nc(?:odedcommand)?)\s+([A-Za-z0-9+/=]{20,})',
        re.IGNORECASE
    )
    if b64_pattern.search(script_content):
        techniques.append("Base64 EncodedCommand")

    # Check for FromBase64String
    if re.search(r'\[Convert\]::FromBase64String', script_content, re.IGNORECASE):
        techniques.append("Base64 FromBase64String")

    # Check for string concatenation
    concat_count = script_content.count("'+'") + script_content.count('"+"')
    if concat_count > 3:
        techniques.append(f"String Concatenation ({concat_count} joins)")

    # Check for char array construction
    if re.search(r'\[char\]\s*\d+', script_content, re.IGNORECASE):
        techniques.append("Character Code Array")

    # Check for Invoke-Expression variants
    iex_patterns = [
        r'Invoke-Expression',
        r'\bIEX\b',
        r'\.\s*\(\s*\$',
        r'&\s*\(\s*\$',
        r'\|\s*IEX',
        r'\|\s*Invoke-Expression',
    ]
    for pattern in iex_patterns:
        if re.search(pattern, script_content, re.IGNORECASE):
            techniques.append(f"Invoke-Expression variant: {pattern}")

    # Check for tick-mark obfuscation
    tick_count = script_content.count('`')
    if tick_count > 5:
        techniques.append(f"Tick-mark Insertion ({tick_count} backticks)")

    # Check for environment variable abuse
    if re.search(r'\$env:', script_content, re.IGNORECASE):
        env_refs = re.findall(r'\$env:\w+', script_content, re.IGNORECASE)
        if len(env_refs) > 2:
            techniques.append(f"Environment Variable Abuse ({len(env_refs)} refs)")

    # Check for SecureString
    if re.search(r'ConvertTo-SecureString', script_content, re.IGNORECASE):
        techniques.append("SecureString Encryption")

    # Check for compression
    if re.search(r'IO\.Compression|DeflateStream|GZipStream',
                 script_content, re.IGNORECASE):
        techniques.append("Compression (Deflate/GZip)")

    # Check for XOR encoding
    if re.search(r'-bxor\s+\d+', script_content, re.IGNORECASE):
        techniques.append("XOR Encoding")

    # Check for Replace chain
    replace_count = len(re.findall(r'\.Replace\(', script_content))
    if replace_count > 2:
        techniques.append(f"Replace Chain ({replace_count} replacements)")

    return techniques


def decode_base64_command(script_content):
    """Extract and decode Base64 encoded commands."""
    b64_match = re.search(
        r'-[Ee](?:nc(?:odedcommand)?)\s+([A-Za-z0-9+/=]{20,})',
        script_content, re.IGNORECASE
    )
    if b64_match:
        encoded = b64_match.group(1)
        try:
            decoded = base64.b64decode(encoded).decode('utf-16-le')
            return decoded
        except Exception:
            return None
    return None


def remove_tick_marks(script_content):
    """Remove PowerShell tick-mark obfuscation."""
    # Remove backticks that are not escape sequences
    escape_chars = {'`n', '`r', '`t', '`a', '`b', '`f', '`v', '`0', '``'}
    result = []
    i = 0
    while i < len(script_content):
        if script_content[i] == '`' and i + 1 < len(script_content):
            pair = script_content[i:i+2]
            if pair in escape_chars:
                result.append(pair)
                i += 2
            else:
                # Skip the backtick, keep the next char
                result.append(script_content[i+1])
                i += 2
        else:
            result.append(script_content[i])
            i += 1
    return ''.join(result)


def resolve_string_concat(script_content):
    """Resolve simple string concatenation patterns."""
    # Pattern: 'str1' + 'str2'
    pattern = re.compile(r"'([^']*)'\s*\+\s*'([^']*)'")
    while pattern.search(script_content):
        script_content = pattern.sub(lambda m: f"'{m.group(1)}{m.group(2)}'",
                                      script_content)
    # Pattern: "str1" + "str2"
    pattern = re.compile(r'"([^"]*)"\s*\+\s*"([^"]*)"')
    while pattern.search(script_content):
        script_content = pattern.sub(lambda m: f'"{m.group(1)}{m.group(2)}"',
                                      script_content)
    return script_content


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print(f"Usage: {sys.argv[0]} <powershell_script>")
        sys.exit(1)

    with open(sys.argv[1], 'r', errors='replace') as f:
        content = f.read()

    print("[+] Obfuscation Analysis")
    print("=" * 60)
    techniques = analyze_obfuscation(content)
    for t in techniques:
        print(f"  - {t}")

    # Attempt automatic deobfuscation
    print("\n[+] Attempting Deobfuscation")
    print("=" * 60)

    # Layer 1: Remove tick marks
    deobfuscated = remove_tick_marks(content)

    # Layer 2: Resolve string concatenation
    deobfuscated = resolve_string_concat(deobfuscated)

    # Layer 3: Decode Base64
    b64_decoded = decode_base64_command(deobfuscated)
    if b64_decoded:
        print("[+] Base64 decoded content:")
        print(b64_decoded[:2000])
        deobfuscated = b64_decoded

    print(f"\n[+] Deobfuscated script length: {len(deobfuscated)} chars")
    output_file = sys.argv[1] + ".deobfuscated.ps1"
    with open(output_file, 'w') as f:
        f.write(deobfuscated)
    print(f"[+] Saved to {output_file}")

Step 2: Multi-Layer IEX Replacement

import subprocess
import tempfile
import os

def iex_replacement_deobfuscate(script_content, max_layers=10):
    """Iteratively replace IEX with Write-Output to unwrap layers."""
    # IEX replacement patterns
    replacements = [
        (r'\bInvoke-Expression\b', 'Write-Output'),
        (r'\bIEX\b', 'Write-Output'),
        (r'\|\s*IEX\b', '| Write-Output'),
    ]

    current = script_content
    layers = []

    for layer_num in range(max_layers):
        # Apply IEX replacements
        modified = current
        for pattern, replacement in replacements:
            modified = re.sub(pattern, replacement, modified, flags=re.IGNORECASE)

        if modified == current and layer_num > 0:
            print(f"  [+] No more IEX layers found at layer {layer_num}")
            break

        # Write to temp file and execute in constrained PowerShell
        with tempfile.NamedTemporaryFile(mode='w', suffix='.ps1',
                                          delete=False) as tmp:
            tmp.write(modified)
            tmp_path = tmp.name

        try:
            result = subprocess.run(
                ['powershell', '-NoProfile', '-ExecutionPolicy', 'Bypass',
                 '-File', tmp_path],
                capture_output=True, text=True, timeout=30
            )

            output = result.stdout.strip()
            if output and output != current:
                print(f"  [+] Layer {layer_num + 1}: Unwrapped "
                      f"{len(output)} chars")
                layers.append({
                    "layer": layer_num + 1,
                    "technique": "IEX replacement",
                    "content_length": len(output),
                })
                current = output
            else:
                break

        except subprocess.TimeoutExpired:
            print(f"  [!] Layer {layer_num + 1}: Execution timeout")
            break
        finally:
            os.unlink(tmp_path)

    return current, layers

Step 3: Extract IOCs from Deobfuscated Script

def extract_iocs_from_script(deobfuscated_content):
    """Extract indicators of compromise from deobfuscated PowerShell."""
    iocs = {
        "urls": [],
        "ips": [],
        "domains": [],
        "file_paths": [],
        "registry_keys": [],
        "commands": [],
        "base64_blobs": [],
    }

    # URLs
    url_pattern = re.compile(
        r'https?://[^\s\'"<>)\]]+', re.IGNORECASE
    )
    iocs["urls"] = list(set(url_pattern.findall(deobfuscated_content)))

    # IP addresses
    ip_pattern = re.compile(
        r'\b(?:\d{1,3}\.){3}\d{1,3}\b'
    )
    iocs["ips"] = list(set(ip_pattern.findall(deobfuscated_content)))

    # File paths
    path_pattern = re.compile(
        r'[A-Za-z]:\\[^\s\'"<>|]+|'
        r'\\\\[^\s\'"<>|]+|'
        r'%(?:APPDATA|TEMP|USERPROFILE|PROGRAMFILES)%[^\s\'"<>|]*',
        re.IGNORECASE
    )
    iocs["file_paths"] = list(set(path_pattern.findall(deobfuscated_content)))

    # Registry keys
    reg_pattern = re.compile(
        r'(?:HKLM|HKCU|HKCR|HKU|HKCC)(?:\\[^\s\'"<>|]+)+',
        re.IGNORECASE
    )
    iocs["registry_keys"] = list(set(reg_pattern.findall(deobfuscated_content)))

    # Suspicious commands
    suspicious_cmds = [
        'New-Object Net.WebClient',
        'DownloadString', 'DownloadFile', 'DownloadData',
        'Start-Process', 'Invoke-WebRequest',
        'New-Object IO.MemoryStream',
        'Reflection.Assembly',
        'Add-MpPreference -ExclusionPath',
        'Set-MpPreference -DisableRealtimeMonitoring',
        'New-ScheduledTask', 'Register-ScheduledTask',
    ]
    for cmd in suspicious_cmds:
        if cmd.lower() in deobfuscated_content.lower():
            iocs["commands"].append(cmd)

    return iocs

Validation Criteria

  • All obfuscation layers identified and classified correctly
  • Base64 encoded commands decoded to readable PowerShell
  • Tick-mark and string concatenation obfuscation resolved
  • IEX replacement reveals next-stage payloads
  • URLs, IPs, and file paths extracted from final deobfuscated stage
  • Deobfuscated script matches observed malware behavior in sandbox

References

how to use deobfuscating-powershell-obfuscated-malware

How to use deobfuscating-powershell-obfuscated-malware on Cursor

AI-first code editor with Composer

1

Prerequisites

Before installing skills in Cursor, ensure your development environment meets these requirements:

  • Cursor installed and configured on your development machine
  • Node.js version 16.0+ with npm package manager (verify with node --version)
  • Active project directory or workspace where you want to add deobfuscating-powershell-obfuscated-malware
2

Execute installation command

Execute the skills CLI command in your project's root directory to begin installation:

$npx skills install mukul975/Anthropic-Cybersecurity-Skills/deobfuscating-powershell-obfuscated-malware

The skills CLI fetches deobfuscating-powershell-obfuscated-malware from GitHub repository mukul975/Anthropic-Cybersecurity-Skills and configures it for Cursor.

3

Select Cursor when prompted

The CLI will show a list of available agents. Use arrow keys to navigate and space to select Cursor:

◆ Which agents do you want to install to?
│ ── Universal (.agents/skills) ── always included ────
│ • Amp
│ • Antigravity
│ • Cline
│ • Codex
│ ●Cursor(selected)
│ • Cursor
│ • Windsurf
4

Verify installation

Confirm successful installation by checking the skill directory location:

.cursor/skills/deobfuscating-powershell-obfuscated-malware

Reload or restart Cursor to activate deobfuscating-powershell-obfuscated-malware. Access the skill through slash commands (e.g., /deobfuscating-powershell-obfuscated-malware) or your agent's skill management interface.

Security & Verification Notice

We perform automated surface-level scans (Gen AI Scanner, Socket, Snyk) during installation. These checks detect common vulnerabilities but do not guarantee complete security. Always review skill source code and verify the publisher's reputation before production use.

Skills execute code in your development environment. Always verify the publisher's identity, review recent commits, and test in isolated environments before production deployment.

List & Monetize Your Skill

Submit your Claude Code skill and start earning

GET_STARTED →

Use Cases

Task Automation & Efficiency

Automate repetitive workflows and reduce manual effort

Example

Generate reports, summarize documents, draft communications

Save 3-5 hours per week on routine tasks

Knowledge Enhancement

Learn new skills, understand complex topics, get expert guidance

Example

Explain concepts, provide examples, suggest learning resources

Accelerate learning and skill development by 2x

Quality Improvement

Enhance output quality through reviews, suggestions, and refinements

Example

Review drafts, suggest improvements, catch errors

Improve work quality by 30-40% with less effort

Implementation Guide

Prerequisites

  • Claude Desktop or compatible AI client with skill support
  • Clear understanding of task or problem to solve
  • Willingness to iterate and refine outputs

Time Estimate

15-45 minutes depending on use case complexity

Installation Steps

  1. 1.Install skill using provided installation command
  2. 2.Test with simple use case relevant to your work
  3. 3.Evaluate output quality and relevance
  4. 4.Iterate on prompts to improve results
  5. 5.Integrate into regular workflow if valuable

Common Pitfalls

  • Expecting perfect results without iteration
  • Not providing enough context in prompts
  • Using skill for tasks outside its intended scope
  • Accepting outputs without review and validation

Best Practices

✓ Do

  • +Start with clear, specific prompts
  • +Provide relevant context and constraints
  • +Review and refine all outputs before using
  • +Iterate to improve output quality
  • +Document successful prompt patterns

✗ Don't

  • Don't use without understanding skill limitations
  • Don't skip validation of outputs
  • Don't share sensitive information in prompts
  • Don't expect skill to replace human judgment

💡 Pro Tips

  • Be specific about desired format and style
  • Ask for multiple options to choose from
  • Request explanations to understand reasoning
  • Combine AI efficiency with human expertise

When to Use This

✓ Use When

Use when skill capabilities match your task, clear ROI on time saved, and you can validate outputs. Best for repetitive tasks, learning, and quality improvement.

✗ Avoid When

Avoid when task requires deep expertise you can't validate, involves sensitive decisions, or when learning process is more valuable than speed of completion.

Learning Path

  1. 1Familiarize yourself with skill capabilities and limitations
  2. 2Start with low-risk, non-critical tasks
  3. 3Progress to more complex and valuable use cases
  4. 4Build expertise through regular use and experimentation

Discussion

Product Hunt–style comments (not star reviews)
  • No comments yet — start the thread.
general reviews

Ratings

4.473 reviews
  • Dhruvi Jain· Dec 28, 2024

    deobfuscating-powershell-obfuscated-malware reduced setup friction for our internal harness; good balance of opinion and flexibility.

  • Diya Agarwal· Dec 28, 2024

    We added deobfuscating-powershell-obfuscated-malware from the explainx registry; install was straightforward and the SKILL.md answered most questions upfront.

  • Zaid Gonzalez· Dec 20, 2024

    We added deobfuscating-powershell-obfuscated-malware from the explainx registry; install was straightforward and the SKILL.md answered most questions upfront.

  • Kabir Mehta· Dec 16, 2024

    Useful defaults in deobfuscating-powershell-obfuscated-malware — fewer surprises than typical one-off scripts, and it plays nicely with `npx skills` flows.

  • Noor Brown· Dec 4, 2024

    deobfuscating-powershell-obfuscated-malware reduced setup friction for our internal harness; good balance of opinion and flexibility.

  • Noor Harris· Dec 4, 2024

    deobfuscating-powershell-obfuscated-malware fits our agent workflows well — practical, well scoped, and easy to wire into existing repos.

  • Noor Chen· Nov 23, 2024

    I recommend deobfuscating-powershell-obfuscated-malware for anyone iterating fast on agent tooling; clear intent and a small, reviewable surface area.

  • Noor Huang· Nov 23, 2024

    deobfuscating-powershell-obfuscated-malware is among the better-maintained entries we tried; worth keeping pinned for repeat workflows.

  • Oshnikdeep· Nov 19, 2024

    I recommend deobfuscating-powershell-obfuscated-malware for anyone iterating fast on agent tooling; clear intent and a small, reviewable surface area.

  • Neel Verma· Nov 19, 2024

    Keeps context tight: deobfuscating-powershell-obfuscated-malware is the kind of skill you can hand to a new teammate without a long onboarding doc.

showing 1-10 of 73

1 / 8