Skip to content

Instantly share code, notes, and snippets.

@DissectMalware
Last active January 23, 2022 20:16
Show Gist options
  • Save DissectMalware/114fc674383cb99fc93c78252cd9da10 to your computer and use it in GitHub Desktop.
Save DissectMalware/114fc674383cb99fc93c78252cd9da10 to your computer and use it in GitHub Desktop.
import re
import argparse
def deobfuscate(input_str):
regex_str = r"[\(\{]\s*\"(?P<format>[^\)]*?)\"\s*\-f\s*(?P<params>.*?)[\)\}]"
regex = re.compile(regex_str, re.MULTILINE | re.IGNORECASE)
for match in reversed(list(regex.finditer(input_str))):
format_str = match.group('format')
try:
parameters = [x.strip("'") for x in match.group('params').split(',\'')]
if input_str[match.start()] == '(':
input_str = input_str[:match.start()] + '("{}")'.format(format_str.format(*parameters)) \
+ input_str[match.end():]
else:
input_str = input_str[:match.start()] + '{{"{}"}}'.format(format_str.format(*parameters)) \
+ input_str[match.end():]
except:
match_str = input_str[match.start(): match.end()]
print('ERROR: ' + match_str + '\n')
return input_str
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--file", type=str, help="The path of obfuscated batch file")
args = parser.parse_known_args()
if args[0].file is not None:
file_path = args[0].file
with open(file_path, 'r', encoding='utf_16') as input_file:
text = input_file.read()
with open(file_path + '.out','w', encoding='utf_16') as out:
# caution: this line might corrupt the deobfuscated code, as removing grave character blindly can change the meaning of characters
text = text.replace('`', '')
out.write(deobfuscate(text))
else:
print("Please enter an obfuscated PowerShell command:")
print(deobfuscate(input()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment