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

发布于:2025-04-01 ⋅ 阅读:(25) ⋅ 点赞:(0)

在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创建和管理服务,实现目标权限维持。