LightsOut will generate an obfuscated DLL that will disable AMSI & ETW while trying to evade AV. This is done by randomizing all WinAPI functions used, xor encoding strings, and utilizing basic sandbox checks. Mingw-w64 is used to compile the obfuscated C code into a DLL that can be loaded into any process where AMSI or ETW are present (i.e. PowerShell).
LightsOut is designed to work on Linux systems with python3
and mingw-w64
installed. No other dependencies are required.
Features currently include:
_______________________
| |
| AMSI + ETW |
| |
| LIGHTS OUT |
| _______ |
| || || |
| ||_____|| |
| |/ /|| |
| / / || |
| /____/ /-' |
| |____|/ |
| |
| @icyguider |
| |
| RG|
`-----------------------'
usage: lightsout.py [-h] [-m <method>] [-s <option>] [-sa <value>] [-k <key>] [-o <outfile>] [-p <pid>]
Generate an obfuscated DLL that will disable AMSI & ETW
options:
-h, --help show this help message and exit
-m <method>, --method <method>
Bypass technique (Options: patch, hwbp, remote_patch) (Default: patch)
-s <option>, --sandbox < ;option>
Sandbox evasion technique (Options: mathsleep, username, hostname, domain) (Default: mathsleep)
-sa <value>, --sandbox-arg <value>
Argument for sandbox evasion technique (Ex: WIN10CO-DESKTOP, testlab.local)
-k <key>, --key <key>
Key to encode strings with (randomly generated by default)
-o <outfile>, --outfile <outfile>
File to save DLL to
Remote options:
-p <pid>, --pid <pid>
PID of remote process to patch
Intended Use/Opsec Considerations
This tool was designed to be used on pentests, primarily to execute malicious powershell scripts without getting blocked by AV/EDR. Because of this, the tool is very barebones and a lot can be added to improve opsec. Do not expect this tool to completely evade detection by EDR.
Usage Examples
You can transfer the output DLL to your target system and load it into powershell various ways. For example, it can be done via P/Invoke with LoadLibrary:
Or even easier, copy powershell to an arbitrary location and side load the DLL!
Greetz/Credit/Further Reference:
Sandboxes are commonly used to analyze malware. They provide a temporary, isolated, and secure environment in which to observe whether a suspicious file exhibits any malicious behavior. However, malware developers have also developed methods to evade sandboxes and analysis environments. One such method is to perform checks to determine whether the machine the malware is being executed on is being operated by a real user. One such check is the RAM size. If the RAM size is unrealistically small (e.g., 1GB), it may indicate that the machine is a sandbox. If the malware detects a sandbox, it will not execute its true malicious behavior and may appear to be a benign file
The GetPhysicallyInstalledSystemMemory
API retrieves the amount of RAM that is physically installed on the computer from the SMBIOS firmware tables. It takes a PULONGLONG
parameter and returns TRUE
if the function succeeds, setting the TotalMemoryInKilobytes
to a nonzero value. If the function fails, it returns FALSE
.
The amount of physical memory retrieved by the GetPhysicallyInstalledSystemMemory
function must be equal to or greater than the amount reported by the GlobalMemoryStatusEx
function; if it is less, the SMBIOS data is malformed and the function fails with ERROR_INVALID_DATA
, Malformed SMBIOS data may indicate a problem with the user's computer .
The register rcx
holds the parameter TotalMemoryInKilobytes
. To overwrite the jump address of GetPhysicallyInstalledSystemMemory
, I use the following opcodes: mov qword ptr ss:[rcx],4193B840
. This moves the value 4193B840
(or 1.1 TB) to rcx
. Then, the ret instruction is used to pop the return address off the stack and jump to it, Therefore, whenever GetPhysicallyInstalledSystemMemory
is called, it will set rcx
to the custom value."
vm2-1200
Subparse, is a modular framework developed by Josh Strochein, Aaron Baker, and Odin Bernstein. The framework is designed to parse and index malware files and present the information found during the parsing in a searchable web-viewer. The framework is modular, making use of a core parsing engine, parsing modules, and a variety of enrichers that add additional information to the malware indices. The main input values for the framework are directories of malware files, which the core parsing engine or a user-specified parsing engine parses before adding additional information from any user-specified enrichment engine all before indexing the information parsed into an elasticsearch index. The information gathered can then be searched and viewed via a web-viewer, which also allows for filtering on any value gathered from any file. There are currently 3 parsing engine, the default parsing modules (ELFParser, OLEParser and PEParser), and 4 enrichment modules (ABUSEEnricher, C APEEnricher, STRINGEnricher and YARAEnricher).
ย
To get started using Subparse there are a few requrired/recommened programs that need to be installed and setup before trying to work with our software.
Software | Status | Link |
---|---|---|
Docker | Required | Installation Guide |
Python3.8.1 | Required | Installation Guide |
Pyenv | Recommended | Installation Guide |
After getting the required/recommended software installed to your system there are a few other steps that need to be taken to get Subparse installed.
sudo get apt install build-essential
pip3 install -r ./requirements.txt
docker-compose up
Note: This might take a little time due to downloading the images and setting up the containers that will be needed by Subparse.
ย
Command line options that are available for subparse/parser/subparse.py:
Argument | Alternative | Required | Description |
---|---|---|---|
-h | --help | No | Shows help menu |
-d SAMPLES_DIR | --directory SAMPLES_DIR | Yes | Directory of samples to parse |
-e ENRICHER_MODULES | --enrichers ENRICHER_MODULES | No | Enricher modules to use for additional parsing |
-r | --reset | No | Reset/delete all data in the configured Elasticsearch cluster |
-v | --verbose | No | Display verbose commandline output |
-s | --service-mode | No | Enters service mode allowing for mode samples to be added to the SAMPLES_DIR while processing |
To view the results from Subparse's parsers, navigate to localhost:8080. If you are having trouble viewing the site, make sure that you have the container started up in Docker and that there is not another process running on port 8080 that could cause the site to not be available.
ย
Before any parser is executed general information is collected about the sample regardless of the underlying file type. This information includes:
Parsers are ONLY executed on samples that match the file type. For example, PE files will by default have the PEParser executed against them due to the file type corresponding with those the PEParser is able to examine.
ย
These modules are optional modules that will ONLY get executed if specified via the -e | --enrichers flag on the command line.
ย
Subparse's web view was built using Bootstrap for its CSS, this allows for any built in Bootstrap CSS to be used when developing your own custom Parser/Enricher Vue.js files. We have also provided an example for each to help get started and have also implemented a few custom widgets to ease the process of development and to promote standardization in the way information is being displayed. All Vue.js files are used for dynamically displaying information from the custom Parser/Enricher and are used as templates for the data.
Note: Naming conventions with both class and file names must be strictly adheared to, this is the first thing that should be checked if you run into issues now getting your custom Parser/Enricher to be executed. The naming convention of your Parser/Enricher must use the same name across all of the files and class names.
The logger object is a singleton implementation of the default Python logger. For indepth usage please reference the Offical Doc. For Subparse the only logging methods that we recommend using are the logging levels for output. These are:
Neton is a tool for getting information from Internet connected sandboxes. It is composed by an agent and a web interface that displays the collected information.
The Neton agent gets information from the systems on which it runs and exfiltrates it via HTTPS to the web server.
Some of the information it collects:
All this information can be used to improve Red Team artifacts or to learn how sandboxes work and improve them.
python3 -m venv venv
source venv/bin/activate
pip3 install -r requirements.txt
python3 manage.py migrate
python3 manage.py makemigrations core
python3 manage.py migrate core
python3 manage.py createsuperuser
python3 manage.py runserver
openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout server.key -out server.crt
Launch gunicorn:
./launch_prod.sh
Build solution with Visual Studio. The agent configuration can be done from the Program.cs class.
In the sample data folder there is a sqlite database with several samples collected from the following services:
To access the sample information copy the sqlite file to the NetonWeb folder and run the application.
Credentials:
raccoon
jAmb.Abj3.j11pmMa
The Sandbox Scryer is an open-source tool for producing threat hunting and intelligence data from public sandbox detonation output The tool leverages the MITRE ATT&CK Framework to organize and prioritize findings, assisting in the assembly of IOCs, understanding attack movement and in threat hunting By allowing researchers to send thousands of samples to a sandbox for building a profile that can be used with the ATT&CK technique, the Sandbox Scryer delivers an unprecedented ability to solve use cases at scale The tool is intended for cybersecurity professionals who are interested in threat hunting and attack analysis leveraging sandbox output data. The Sandbox Scryer tool currently consumes output from the free and public Hybrid Analysis malware analysis service helping analysts expedite and scale threat hunting
[root] version.txt - Current tool version LICENSE - Defines license for source and other contents README.md - This file
[root\bin] \Linux - Pre-build binaries for running tool in Linux. Currently supports: Ubuntu x64 \MacOS - Pre-build binaries for running tool in MacOS. Currently supports: OSX 10.15 x64 \Windows - Pre-build binaries for running tool in Windows. Currently supports: Win10 x64
[root\presentation_video] Sandbox_Scryer__BlackHat_Presentation_and_demo.mp4 - Video walking through slide deck and showing demo of tool
[root\screenshots_and_videos] Various backing screenshots
[root\scripts] Parse_report_set.* - Windows PowerShell and DOS Command Window batch file scripts that invoke tool to parse each HA Sandbox report summary in test set Collate_Results.* - Windows PowerShell and DOS Command Window batch file scripts that invoke tool to collate data from parsing report summaries and generate a MITRE Navigator layer file
[root\slides] BlackHat_Arsenal_2022__Sandbox_Scryer__BH_template.pdf - PDF export of slides used to present the Sandbox Scryer at Black Hat 2022
[root\src] Sandbox_Scryer - Folder with source for Sandbox Scryer tool (in c#) and Visual Studio 2019 solution file
[root\test_data] (SHA256 filenames).json - Report summaries from submissions to Hybrid Analysis enterprise-attack__062322.json - MITRE CTI data TopAttackTechniques__High__060922.json - Top MITRE ATT&CK techniques generated with the MITRE calculator. Used to rank techniques for generating heat map in MITRE Navigator
[root\test_output] (SHA256)_report__summary_Error_Log.txt - Errors (if any) encountered while parsing report summary for SHA256 included in name (SHA256)_report__summary_Hits__Complete_List.png - Graphic showing tecniques noted while parsing report summary for SHA256 included in name (SHA256)_report__summary_MITRE_Attck_Hits.csv - For collation step, techniques and tactics with select metadata from parsing report summary for SHA256 included in name (SHA256)_report__summary_MITRE_Attck_Hits.txt - More human-readable form of .csv file. Includes ranking data of noted techniques
\collated_data collated_080122_MITRE_Attck_Heatmap.json - Layer file for import into MITRE Navigator
The Sandbox Scryer is intended to be invoked as a command-line tool, to facilitate scripting
Operation consists of two steps:
Invocation examples:
Parsing
Collation
If the parameter "-h" is specified, the built-in help is displayed as shown here Sandbox_Scryer.exe -h
Options:
-h Display command-line options
-i Input filepath
-ita Input filepath - MITRE report for top techniques
-o Output folder path
-ft Type of file to submit
-name Name to use with output
-sb_name Identifier of sandbox to use (default: ha)
-api_key API key to use with submission to sandbox
-env_id Environment ID to use with submission to sandbox
-inc_sub Include sub-techniques in graphical output (default is to not include)
-mitre_data Filepath for mitre cti data to parse (to populate att&ck techniques)
-cmd Command
Options:
parse Process report file from prior sandbox submission
Uses -i, -ita, - o, -name, -inc_sub, -sig_data parameters
col Collates report data from prior sandbox submissions
Uses -i (treated as folder path), -ita, -o, -name, -inc_sub, -mitre_data parameters
Once the Navigator layer file is produced, it may be loaded into the Navigator for viewing via https://mitre-attack.github.io/attack-navigator/
Within the Navigator, techniques noted in the sandbox report summaries are highlighted and shown with increased heat based on a combined scoring of the technique ranking and the count of hits on the technique in the sandbox report summaries. Howevering of techniques will show select metadata.
The work that follows is a POC to enable malware to "key" itself to a particular victim in order to frustrate efforts of malware analysts.
I assume no responsibility for malicious use of any ideas or code contained within this project. I provide this research to further educate infosec professionals and provide additional training/food for thought for Malware Analysts, Reverse Engineers, and Blue Teamers at large.
The first time the malware runs on a victim it AES encrypts the actual payload(an RDLL) using environmental data from that victim. Each subsequent time the malware is ran it gathers that same environmental info, AES decrypts the payload stored as a byte array within the malware, and runs it. If it fails to decrypt/the payload fails to run, the malware deletes itself. Protection against reverse engineers and malware analysts.
I didn't feel finished with this project so I went back and did a fairly substantial re-write. The original research and tradecraft may be found Here.
Major changes are as follows:
There are quite a few different things that could be taken from the source code of this project for use elsewhere. Hopefully it will be useful for someone.
There were a few shortcomings with the original release of BeatRev that I decided to try and address.
Stage2 was previously a standalone executable that was stored as the alternate data stream(ADS) of Stage1. In order to acheive the AES encryption-by-victim and subsequent decryption and execution, each time Stage1 was ran it would read the ADS, decrypt it, write back to the ADS, call CreateProcess, and then re-encrypt Stage2 and write it back to disk in the ADS. This was a lot of I/O operations and the CreateProcess call of course wasn't great.
I happened to come upon Steven Fewer's research concerning Reflective DLL's and it seemed like a good fit. Stage2 is now an RDLL; our malware/shellcode runner/whatever we want to protect can be ported to RDLL format and stored as a byte array within Stage1 that is then decrypted on runtime and executed by Stage1. This removes all of the I/O operations and the CreateProcess call from Version1 and is a welcome change.
Stage1 did not have any real kind of AV evasion measures programmed in; this was intentional, as it is extra work and wasn't really the point of this research. During the re-write I took it as an added challenge and added API-hashing to remove functions from the Import Address Table of Stage1. This has helped with detection and Stage1 has a 4/66 detection rate on VirusTotal. I was comfortable uploading Stage1 given that is is already keyed to the original box it was ran on and the file signature constantly changes because of the AES encryption that happens.
I recently started paying attention to entropy as a means to detect malware; to try and lower the otherwise very high entropy that a giant AES encrypted binary blob gives an executable I looked into integrating shellcode stored as UUID's. Because the binary is stored in string representation, there is lower overall entropy in the executable. Using this technique The entropy of Stage0 is now ~6.8 and Stage1 ~4.5 (on a max scale of 8).
Finally it is a giant chore to integrate and produce a complete Stage0 due to all of the pieces that must be manipulated. To make this easier I made a builder application that will ingest a Stage0.c template file, a Stage1 stub, a Stage2 stub, and a raw shellcode file (this was build around Stage2 being a shellcode runner containing CobaltStrike shellcode) and produce a compiled Stage0 payload for use on target.
The Reflective DLL code from Stephen Fewer contains some Visual Studio compiler-specific instructions; I'm sure it is possible to port the technique over to MingW but I do not have the skills to do so. The main problem here is that the CobaltStrike shellcode (stageless is ~265K) needs to go inside the RDLL and be compiled. To get around this and integrate it nicely with the rest of the process I wrote my Stage2 RDLL to contain a global variable chunk of memory that is the size of the CS shellcode; this ~265K chunk of memory has a small placeholder in it that can be located in the compiled binary. The code in src/Stage2 has this added already.
Once compiled, this Stage2stub is transfered to kali where a binary patch may be performed to stick the real CS shellcode into the place in memory that it belongs. This produces the complete Stage2.
To avoid the I/O and CreateProcess fiasco previously described, the complete Stage2 must also be patched into the compiled Stage1 by Stage0; this is necessary in order to allow Stage2 to be encrypted once on-target in addition to preventing Stage2 from being stored separately on disk. The same concept previously described for Stage2 is conducted by Stage0 on target in order to assemble the final Stage1 payload. It should be noted that the memmem function is used in order to locate the placeholder within each stub; this function is no available on Windows, so a custom implementation was used. Thanks to Foxik384 for his code.
In order to perform a binary patch, we must allocate the required memory up front; this has a compounding effect, as Stage1 must now be big enough to also contain Stage2. With the added step of converting Stage2 to a UUID string, Stage2 balloons in size as does Stage1 in order to hold it. A stage2 RDLL with a compiled size of ~290K results in a Stage0 payload of ~1.38M, and a Stage1 payload of ~700K.
The builder application only supports creating x64 EXE's. However with a little more work in theory you could make Stage0 a DLL, as well as Stage1, and have the whole lifecycle exist as a DLL hijack instead of a standalone executable.
These instructions will get you on your way to using this POC.
About 6 months ago it occured to me that while I had learned and done a lot with malware concerning AV/EDR evasion, I had spent very little time concerned with trying to evade or defeat reverse engineering/malware analysis. This was for a few good reasons:
Nonetheless it was an interesting thought experiment and I had a few colleagues who DO know about malware analysis that I could bounce ideas off of. It seemed a challenge of a whole different magnitude compared to AV/EDR evasion and one I decided to take a stab at.
My initial premise was that the malware, on the first time of being ran, would somehow "key" itself to that victim machine; any subsequent attempts to run it would evaluate something in the target environment and compare it for a match in the malware. If those two factors matched, it executes as expected. If they do not (as in the case where the sample had been transfered to a malware analysts sandbox), the malware deletes itself (Once again heavily leaning on the work of LloydLabs and his delete-self-poc).
This "key" must be something "unique" to the victim computer. Ideally it will be a combination of several pieces of information, and then further obfuscated. As an example, we could gather the hostname of the computer as well as the amount of RAM installed; these two values can then be concatenated (e.g. Client018192MB) and then hashed using a user-defined function to produce a number (e.g. 5343823956).
There are a ton of choices in what information to gather, but thought should be given as to what values a Blue Teamer could easily spoof; a MAC address for example may seem like an attractive "unique" identifier for a victim, however MAC addresses can easily be set manually in order for a Reverse Engineer to match their sandbox to the original victim. Ideally the values chosen and enumerated will be one that are difficult for a reverse engineer to replicate in their environment.
With some self-deletion magic, the malware could read itself into a buffer, locate a placeholder variable and replace it with this number, delete itself, and then write the modified malware back to disk in the same location. Combined with an if/else statement in Main, the next time the malware runs it will detect that it has been ran previously and then go gather the hostname and amount of RAM again in order to produce the hashed number. This would then be evaluated against the number stored in the malware during the first run (5343823956). If it matches (as is the case if the malware is running on the same machine as it originally did), it executes as expected however if a different value is returned it will again call the self-delete function in order to remove itself from disk and protect the author from the malware analyst.
This seemed like a fine idea in theory until I spoke with a colleague who has real malware analysis and reverse engineering experience. I was told that a reverse engineer would be able to observe the conditional statement in the malware (if ValueFromFirstRun != GetHostnameAndRAM()), and seeing as the expected value is hard-coded on one side of the conditional statement, simply modify the registers to contain the expected value thus completely bypassing the entire protection mechanism.
This new knowledge completely derailed the thought experiment and seeing as I didn't really have a use for a capability like this in the first place, this is where the project stopped for ~6 months.
This project resurfaced a few times over the intervening 6 months but each time was little more than a passing thought, as I had gained no new knowledge of reversing/malware analysis and again had no need for such a capability. A few days ago the idea rose again and while still neither of those factors have really changed, I guess I had a little bit more knowledge under my belt and couldn't let go of the idea this time.
With the aforementioned problem regarding hard-coding values in mind, I ultimately decided to go for a multi-stage design. I will refer to them as Stage0, Stage1, and Stage2.
Stage0: Setup. Ran on initial infection and deleted afterwards
Stage1: Runner. Ran each subsequent time the malware executes
Stage2: Payload. The malware you care about protecting. Spawns a process and injects shellcode in order to return a Beacon.
Stage0 is the fresh executable delivered to target by the attacker. It contains Stage1 and Stage2 as AES encrypted byte arrays; this is done to protect the malware in transit, or should a defender somehow get their hands on a copy of Stage0 (which shouldn't happen). The AES Key and IV are contained within Stage0 so in reality this won't protect Stage1 or Stage2 from a competent Blue Teamer.
Stage0 performs the following actions:
At the conclusion of this sequence of events, Stage0 exits. Because it was deleted from disk in step 2 and is no longer running in memory, Stage0 is effectively gone; Without prior knowledge of this technique the rest of the malware lifecycle will be a whole lot more confusing than it already is.
In step 4 the processor name and Microsoft ProductID are gathered; the ProductID is retreived from the Registry, and this value can be manually modified which presents and easy opportunity for a Blue Teamer to match their sandbox to the target environment. Depending on what environmental information is gathered this can become easier or more difficult.
Stage1 was dropped by Stage0 and exists in the same exact location as Stage0 did (to include the name). Stage2 is stored as an ADS of Stage1. When the attacker/persistence subsequently executes the malware, they are executing Stage1.
Stage1 performs the following actions:
Note that Stage2 MUST exit in order for it to be overwritten; the self-deletion trick does not appear to work on files that are already ADS's, as the self-deletion technique relies on renaming the primary data stream of the executable. Stage2 will ideally be an inject or spawn+inject executable.
There are two points that Stage1 could detect that it is not being ran from the same victim and delete itself/Stage2 in order to protect the threat actor. The first is the check for the executable header after decrypting Stage2 using the gathered environmental information; in theory this step could be bypassed by a reverse engineer, but it is a first good check. The second protection point is the result of the CreateProcess call- if it fails because Stage2 was not properly decrypted, the malware is similiary deleted. The result of this call could also be modified to prevent deletion by the reverse engineer, however this doesn't change the fact that Stage2 is encrypted and inaccessible.
Stage2 is the meat and potatoes of the malware chain; It is a fully fledged shellcode runner/piece of malware itself. By encrypting and protecting it in the way that we have, the actions of the end state malware are much better obfuscated and protected from reverse engineers and malware analysts. During development I used one of my existing shellcode runners containing CobaltStrike shellcode, but this could be anything the attacker wants to run and protect.
So what is actually accomplished with a malware lifecycle like this? There are a few interesting quirks to talk about.
Alternate data streams are a feature unique to NTFS file systems; this means that most ways of transfering the malware after initial infection will strip and lose Stage2 because it is an ADS of Stage1. Special care would have to be given in order to transfer the sample in order to preserve Stage2, as without it a lot of reverse engineers and malware analysts are going to be very confused as to what is happening. RAR archives are able to preserve ADS's and tools like 7Z and Peazip can extract files and their ADS's.
As previously mentioned, by the time malware using this lifecycle hits a Blue Teamer it should be at Stage1; Stage0 has come and gone, and Stage2 is already encrypted with the environmental information gathered by stage 0. Not knowing that Stage0 even existed will add considerable uncertainty to understanding the lifecycle and decrypting Stage2.
In theory (because again I have no reversing experience), Stage1 should be able to be reversed (after the Blue Teamers rolls through a few copies of it because it keeps deleting itself) and the information that Stage1 gathers from the target system should be able to be identified. Provided a well-orchestrated response, Blue Team should be able to identify the victim that the malware came from and go and gather that information from it and feed it into the program so that it may be transformed appropriately into the AES Key/IV that decrypts Stage2. There are a lot "ifs" in there however related to the relative skill of the reverse engineer as well as the victim machine being available for that information to be recovered.
Application Whitelisting would significantly frustrate this lifecycle. Stage0/Stage1 may be able to be side loaded as a DLL, however I suspect that Stage2 as an ADS would present some issues. I do not have an environment to test malware against AWL nor have I bothered porting this all to DLL format so I cannot say. I am sure there are creative ways around these issues.
I am also fairly confident that there are smarter ways to run Stage2 than dropping to disk and calling CreateProcess; Either manually mapping the executable or using a tool like Donut to turn it into shellcode seem like reasonable ideas.
During development I created a Builder application that Stage1 and Stage2 may be fed to in order to produce a functional Stage0; this will not be provided however I will be providing most of the source code for stage1 as it is the piece that would be most visible to a Blue Teamer. Stage0 will be excluded as an exercise for the reader, and stage2 is whatever standalone executable you want to run+protect. This POC may be further researched at the effort and discretion of able readers.
I will be providing a compiled copy of this malware as Dropper64.exe. Dropper64.exe is compiled for x64. Dropper64.exe is Stage0; it contains Stage1 and Stage2. On execution, Stage1 and Stage2 will drop to disk but will NOT automatically execute, you must run Dropper64.exe(now Stage1) again. Stage2 is an x64 version of calc.exe. I am including this for any Blue Teamers who want to take a look at this, but keep in mind in an incident response scenario 99& of the time you will be getting Stage1/Stage2, Stage0 will be gone.
This was an interesting pet project that ate up a long weekend. I'm sure it would be a lot more advanced/more complete if I had experience in a debugger and disassembler, but you do the best with what you have. I am eager to hear from Blue Teamers and other Malware Devs what they think. I am sure I have over-complicatedly re-invented the wheel here given what actual APT's are doing, but I learned a few things along the way. Thank you for reading!
In preparation for a VBS AV Evasion Stream/Video I was doing some research for Office Macro code execution methods and evasion techniques.
The list got longer and longer and I found no central place for offensive VBA templates - so this repo can be used for such. It is very far away from being complete. If you know any other cool technique or useful template feel free to contribute and create a pull request!
Most of the templates in this repo were already published somewhere. I just copy pasted most templates from ms-docs sites, blog posts or from other tools.
File | Description |
---|---|
ShellApplication_ShellExecute.vba | Execute an OS command via ShellApplication object and ShellExecute method |
ShellApplication_ShellExecute_privileged.vba | Execute an privileged OS command via ShellApplication object and ShellExecute method - UAC prompt |
Shellcode_CreateThread.vba | Execute shellcode in the current process via Win32 CreateThread |
Shellcode_EnumChildWindowsCallback.vba | Execute shellcode in the current process via EnumChildWindows |
Win32_CreateProcess.vba | Create a new process for code execution via Win32 CreateProcess function |
Win32_ShellExecute.vba | Create a new process for code execution via Win32 ShellExecute function |
WMI_Process_Create.vba | Create a new process via WMI for code execution |
WMI_Process_Create2.vba | Another WMI code execution example |
WscriptShell_Exec.vba | Execute an OS command via WscriptShell object and Exec method |
WscriptShell_run.vba | Execute an OS command via WscriptShell object and Run method |
VBA-RunPE | @itm4n's RunPE technique in VBA |
GadgetToJScript | med0x2e's C# script for generating .NET serialized gadgets that can trigger .NET assembly load/execution when deserialized using BinaryFormatter from JS/VBS/VBA based scripts. |
PPID_Spoof.vba | christophetd's spoofing-office-macro copy |
AMSIBypass_AmsiScanBuffer_ordinal.vba | rmdavy's AMSI Bypass to patch AmsiScanBuffer using ordinal values for a signature bypass |
AMSIBypass_AmsiScanBuffer_Classic.vba | rasta-mouse's classic AmsiScanBuffer patch |
AMSIBypass_Heap.vba | rmdavy's HeapsOfFun repo copy |
AMSIbypasses.vba | outflanknl's AMSI bypass blog |
COMHijack_DLL_Load.vba | Load DLL via COM Hijacking |
COM_Process_create.vba | Create process via COM object |
Download_Autostart.vba | Download a file from a remote webserver and put it into the StartUp folder |
Download_Autostart_WinAPI.vba | Download a file from a remote webserver via URLDownloadtoFileA and put it into the StartUp folder |
Dropper_Autostart.vba | Drop batch file into the StartUp folder |
Registry_Persist_wmi.vba | Create StartUp registry key for persistence via WMI |
Registry_Persist_wscript.vba | Create StartUp registry key for persistence via wscript object |
ScheduledTask_Create.vba | Create and start sheduled task for code execution/persistence |
XMLDOM_Load_XSL_Process_create.vba | Load XSL from a remote webserver to execute code |
regsvr32_sct_DownloadExecute.vba | Execute regsvr32 to download a remote webservers SCT file for code execution |
BlockETW.vba | Patch EtwEventWrite in ntdll.dll to block ETW data collection |
BlockETW_COMPLUS_ETWEnabled_ENV.vba | Block ETW data collection by setting the environment variable COMPLUS_ETWEnabled to 0, credit to @xpn |
ShellWindows_Process_create.vba | ShellWindows Process create to get explorer.exe as parent process |
AES.vba | An example to use AES encryption/decryption in VBA from Here |
Dropper_Executable_Autostart.vba | Get executable bytes from VBA and drop into Autostart - no download in this case |
MarauderDrop.vba | Drop a COM registered .NET DLL into temp, import the function and execute code - in this case loads a remote C# binary from a webserver to memory and executes it - credit to @Jean_Maes_1994 for MaraudersMap |
Dropper_Workfolders_lolbas_Execute.vba | Drop an embedded executable into the TEMP directory and execute it using C:\windows\system32\Workfolders.exe as LOLBAS - credit to @YoSignals |
SandBoxEvasion | Some SandBox Evasion templates |
Evasion Dropper Autostart.vba | Drops a file to the Startup directory bypassing file write monitoring via renamed folder operation |
Evasion MsiInstallProduct.vba | Installs a remote MSI package using WindowsInstaller ActiveXObject avoiding spawning suspicious office child process, the msi installation will be executed as a child of the MSIEXEC /V service
|
StealNetNTLMv2.vba | Steal NetNTLMv2 Hash via share connection - credit to https://book.hacktricks.xyz/windows/ntlm/places-to-steal-ntlm-creds |
Parse-Outlook.vba | Parses Outlook for sensitive keywords and file extensions, and exfils them via email - credit to JohnWoodman |
Reverse-Shell.vba | Reverse shell written entirely in VBA using Windows API calls - credit to JohnWoodman |
File | Description |
---|---|
Unhooker.vba | Unhook API's in memory to get rid of hooks |
Syscalls.vba | Syscall usage - fresh from disk or Syswhispers like |
Manymore.vba | If you have any more ideas feel free to contribute |
ASR bypass: http://blog.sevagas.com/IMG/pdf/bypass_windows_defender_attack_surface_reduction.pdf
Shellcode to VBScript conversion: https://github.com/DidierStevens/DidierStevensSuite/blob/master/shellcode2vbscript.py
Bypass AMSI in VBA: https://outflank.nl/blog/2019/04/17/bypassing-amsi-for-vba/
VBA purging: https://www.mandiant.com/resources/purgalicious-vba-macro-obfuscation-with-vba-purging
F-Secure VBA Evasion and detection post: https://blog.f-secure.com/dechaining-macros-and-evading-edr/
One more F-Secure blog: https://labs.f-secure.com/archive/dll-tricks-with-vba-to-improve-offensive-macro-capability/
Untethered + Unsandboxed code execution haxx as root on iOS 14 - iOS 14.8.1.
Based on CoreTrustDemo, also please note that certificates are not copyrightable.
Note: requires macOS + existing jailbreak
password
.make
to build/System/Library/PrivateFrameworks/CoreAnalytics.framework/Support/analyticsd
to /System/Library/PrivateFrameworks/CoreAnalytics.framework/Support/analyticsd.back
/System/Library/PrivateFrameworks/CoreAnalytics.framework/Support/analyticsd
with /usr/bin/fileproviderctl
/private/var/haxx
directory, mode should be 0777fileproviderctl_internal
and haxx
generated from the build to /usr/local/bin
on the device, mode should be 0755.After doing the above steps, fileproviderctl
will be broken, to fix it do the following steps
/usr/bin/fileproviderctl
on your device to your macgsed -i 's|/usr/local/bin/fileproviderctl_internal|/usr/local/bin/fileproviderctl_XXXXXXXX|g' fileproviderctl
codesign -s "Worth Doing Badly iPhone OS Application Signing" --preserve-metadata=entitlements --force fileproviderctl
To remove the installation, do the following steps
/System/Library/PrivateFrameworks/CoreAnalytics.framework/Support/analyticsd
to /usr/bin/fileproviderctl
/System/Library/PrivateFrameworks/CoreAnalytics.framework/Support/analyticsd.back
to /System/Library/PrivateFrameworks/CoreAnalytics.framework/Support/analyticsd
/var/haxx
, /usr/local/bin/fileproviderctl_internal
as well as /usr/local/bin/haxx
"Norimaci" is a simple and lightweight malware analysis sandbox for macOS. This tool was inspired by "Noriben". Norimaci uses the features of OpenBSM or Monitor.app to monitor macOS system activity instead of Sysinternals Process Monitor (procmon).
Norimaci consists of 3 Python scripts.
OpenBSM is a framework to audit activities on macOS. Please see their web site for details.
Monitor.app is a free tool which is made by FireEye. Please see their web site for details.
My former colleague (@cci_forensics) suggested this name.
"Norimaci" is a coined word combining "Noriben" and "Macintosh". It is pronounced "Norimaki", and it represents "ใฎใๅทปใ" in Japanese. It means "sushi roll" in English.
Noriben is a Japanese style lunch box that consists of minimal ingredients. The ingredients of norimaki are similar to noriben (seaweed, rice, and other you prefer).
So, I decided to name this tool "Norimaci".
Note that, Monitor.app supports only macOS 10.12 - 10.14. You don't have to install it, if you want to execute malware on macOS 10.15 or later. You have to use OpenBSM instead of it.
You have to install libraries below from their source repositories or pip, if you use Norimaci with Monitor.app.
You have to build a macOS VM to execute malware samples. In addition, it is highly recommended to build another VM for fake Internet connections. Because, many malware attempt to connect their servers (e.g. C2 servers).
PolarProxy and INetSim are very useful tools to provide fake HTTP/HTTPS and DNS services. Please refer NETRESEC blog to build a fake Internet.
If you use OpenBSM to monitor system activities, you have to modify /etc/security/audit_control file like below. Because, OpenBSM records audit logs about only login and authentication by default. But, Norimaci needs more kinds of audit logs (file creation, file deletion, process execution, networking, etc).
The computer has to be rebooted after the modification to apply the setting.
#
# $P4: //depot/projects/trustedbsd/openbsm/etc/audit_control#8 $
#
dir:/var/audit
flags:lo,aa,fc,fd,pc,nt,ex <- edit here like this
minfree:5
naflags:lo,aa,fc,fd,pc,nt,ex <- edit here like this
policy:cnt,argv
filesz:2M
expire-after:10M
superuser-set-sflags-mask:has_authenticated,has_console_access
superuser-clear-sflags-mask:has_authenticated,has_console_access
member-set-sflags-mask:
member-clear-sflags-mask:has_authenticated
$ sudo python3 ./norimaci.py -m openbsm -o ./out/
Password:
--===[ Norimaci v0.1.0
--===[ Minoru Kobayashi [@unkn0wnbit]
[*] Launching OpenBSM agent...
[*] When runtime is complete, press CTRL+C to stop logging.
^C
[*] Termination of OpenBSM agent commencing... please wait
[*] Converting OpenBSM data ...
[*] Loading converted macOS activity data ...
[*] Saving report to: /Users/macforensics/tools/norimaci/out/Norimaci_14_Jan_20__15_55_093219.txt
[*] Saving timeline to: /Users/macforensics/tools/norimaci/out/Norimaci_14_Jan_20__15_55_093219_timeline.csv
Note: Monitor.app can not run on macOS 10.15. But, it works fine on macOS 10.14 or earlier.
$ python3 ./norimaci.py -h
--===[ Norimaci v0.1.0
--===[ Minoru Kobayashi [@unkn0wnbit]
usage: norimaci.py [-h] [-m MONITOR] [-j JSON] [-bl OPENBSM_LOG] [-p PROCLIST]
[-ml MONITORAPP_LOG] [-o OUTPUT] [--force] [--debug]
Light weight sandbox which works with OpenBSM or Fireeye's Monitor.app
optional arguments:
-h, --help show this help message and exit
-m MONITOR, --monitor MONITOR
Specify a program to monitor macOS activity. You can
choose 'openbsm' or 'monitorapp'.
-j JSON, --json JSON Path to a JSON file which is converted by
'openbsmconv.py' or 'monitorappconv.py'.
-bl OPENBSM_LOG, --openbsm-log OPENBSM_LOG
Path to an OpenBSM log file.
-p PROCLIST, --proclist PROCLIST
Path to a process list file to process OpenBSM log
file. A file which has ".proclist" extnsion would be
used, if this option is not specified.
-ml MONITORAPP_LOG, --monitorapp-log MONITORAPP_LOG
Path to a Monitor.app data file.
-o OUTPUT, --output OUTPUT
Path to an output directory.
--force Enable to overwrite output files.
--debug Enable debug mode.
$ python3 ./openbsmconv.py -h
usage: openbsmconv.py [-h] [-f FILE] [-p PROCLIST] [-o OUT] [-c] [-rp]
[--with-failure] [--with-failure-socket] [--force]
[--debug]
Converts OpenBSM log file to JSON format.
optional arguments:
-h, --help show this help message and exit
-f FILE, --file FILE Path to a bsm log file
-p PROCLIST, --proclist PROCLIST
Path to a process list file
-o OUT, --out OUT Path to an output file
-c, --console Output JSON data to stdout.
-rp, --use-running-proclist
Use current running process list instead of a existing
process list file. And, the process list is saved to a
file which places in the same directory of '--file' or
to a file which speci fied '--proclist'.
--with-failure Output records which has a failure status too.
--with-failure-socket
Output records which has a failure status too (related
socket() syscall only).
--force Enable to overwrite an existing output file.
--debug Enable debug mode.
$ python3 ./monitorappconv.py -h
usage: monitorappconv.py [-h] [-f FILE] [-o OUT] [-c] [--force] [--debug]
Parses data of Fireeye Monitor.app and converts it to JSON format. Please note
that strings in JSON data are saved as UTF-8.
optional arguments:
-h, --help show this help message and exit
-f FILE, --file FILE Path to a saved data of Monitor.app.
-o OUT, --out OUT Path to an output file.
-c, --console Output JSON data to stdout.
--force Enable to overwrite an output file.
--debug Enable debug mode.
Analyze AppleJeus.A on macOS 10.15 Catalina with Norimaci. This demo movie was made for Japan Security Analyst Conference 2020 (JSAC2020)
git clone https://github.com/mnrkbys/norimaci.git