reverse-skills-max: initial public release (restored, redacted, hardened)
This commit is contained in:
@@ -0,0 +1,201 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to the Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by the Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding any notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. Please do not remove or change
|
||||
the license header comment from a contributed file except when
|
||||
necessary.
|
||||
|
||||
Copyright 2026 mukul975
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,386 @@
|
||||
---
|
||||
name: deobfuscating-powershell-obfuscated-malware
|
||||
description: Systematically deobfuscates multi-layer PowerShell malware using AST analysis, dynamic tracing, and tools like PSDecode and PowerDecode to reveal hidden payloads and C2 infrastructure. Use during incident response or malware analysis when a PowerShell script is obfuscated with encoding, string manipulation, or invocation tricks and you need to recover the underlying commands, dropped payloads, or C2 endpoints.
|
||||
domain: cybersecurity
|
||||
subdomain: malware-analysis
|
||||
tags:
|
||||
- powershell
|
||||
- deobfuscation
|
||||
- malware-analysis
|
||||
- scripting
|
||||
- obfuscation
|
||||
- ast-analysis
|
||||
- incident-response
|
||||
mitre_attack:
|
||||
- T1059.001
|
||||
- T1027.010
|
||||
- T1140
|
||||
- T1027
|
||||
- T1620
|
||||
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 (`I`nv`oke-Exp`ression`). 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
|
||||
|
||||
```python
|
||||
#!/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
|
||||
|
||||
```python
|
||||
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
|
||||
|
||||
```python
|
||||
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
|
||||
|
||||
- [PSDecode - PowerShell Deobfuscation](https://github.com/R3MRUM/PSDecode)
|
||||
- [PowerDecode - Multi-layer Deobfuscation](https://github.com/Malandrone/PowerDecode)
|
||||
- [PowerPeeler - Instruction-level Deobfuscation](https://arxiv.org/html/2406.04027v2)
|
||||
- [SentinelOne - Deconstructing PowerShell Obfuscation](https://www.sentinelone.com/blog/deconstructing-powershell-obfuscation-in-malspam-campaigns/)
|
||||
- [MITRE ATT&CK T1059.001 - PowerShell](https://attack.mitre.org/techniques/T1059/001/)
|
||||
@@ -0,0 +1,66 @@
|
||||
# PowerShell Deobfuscation Analysis Report
|
||||
|
||||
## Report Metadata
|
||||
| Field | Value |
|
||||
|-------|-------|
|
||||
| Report ID | PS-DEOB-YYYY-NNNN |
|
||||
| Date | YYYY-MM-DD |
|
||||
| Sample Hash (SHA-256) | |
|
||||
| Original Filename | |
|
||||
| Classification | TLP:AMBER |
|
||||
|
||||
## Obfuscation Layers Identified
|
||||
|
||||
| Layer | Technique | Description |
|
||||
|-------|-----------|-------------|
|
||||
| 1 | | |
|
||||
| 2 | | |
|
||||
| 3 | | |
|
||||
|
||||
## Deobfuscation Results
|
||||
|
||||
### Layer-by-Layer Breakdown
|
||||
| Layer | Input Size | Output Size | Technique Applied |
|
||||
|-------|-----------|-------------|-------------------|
|
||||
| 1 | bytes | bytes | |
|
||||
| 2 | bytes | bytes | |
|
||||
|
||||
### Final Deobfuscated Script Summary
|
||||
- **Total layers removed**:
|
||||
- **Final script purpose**:
|
||||
- **Execution method**:
|
||||
|
||||
## Extracted IOCs
|
||||
|
||||
### URLs
|
||||
| URL | Purpose |
|
||||
|-----|---------|
|
||||
| | Payload download / C2 |
|
||||
|
||||
### IP Addresses
|
||||
| IP | Context |
|
||||
|----|---------|
|
||||
| | |
|
||||
|
||||
### File System Artifacts
|
||||
| Path | Action |
|
||||
|------|--------|
|
||||
| | Created / Modified / Deleted |
|
||||
|
||||
### Registry Keys
|
||||
| Key | Action |
|
||||
|-----|--------|
|
||||
| | Created / Modified |
|
||||
|
||||
## Behavioral Analysis
|
||||
- **Download behavior**:
|
||||
- **Persistence mechanism**:
|
||||
- **Evasion techniques**:
|
||||
- **Payload type**:
|
||||
|
||||
## MITRE ATT&CK Mapping
|
||||
| Technique | ID | Evidence |
|
||||
|-----------|-----|---------|
|
||||
| PowerShell | T1059.001 | Script execution |
|
||||
| Obfuscated Files | T1027 | Multi-layer encoding |
|
||||
| | | |
|
||||
@@ -0,0 +1,34 @@
|
||||
# PowerShell Deobfuscation — API Reference
|
||||
|
||||
## Libraries
|
||||
|
||||
| Library | Install | Purpose |
|
||||
|---------|---------|---------|
|
||||
| re | stdlib | Regex pattern matching for obfuscation detection |
|
||||
| base64 | stdlib | Base64 decoding of encoded commands |
|
||||
| pySigma | `pip install pySigma` | Sigma rule generation for detections |
|
||||
|
||||
## Common Obfuscation Techniques
|
||||
|
||||
| Technique | Pattern | Example |
|
||||
|-----------|---------|---------|
|
||||
| Base64 Encoding | `-EncodedCommand <b64>` | `powershell -enc SQBFAFgA...` |
|
||||
| String Concatenation | `'str1'+'str2'` | `'Inv'+'oke'+'-Exp'+'ression'` |
|
||||
| Character Codes | `[char]73+[char]69` | `[char]73` = I, `[char]69` = E |
|
||||
| Backtick Escape | `` `I`E`X `` | Backtick breaks keyword detection |
|
||||
| Variable Substitution | `$env:COMSPEC` | Use env vars as execution paths |
|
||||
| Compression | `IO.Compression.DeflateStream` | Compressed + Base64 payload |
|
||||
|
||||
## Detection Event IDs
|
||||
|
||||
| Source | Event ID | Description |
|
||||
|--------|----------|-------------|
|
||||
| PowerShell | 4104 | Script block logging (deobfuscated content) |
|
||||
| Sysmon | 1 | Process creation with command line |
|
||||
| Defender | 1116 | Malware detection |
|
||||
|
||||
## External References
|
||||
|
||||
- [Invoke-Obfuscation](https://github.com/danielbohannon/Invoke-Obfuscation)
|
||||
- [PSDecode](https://github.com/R3MRUM/PSDecode)
|
||||
- [PowerShell ScriptBlock Logging](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_logging)
|
||||
@@ -0,0 +1,41 @@
|
||||
# Standards and Frameworks Reference
|
||||
|
||||
## PowerShell Obfuscation Taxonomy
|
||||
|
||||
### Layer Classification
|
||||
| Layer | Technique | Example |
|
||||
|-------|-----------|---------|
|
||||
| L1 | Base64 EncodedCommand | `powershell -enc SQBFAFgA...` |
|
||||
| L2 | String Concatenation | `$a='Inv'+'oke'+'-Ex'+'pression'` |
|
||||
| L3 | Character Code Array | `[char[]](73,69,88)-join''` |
|
||||
| L4 | Tick-Mark Insertion | `` I`nv`oke-Exp`ress`ion `` |
|
||||
| L5 | Environment Variable | `$env:COMSPEC[4,15,25]-join''` |
|
||||
| L6 | SecureString | `ConvertTo-SecureString ... -Key` |
|
||||
| L7 | Compression + Base64 | `IO.Compression.DeflateStream` |
|
||||
| L8 | XOR Encoding | `$bytes | %{ $_ -bxor 0x42 }` |
|
||||
| L9 | Replace Chain | `.Replace('abc','I').Replace(...)` |
|
||||
| L10 | Format String | `("{2}{0}{1}" -f 'ke-','Ex','Invo')` |
|
||||
|
||||
### MITRE ATT&CK Mappings
|
||||
| Technique | ID | Description |
|
||||
|-----------|-----|------------|
|
||||
| Command and Scripting Interpreter: PowerShell | T1059.001 | Malicious PowerShell execution |
|
||||
| Obfuscated Files or Information | T1027 | Encoding/encryption of scripts |
|
||||
| Deobfuscate/Decode Files | T1140 | Runtime deobfuscation |
|
||||
| Ingress Tool Transfer | T1105 | Downloading payloads via PS |
|
||||
| System Binary Proxy Execution | T1218 | Using trusted binaries |
|
||||
|
||||
## PowerShell AST Node Types for Analysis
|
||||
|
||||
### Key Expression Nodes
|
||||
- `CommandExpression`: Direct command invocations
|
||||
- `InvokeMemberExpression`: Method calls on objects
|
||||
- `BinaryExpression`: String concatenation operators
|
||||
- `ArrayExpression`: Character array construction
|
||||
- `SubExpression`: Nested expression evaluation
|
||||
- `ExpandableStringExpression`: String interpolation
|
||||
|
||||
## References
|
||||
- [PowerShell Language Specification](https://docs.microsoft.com/en-us/powershell/scripting/lang-spec/chapter-01)
|
||||
- [Invoke-Obfuscation Framework](https://github.com/danielbohannon/Invoke-Obfuscation)
|
||||
- [AMSI Interface Documentation](https://docs.microsoft.com/en-us/windows/win32/amsi/)
|
||||
@@ -0,0 +1,50 @@
|
||||
# PowerShell Deobfuscation Workflows
|
||||
|
||||
## Workflow 1: Automated Multi-Layer Deobfuscation
|
||||
|
||||
```
|
||||
[Obfuscated Script] --> [Identify Techniques] --> [Remove Tick Marks]
|
||||
|
|
||||
v
|
||||
[Resolve Concatenation]
|
||||
|
|
||||
v
|
||||
[Decode Base64 Layers]
|
||||
|
|
||||
v
|
||||
[IEX -> Write-Output]
|
||||
|
|
||||
v
|
||||
[Extract Final Payload]
|
||||
```
|
||||
|
||||
## Workflow 2: AST-Based Analysis
|
||||
|
||||
```
|
||||
[Script Input] --> [Parse AST] --> [Walk Expression Nodes] --> [Evaluate Expressions]
|
||||
|
|
||||
v
|
||||
[Reconstruct Commands]
|
||||
|
|
||||
v
|
||||
[Extract IOCs]
|
||||
```
|
||||
|
||||
## Workflow 3: Dynamic Sandbox Deobfuscation
|
||||
|
||||
```
|
||||
[Obfuscated Script] --> [Execute in Sandbox] --> [Capture ScriptBlock Logs]
|
||||
|
|
||||
v
|
||||
[Event ID 4104 Analysis]
|
||||
|
|
||||
v
|
||||
[Reconstruct Execution Chain]
|
||||
```
|
||||
|
||||
### Steps:
|
||||
1. **Enable Logging**: Enable PowerShell ScriptBlock logging (Event ID 4104)
|
||||
2. **Execute**: Run obfuscated script in isolated sandbox
|
||||
3. **Collect**: Gather all ScriptBlock log entries
|
||||
4. **Reconstruct**: Assemble deobfuscated script from logged blocks
|
||||
5. **Extract**: Pull IOCs from the reconstructed clear-text script
|
||||
@@ -0,0 +1,132 @@
|
||||
#!/usr/bin/env python3
|
||||
"""PowerShell obfuscated malware deobfuscation agent."""
|
||||
|
||||
import json
|
||||
import argparse
|
||||
import re
|
||||
import base64
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
def decode_base64_commands(script_content):
|
||||
"""Find and decode Base64 encoded PowerShell commands."""
|
||||
decoded = []
|
||||
b64_pattern = re.compile(r'-[eE](?:nc(?:odedcommand)?)\s+([A-Za-z0-9+/=]{20,})')
|
||||
for match in b64_pattern.finditer(script_content):
|
||||
encoded = match.group(1)
|
||||
try:
|
||||
raw = base64.b64decode(encoded)
|
||||
text = raw.decode("utf-16-le", errors="replace")
|
||||
decoded.append({"encoded": encoded[:60] + "...", "decoded": text[:500]})
|
||||
except Exception:
|
||||
pass
|
||||
standalone_b64 = re.compile(r'["\']([A-Za-z0-9+/]{40,}={0,2})["\']')
|
||||
for match in standalone_b64.finditer(script_content):
|
||||
try:
|
||||
raw = base64.b64decode(match.group(1))
|
||||
text = raw.decode("utf-8", errors="replace")
|
||||
if text.isprintable() or "http" in text.lower():
|
||||
decoded.append({"encoded": match.group(1)[:60] + "...", "decoded": text[:500]})
|
||||
except Exception:
|
||||
pass
|
||||
return decoded
|
||||
|
||||
|
||||
def deobfuscate_string_concatenation(script_content):
|
||||
"""Resolve string concatenation obfuscation."""
|
||||
concat_pattern = re.compile(r"(?:'[^']*'\s*\+\s*){2,}'[^']*'")
|
||||
resolved = []
|
||||
for match in concat_pattern.finditer(script_content):
|
||||
original = match.group(0)
|
||||
parts = re.findall(r"'([^']*)'", original)
|
||||
result = "".join(parts)
|
||||
resolved.append({"obfuscated": original[:80], "resolved": result[:500]})
|
||||
return resolved
|
||||
|
||||
|
||||
def detect_obfuscation_techniques(script_content):
|
||||
"""Identify obfuscation techniques used in the script."""
|
||||
techniques = []
|
||||
checks = [
|
||||
(r'-[eE](?:nc(?:odedcommand)?)', "Base64 encoded command", "HIGH"),
|
||||
(r'\[(?:char|int)\]\s*\d+', "Character code conversion", "MEDIUM"),
|
||||
(r'(?:iex|invoke-expression)', "Invoke-Expression (IEX) execution", "HIGH"),
|
||||
(r'\$\{[^}]+\}', "Variable name obfuscation with braces", "LOW"),
|
||||
(r'\.(?:replace|split|reverse)\(', "String manipulation methods", "MEDIUM"),
|
||||
(r'-(?:join|split)\s', "Array join/split obfuscation", "MEDIUM"),
|
||||
(r'(?:Net\.WebClient|DownloadString|DownloadFile)', "Web download cradle", "CRITICAL"),
|
||||
(r'(?:Start-Process|Invoke-Item|cmd\s*/c)', "Process execution", "HIGH"),
|
||||
(r'\[System\.Convert\]::FromBase64String', ".NET Base64 decode", "HIGH"),
|
||||
(r'(?:gci|ls|dir)\s+env:', "Environment variable access", "LOW"),
|
||||
]
|
||||
for pattern, name, severity in checks:
|
||||
if re.search(pattern, script_content, re.IGNORECASE):
|
||||
techniques.append({"technique": name, "severity": severity})
|
||||
return techniques
|
||||
|
||||
|
||||
def extract_iocs(script_content):
|
||||
"""Extract indicators of compromise from deobfuscated content."""
|
||||
iocs = {"urls": [], "ips": [], "domains": [], "file_paths": []}
|
||||
url_pattern = re.compile(r'https?://[^\s"\'<>]+')
|
||||
ip_pattern = re.compile(r'\b(?:\d{1,3}\.){3}\d{1,3}\b')
|
||||
path_pattern = re.compile(r'[A-Z]:\\[\w\\]+\.\w{2,4}|/(?:tmp|var|etc)/[\w/]+')
|
||||
iocs["urls"] = list(set(url_pattern.findall(script_content)))
|
||||
iocs["ips"] = list(set(ip_pattern.findall(script_content)))
|
||||
iocs["file_paths"] = list(set(path_pattern.findall(script_content)))
|
||||
return iocs
|
||||
|
||||
|
||||
def run_analysis(script_path):
|
||||
"""Execute PowerShell deobfuscation analysis."""
|
||||
print(f"\n{'='*60}")
|
||||
print(f" POWERSHELL MALWARE DEOBFUSCATION")
|
||||
print(f" File: {script_path}")
|
||||
print(f" Generated: {datetime.utcnow().isoformat()} UTC")
|
||||
print(f"{'='*60}\n")
|
||||
|
||||
with open(script_path, "r", errors="replace") as f:
|
||||
content = f.read()
|
||||
|
||||
techniques = detect_obfuscation_techniques(content)
|
||||
print(f"--- OBFUSCATION TECHNIQUES ({len(techniques)}) ---")
|
||||
for t in techniques:
|
||||
print(f" [{t['severity']}] {t['technique']}")
|
||||
|
||||
b64 = decode_base64_commands(content)
|
||||
print(f"\n--- BASE64 DECODED ({len(b64)}) ---")
|
||||
for d in b64[:5]:
|
||||
print(f" {d['decoded'][:100]}")
|
||||
|
||||
concat = deobfuscate_string_concatenation(content)
|
||||
print(f"\n--- STRING CONCAT RESOLVED ({len(concat)}) ---")
|
||||
for c in concat[:5]:
|
||||
print(f" {c['resolved'][:100]}")
|
||||
|
||||
all_decoded = content
|
||||
for d in b64:
|
||||
all_decoded += "\n" + d["decoded"]
|
||||
iocs = extract_iocs(all_decoded)
|
||||
print(f"\n--- IOCs ---")
|
||||
print(f" URLs: {iocs['urls'][:5]}")
|
||||
print(f" IPs: {iocs['ips'][:5]}")
|
||||
print(f" Paths: {iocs['file_paths'][:5]}")
|
||||
|
||||
return {"techniques": techniques, "decoded_b64": b64, "concat": concat, "iocs": iocs}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="PowerShell Deobfuscation Agent")
|
||||
parser.add_argument("--script", required=True, help="Path to obfuscated PowerShell script")
|
||||
parser.add_argument("--output", help="Save report to JSON file")
|
||||
args = parser.parse_args()
|
||||
|
||||
report = run_analysis(args.script)
|
||||
if args.output:
|
||||
with open(args.output, "w") as f:
|
||||
json.dump(report, f, indent=2, default=str)
|
||||
print(f"\n[+] Report saved to {args.output}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,321 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
PowerShell Malware Deobfuscation Script
|
||||
|
||||
Identifies and removes multiple layers of PowerShell obfuscation
|
||||
to reveal the underlying malicious payload and extract IOCs.
|
||||
|
||||
Requirements:
|
||||
pip install regex
|
||||
|
||||
Usage:
|
||||
python process.py --file obfuscated.ps1 --output deobfuscated.ps1
|
||||
python process.py --file obfuscated.ps1 --extract-iocs
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class PowerShellDeobfuscator:
|
||||
"""Multi-layer PowerShell deobfuscation engine."""
|
||||
|
||||
def __init__(self):
|
||||
self.layers = []
|
||||
self.iocs = {
|
||||
"urls": set(),
|
||||
"ips": set(),
|
||||
"domains": set(),
|
||||
"file_paths": set(),
|
||||
"registry_keys": set(),
|
||||
"suspicious_commands": set(),
|
||||
}
|
||||
|
||||
def analyze(self, content):
|
||||
"""Identify obfuscation techniques present."""
|
||||
techniques = []
|
||||
|
||||
checks = [
|
||||
(r'-[Ee]nc(?:odedcommand)?\s+[A-Za-z0-9+/=]{20,}',
|
||||
"Base64 EncodedCommand"),
|
||||
(r'\[Convert\]::FromBase64String', "FromBase64String"),
|
||||
(r"'\s*\+\s*'", "String Concatenation (single-quote)"),
|
||||
(r'"\s*\+\s*"', "String Concatenation (double-quote)"),
|
||||
(r'\[char\]\s*\d+', "Character Code Casting"),
|
||||
(r'\[char\[\]\]\s*\([\d,\s]+\)', "Character Array"),
|
||||
(r'`[a-zA-Z]', "Tick-Mark Insertion"),
|
||||
(r'Invoke-Expression', "Invoke-Expression"),
|
||||
(r'\bIEX\b', "IEX Alias"),
|
||||
(r'\|\s*IEX', "Pipeline IEX"),
|
||||
(r'IO\.Compression', "Compression Stream"),
|
||||
(r'-bxor\s+\d+', "XOR Encoding"),
|
||||
(r'\.Replace\(', "Replace Chain"),
|
||||
(r'ConvertTo-SecureString', "SecureString"),
|
||||
(r'\$env:', "Environment Variable"),
|
||||
(r'-f\s+[\'"]', "Format String Operator"),
|
||||
(r'New-Object\s+IO\.MemoryStream', "MemoryStream"),
|
||||
]
|
||||
|
||||
for pattern, name in checks:
|
||||
matches = re.findall(pattern, content, re.IGNORECASE)
|
||||
if matches:
|
||||
techniques.append({"technique": name, "count": len(matches)})
|
||||
|
||||
return techniques
|
||||
|
||||
def deobfuscate(self, content):
|
||||
"""Apply all deobfuscation layers iteratively."""
|
||||
current = content
|
||||
iteration = 0
|
||||
|
||||
while iteration < 20:
|
||||
previous = current
|
||||
|
||||
# Layer: Remove tick marks
|
||||
current = self._remove_ticks(current)
|
||||
|
||||
# Layer: Resolve string concatenation
|
||||
current = self._resolve_concat(current)
|
||||
|
||||
# Layer: Decode Base64 EncodedCommand
|
||||
current = self._decode_base64_command(current)
|
||||
|
||||
# Layer: Decode FromBase64String calls
|
||||
current = self._decode_frombase64(current)
|
||||
|
||||
# Layer: Resolve character arrays
|
||||
current = self._resolve_char_arrays(current)
|
||||
|
||||
# Layer: Resolve format strings
|
||||
current = self._resolve_format_strings(current)
|
||||
|
||||
# Layer: Decompress streams
|
||||
current = self._decompress_streams(current)
|
||||
|
||||
if current == previous:
|
||||
break
|
||||
|
||||
self.layers.append({
|
||||
"iteration": iteration + 1,
|
||||
"length_before": len(previous),
|
||||
"length_after": len(current),
|
||||
})
|
||||
iteration += 1
|
||||
|
||||
# Extract IOCs from final result
|
||||
self._extract_iocs(current)
|
||||
|
||||
return current
|
||||
|
||||
def _remove_ticks(self, content):
|
||||
"""Remove backtick obfuscation."""
|
||||
escape_sequences = {'`n', '`r', '`t', '`a', '`b', '`f', '`v', '`0', '``'}
|
||||
result = []
|
||||
i = 0
|
||||
while i < len(content):
|
||||
if content[i] == '`' and i + 1 < len(content):
|
||||
pair = content[i:i+2]
|
||||
if pair in escape_sequences:
|
||||
result.append(pair)
|
||||
i += 2
|
||||
else:
|
||||
result.append(content[i+1])
|
||||
i += 2
|
||||
else:
|
||||
result.append(content[i])
|
||||
i += 1
|
||||
return ''.join(result)
|
||||
|
||||
def _resolve_concat(self, content):
|
||||
"""Resolve string concatenation."""
|
||||
# Single-quoted concatenation
|
||||
pattern = re.compile(r"'([^']*)'\s*\+\s*'([^']*)'")
|
||||
while pattern.search(content):
|
||||
content = pattern.sub(r"'\1\2'", content)
|
||||
|
||||
# Double-quoted concatenation
|
||||
pattern = re.compile(r'"([^"]*)"\s*\+\s*"([^"]*)"')
|
||||
while pattern.search(content):
|
||||
content = pattern.sub(r'"\1\2"', content)
|
||||
|
||||
return content
|
||||
|
||||
def _decode_base64_command(self, content):
|
||||
"""Decode -EncodedCommand Base64 arguments."""
|
||||
pattern = re.compile(
|
||||
r'-[Ee]nc(?:odedcommand)?\s+([A-Za-z0-9+/=]{20,})',
|
||||
re.IGNORECASE
|
||||
)
|
||||
match = pattern.search(content)
|
||||
if match:
|
||||
try:
|
||||
decoded = base64.b64decode(match.group(1)).decode('utf-16-le')
|
||||
content = pattern.sub(decoded, content)
|
||||
except Exception:
|
||||
pass
|
||||
return content
|
||||
|
||||
def _decode_frombase64(self, content):
|
||||
"""Decode [Convert]::FromBase64String calls."""
|
||||
pattern = re.compile(
|
||||
r"\[Convert\]::FromBase64String\(\s*['\"]([A-Za-z0-9+/=]+)['\"]\s*\)",
|
||||
re.IGNORECASE
|
||||
)
|
||||
for match in pattern.finditer(content):
|
||||
try:
|
||||
decoded = base64.b64decode(match.group(1))
|
||||
decoded_str = decoded.decode('utf-8', errors='replace')
|
||||
content = content.replace(match.group(0), f"'{decoded_str}'")
|
||||
except Exception:
|
||||
pass
|
||||
return content
|
||||
|
||||
def _resolve_char_arrays(self, content):
|
||||
"""Resolve [char] and [char[]] expressions."""
|
||||
# [char]NN patterns
|
||||
pattern = re.compile(r'\[char\]\s*(\d+)', re.IGNORECASE)
|
||||
for match in pattern.finditer(content):
|
||||
try:
|
||||
char_val = chr(int(match.group(1)))
|
||||
content = content.replace(match.group(0), f"'{char_val}'")
|
||||
except (ValueError, OverflowError):
|
||||
pass
|
||||
|
||||
return content
|
||||
|
||||
def _resolve_format_strings(self, content):
|
||||
"""Resolve PowerShell format string operator."""
|
||||
pattern = re.compile(
|
||||
r"\(?\s*['\"](\{[\d\}{\s]+[^'\"]*)['\"]"
|
||||
r"\s*-f\s*([^)]+)\)?",
|
||||
re.IGNORECASE
|
||||
)
|
||||
for match in pattern.finditer(content):
|
||||
try:
|
||||
fmt_str = match.group(1)
|
||||
args_str = match.group(2)
|
||||
args = [a.strip().strip("'\"") for a in args_str.split(",")]
|
||||
resolved = fmt_str
|
||||
for i, arg in enumerate(args):
|
||||
resolved = resolved.replace(f"{{{i}}}", arg)
|
||||
content = content.replace(match.group(0), f"'{resolved}'")
|
||||
except Exception:
|
||||
pass
|
||||
return content
|
||||
|
||||
def _decompress_streams(self, content):
|
||||
"""Attempt to decode compressed Base64 payloads."""
|
||||
import zlib
|
||||
import io
|
||||
|
||||
b64_pattern = re.compile(r'[A-Za-z0-9+/=]{100,}')
|
||||
for match in b64_pattern.finditer(content):
|
||||
try:
|
||||
raw = base64.b64decode(match.group(0))
|
||||
# Try deflate
|
||||
decompressed = zlib.decompress(raw, -zlib.MAX_WBITS)
|
||||
decoded = decompressed.decode('utf-8', errors='replace')
|
||||
if len(decoded) > 50:
|
||||
content = content.replace(match.group(0), decoded)
|
||||
except Exception:
|
||||
try:
|
||||
# Try gzip
|
||||
raw = base64.b64decode(match.group(0))
|
||||
decompressed = zlib.decompress(raw, zlib.MAX_WBITS | 16)
|
||||
decoded = decompressed.decode('utf-8', errors='replace')
|
||||
if len(decoded) > 50:
|
||||
content = content.replace(match.group(0), decoded)
|
||||
except Exception:
|
||||
pass
|
||||
return content
|
||||
|
||||
def _extract_iocs(self, content):
|
||||
"""Extract IOCs from deobfuscated content."""
|
||||
# URLs
|
||||
for url in re.findall(r'https?://[^\s\'"<>)\]]+', content, re.I):
|
||||
self.iocs["urls"].add(url)
|
||||
|
||||
# IPs
|
||||
for ip in re.findall(r'\b(?:\d{1,3}\.){3}\d{1,3}\b', content):
|
||||
self.iocs["ips"].add(ip)
|
||||
|
||||
# File paths
|
||||
for path in re.findall(
|
||||
r'[A-Za-z]:\\[^\s\'"<>|]+', content, re.I
|
||||
):
|
||||
self.iocs["file_paths"].add(path)
|
||||
|
||||
# Registry keys
|
||||
for key in re.findall(
|
||||
r'(?:HKLM|HKCU|HKCR)(?:\\[^\s\'"<>|]+)+', content, re.I
|
||||
):
|
||||
self.iocs["registry_keys"].add(key)
|
||||
|
||||
# Suspicious commands
|
||||
for cmd in ['DownloadString', 'DownloadFile', 'Invoke-WebRequest',
|
||||
'Start-Process', 'New-ScheduledTask', 'Add-MpPreference',
|
||||
'Reflection.Assembly']:
|
||||
if cmd.lower() in content.lower():
|
||||
self.iocs["suspicious_commands"].add(cmd)
|
||||
|
||||
def get_report(self):
|
||||
"""Generate analysis report."""
|
||||
return {
|
||||
"layers_processed": len(self.layers),
|
||||
"layer_details": self.layers,
|
||||
"iocs": {k: sorted(v) for k, v in self.iocs.items()},
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="PowerShell Malware Deobfuscator"
|
||||
)
|
||||
parser.add_argument("--file", required=True, help="Input PS1 file")
|
||||
parser.add_argument("--output", help="Output deobfuscated file")
|
||||
parser.add_argument("--extract-iocs", action="store_true",
|
||||
help="Extract IOCs from result")
|
||||
parser.add_argument("--report", help="Save JSON report")
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
with open(args.file, 'r', errors='replace') as f:
|
||||
content = f.read()
|
||||
|
||||
deob = PowerShellDeobfuscator()
|
||||
|
||||
print("[+] Analyzing obfuscation techniques...")
|
||||
techniques = deob.analyze(content)
|
||||
for t in techniques:
|
||||
print(f" - {t['technique']} ({t['count']} occurrences)")
|
||||
|
||||
print(f"\n[+] Deobfuscating ({len(content)} chars)...")
|
||||
result = deob.deobfuscate(content)
|
||||
print(f"[+] Result: {len(result)} chars")
|
||||
|
||||
if args.output:
|
||||
with open(args.output, 'w') as f:
|
||||
f.write(result)
|
||||
print(f"[+] Saved to {args.output}")
|
||||
|
||||
report = deob.get_report()
|
||||
if args.extract_iocs or args.report:
|
||||
print(f"\n[+] Extracted IOCs:")
|
||||
for category, values in report["iocs"].items():
|
||||
if values:
|
||||
print(f" {category}:")
|
||||
for v in values:
|
||||
print(f" - {v}")
|
||||
|
||||
if args.report:
|
||||
with open(args.report, 'w') as f:
|
||||
json.dump(report, f, indent=2)
|
||||
print(f"[+] Report saved to {args.report}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user