添加进程杀手

This commit is contained in:
snltty
2024-02-05 17:29:06 +08:00
parent 104a8900bd
commit 369056fe5f
22 changed files with 729 additions and 165 deletions

1
.gitignore vendored
View File

@@ -5,4 +5,5 @@ obj
node_modules node_modules
/public/* /public/*
/cmonitor.volume/x64/* /cmonitor.volume/x64/*
/cmonitor.killer/x64/*
/x64/* /x64/*

View File

@@ -3,9 +3,4 @@
<PropertyGroup> <PropertyGroup>
<_LastSelectedProfileId>D:\desktop\cmonitor\cmonitor.install.win\Properties\PublishProfiles\FolderProfile.pubxml</_LastSelectedProfileId> <_LastSelectedProfileId>D:\desktop\cmonitor\cmonitor.install.win\Properties\PublishProfiles\FolderProfile.pubxml</_LastSelectedProfileId>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<Compile Update="MainForm.cs">
<SubType>Form</SubType>
</Compile>
</ItemGroup>
</Project> </Project>

Binary file not shown.

View File

@@ -0,0 +1,167 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>17.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{e19b86ac-ac42-417a-8536-c2fff1fb7fdc}</ProjectGuid>
<RootNamespace>cmonitorkiller</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<OutDir>.\bin</OutDir>
<IntDir>.\bin</IntDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<OutDir>.\bin</OutDir>
<IntDir>.\bin</IntDir>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;CMONITORKILLER_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<PrecompiledHeader>Use</PrecompiledHeader>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableUAC>false</EnableUAC>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;CMONITORKILLER_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<PrecompiledHeader>Use</PrecompiledHeader>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableUAC>false</EnableUAC>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;CMONITORKILLER_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<PrecompiledHeader>Use</PrecompiledHeader>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableUAC>false</EnableUAC>
<AdditionalDependencies>D:\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.38.33130\lib\x64\libcpmtd.lib;D:\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.38.33130\lib\x64\libcmtd.lib;D:\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.38.33130\lib\x64\oldnames.lib;D:\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.38.33130\lib\x64\libvcruntimed.lib;D:\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.38.33130\lib\x64\msvcprtd.lib;D:\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.38.33130\lib\x64\MSVCRTD.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;CMONITORKILLER_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<PrecompiledHeader>Use</PrecompiledHeader>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableUAC>false</EnableUAC>
<AdditionalDependencies>D:\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.38.33130\lib\x64\libcpmtd.lib;D:\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.38.33130\lib\x64\libcmtd.lib;D:\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.38.33130\lib\x64\oldnames.lib;D:\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.38.33130\lib\x64\libvcruntimed.lib;D:\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.38.33130\lib\x64\msvcprtd.lib;D:\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.38.33130\lib\x64\MSVCRTD.lib;D:\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.38.33130\lib\x64\msvcprt.lib;D:\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.38.33130\lib\x64\MSVCRT.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="framework.h" />
<ClInclude Include="pch.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="dllmain.cpp" />
<ClCompile Include="pch.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Create</PrecompiledHeader>
</ClCompile>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@@ -0,0 +1,33 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="源文件">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="头文件">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="资源文件">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClInclude Include="framework.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="pch.h">
<Filter>头文件</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="dllmain.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="pch.cpp">
<Filter>源文件</Filter>
</ClCompile>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup />
</Project>

View File

@@ -0,0 +1,90 @@
// dllmain.cpp : 定义 DLL 应用程序的入口点。
#include "pch.h"
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <Windows.h>
#include <tlhelp32.h>
#define IOCTL_REGISTER_PROCESS 0x80002010
#define IOCTL_TERMINATE_PROCESS 0x80002048
extern "C" __declspec(dllexport) int LoadDriver(char* g_serviceName,char* driverPath)
{
SC_HANDLE hSCM, hService;
hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (hSCM == NULL)
return (1);
hService = OpenServiceA(hSCM, g_serviceName, SERVICE_ALL_ACCESS);
if (hService != NULL) {
SERVICE_STATUS serviceStatus;
if (!QueryServiceStatus(hService, &serviceStatus)) {
CloseServiceHandle(hService);
CloseServiceHandle(hSCM);
return (1);
}
if (serviceStatus.dwCurrentState == SERVICE_STOPPED) {
if (!StartServiceA(hService, 0, nullptr)) {
CloseServiceHandle(hService);
CloseServiceHandle(hSCM);
return (1);
}
}
CloseServiceHandle(hService);
CloseServiceHandle(hSCM);
return (0);
}
hService = CreateServiceA(hSCM, g_serviceName, g_serviceName, SERVICE_ALL_ACCESS,
SERVICE_KERNEL_DRIVER, SERVICE_DEMAND_START,
SERVICE_ERROR_IGNORE, driverPath, NULL, NULL, NULL,
NULL, NULL);
if (hService == NULL) {
CloseServiceHandle(hSCM);
return (1);
}
if (!StartServiceA(hService, 0, nullptr)) {
CloseServiceHandle(hService);
CloseServiceHandle(hSCM);
return (1);
}
CloseServiceHandle(hService);
CloseServiceHandle(hSCM);
return (0);
}
extern "C" __declspec(dllexport) int ProcessKiller(unsigned int procId)
{
HANDLE hDevice = CreateFile(L"\\\\.\\ZemanaAntiMalware", GENERIC_WRITE | GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hDevice == INVALID_HANDLE_VALUE)
{
printf("Failed to open handle to driver !! ");
return (-1);
}
unsigned int input = GetCurrentProcessId();
if (!DeviceIoControl(hDevice, IOCTL_REGISTER_PROCESS, &input, sizeof(input), NULL, 0, NULL, NULL))
{
printf("Failed to register the process in the trusted list %X !!\n", IOCTL_REGISTER_PROCESS);
CloseHandle(hDevice);
return (-1);
}
unsigned int pOutbuff = 0;
DWORD bytesRet = 0;
DeviceIoControl(hDevice, IOCTL_TERMINATE_PROCESS, &procId, sizeof(procId), &pOutbuff, sizeof(pOutbuff), &bytesRet, NULL);
CloseHandle(hDevice);
return 0;
}

View File

@@ -0,0 +1,5 @@
#pragma once
#define WIN32_LEAN_AND_MEAN // 从 Windows 头文件中排除极少使用的内容
// Windows 头文件
#include <windows.h>

5
cmonitor.killer/pch.cpp Normal file
View File

@@ -0,0 +1,5 @@
// pch.cpp: 与预编译标头对应的源文件
#include "pch.h"
// 当使用预编译的头时,需要使用此源文件,编译才能成功。

13
cmonitor.killer/pch.h Normal file
View File

@@ -0,0 +1,13 @@
// pch.h: 这是预编译标头文件。
// 下方列出的文件仅编译一次,提高了将来生成的生成性能。
// 这还将影响 IntelliSense 性能,包括代码完成和许多代码浏览功能。
// 但是,如果此处列出的文件中的任何一个在生成之间有更新,它们全部都将被重新编译。
// 请勿在此处添加要频繁更新的文件,这将使得性能优势无效。
#ifndef PCH_H
#define PCH_H
// 添加要在此处预编译的标头
#include "framework.h"
#endif //PCH_H

BIN
cmonitor.killer/pch.obj Normal file

Binary file not shown.

View File

@@ -1,8 +1,2 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" />
<ItemGroup>
<Compile Update="MainForm.cs">
<SubType>Form</SubType>
</Compile>
</ItemGroup>
</Project>

View File

@@ -23,7 +23,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "cmonitor.message.win", "cmo
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "cmonitor.snatch.win", "cmonitor.snatch.win\cmonitor.snatch.win.csproj", "{5267B401-6818-407C-8323-E6C8A3CC01D6}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "cmonitor.snatch.win", "cmonitor.snatch.win\cmonitor.snatch.win.csproj", "{5267B401-6818-407C-8323-E6C8A3CC01D6}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "cmonitor.share.win", "cmonitor.share.win\cmonitor.share.win.csproj", "{AB10024E-9307-4231-872E-3564A57BA035}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "cmonitor.share.win", "cmonitor.share.win\cmonitor.share.win.csproj", "{AB10024E-9307-4231-872E-3564A57BA035}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "cmonitor.killer", "cmonitor.killer\cmonitor.killer.vcxproj", "{E19B86AC-AC42-417A-8536-C2FFF1FB7FDC}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -167,6 +169,18 @@ Global
{AB10024E-9307-4231-872E-3564A57BA035}.Release|x64.Build.0 = Release|Any CPU {AB10024E-9307-4231-872E-3564A57BA035}.Release|x64.Build.0 = Release|Any CPU
{AB10024E-9307-4231-872E-3564A57BA035}.Release|x86.ActiveCfg = Release|Any CPU {AB10024E-9307-4231-872E-3564A57BA035}.Release|x86.ActiveCfg = Release|Any CPU
{AB10024E-9307-4231-872E-3564A57BA035}.Release|x86.Build.0 = Release|Any CPU {AB10024E-9307-4231-872E-3564A57BA035}.Release|x86.Build.0 = Release|Any CPU
{E19B86AC-AC42-417A-8536-C2FFF1FB7FDC}.Debug|Any CPU.ActiveCfg = Debug|x64
{E19B86AC-AC42-417A-8536-C2FFF1FB7FDC}.Debug|Any CPU.Build.0 = Debug|x64
{E19B86AC-AC42-417A-8536-C2FFF1FB7FDC}.Debug|x64.ActiveCfg = Debug|x64
{E19B86AC-AC42-417A-8536-C2FFF1FB7FDC}.Debug|x64.Build.0 = Debug|x64
{E19B86AC-AC42-417A-8536-C2FFF1FB7FDC}.Debug|x86.ActiveCfg = Debug|Win32
{E19B86AC-AC42-417A-8536-C2FFF1FB7FDC}.Debug|x86.Build.0 = Debug|Win32
{E19B86AC-AC42-417A-8536-C2FFF1FB7FDC}.Release|Any CPU.ActiveCfg = Release|x64
{E19B86AC-AC42-417A-8536-C2FFF1FB7FDC}.Release|Any CPU.Build.0 = Release|x64
{E19B86AC-AC42-417A-8536-C2FFF1FB7FDC}.Release|x64.ActiveCfg = Release|x64
{E19B86AC-AC42-417A-8536-C2FFF1FB7FDC}.Release|x64.Build.0 = Release|x64
{E19B86AC-AC42-417A-8536-C2FFF1FB7FDC}.Release|x86.ActiveCfg = Release|Win32
{E19B86AC-AC42-417A-8536-C2FFF1FB7FDC}.Release|x86.Build.0 = Release|Win32
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE

View File

@@ -37,11 +37,9 @@ using System.Reflection;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
using cmonitor.client.reports.keyboard; using cmonitor.client.reports.keyboard;
using cmonitor.client.reports.wallpaper; using cmonitor.client.reports.wallpaper;
using common.libs.winapis;
using cmonitor.client.reports.snatch; using cmonitor.client.reports.snatch;
using cmonitor.service.messengers.snatch; using cmonitor.service.messengers.snatch;
using cmonitor.libs; using cmonitor.libs;
using System.Text;
namespace cmonitor namespace cmonitor
@@ -62,15 +60,13 @@ namespace cmonitor
//读取参数 //读取参数
Dictionary<string, string> dic = ArgumentParser.Parse(args, out string error); Dictionary<string, string> dic = ArgumentParser.Parse(args, out string error);
//#if RELEASE #if RELEASE
//提权 //提权
if (dic.ContainsKey("elevated") == false) if (dic.ContainsKey("elevated") == false)
{ {
Win32Interop.RelaunchElevated(); Win32Interop.RelaunchElevated();
} }
//#endif #endif
Win32Interop.ProcessElevated();
//初始化配置文件 //初始化配置文件
Config config = new Config(); Config config = new Config();

View File

@@ -2,8 +2,8 @@
using common.libs.winapis; using common.libs.winapis;
using Microsoft.Win32; using Microsoft.Win32;
using System.Diagnostics; using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text; using System.Text;
using static common.libs.winapis.Kernel32;
namespace cmonitor.client.reports.active namespace cmonitor.client.reports.active
{ {
@@ -20,8 +20,10 @@ namespace cmonitor.client.reports.active
{ {
CommandHelper.Windows(string.Empty, new string[] { "gpupdate /force" }); CommandHelper.Windows(string.Empty, new string[] { "gpupdate /force" });
}); });
InitDriver();
} }
} }
private void CreateKey() private void CreateKey()
{ {
try try
@@ -40,24 +42,6 @@ namespace cmonitor.client.reports.active
{ {
} }
} }
public void Kill(int pid)
{
try
{
IntPtr handle = Kernel32.OpenProcess(ProcessAccessFlags.Terminate, false, pid);
if(handle != IntPtr.Zero)
{
Kernel32.TerminateProcess(handle, 0);
Kernel32.ZwTerminateProcess(handle, 0);
}
}
catch (Exception ex)
{
Logger.Instance.Error(ex);
}
}
private string[] disallowNames = Array.Empty<string>(); private string[] disallowNames = Array.Empty<string>();
public void DisallowRun(string[] names) public void DisallowRun(string[] names)
{ {
@@ -156,6 +140,7 @@ namespace cmonitor.client.reports.active
|| (filenameSpan.Length >= nameSpan.Length && filenameSpan.Slice(filenameSpan.Length - nameSpan.Length, nameSpan.Length).SequenceEqual(nameSpan)); || (filenameSpan.Length >= nameSpan.Length && filenameSpan.Slice(filenameSpan.Length - nameSpan.Length, nameSpan.Length).SequenceEqual(nameSpan));
if (result) if (result)
{ {
ProcessKiller((uint)pid);
Task.Run(() => Task.Run(() =>
{ {
CommandHelper.Windows(string.Empty, new string[] { $"taskkill /f /pid {pid}" }); CommandHelper.Windows(string.Empty, new string[] { $"taskkill /f /pid {pid}" });
@@ -214,7 +199,6 @@ namespace cmonitor.client.reports.active
} }
return activeWindowInfo; return activeWindowInfo;
} }
public int GetWindowCount() public int GetWindowCount()
{ {
int length = 0; int length = 0;
@@ -235,7 +219,6 @@ namespace cmonitor.client.reports.active
}, IntPtr.Zero); }, IntPtr.Zero);
return length; return length;
} }
public Dictionary<uint, string> GetWindows() public Dictionary<uint, string> GetWindows()
{ {
Dictionary<uint, string> dic = new Dictionary<uint, string>(); Dictionary<uint, string> dic = new Dictionary<uint, string>();
@@ -262,6 +245,34 @@ namespace cmonitor.client.reports.active
return dic; return dic;
} }
private void InitDriver()
{
try
{
LoadDriver("cmonitor.killer", Path.GetFullPath(Path.Join("./", "killer.sys")));
}
catch (Exception ex)
{
Logger.Instance.Error(ex);
}
}
public void Kill(int pid)
{
try
{
ProcessKiller((uint)pid);
}
catch (Exception ex)
{
Logger.Instance.Error(ex);
}
}
[DllImport("cmonitor.killer.dll")]
public static extern int LoadDriver(string serviceName, string driverPath);
[DllImport("cmonitor.killer.dll")]
public static extern int ProcessKiller(uint pid);
} }
} }

View File

@@ -36,6 +36,9 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Update="cmonitor.killer.dll">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="ffmpeg\avcodec-60.dll"> <None Update="ffmpeg\avcodec-60.dll">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None> </None>
@@ -69,6 +72,9 @@
<None Update="ffmpeg\swscale-7.dll"> <None Update="ffmpeg\swscale-7.dll">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None> </None>
<None Update="killer.sys">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Remove="Properties\**" /> <Compile Remove="Properties\**" />
@@ -92,10 +98,4 @@
<TrimmerRootAssembly Include="FFmpeg.AutoGen" /> <TrimmerRootAssembly Include="FFmpeg.AutoGen" />
</ItemGroup> </ItemGroup>
<!--<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="call copy.bat &quot;$(OutDir)&quot;" />
</Target>-->
</Project> </Project>

Binary file not shown.

View File

@@ -1 +0,0 @@
echo F|xcopy "publish\\*" "%1" /s /f /h /y

BIN
cmonitor/killer.sys Normal file

Binary file not shown.

View File

@@ -5,7 +5,7 @@ using System.Text;
namespace common.libs.winapis; namespace common.libs.winapis;
public static class ADVAPI32 public static unsafe class ADVAPI32
{ {
#region Structs #region Structs
public struct TOKEN_PRIVILEGES public struct TOKEN_PRIVILEGES
@@ -390,33 +390,349 @@ public static class ADVAPI32
out int peUse out int peUse
); );
[DllImport("advapi32.dll", EntryPoint = "OpenSCManagerW", ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern nint OpenSCManager(uint machineName, uint databaseName, uint dwAccess);
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern nint OpenService(nint hSCManager, string lpServiceName, uint dwDesiredAccess);
[DllImport("advapi32.dll", SetLastError = true)] [DllImport("advapi32.dll", SetLastError = true)]
public static extern bool GetKernelObjectSecurity(IntPtr Handle, int securityInformation, [Out] byte[] pSecurityDescriptor, uint nLength, out uint lpnLengthNeeded); [return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CloseServiceHandle(nint hSCObject);
[DllImport("advapi32.dll", SetLastError = true)] [DllImport("advapi32.dll", SetLastError = true)]
public static extern bool SetKernelObjectSecurity(IntPtr Handle, int securityInformation, [In] byte[] pSecurityDescriptor); [return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ControlService(nint hService, SERVICE_CONTROL dwControl, ref SERVICE_STATUS lpServiceStatus);
[DllImport("advapi32", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool StartService(
nint hService,
int dwNumServiceArgs,
string[] lpServiceArgVectors
);
[DllImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DeleteService(nint hService);
[Flags]
public enum SERVICE_TYPE : int
{
SERVICE_KERNEL_DRIVER = 0x00000001,
SERVICE_FILE_SYSTEM_DRIVER = 0x00000002,
SERVICE_WIN32_OWN_PROCESS = 0x00000010,
SERVICE_WIN32_SHARE_PROCESS = 0x00000020,
SERVICE_INTERACTIVE_PROCESS = 0x00000100
}
[Flags]
public enum SERVICE_CONTROL : uint
{
STOP = 0x00000001,
PAUSE = 0x00000002,
CONTINUE = 0x00000003,
INTERROGATE = 0x00000004,
SHUTDOWN = 0x00000005,
PARAMCHANGE = 0x00000006,
NETBINDADD = 0x00000007,
NETBINDREMOVE = 0x00000008,
NETBINDENABLE = 0x00000009,
NETBINDDISABLE = 0x0000000A,
DEVICEEVENT = 0x0000000B,
HARDWAREPROFILECHANGE = 0x0000000C,
POWEREVENT = 0x0000000D,
SESSIONCHANGE = 0x0000000E
}
public enum SERVICE_STATE : uint
{
SERVICE_STOPPED = 0x00000001,
SERVICE_START_PENDING = 0x00000002,
SERVICE_STOP_PENDING = 0x00000003,
SERVICE_RUNNING = 0x00000004,
SERVICE_CONTINUE_PENDING = 0x00000005,
SERVICE_PAUSE_PENDING = 0x00000006,
SERVICE_PAUSED = 0x00000007
}
public enum SERVICE_ACCESS : uint
{
/// <summary>
/// Required to call the QueryServiceConfig and
/// QueryServiceConfig2 functions to query the service configuration.
/// </summary>
SERVICE_QUERY_CONFIG = 0x00001,
/// <summary>
/// Required to call the ChangeServiceConfig or ChangeServiceConfig2 function
/// to change the service configuration. Because this grants the caller
/// the right to change the executable file that the system runs,
/// it should be granted only to administrators.
/// </summary>
SERVICE_CHANGE_CONFIG = 0x00002,
/// <summary>
/// Required to call the QueryServiceStatusEx function to ask the service
/// control manager about the status of the service.
/// </summary>
SERVICE_QUERY_STATUS = 0x00004,
/// <summary>
/// Required to call the EnumDependentServices function to enumerate all
/// the services dependent on the service.
/// </summary>
SERVICE_ENUMERATE_DEPENDENTS = 0x00008,
/// <summary>
/// Required to call the StartService function to start the service.
/// </summary>
SERVICE_START = 0x00010,
/// <summary>
/// Required to call the ControlService function to stop the service.
/// </summary>
SERVICE_STOP = 0x00020,
/// <summary>
/// Required to call the ControlService function to pause or continue
/// the service.
/// </summary>
SERVICE_PAUSE_CONTINUE = 0x00040,
/// <summary>
/// Required to call the EnumDependentServices function to enumerate all
/// the services dependent on the service.
/// </summary>
SERVICE_INTERROGATE = 0x00080,
/// <summary>
/// Required to call the ControlService function to specify a user-defined
/// control code.
/// </summary>
SERVICE_USER_DEFINED_CONTROL = 0x00100,
/// <summary>
/// Includes STANDARD_RIGHTS_REQUIRED in addition to all access rights in this table.
/// </summary>
SERVICE_ALL_ACCESS = ACCESS_MASK.STANDARD_RIGHTS_REQUIRED |
SERVICE_QUERY_CONFIG |
SERVICE_CHANGE_CONFIG |
SERVICE_QUERY_STATUS |
SERVICE_ENUMERATE_DEPENDENTS |
SERVICE_START |
SERVICE_STOP |
SERVICE_PAUSE_CONTINUE |
SERVICE_INTERROGATE |
SERVICE_USER_DEFINED_CONTROL,
GENERIC_READ = ACCESS_MASK.STANDARD_RIGHTS_READ |
SERVICE_QUERY_CONFIG |
SERVICE_QUERY_STATUS |
SERVICE_INTERROGATE |
SERVICE_ENUMERATE_DEPENDENTS,
GENERIC_WRITE = ACCESS_MASK.STANDARD_RIGHTS_WRITE |
SERVICE_CHANGE_CONFIG,
GENERIC_EXECUTE = ACCESS_MASK.STANDARD_RIGHTS_EXECUTE |
SERVICE_START |
SERVICE_STOP |
SERVICE_PAUSE_CONTINUE |
SERVICE_USER_DEFINED_CONTROL,
/// <summary>
/// Required to call the QueryServiceObjectSecurity or
/// SetServiceObjectSecurity function to access the SACL. The proper
/// way to obtain this access is to enable the SE_SECURITY_NAME
/// privilege in the caller's current access token, open the handle
/// for ACCESS_SYSTEM_SECURITY access, and then disable the privilege.
/// </summary>
ACCESS_SYSTEM_SECURITY = ACCESS_MASK.ACCESS_SYSTEM_SECURITY,
/// <summary>
/// Required to call the DeleteService function to delete the service.
/// </summary>
DELETE = ACCESS_MASK.DELETE,
/// <summary>
/// Required to call the QueryServiceObjectSecurity function to query
/// the security descriptor of the service object.
/// </summary>
READ_CONTROL = ACCESS_MASK.READ_CONTROL,
/// <summary>
/// Required to call the SetServiceObjectSecurity function to modify
/// the Dacl member of the service object's security descriptor.
/// </summary>
WRITE_DAC = ACCESS_MASK.WRITE_DAC,
/// <summary>
/// Required to call the SetServiceObjectSecurity function to modify
/// the Owner and Group members of the service object's security
/// descriptor.
/// </summary>
WRITE_OWNER = ACCESS_MASK.WRITE_OWNER,
}
[StructLayout(LayoutKind.Sequential, Pack = 0)]
public struct SERVICE_STATUS
{
public SERVICE_TYPE dwServiceType;
public SERVICE_STATE dwCurrentState;
public uint dwControlsAccepted;
public uint dwWin32ExitCode;
public uint dwServiceSpecificExitCode;
public uint dwCheckPoint;
public uint dwWaitHint;
}
[Flags] [Flags]
public enum ProcessAccessRights public enum ACCESS_MASK : uint
{ {
PROCESS_CREATE_PROCESS = 0x0080, // Required to create a process. DELETE = 0x00010000,
PROCESS_CREATE_THREAD = 0x0002, // Required to create a thread. READ_CONTROL = 0x00020000,
PROCESS_DUP_HANDLE = 0x0040, // Required to duplicate a handle using DuplicateHandle. WRITE_DAC = 0x00040000,
PROCESS_QUERY_INFORMATION = 0x0400, // Required to retrieve certain information about a process, such as its token, exit code, and priority class (see OpenProcessToken, GetExitCodeProcess, GetPriorityClass, and IsProcessInJob). WRITE_OWNER = 0x00080000,
PROCESS_QUERY_LIMITED_INFORMATION = 0x1000, // Required to retrieve certain information about a process (see QueryFullProcessImageName). A handle that has the PROCESS_QUERY_INFORMATION access right is automatically granted PROCESS_QUERY_LIMITED_INFORMATION. Windows Server 2003 and Windows XP/2000: This access right is not supported. SYNCHRONIZE = 0x00100000,
PROCESS_SET_INFORMATION = 0x0200, // Required to set certain information about a process, such as its priority class (see SetPriorityClass).
PROCESS_SET_QUOTA = 0x0100, // Required to set memory limits using SetProcessWorkingSetSize. STANDARD_RIGHTS_REQUIRED = 0x000F0000,
PROCESS_SUSPEND_RESUME = 0x0800, // Required to suspend or resume a process.
PROCESS_TERMINATE = 0x0001, // Required to terminate a process using TerminateProcess. STANDARD_RIGHTS_READ = 0x00020000,
PROCESS_VM_OPERATION = 0x0008, // Required to perform an operation on the address space of a process (see VirtualProtectEx and WriteProcessMemory). STANDARD_RIGHTS_WRITE = 0x00020000,
PROCESS_VM_READ = 0x0010, // Required to read memory in a process using ReadProcessMemory. STANDARD_RIGHTS_EXECUTE = 0x00020000,
PROCESS_VM_WRITE = 0x0020, // Required to write to memory in a process using WriteProcessMemory.
DELETE = 0x00010000, // Required to delete the object. STANDARD_RIGHTS_ALL = 0x001F0000,
READ_CONTROL = 0x00020000, // Required to read information in the security descriptor for the object, not including the information in the SACL. To read or write the SACL, you must request the ACCESS_SYSTEM_SECURITY access right. For more information, see SACL Access Right.
SYNCHRONIZE = 0x00100000, // The right to use the object for synchronization. This enables a thread to wait until the object is in the signaled state. SPECIFIC_RIGHTS_ALL = 0x0000FFFF,
WRITE_DAC = 0x00040000, // Required to modify the DACL in the security descriptor for the object.
WRITE_OWNER = 0x00080000, // Required to change the owner in the security descriptor for the object. ACCESS_SYSTEM_SECURITY = 0x01000000,
STANDARD_RIGHTS_REQUIRED = 0x000f0000,
PROCESS_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0xFFF),// All possible access rights for a process object. MAXIMUM_ALLOWED = 0x02000000,
GENERIC_READ = 0x80000000,
GENERIC_WRITE = 0x40000000,
GENERIC_EXECUTE = 0x20000000,
GENERIC_ALL = 0x10000000,
DESKTOP_READOBJECTS = 0x00000001,
DESKTOP_CREATEWINDOW = 0x00000002,
DESKTOP_CREATEMENU = 0x00000004,
DESKTOP_HOOKCONTROL = 0x00000008,
DESKTOP_JOURNALRECORD = 0x00000010,
DESKTOP_JOURNALPLAYBACK = 0x00000020,
DESKTOP_ENUMERATE = 0x00000040,
DESKTOP_WRITEOBJECTS = 0x00000080,
DESKTOP_SWITCHDESKTOP = 0x00000100,
WINSTA_ENUMDESKTOPS = 0x00000001,
WINSTA_READATTRIBUTES = 0x00000002,
WINSTA_ACCESSCLIPBOARD = 0x00000004,
WINSTA_CREATEDESKTOP = 0x00000008,
WINSTA_WRITEATTRIBUTES = 0x00000010,
WINSTA_ACCESSGLOBALATOMS = 0x00000020,
WINSTA_EXITWINDOWS = 0x00000040,
WINSTA_ENUMERATE = 0x00000100,
WINSTA_READSCREEN = 0x00000200,
WINSTA_ALL_ACCESS = 0x0000037F
} }
public enum SERVICE_START : uint
{
/// <summary>
/// A device driver started by the system loader. This value is valid
/// only for driver services.
/// </summary>
SERVICE_BOOT_START = 0x00000000,
/// <summary>
/// A device driver started by the IoInitSystem function. This value
/// is valid only for driver services.
/// </summary>
SERVICE_SYSTEM_START = 0x00000001,
/// <summary>
/// A service started automatically by the service control manager
/// during system startup. For more information, see Automatically
/// Starting Services.
/// </summary>
SERVICE_AUTO_START = 0x00000002,
/// <summary>
/// A service started by the service control manager when a process
/// calls the StartService function. For more information, see
/// Starting Services on Demand.
/// </summary>
SERVICE_DEMAND_START = 0x00000003,
/// <summary>
/// A service that cannot be started. Attempts to start the service
/// result in the error code ERROR_SERVICE_DISABLED.
/// </summary>
SERVICE_DISABLED = 0x00000004,
}
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern nint CreateServiceW(
nint hSCManager,
string lpServiceName,
string lpDisplayName,
uint dwDesiredAccess,
uint dwServiceType,
uint dwStartType,
uint dwErrorControl,
string lpBinaryPathName,
uint lpLoadOrderGroup,
uint lpdwTagId,
uint lpdwTagId1,
uint lpDependencies,
uint lpServiceStartName,
uint lpPassword);
[DllImport("ntdll.dll", CharSet = CharSet.Auto)]
public static extern uint NtOpenFile(nint* FileHandle, uint DesiredAccess, OBJECT_ATTRIBUTES* ObjectAttributes, IO_STATUS_BLOCK* IoStatusBlock, uint ShareAccess, uint OpenOptions);
[StructLayout(LayoutKind.Sequential, Pack = 0)]
public struct IO_STATUS_BLOCK
{
public uint status;
public nint information;
}
[StructLayout(LayoutKind.Sequential)]
public struct UNICODE_STRING : IDisposable
{
public ushort Length;
public ushort MaximumLength;
private nint buffer;
public UNICODE_STRING(string s)
{
Length = (ushort)(s.Length * 2);
MaximumLength = (ushort)(Length + 2);
buffer = Marshal.StringToHGlobalUni(s);
}
public void Dispose()
{
Marshal.FreeHGlobal(buffer);
buffer = nint.Zero;
}
public override string ToString()
{
return Marshal.PtrToStringUni(buffer);
}
}
public struct OBJECT_ATTRIBUTES
{
public int Length;
public nint RootDirectory;
public nint ObjectName;
public uint Attributes;
public nint SecurityDescriptor;
public nint SecurityQualityOfService;
}
} }

View File

@@ -6,7 +6,7 @@ using System.Runtime.InteropServices;
namespace common.libs.winapis; namespace common.libs.winapis;
public static class Kernel32 public static unsafe class Kernel32
{ {
[DllImport("kernel32.dll", SetLastError = true)] [DllImport("kernel32.dll", SetLastError = true)]
public static extern bool CloseHandle(nint hSnapshot); public static extern bool CloseHandle(nint hSnapshot);
@@ -93,32 +93,20 @@ public static class Kernel32
[DllImport("kernel32.dll")] [DllImport("kernel32.dll")]
public static extern bool SetHandleInformation(IntPtr hObject, int dwMask, int dwFlags); public static extern bool SetHandleInformation(IntPtr hObject, int dwMask, int dwFlags);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool TerminateProcess(IntPtr hProcess, uint uExitCode);
[DllImport("ntdll.dll", SetLastError = true)] [DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
public static extern uint ZwTerminateProcess(IntPtr ProcessHandle, uint ExitStatus); public static extern nint CreateFileA(
string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
nint lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
nint hTemplateFile);
[DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool DeviceIoControl(nint hDevice, uint dwIoControlCode, nint lpInBuffer, uint nInBufferSize, nint lpOutBuffer, uint nOutBufferSize, ulong* lpBytesReturned, uint lpOverlapped);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr OpenProcess(ProcessAccessFlags processAccess, bool bInheritHandle, int processId);
[Flags]
public enum ProcessAccessFlags : uint
{
Terminate = 0x0001,
CreateThread = 0x0002,
VirtualMemoryOperation = 0x0008,
VirtualMemoryRead = 0x0010,
VirtualMemoryWrite = 0x0020,
DuplicateHandle = 0x0040,
CreateProcess = 0x0080,
SetQuota = 0x0100,
SetInformation = 0x0200,
QueryInformation = 0x0400,
QueryLimitedInformation = 0x1000,
Synchronize = 0x100000
}
[DllImport("ntdll.dll", SetLastError = true)]
public static extern uint NtTerminateProcess(IntPtr ProcessHandle, uint ExitStatus);
public struct SYSTEMTIME public struct SYSTEMTIME
{ {
@@ -133,7 +121,4 @@ public static class Kernel32
} }
[DllImport("kernel32.dll", SetLastError = true)] [DllImport("kernel32.dll", SetLastError = true)]
public static extern bool SetSystemTime(ref SYSTEMTIME time); public static extern bool SetSystemTime(ref SYSTEMTIME time);
[DllImport("kernel32.dll")]
public static extern IntPtr GetCurrentProcess();
} }

View File

@@ -1,14 +1,12 @@
using cmonitor.libs.winapis; using cmonitor.libs.winapis;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics; using System.Diagnostics;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using System.Net.Sockets; using System.Net.Sockets;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using System.Security.AccessControl;
using System.Security.Principal; using System.Security.Principal;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
@@ -103,7 +101,7 @@ namespace common.libs.winapis
public static nint OpenInputDesktop() public static nint OpenInputDesktop()
{ {
return User32.OpenInputDesktop(0, true, ACCESS_MASK.GENERIC_ALL); return User32.OpenInputDesktop(0, true, User32.ACCESS_MASK.GENERIC_ALL);
} }
public static bool SwitchToInputDesktop() public static bool SwitchToInputDesktop()
{ {
@@ -458,68 +456,6 @@ namespace common.libs.winapis
}; };
Kernel32.SetSystemTime(ref st); Kernel32.SetSystemTime(ref st);
} }
private static RawSecurityDescriptor GetProcessSecurityDescriptor(IntPtr processHandle)
{
if (OperatingSystem.IsWindows())
{
const int DACL_SECURITY_INFORMATION = 0x00000004;
byte[] psd = new byte[0];
uint bufSizeNeeded;
// Call with 0 size to obtain the actual size needed in bufSizeNeeded
GetKernelObjectSecurity(processHandle, DACL_SECURITY_INFORMATION, psd, 0, out bufSizeNeeded);
if (bufSizeNeeded < 0 || bufSizeNeeded > short.MaxValue)
throw new Win32Exception();
// Allocate the required bytes and obtain the DACL
if (!GetKernelObjectSecurity(processHandle, DACL_SECURITY_INFORMATION,
psd = new byte[bufSizeNeeded], bufSizeNeeded, out bufSizeNeeded))
throw new Win32Exception();
// Use the RawSecurityDescriptor class from System.Security.AccessControl to parse the bytes:
return new RawSecurityDescriptor(psd, 0);
}
return null;
}
private static void SetProcessSecurityDescriptor(IntPtr processHandle, RawSecurityDescriptor dacl)
{
if (OperatingSystem.IsWindows())
{
const int DACL_SECURITY_INFORMATION = 0x00000004;
byte[] rawsd = new byte[dacl.BinaryLength];
dacl.GetBinaryForm(rawsd, 0);
if (!SetKernelObjectSecurity(processHandle, DACL_SECURITY_INFORMATION, rawsd))
throw new Win32Exception();
}
}
public static void ProcessElevated()
{
if (OperatingSystem.IsWindows())
{
// Get the current process handle
IntPtr hProcess = GetCurrentProcess();
// Read the DACL
RawSecurityDescriptor dacl = GetProcessSecurityDescriptor(hProcess);
if (dacl != null)
{
// Insert the new ACE
dacl.DiscretionaryAcl.InsertAce(
0,
new CommonAce(
AceFlags.None,
AceQualifier.AccessDenied,
(int)ProcessAccessRights.PROCESS_ALL_ACCESS,
new SecurityIdentifier(WellKnownSidType.WorldSid, null),
false,
null)
);
// Save the DACL
SetProcessSecurityDescriptor(hProcess, dacl);
}
}
}
} }