.NET 调用API创建系统服务实现权限维持

在Windows操作系统中,Services服务以后台进程的形式运行的,通常具备非常高的权限启动和运行服务。因此红队往往利用.NET框架通过创建和管理Windows服务来实现权限维持。本文将详细介绍如何通过.NET创建Windows服务,以实现权限维持的基本原理和步骤。

0x01 OpenSCManager

在创建Windows服务之前,首先需要打开SCM服务控制管理数据库。服务控制管理器是Windows用来管理所有系统服务的组件。通过调用OpenSCManager函数,可以打开该数据库并获取其句柄。函数原型如下所示。

复制代码
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr OpenSCManager(string machineName, string databaseName, uint dwAccess);

只有成功打开了服务控制管理器数据库,才能继续创建服务。比如通过.NET进行调用,如下代码所示。

复制代码
IntPtr intPtr = Program.OpenSCManager(null, null, 2U);
if (intPtr == IntPtr.Zero)
{
     throw new Exception("Failed to open service control manager.");
}

上述代码中,指定访问权限为2U,代表SC_MANAGER_CREATE_SERVICE,表示允许创建系统服务。

0x02 CreateService

在成功获取服务控制管理器数据库的句柄后,可以调用CreateService函数来创建一个新的系统服务。函数在.NET中的调用如下所示。

复制代码
[DllImport("Advapi32.dll")]
public static extern IntPtr CreateService(IntPtr serviceControlManagerHandle, string lpSvcName, string lpDisplayName, Program.SERVICE_ACCESS dwDesiredAccess, uint dwServiceType, uint dwStartType, uint dwErrorControl, string lpPathName, string lpLoadOrderGroup, IntPtr lpdwTagId, string lpDependencies, string lpServiceStartName, string lpPassword);

string serviceName = "MyService";
string serviceDisplayName = "My Custom Service";
string binPath = @"C:\Path\To\YourService.exe";
IntPtr intPtr2 = Program.CreateService(intPtr, serviceName, serviceDisplayName , SERVICE_ACCESS.SERVICE_ALL_ACCESS, 16U, 2U, 1U, binPath, null, IntPtr.Zero, null, null, null);
if (intPtr2 == IntPtr.Zero)
{
     throw new Exception("Failed to a handle to service");
}

该函数需要提供一系列参数来定义服务的属性和行为,包括服务名称、描述、启动类型、可执行文件路径等。

0x03 StartService

服务创建成功后,可以通过调用StartService函数来启动该服务。启动服务后,服务将按照指定的行为在后台运行。

复制代码
[DllImport("advapi32.dll")]
private static extern int StartService(IntPtr serviceHandle, int dwNumServiceArgs, string lpServiceArgVectors);

bool result = StartService(intPtr2, 0, null);
if (!result)
{
    throw new Exception("Failed to start service.");
}

上述代码中,我们使用StartService函数启动服务,并检查启动结果是否成功。

通过打开服务控制管理器数据库、创建系统服务以及启动服务等这些步骤,可以在Windows系统中使用.NET创建和管理服务,实现目标权限维持。

相关推荐
Python私教18 分钟前
Rust:重新定义系统编程的安全与效率边界
开发语言·安全·rust
iSee8572 小时前
DocsGPT 远程命令执行漏洞复现(CVE-2025-0868)
安全·web安全
陈苏同学3 小时前
[已解决] VS Code / Cursor / Trae 的 PowerShell 终端 conda activate 进不去环境的常见问题
linux·windows·conda
辰%3 小时前
如何重启pycharm中的项目?
windows·python·pycharm
w23617346013 小时前
OAuth安全架构深度剖析:协议机制与攻防实践
安全·oauth·安全架构
筑梦之月4 小时前
全流量解析:让安全防御从“被动挨打”升级为“主动狩猎”
网络·安全
唐山柳林4 小时前
城市生命线综合管控系统解决方案-守护城市生命线安全
java·安全·servlet
Waitccy5 小时前
深度解析网闸策略:构建坚固的网络安全防线
网络·安全·web安全
iangyu6 小时前
【windows server脚本每天从网络盘复制到本地】
开发语言·windows·php
非凡ghost6 小时前
猫眼浏览器:简约安全,极速浏览
安全·软件需求