FreshRSS

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

Hfinger - Fingerprinting HTTP Requests

By: Zion3R


Tool for Fingerprinting HTTP requests of malware. Based on Tshark and written in Python3. Working prototype stage :-)

Its main objective is to provide unique representations (fingerprints) of malware requests, which help in their identification. Unique means here that each fingerprint should be seen only in one particular malware family, yet one family can have multiple fingerprints. Hfinger represents the request in a shorter form than printing the whole request, but still human interpretable.

Hfinger can be used in manual malware analysis but also in sandbox systems or SIEMs. The generated fingerprints are useful for grouping requests, pinpointing requests to particular malware families, identifying different operations of one family, or discovering unknown malicious requests omitted by other security systems but which share fingerprint.

An academic paper accompanies work on this tool, describing, for example, the motivation of design choices, and the evaluation of the tool compared to p0f, FATT, and Mercury.


    The idea

    The basic assumption of this project is that HTTP requests of different malware families are more or less unique, so they can be fingerprinted to provide some sort of identification. Hfinger retains information about the structure and values of some headers to provide means for further analysis. For example, grouping of similar requests - at this moment, it is still a work in progress.

    After analysis of malware's HTTP requests and headers, we have identified some parts of requests as being most distinctive. These include: * Request method * Protocol version * Header order * Popular headers' values * Payload length, entropy, and presence of non-ASCII characters

    Additionally, some standard features of the request URL were also considered. All these parts were translated into a set of features, described in details here.

    The above features are translated into varying length representation, which is the actual fingerprint. Depending on report mode, different features are used to fingerprint requests. More information on these modes is presented below. The feature selection process will be described in the forthcoming academic paper.

    Installation

    Minimum requirements needed before installation: * Python >= 3.3, * Tshark >= 2.2.0.

    Installation available from PyPI:

    pip install hfinger

    Hfinger has been tested on Xubuntu 22.04 LTS with tshark package in version 3.6.2, but should work with older versions like 2.6.10 on Xubuntu 18.04 or 3.2.3 on Xubuntu 20.04.

    Please note that as with any PoC, you should run Hfinger in a separated environment, at least with Python virtual environment. Its setup is not covered here, but you can try this tutorial.

    Usage

    After installation, you can call the tool directly from a command line with hfinger or as a Python module with python -m hfinger.

    For example:

    foo@bar:~$ hfinger -f /tmp/test.pcap
    [{"epoch_time": "1614098832.205385000", "ip_src": "127.0.0.1", "ip_dst": "127.0.0.1", "port_src": "53664", "port_dst": "8080", "fingerprint": "2|3|1|php|0.6|PO|1|us-ag,ac,ac-en,ho,co,co-ty,co-le|us-ag:f452d7a9/ac:as-as/ac-en:id/co:Ke-Al/co-ty:te-pl|A|4|1.4"}]

    Help can be displayed with short -h or long --help switches:

    usage: hfinger [-h] (-f FILE | -d DIR) [-o output_path] [-m {0,1,2,3,4}] [-v]
    [-l LOGFILE]

    Hfinger - fingerprinting malware HTTP requests stored in pcap files

    optional arguments:
    -h, --help show this help message and exit
    -f FILE, --file FILE Read a single pcap file
    -d DIR, --directory DIR
    Read pcap files from the directory DIR
    -o output_path, --output-path output_path
    Path to the output directory
    -m {0,1,2,3,4}, --mode {0,1,2,3,4}
    Fingerprint report mode.
    0 - similar number of collisions and fingerprints as mode 2, but using fewer features,
    1 - representation of all designed features, but a little more collisions than modes 0, 2, and 4,
    2 - optimal (the default mode),
    3 - the lowest number of generated fingerprints, but the highest number of collisions,
    4 - the highest fingerprint entropy, but slightly more fingerprints than modes 0-2
    -v, --verbose Report information about non-standard values in the request
    (e.g., non-ASCII characters, no CRLF tags, values not present in the configuration list).
    Without --logfile (-l) will print to the standard error.
    -l LOGFILE, --logfile LOGFILE
    Output logfile in the verbose mode. Implies -v or --verbose switch.

    You must provide a path to a pcap file (-f), or a directory (-d) with pcap files. The output is in JSON format. It will be printed to standard output or to the provided directory (-o) using the name of the source file. For example, output of the command:

    hfinger -f example.pcap -o /tmp/pcap

    will be saved to:

    /tmp/pcap/example.pcap.json

    Report mode -m/--mode can be used to change the default report mode by providing an integer in the range 0-4. The modes differ on represented request features or rounding modes. The default mode (2) was chosen by us to represent all features that are usually used during requests' analysis, but it also offers low number of collisions and generated fingerprints. With other modes, you can achieve different goals. For example, in mode 3 you get a lower number of generated fingerprints but a higher chance of a collision between malware families. If you are unsure, you don't have to change anything. More information on report modes is here.

    Beginning with version 0.2.1 Hfinger is less verbose. You should use -v/--verbose if you want to receive information about encountered non-standard values of headers, non-ASCII characters in the non-payload part of the request, lack of CRLF tags (\r\n\r\n), and other problems with analyzed requests that are not application errors. When any such issues are encountered in the verbose mode, they will be printed to the standard error output. You can also save the log to a defined location using -l/--log switch (it implies -v/--verbose). The log data will be appended to the log file.

    Using hfinger in a Python application

    Beginning with version 0.2.0, Hfinger supports importing to other Python applications. To use it in your app simply import hfinger_analyze function from hfinger.analysis and call it with a path to the pcap file and reporting mode. The returned result is a list of dicts with fingerprinting results.

    For example:

    from hfinger.analysis import hfinger_analyze

    pcap_path = "SPECIFY_PCAP_PATH_HERE"
    reporting_mode = 4
    print(hfinger_analyze(pcap_path, reporting_mode))

    Beginning with version 0.2.1 Hfinger uses logging module for logging information about encountered non-standard values of headers, non-ASCII characters in the non-payload part of the request, lack of CRLF tags (\r\n\r\n), and other problems with analyzed requests that are not application errors. Hfinger creates its own logger using name hfinger, but without prior configuration log information in practice is discarded. If you want to receive this log information, before calling hfinger_analyze, you should configure hfinger logger, set log level to logging.INFO, configure log handler up to your needs, add it to the logger. More information is available in the hfinger_analyze function docstring.

    Fingerprint creation

    A fingerprint is based on features extracted from a request. Usage of particular features from the full list depends on the chosen report mode from a predefined list (more information on report modes is here). The figure below represents the creation of an exemplary fingerprint in the default report mode.

    Three parts of the request are analyzed to extract information: URI, headers' structure (including method and protocol version), and payload. Particular features of the fingerprint are separated using | (pipe). The final fingerprint generated for the POST request from the example is:

    2|3|1|php|0.6|PO|1|us-ag,ac,ac-en,ho,co,co-ty,co-le|us-ag:f452d7a9/ac:as-as/ac-en:id/co:Ke-Al/co-ty:te-pl|A|4|1.4

    The creation of features is described below in the order of appearance in the fingerprint.

    Firstly, URI features are extracted: * URI length represented as a logarithm base 10 of the length, rounded to an integer, (in the example URI is 43 characters long, so log10(43)≈2), * number of directories, (in the example there are 3 directories), * average directory length, represented as a logarithm with base 10 of the actual average length of the directory, rounded to an integer, (in the example there are three directories with total length of 20 characters (6+6+8), so log10(20/3)≈1), * extension of the requested file, but only if it is on a list of known extensions in hfinger/configs/extensions.txt, * average value length represented as a logarithm with base 10 of the actual average value length, rounded to one decimal point, (in the example two values have the same length of 4 characters, what is obviously equal to 4 characters, and log10(4)≈0.6).

    Secondly, header structure features are analyzed: * request method encoded as first two letters of the method (PO), * protocol version encoded as an integer (1 for version 1.1, 0 for version 1.0, and 9 for version 0.9), * order of the headers, * and popular headers and their values.

    To represent order of the headers in the request, each header's name is encoded according to the schema in hfinger/configs/headerslow.json, for example, User-Agent header is encoded as us-ag. Encoded names are separated by ,. If the header name does not start with an upper case letter (or any of its parts when analyzing compound headers such as Accept-Encoding), then encoded representation is prefixed with !. If the header name is not on the list of the known headers, it is hashed using FNV1a hash, and the hash is used as encoding.

    When analyzing popular headers, the request is checked if they appear in it. These headers are: * Connection * Accept-Encoding * Content-Encoding * Cache-Control * TE * Accept-Charset * Content-Type * Accept * Accept-Language * User-Agent

    When the header is found in the request, its value is checked against a table of typical values to create pairs of header_name_representation:value_representation. The name of the header is encoded according to the schema in hfinger/configs/headerslow.json (as presented before), and the value is encoded according to schema stored in hfinger/configs directory or configs.py file, depending on the header. In the above example Accept is encoded as ac and its value */* as as-as (asterisk-asterisk), giving ac:as-as. The pairs are inserted into fingerprint in order of appearance in the request and are delimited using /. If the header value cannot be found in the encoding table, it is hashed using the FNV1a hash.
    If the header value is composed of multiple values, they are tokenized to provide a list of values delimited with ,, for example, Accept: */*, text/* would give ac:as-as,te-as. However, at this point of development, if the header value contains a "quality value" tag (q=), then the whole value is encoded with its FNV1a hash. Finally, values of User-Agent and Accept-Language headers are directly encoded using their FNV1a hashes.

    Finally, in the payload features: * presence of non-ASCII characters, represented with the letter N, and with A otherwise, * payload's Shannon entropy, rounded to an integer, * and payload length, represented as a logarithm with base 10 of the actual payload length, rounded to one decimal point.

    Report modes

    Hfinger operates in five report modes, which differ in features represented in the fingerprint, thus information extracted from requests. These are (with the number used in the tool configuration): * mode 0 - producing a similar number of collisions and fingerprints as mode 2, but using fewer features, * mode 1 - representing all designed features, but producing a little more collisions than modes 0, 2, and 4, * mode 2 - optimal (the default mode), representing all features which are usually used during requests' analysis, but also offering a low number of collisions and generated fingerprints, * mode 3 - producing the lowest number of generated fingerprints from all modes, but achieving the highest number of collisions, * mode 4 - offering the highest fingerprint entropy, but also generating slightly more fingerprints than modes 0-2.

    The modes were chosen in order to optimize Hfinger's capabilities to uniquely identify malware families versus the number of generated fingerprints. Modes 0, 2, and 4 offer a similar number of collisions between malware families, however, mode 4 generates a little more fingerprints than the other two. Mode 2 represents more request features than mode 0 with a comparable number of generated fingerprints and collisions. Mode 1 is the only one representing all designed features, but it increases the number of collisions by almost two times comparing to modes 0, 1, and 4. Mode 3 produces at least two times fewer fingerprints than other modes, but it introduces about nine times more collisions. Description of all designed features is here.

    The modes consist of features (in the order of appearance in the fingerprint): * mode 0: * number of directories, * average directory length represented as an integer, * extension of the requested file, * average value length represented as a float, * order of headers, * popular headers and their values, * payload length represented as a float. * mode 1: * URI length represented as an integer, * number of directories, * average directory length represented as an integer, * extension of the requested file, * variable length represented as an integer, * number of variables, * average value length represented as an integer, * request method, * version of protocol, * order of headers, * popular headers and their values, * presence of non-ASCII characters, * payload entropy represented as an integer, * payload length represented as an integer. * mode 2: * URI length represented as an integer, * number of directories, * average directory length represented as an integer, * extension of the requested file, * average value length represented as a float, * request method, * version of protocol, * order of headers, * popular headers and their values, * presence of non-ASCII characters, * payload entropy represented as an integer, * payload length represented as a float. * mode 3: * URI length represented as an integer, * average directory length represented as an integer, * extension of the requested file, * average value length represented as an integer, * order of headers. * mode 4: * URI length represented as a float, * number of directories, * average directory length represented as a float, * extension of the requested file, * variable length represented as a float, * average value length represented as a float, * request method, * version of protocol, * order of headers, * popular headers and their values, * presence of non-ASCII characters, * payload entropy represented as a float, * payload length represented as a float.



    Grandoreiro Banking Trojan Resurfaces, Targeting Over 1,500 Banks Worldwide

    The threat actors behind the Windows-based Grandoreiro banking trojan have returned in a global campaign since March 2024 following a law enforcement takedown in January. The large-scale phishing attacks, likely facilitated by other cybercriminals via a malware-as-a-service (MaaS) model, target over 1,500 banks across the world, spanning more than 60 countries in Central and South

    New 'Cuckoo' Persistent macOS Spyware Targeting Intel and Arm Macs

    Cybersecurity researchers have discovered a new information stealer targeting Apple macOS systems that's designed to set up persistence on the infected hosts and act as a spyware. Dubbed Cuckoo by Kandji, the malware is a universal Mach-O binary that's capable of running on both Intel- and Arm-based Macs. The exact distribution vector is currently unclear, although there are

    Sandbox Escape Vulnerabilities in Judge0 Expose Systems to Complete Takeover

    Multiple critical security flaws have been disclosed in the Judge0 open-source online code execution system that could be exploited to obtain code execution on the target system. The three flaws, all critical in nature, allow an "adversary with sufficient access to perform a sandbox escape and obtain root permissions on the host machine," Australian

    Google Postpones Third-Party Cookie Deprecation Amid U.K. Regulatory Scrutiny

    Google has once again pushed its plans to deprecate third-party tracking cookies in its Chrome web browser as it works to address outstanding competition concerns from U.K. regulators over its Privacy Sandbox initiative. The tech giant said it's working closely with the U.K. Competition and Markets Authority (CMA) and hopes to achieve an agreement by the end of the year. As part of the

    How to Conduct Advanced Static Analysis in a Malware Sandbox

    Sandboxes are synonymous with dynamic malware analysis. They help to execute malicious files in a safe virtual environment and observe their behavior. However, they also offer plenty of value in terms of static analysis. See these five scenarios where a sandbox can prove to be a useful tool in your investigations. Detecting Threats in PDFs PDF files are frequently exploited by threat actors to

    Google Chrome Adds V8 Sandbox - A New Defense Against Browser Attacks

    Google has announced support for what's called a V8 Sandbox in the Chrome web browser in an effort to address memory corruption issues. The sandbox, according to V8 security technical lead Samuel Groß, aims to prevent "memory corruption in V8 from spreading within the host process." The search behemoth has described V8 Sandbox as a lightweight, in-process sandbox

    Microsoft Edge Bug Could Have Allowed Attackers to Silently Install Malicious Extensions

    A now-patched security flaw in the Microsoft Edge web browser could have been abused to install arbitrary extensions on users' systems and carry out malicious actions.  "This flaw could have allowed an attacker to exploit a private API, initially intended for marketing purposes, to covertly install additional browser extensions with broad permissions without the user's knowledge," Guardio

    Demystifying a Common Cybersecurity Myth

    One of the most common misconceptions in file upload cybersecurity is that certain tools are “enough” on their own—this is simply not the case. In our latest whitepaper OPSWAT CEO and Founder, Benny Czarny, takes a comprehensive look at what it takes to prevent malware threats in today’s ever-evolving file upload security landscape, and a big part of that is understanding where the

    TimbreStealer Malware Spreading via Tax-themed Phishing Scam Targets IT Users

    Mexican users have been targeted with tax-themed phishing lures at least since November 2023 to distribute a previously undocumented Windows malware called TimbreStealer. Cisco Talos, which discovered the activity, described the authors as skilled and that the "threat actor has previously used similar tactics, techniques and procedures (TTPs) to distribute a banking trojan known

    From Alert to Action: How to Speed Up Your SOC Investigations

    Processing alerts quickly and efficiently is the cornerstone of a Security Operations Center (SOC) professional's role. Threat intelligence platforms can significantly enhance their ability to do so. Let's find out what these platforms are and how they can empower analysts. The Challenge: Alert Overload The modern SOC faces a relentless barrage of security alerts generated by SIEMs and EDRs.

    Google's New Tracking Protection in Chrome Blocks Third-Party Cookies

    Google on Thursday announced that it will start testing a new feature called "Tracking Protection" beginning January 4, 2024, to 1% of Chrome users as part of its efforts to deprecate third-party cookies in the web browser. The setting is designed to limit "cross-site tracking by restricting website access to third-party cookies by default," Anthony Chavez, vice president of Privacy

    New FjordPhantom Android Malware Targets Banking Apps in Southeast Asia

    Cybersecurity researchers have disclosed a new sophisticated Android malware called FjordPhantom that has been observed targeting users in Southeast Asian countries like Indonesia, Thailand, and Vietnam since early September 2023. "Spreading primarily through messaging services, it combines app-based malware with social engineering to defraud banking customers," Oslo-based mobile app

    Zero-Day Alert: Google Chrome Under Active Attack, Exploiting New Vulnerability

    Google has rolled out security updates to fix seven security issues in its Chrome browser, including a zero-day that has come under active exploitation in the wild. Tracked as CVE-2023-6345, the high-severity vulnerability has been described as an integer overflow bug in Skia, an open source 2D graphics library. Benoît Sevens and Clément Lecigne of Google's Threat Analysis Group (TAG) have

    LummaC2 Malware Deploys New Trigonometry-Based Anti-Sandbox Technique

    The stealer malware known as LummaC2 (aka Lumma Stealer) now features a new anti-sandbox technique that leverages the mathematical principle of trigonometry to evade detection and exfiltrate valuable information from infected hosts. The method is designed to "delay detonation of the sample until human mouse activity is detected," Outpost24 security researcher Alberto Marín said in a technical

    LightsOut - Generate An Obfuscated DLL That Will Disable AMSI And ETW

    By: Zion3R


    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:

    • XOR encoding for strings
    • WinAPI function name randomization
    • Multiple sandbox check options
    • Hardware breakpoint bypass option
     _______________________
    | |
    | 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 &lt ;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:



    Google Chrome Rolls Out Support for 'Privacy Sandbox' to Bid Farewell to Tracking Cookies

    By: THN
    Google has officially begun its rollout of Privacy Sandbox in the Chrome web browser to a majority of its users, nearly four months after it announced the plans. "We believe it is vital to both improve privacy and preserve access to information, whether it's news, a how-to-guide, or a fun video," Anthony Chavez, vice president of Privacy Sandbox initiatives at Google, said. "Without viable

    New BLISTER Malware Update Fuelling Stealthy Network Infiltration

    By: THN
    An updated version of a malware loader known as BLISTER is being used as part of SocGholish infection chains to distribute an open-source command-and-control (C2) framework called Mythic. “New BLISTER update includes keying feature that allows for precise targeting of victim networks and lowers exposure within VM/sandbox environments,” Elastic Security Labs researchers Salim Bitam and Daniel

    New P2PInfect Worm Targeting Redis Servers on Linux and Windows Systems

    By: THN
    Cybersecurity researchers have uncovered a new cloud targeting, peer-to-peer (P2P) worm called P2PInfect that targets vulnerable Redis instances for follow-on exploitation. "P2PInfect exploits Redis servers running on both Linux and Windows Operating Systems making it more scalable and potent than other worms," Palo Alto Networks Unit 42 researchers William Gamazo and Nathaniel Quist said. "This

    Bypass-Sandbox-Evasion - Bypass Malware Sandbox Evasion Ram Check

    By: Zion3R


    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

    Details

    • 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."



    Privacy Sandbox Initiative: Google to Phase Out Third-Party Cookies Starting 2024

    Google has announced plans to officially flip the switch on its twice-delayed Privacy Sandbox initiatives as it slowly works its way to deprecate support for third-party cookies in Chrome browser. To that end, the search and advertising giant said it intends to phase out third-party cookies for 1% of Chrome users globally in the first quarter of 2024. "This will support developers in conducting

    Why Your Detection-First Security Approach Isn't Working

    Stopping new and evasive threats is one of the greatest challenges in cybersecurity. This is among the biggest reasons why attacks increased dramatically in the past year yet again, despite the estimated $172 billion spent on global cybersecurity in 2022. Armed with cloud-based tools and backed by sophisticated affiliate networks, threat actors can develop new and evasive malware more quickly

    Critical Flaws in vm2 JavaScript Library Can Lead to Remote Code Execution

    A fresh round of patches has been made available for the vm2 JavaScript library to address two critical flaws that could be exploited to break out of sandbox protections and achieve code execution. Both the flaws – CVE-2023-29199 and CVE-2023-30547 – are rated 9.8 out of 10 on the CVSS scoring system and have been addressed in versions 3.9.16 and 3.9.17, respectively. Successful exploitation of

    Popular server-side JavaScript security sandbox “vm2” patches remote execution hole

    The security error was in the error handling system that was supposed to catch potential security errors...

    vm2-1200

    Researchers Discover Critical Remote Code Execution Flaw in vm2 Sandbox Library

    The maintainers of the vm2 JavaScript sandbox module have shipped a patch to address a critical flaw that could be abused to break out of security boundaries and execute arbitrary shellcode. The flaw, which affects all versions, including and prior to 3.9.14, was reported by researchers from South Korea-based KAIST WSP Lab on April 6, 2023, prompting vm2 to release a fix with version 3.9.15 on

    Google Rolling Out Privacy Sandbox Beta on Android 13 Devices

    Google announced on Tuesday that it's officially rolling out Privacy Sandbox on Android in beta to eligible mobile devices running Android 13. "The Privacy Sandbox Beta provides new APIs that are designed with privacy at the core, and don't use identifiers that can track your activity across apps and websites," the search and advertising giant said. "Apps that choose to participate in the Beta

    Subparse - Modular Malware Analysis Artifact Collection And Correlation Framework


    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).

     

    Getting Started

    Software Requirements

    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

    Additional Requirements

    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.


    Python Requirements
    Python requires some other packages to be installed that Subparse is dependent on for its processes. To get the Python set up completed navigate to the location of your Subparse installation and go to the *parser* folder. The following commands that you will need to use to install the Python requirements is:
    sudo get apt install build-essential
    pip3 install -r ./requirements.txt

    Docker Requirements
    Since Subparse uses Docker for its backend and web interface, the set up of the Docker containers needs to be completed before being able to use the program. To do this navigate to the root directory of the Subparse installation location, and use the following command to set up the docker instances:
    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.

     

    Installation steps


    Usage

    Command Line Options

    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

    Viewing Results

    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.

     

    General Information Collected

    Before any parser is executed general information is collected about the sample regardless of the underlying file type. This information includes:

    • MD5 hash of the sample
    • SHA256 hash of the sample
    • Sample name
    • Sample size
    • Extension of sample
    • Derived extension of sample

    Parser Modules

    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.

    Default Modules


    ELFParser
    This is the default parsing module that will be executed against ELF files. Information that is collected:
    • General Information
    • Program Headers
    • Section Headers
    • Notes
    • Architecture Specific Data
    • Version Information
    • Arm Unwind Information
    • Relocation Data
    • Dynamic Tags

    OLEParser
    This is the default parsing module that will be executed against OLE and RTF formatted files, this uses the OLETools package to obtain data. The information that is collected:
    • Meta Data
    • MRaptor
    • RTF
    • Times
    • Indicators
    • VBA / VBA Macros
    • OLE Objects

    PEParser
    This is the default parsing module that will be executed against PE files that match or include the file types: PE32 and MS-Dos. Information that is collected:
    • Section code and count
    • Entry point
    • Image base
    • Signature
    • Imports
    • Exports

     

    Enricher Modules

    These modules are optional modules that will ONLY get executed if specified via the -e | --enrichers flag on the command line.

    Default Modules


    ABUSEEnricher
    This enrichers uses the [Abuse.ch](https://abuse.ch/) API and [Malware Bazaar](https://bazaar.abuse.ch) to collect more information about the sample(s) subparse is analyzing, the information is then aggregated and stored in the Elastic database.
    CAPEEnricher
    This enrichers is used to communicate with a CAPEv2 Sandbox instance, to collect more information about the sample(s) through dynamic analysis, the information is then aggregated and stored in the Elastic database utilizing the Kafka Messaging Service for background processing.
    STRINGEnricher
    This enricher is a smart string enricher, that will parse the sample for potentially interesting strings. The categories of strings that this enricher looks for include: Audio, Images, Executable Files, Code Calls, Compressed Files, Work (Office Docs.), IP Addresses, IP Address + Port, Website URLs, Command Line Arguments.
    YARAEnricher
    This ericher uses a pre-compiled yara file located at: parser/src/enrichers/yara_rules. This pre-compiled file includes rules from VirusTotal and YaraRulesProject

     

    Developing Custom Parsers & Enrichers

    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.



    Logging

    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:

    • debug
    • warning
    • error
    • critical
    • exception
    • log
    • info


    ACKNOWLEDGEMENTS

    • This research and all the co-authors have been supported by NSA Grant H98230-20-1-0326.


    Neton - Tool For Getting Information From Internet Connected Sandboxes


    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:

    • Operating system and hardware information
    • Find files on mounted drives
    • List unsigned microsoft drivers
    • Run SharpEDRChecker
    • Run Pafish
    • Run Al-Khaser
    • Detect hooks
    • Take screenshots of the desktop

    All this information can be used to improve Red Team artifacts or to learn how sandboxes work and improve them.


    Images

    Deployment

    NetonWeb

    1. Install (with virtualenv):
    python3 -m venv venv
    source venv/bin/activate
    pip3 install -r requirements.txt
    1. Configure the database:
    python3 manage.py migrate
    python3 manage.py makemigrations core
    python3 manage.py migrate core
    • Create user:
    python3 manage.py createsuperuser

    Launch (test)

    python3 manage.py runserver

    Launch (prod)

    • Generate the certificates and store them in the certs folder:
    openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout server.key -out server.crt

    Launch gunicorn:

    ./launch_prod.sh

    Agent

    Build solution with Visual Studio. The agent configuration can be done from the Program.cs class.

    • url variable: Url where the information will be exfiltrated (NetonWeb's).
    • sandboxId variable: Identifier of the sandbox where the samples are uploaded.
    • wave variable: Way of organising the different times the samples are sent. muestras.

    Sample data

    In the sample data folder there is a sqlite database with several samples collected from the following services:

    • Virustotal
    • Tria.ge
    • Metadefender
    • Hybrid Analysis
    • Any.run
    • Intezer Analyze
    • Pikker
    • AlienVault OTX
    • Threat.Zone

    To access the sample information copy the sqlite file to the NetonWeb folder and run the application.

    Credentials:

    • User: raccoon
    • Password: jAmb.Abj3.j11pmMa

    Extra info

    Credits



    Sandbox_Scryer - Tool For Producing Threat Hunting And Intelligence Data From Public Sandbox Detonation Output


    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


    Repository contents

    [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

    Operation

    The Sandbox Scryer is intended to be invoked as a command-line tool, to facilitate scripting

    Operation consists of two steps:

    • Parsing, where a specified report summary is parsed to extract the output noted earlier
    • Collation, where the data from the set of parsing results from the parsing step is collated to produce a Navigator layer file

    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.



    Google to Roll Out Privacy Sandbox Beta on Android 13 by Early 2023

    Internet behemoth Google on Tuesday said it plans to roll out Privacy Sandbox for Android in beta to mobile devices running Android 13 starting early next year. "The Privacy Sandbox Beta will be available for ad tech and app developers who wish to test the ads-related APIs as part of their solutions," the company said. To that end, developers will need to complete an enrollment process in order

    Not All Sandboxes Are for Children: How to Secure Your SaaS Sandbox

    When creating a Sandbox, the mindset tends to be that the Sandbox is considered a place to play around, test things, and there will be no effect on the production or operational system. Therefore, people don't actively think they need to worry about its security. This mindset is not only wrong, but extremely dangerous.  When it comes to software developers, their version of sandbox is similar to

    Researchers Detail Critical RCE Flaw Reported in Popular vm2 JavaScript Sandbox

    A now-patched security flaw in the vm2 JavaScript sandbox module could be abused by a remote adversary to break out of security barriers and perform arbitrary operations on the underlying machine. "A threat actor can bypass the sandbox protections to gain remote code execution rights on the host running the sandbox," GitHub said in an advisory published on September 28, 2022. <!--adsense--> The

    BeatRev - POC For Frustrating/Defeating Malware Analysts


    BeatRev Version 2

    Disclaimer/Liability

    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.


    TLDR

    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.



    Updated 6 JUNE 2022



    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:

    1. I have released all source code
    2. I integrated Stephen Fewer's ReflectiveDLL into the project to replace Stage2
    3. I formatted some of the byte arrays in this project into string format and parse them with UuidFromStringA. This Repo was used as a template. This was done to lower entropy of Stage0 and Stage1
    4. Stage0 has had a fair bit of AV evasion built into it. Thanks to Cerbersec's Project Ares for inspiration
    5. The builder application to produce Stage0 has been included

    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.

    Problems with Original Release and Mitigations

    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.

    Technical Details

    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.

    Instructions

    These instructions will get you on your way to using this POC.

    1. Compile Builder using gcc -o builder src/Builder/BeatRevV2Builder.c
    2. Modify sc_length variable in src/Stage2/dll/src/ReflectiveDLL.c to match the length of raw shellcode file used with builder ( I have included fakesc.bin for example)
    3. Compile Stage2 (in visual studio, ReflectiveDLL project uses some VS compiler-specific instructions)
    4. Move compiled stage2stub.dll back to kali, modify src/Stage1/newstage1.c and define stage2size as the size of stage2stub
    5. Compile stage1stub using x86_64-w64-mingw32-gcc newstage1.c -o stage1stub.exe -s -DUNICODE -Os -L /usr/x86_64-w64-mingw32/lib -l:librpcrt4.a
    6. Run builder using syntax: ./builder src/Stage0/newstage0_exe.c x64 stage1stub.exe stage2stub.dll shellcode.bin
    7. Builder will produce dropper.exe. This is a formatted and compiled Stage0 payload for use on target.

    BeatRev Original Release

    Introduction

    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:

    1. I don't know anything about malware analysis or reverse engineering
    2. When you are talking about legal, sanctioned Red Team work there isn't really a need to try and frustrate or defeat a reverse engineer because the activity should have been deconflicted long before it reaches that stage.

    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.

    Premise

    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.

    Overview

    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.

    Lifecycle

    Stage0

    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:

    1. Sandbox evasion.
    2. Delete itself from disk. It is still running in memory.
    3. Decrypts Stage1 using stored AES Key/IV and writes to disk in place of Stage0.
    4. Gathers the processor name and the Microsoft ProductID.
    5. Hashes this value and then pads it to fit a 16 byte AES key length. This value reversed serves as the AES IV.
    6. Decrypts Stage2 using stored AES Key/IV.
    7. Encrypts Stage2 using new victim-specific AES Key/IV.
    8. Writes Stage2 to disk as an alternate data stream of Stage1.

    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

    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:

    1. Sandbox evasion.
    2. Gathers the processor name and the Microsoft ProductID.
    3. Hashes this value and then pads it to fit a 16 byte AES key length. This value reversed serves as the AES IV.
    4. Reads Stage2 from Stage1's ADS into memory.
    5. Decrypts Stage2 using the victim-specific AES Key/IV.
    6. Checks first two bytes of decryted Stage2 buffer; if not MZ (unsuccessful decryption), delete Stage1/Stage2, exit.
    7. Writes decrypted Stage2 back to disk as ADS of Stage1
    8. Calls CreateProcess on Stage2. If this fails (unsuccessful decryption), delete Stage1/Stage2, exit.
    9. Sleeps 5 seconds to allow Stage2 to execute + exit so it can be overwritten.
    10. Encrypts Stage2 using victim-specific AES Key/IV
    11. Writes encrypted Stage2 back to disk as ADS of Stage1.

    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

    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.

    Impact, Mitigation, and Further Work

    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.

    Code and binary

    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.

    Conclusion

    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!



    OffensiveVBA - Code Execution And AV Evasion Methods For Macros In Office Documents


    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.


    Templates in this repo

    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

    Missing - ToDos

    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

    Obfuscators / Payload generators

    1. VBad
    2. wePWNise
    3. VisualBasicObfuscator - needs some modification as it doesn't split up lines and is therefore not usable for office document macros
    4. macro_pack
    5. shellcode2vbscript.py
    6. EvilClippy
    7. OfficePurge
    8. SharpShooter
    9. VBS-Obfuscator-in-Python - - needs some modification as it doesn't split up lines and is therefore not usable for office document macros

    Credits / usefull resources

    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/



    Google Delays Blocking 3rd-Party Cookies in Chrome Browser Until 2024

    Google on Wednesday said it's once again delaying its plans to turn off third-party cookies in the Chrome web browser from late 2023 to the second half of 2024. "The most consistent feedback we've received is the need for more time to evaluate and test the new Privacy Sandbox technologies before deprecating third-party cookies in Chrome," Anthony Chavez, vice president of Privacy Sandbox, said.

    Microsoft Details App Sandbox Escape Bug Impacting Apple iOS, iPadOS, macOS Devices

    Microsoft on Wednesday shed light on a now patched security vulnerability affecting Apple's operating systems that, if successfully exploited, could allow attackers to escalate device privileges and deploy malware. "An attacker could take advantage of this sandbox escape vulnerability to gain elevated privileges on the affected device or execute malicious commands like installing additional

    Haxx - Untethered + Unsandboxed Code Execution Haxx As Root On iOS 14 - iOS 14.8.1


    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.


    Usage

    Note: requires macOS + existing jailbreak

    Get up and running

    1. On your mac import dev_certificate.p12 into the keychain, and the password is password.
    2. Modify haxx.c to include your own code (if you need it).
    3. Run make to build
    4. On the device, Copy /System/Library/PrivateFrameworks/CoreAnalytics.framework/Support/analyticsd to /System/Library/PrivateFrameworks/CoreAnalytics.framework/Support/analyticsd.back
    5. Then replace /System/Library/PrivateFrameworks/CoreAnalytics.framework/Support/analyticsd with /usr/bin/fileproviderctl
    6. Create the /private/var/haxx directory, mode should be 0777
    7. Copy fileproviderctl_internal and haxx generated from the build to /usr/local/bin on the device, mode should be 0755.
    8. Profit.

    Fixing fileproviderctl

    After doing the above steps, fileproviderctl will be broken, to fix it do the following steps

    1. Grab a copy of /usr/bin/fileproviderctl on your device to your mac
    2. Patch the binary with GNU sed: gsed -i 's|/usr/local/bin/fileproviderctl_internal|/usr/local/bin/fileproviderctl_XXXXXXXX|g' fileproviderctl
    3. Resign it: codesign -s "Worth Doing Badly iPhone OS Application Signing" --preserve-metadata=entitlements --force fileproviderctl
    4. Put the fixed binary back onto your device.

    Removal

    To remove the installation, do the following steps

    1. Copy /System/Library/PrivateFrameworks/CoreAnalytics.framework/Support/analyticsd to /usr/bin/fileproviderctl
    2. Move /System/Library/PrivateFrameworks/CoreAnalytics.framework/Support/analyticsd.back to /System/Library/PrivateFrameworks/CoreAnalytics.framework/Support/analyticsd
    3. Delete /var/haxx, /usr/local/bin/fileproviderctl_internal as well as /usr/local/bin/haxx


    Firefox out-of-band update to 100.0.1 – just in time for Pwn2Own?

    A new point-release of Firefox. Not unusual, but the timing of this one is interesting, with Pwn2Own coming up in a few days.

    Firefox update brings a whole new sort of security sandbox

    Firefox 95.0 is out, with the usual security fixes... plus some funky new ones.

    ❌