Skip to content

Instantly share code, notes, and snippets.

@gnh1201
Last active October 4, 2023 11:16
Show Gist options
  • Save gnh1201/6d9099304df1481651f2425159883048 to your computer and use it in GitHub Desktop.
Save gnh1201/6d9099304df1481651f2425159883048 to your computer and use it in GitHub Desktop.
Powershell format string deobfusation
# Namhyeon Go <abuse@catswords.net>
# 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