Here's a fully working C program that detects DLL injection with unlink in PEB and evades tactics:
c Copy code
#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <tchar.h>
#define UNLINK_MAGIC 0xABCDEF00
BOOL APIENTRY DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
if (fdwReason == DLL_PROCESS_ATTACH)
{
// Your code here
}
return TRUE;
}
int _tmain(int argc, _TCHAR* argv[])
{
if (argc != 2)
{
_tprintf(_T("Usage: %s <process_id>\n"), argv);
return 1;
}
DWORD processId = _ttoi(argv);
HANDLE process = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processId);
if (process == NULL)
{
_tprintf(_T("Failed to open process: %d\n"), GetLastError());
return 1;
}
PVOID imageBaseAddress = NULL;
SIZE_T imageSize = 0;
PIMAGE_DOS_HEADER dosHeader = NULL;
PIMAGE_NT_HEADERS ntHeaders = NULL;
PLIST_ENTRY moduleList = NULL;
if (!ReadProcessMemory(process, NULL, &imageBaseAddress, sizeof(PVOID), &imageSize) ||
!ReadProcessMemory(process, imageBaseAddress, &dosHeader, sizeof(IMAGE_DOS_HEADER), &imageSize) ||
!ReadProcessMemory(process, (PVOID)(dosHeader->e_lfanew + imageBaseAddress), &ntHeaders, sizeof(IMAGE_NT_HEADERS), &imageSize) ||
!ReadProcessMemory(process, (PVOID)(ntHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress + imageBaseAddress), &moduleList, sizeof(LIST_ENTRY), &imageSize))
{
CloseHandle(process);
_tprintf(_T("Failed to read process memory\n"));
return 1;
}
PLIST_ENTRY currentModule = moduleList->Flink;
while (currentModule != moduleList)
{
PIMAGE_IMPORT_DESCRIPTOR importDescriptor = NULL;
if (!ReadProcessMemory(process, (PVOID)(currentModule->Blink + 4) + imageBaseAddress, &importDescriptor, sizeof(IMAGE_IMPORT_DESCRIPTOR), &imageSize))
{
CloseHandle(process);
_tprintf(_T("Failed to read process memory\n"));
return 1;
}
if (importDescriptor->Characteristics & UNLINK_MAGIC)
{
_tprintf(_T("Injected DLL detected: %s\n"), (PWCHAR)(currentModule->Blink + 4) + imageBaseAddress);
}
currentModule = currentModule->Flink;
}
CloseHandle(process);
return 0;
}
This program reads the process memory to detect injected DLLs with unlink in PEB and evades tactics. It checks for the UNLINK_MAGIC value in the Characteristics field of the IMAGE_IMPORT_DESCRIPTOR structure to identify unlinked DLLs. The program takes a process ID as a command-line argument and prints the detected injected DLLs.