Last active
October 4, 2023 11:16
-
-
Save gnh1201/6d9099304df1481651f2425159883048 to your computer and use it in GitHub Desktop.
Powershell format string deobfusation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Namhyeon Go <[email protected]> | |
# 2023-10-04 | |
import re | |
# Text to search (Example text using PowerShell format strings) | |
text = """ | |
&("{0}{1}{2}" -f 'Set','-Var','iable') | |
&("{0} {1} {2}" -f 'Set','-Var','iable') | |
&("This is a test {0}" -f 'arg1') | |
&('Another example: {0} {1} {2}' -f 'arg1', 'arg2', 'arg3') | |
&("{0}{1}{2}" -f 'Set','-Var','iable') | |
&("{0}{1}{2}" -F 'Set','-Var','iable') | |
&("{0}{1}{2}" -f 'Set', '-Var', 'iable') | |
&("{0} {1} {2}" -F 'Set', '-Var', 'iable') | |
&("{0} {1} {2}" -f 'Set','-Var','iable') | |
# Additional example without the '&' character | |
("{0}{1}{2}" -f 'No', 'Ampersand', 'Here') | |
""" | |
#text = open('example.ps1', 'r').read() | |
# Regular expression pattern to find PowerShell format strings | |
pattern = r'&?\("([^"]+)"\s*-f\s*([^)]+)\)' | |
# Find matches of the pattern in the text, case insensitive | |
matches = re.finditer(pattern, text, re.IGNORECASE) | |
# Regular expression pattern for transformation | |
transform_pattern = r'&?\("([^"]+)"\s*-f\s*([^)]+)\)' | |
#transform_pattern = r'&\("([^"]+)"[ ]*-f[ ]*([^)]+)\)' # the same meaning | |
# Function to replace the matched format string with the formatted text | |
def replace_match(match): | |
format_args = match.group(2).split(',') | |
formatted_string = '"{}"'.format(match.group(1)) | |
formatted_string = formatted_string.format(*format_args) | |
return formatted_string | |
# Iterate through matches and replace them with the formatted text | |
for match in matches: | |
matched_text = match.group() | |
try: | |
transformed_text = re.sub(transform_pattern, replace_match, matched_text).replace('\'', '') | |
text = text.replace(matched_text, transformed_text) | |
except: | |
print(f"Transformation failed: {matched_text}") | |
pass | |
# Save the decoded text to a new file | |
with open('example_decoded.ps1', 'w') as file: | |
file.write(text) | |
print("Saved as example_decoded.ps1.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment