Created
November 13, 2016 14:32
-
-
Save anonymous/f0b9a85e25ea097f810b4d79e9e005a5 to your computer and use it in GitHub Desktop.
PowerShell decoder by @JohnLaTwC
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
## hacked together by @JohnLaTwC, Nov 2016, v 0.5 | |
## This script attempts to decode common PowerShell encoded scripts. This version handles: | |
## * base64 data which encode unicode, gzip, or deflate encoded strings | |
## * it can operate on a file or stdin | |
## * it can run recursively in the event of multiple layers | |
## With apologies to @Lee_Holmes for using Python instead of PowerShell | |
## | |
import sys | |
import zlib | |
import re | |
import argparse | |
def xray(sz0): | |
out = '' | |
#find the B64 encoded blob by looking for the longest string | |
sz = max(filter(None, re.split("[\\\\ '\";]", sz0)), key=len).strip() | |
sz1 = str(sz) | |
if re.search('base64',sz0, re.IGNORECASE) or re.search('powershell',sz0, re.IGNORECASE): ## print('Found base64') | |
out = sz = sz.decode('base64') | |
if re.search('gzip',sz0, re.IGNORECASE): ## print('Found GZip') | |
out = str(zlib.decompressobj(32 + zlib.MAX_WBITS).decompress(sz)) | |
elif re.search('deflate',sz0, re.IGNORECASE): ## print('Found Deflate') | |
out = str(zlib.decompress( sz, -15)) | |
## TODO: scan and decode common shellcode patterns | |
else: | |
out = sz.decode('utf16', 'ignore') | |
return out | |
if __name__ == '__main__': | |
parser = argparse.ArgumentParser(description= \ | |
"""Attempt to decode PowerShell scripts by looking for some common encoded data. It defauts to reading from stdin. \n | |
""" | |
) | |
parser.add_argument('--recurse','-r', help='Recursively decode until done', action='store_true',default=False) | |
parser.add_argument('--file','-f', help='Read input from a file', action='store', type=str, default=None) | |
args = parser.parse_args() | |
psz = sz = None | |
if args.file is not None: | |
file = open(args.file, 'r') | |
sz = ''.join(file.readlines()) | |
else: | |
sz = ' '.join(sys.stdin.readlines()) | |
sz0 = str(sz) | |
if args.recurse: | |
try: | |
fRecurse = True | |
while fRecurse: | |
psz = str(sz) | |
sz2 = xray(sz) | |
if len(sz2) == 0: | |
fRecurse = False | |
sz = sz2 | |
except: | |
print(psz) | |
pass | |
else: | |
print(xray(sz)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment