From d40eab1829df2541581a81bd948d2e13955ec716 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20=C5=81ugowski?= Date: Sat, 2 May 2026 09:00:01 +0200 Subject: [PATCH 1/4] Unificate NativeMethods class. --- .../agent_code/ExecutePE/Helpers/Utils.cs | 1 + .../ExecutePE/Internals/NativeDeclarations.cs | 37 ++++- .../ExecutePE/NativeDeclarations.cs | 148 ------------------ .../ExecutePE/Patchers/ArgumentPatcher.cs | 1 + .../ExecutePE/Patchers/ExitPatcher.cs | 1 + .../agent_code/ExecutePE/Patchers/IATHooks.cs | 1 + 6 files changed, 37 insertions(+), 152 deletions(-) delete mode 100644 Payload_Type/apollo/apollo/agent_code/ExecutePE/NativeDeclarations.cs diff --git a/Payload_Type/apollo/apollo/agent_code/ExecutePE/Helpers/Utils.cs b/Payload_Type/apollo/apollo/agent_code/ExecutePE/Helpers/Utils.cs index f6443442..ef7197ba 100644 --- a/Payload_Type/apollo/apollo/agent_code/ExecutePE/Helpers/Utils.cs +++ b/Payload_Type/apollo/apollo/agent_code/ExecutePE/Helpers/Utils.cs @@ -1,6 +1,7 @@ using System; using System.Linq; using System.Runtime.InteropServices; +using ExecutePE.Internals; namespace ExecutePE.Helpers { diff --git a/Payload_Type/apollo/apollo/agent_code/ExecutePE/Internals/NativeDeclarations.cs b/Payload_Type/apollo/apollo/agent_code/ExecutePE/Internals/NativeDeclarations.cs index 9e825f00..a998d612 100644 --- a/Payload_Type/apollo/apollo/agent_code/ExecutePE/Internals/NativeDeclarations.cs +++ b/Payload_Type/apollo/apollo/agent_code/ExecutePE/Internals/NativeDeclarations.cs @@ -15,7 +15,7 @@ public enum DuplicateOptions : uint DuplicateSameAccess = 0x00000002 } - internal enum StdHandles + internal enum StdHandle { Stdin = -10, Stdout = -11, @@ -40,13 +40,36 @@ internal enum StdHandles [StructLayout(LayoutKind.Sequential)] internal struct IMAGE_BASE_RELOCATION { - internal uint VirtualAdress; + internal uint VirtualAddress; internal uint SizeOfBlock; + + private IMAGE_BASE_RELOCATION(uint virtualAddress, uint sizeOfBlock) + { + VirtualAddress = virtualAddress; + SizeOfBlock = sizeOfBlock; + } + + public static IMAGE_BASE_RELOCATION Parse(byte[] b) + { + var virtualAddress = BitConverter.ToUInt32(b, 0); + var sizeOfBlock = BitConverter.ToUInt32(b, 4); + return new IMAGE_BASE_RELOCATION(virtualAddress, sizeOfBlock); + } + } + + internal enum X86BaseRelocationType : byte + { + IMAGE_REL_BASED_ABSOLUTE = 0, + IMAGE_REL_BASED_HIGH = 1, + IMAGE_REL_BASED_LOW = 2, + IMAGE_REL_BASED_HIGHLOW = 3, + IMAGE_REL_BASED_HIGHADJ = 4, + IMAGE_REL_BASED_DIR64 = 10, } [DllImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool SetStdHandle(StdHandles nStdHandle, IntPtr hHandle); + internal static extern bool SetStdHandle(StdHandle nStdHandle, IntPtr hHandle); [DllImport("kernel32.dll")] internal static extern uint GetLastError(); @@ -73,7 +96,7 @@ internal static extern SafeFileHandle CreateFileA( IntPtr hTemplateFile); [DllImport("kernel32.dll", SetLastError = true)] - internal static extern IntPtr GetStdHandle(StdHandles nStdHandle); + internal static extern IntPtr GetStdHandle(StdHandle nStdHandle); [StructLayout(LayoutKind.Sequential)] internal struct SECURITY_ATTRIBUTES @@ -141,6 +164,12 @@ internal static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uin [DllImport("kernel32.dll", CharSet = CharSet.Auto)] internal static extern IntPtr GetModuleHandle(string lpModuleName); + + [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] + internal static extern bool AllocConsole(); + + [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] + internal static extern bool AttachConsole(int pid); [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] internal static extern bool VirtualFree(IntPtr pAddress, uint size, uint freeType); diff --git a/Payload_Type/apollo/apollo/agent_code/ExecutePE/NativeDeclarations.cs b/Payload_Type/apollo/apollo/agent_code/ExecutePE/NativeDeclarations.cs deleted file mode 100644 index c837e9ce..00000000 --- a/Payload_Type/apollo/apollo/agent_code/ExecutePE/NativeDeclarations.cs +++ /dev/null @@ -1,148 +0,0 @@ -using Microsoft.Win32.SafeHandles; -using System; -using System.Runtime.ConstrainedExecution; -using System.Runtime.InteropServices; -using System.Security; - -namespace ExecutePE -{ - internal static unsafe class NativeDeclarations - { - internal enum StdHandle - { - Stdin = -10, - Stdout = -11, - Stderr = -12 - } - - internal const uint PAGE_EXECUTE_READWRITE = 0x40; - internal const uint PAGE_READWRITE = 0x04; - internal const uint PAGE_EXECUTE_READ = 0x20; - internal const uint PAGE_EXECUTE = 0x10; - internal const uint PAGE_EXECUTE_WRITECOPY = 0x80; - internal const uint PAGE_NOACCESS = 0x01; - internal const uint PAGE_READONLY = 0x02; - internal const uint PAGE_WRITECOPY = 0x08; - internal const uint MEM_COMMIT = 0x1000; - internal const uint MEM_RELEASE = 0x00008000; - - internal const uint IMAGE_SCN_MEM_EXECUTE = 0x20000000; - internal const uint IMAGE_SCN_MEM_READ = 0x40000000; - internal const uint IMAGE_SCN_MEM_WRITE = 0x80000000; - - public struct IMAGE_BASE_RELOCATION - { - internal uint VirtualAddress; - internal uint SizeOfBlock; - - private IMAGE_BASE_RELOCATION(uint virtualAddress, uint sizeOfBlock) - { - VirtualAddress = virtualAddress; - SizeOfBlock = sizeOfBlock; - } - - public static IMAGE_BASE_RELOCATION Parse(byte[] b) - { - var virtualAddress = BitConverter.ToUInt32(b, 0); - var sizeOfBlock = BitConverter.ToUInt32(b, 4); - return new IMAGE_BASE_RELOCATION(virtualAddress, sizeOfBlock); - } - } - - internal enum X86BaseRelocationType : byte - { - IMAGE_REL_BASED_ABSOLUTE = 0, - IMAGE_REL_BASED_HIGH = 1, - IMAGE_REL_BASED_LOW = 2, - IMAGE_REL_BASED_HIGHLOW = 3, - IMAGE_REL_BASED_HIGHADJ = 4, - IMAGE_REL_BASED_DIR64 = 10, - } - - [DllImport("kernel32.dll")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool SetStdHandle(StdHandle nStdHandle, IntPtr hHandle); - - [DllImport("kernel32.dll")] - internal static extern uint GetLastError(); - - [DllImport("kernel32.dll", SetLastError = true)] - internal static extern IntPtr GetStdHandle(StdHandle nStdHandle); - - [StructLayout(LayoutKind.Sequential)] - internal struct SECURITY_ATTRIBUTES - { - internal int nLength; - internal byte* lpSecurityDescriptor; - internal int bInheritHandle; - } - - [DllImport("kernel32.dll", SetLastError = true)] - internal static extern bool ReadFile(IntPtr hFile, [Out] byte[] lpBuffer, - uint nNumberOfBytesToRead, out uint lpNumberOfBytesRead, IntPtr lpOverlapped); - - [DllImport("kernel32.dll")] - internal static extern bool CreatePipe(out SafeFileHandle hReadPipe, out SafeFileHandle hWritePipe, - ref SECURITY_ATTRIBUTES lpPipeAttributes, uint nSize); - - [DllImport("ntdll.dll", SetLastError = true)] - internal static extern int NtQueryInformationProcess(IntPtr processHandle, int processInformationClass, - IntPtr processInformation, uint processInformationLength, IntPtr returnLength); - - [DllImport("kernel32")] - internal static extern IntPtr VirtualAlloc(IntPtr lpStartAddr, uint size, uint flAllocationType, - uint flProtect); - - [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] - internal static extern IntPtr LoadLibrary(string lpFileName); - - [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)] - internal static extern IntPtr GetProcAddress(IntPtr hModule, string procName); - - [DllImport("kernel32.dll", SetLastError = true)] - internal static extern IntPtr GetCurrentProcess(); - - [DllImport("kernel32.dll", CharSet = CharSet.Auto)] - internal static extern IntPtr GetCommandLine(); - - [DllImport("kernel32.dll", SetLastError = true)] - [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] - [SuppressUnmanagedCodeSecurity] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool CloseHandle(IntPtr hObject); - - [DllImport("kernel32")] - internal static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, - IntPtr param, uint dwCreationFlags, IntPtr lpThreadId); - - [DllImport("kernel32.dll")] - internal static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, - out uint lpFlOldProtect); - - [DllImport("kernel32.dll", CharSet = CharSet.Auto)] - internal static extern IntPtr GetModuleHandle(string lpModuleName); - - [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] - internal static extern bool AllocConsole(); - - [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] - internal static extern bool AttachConsole(int pid); - - [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] - internal static extern bool VirtualFree(IntPtr pAddress, uint size, uint freeType); - - [DllImport("kernel32")] - internal static extern uint WaitForSingleObject(IntPtr hHandle, uint dwMilliseconds); - - [StructLayout(LayoutKind.Sequential)] - internal struct PROCESS_BASIC_INFORMATION - { - internal uint ExitStatus; - internal IntPtr PebAddress; - internal UIntPtr AffinityMask; - internal int BasePriority; - internal UIntPtr UniqueProcessId; - internal UIntPtr InheritedFromUniqueProcessId; - } - } -} diff --git a/Payload_Type/apollo/apollo/agent_code/ExecutePE/Patchers/ArgumentPatcher.cs b/Payload_Type/apollo/apollo/agent_code/ExecutePE/Patchers/ArgumentPatcher.cs index a0eacc31..02cf66eb 100644 --- a/Payload_Type/apollo/apollo/agent_code/ExecutePE/Patchers/ArgumentPatcher.cs +++ b/Payload_Type/apollo/apollo/agent_code/ExecutePE/Patchers/ArgumentPatcher.cs @@ -3,6 +3,7 @@ using System.Runtime.InteropServices; using System.Text; using ExecutePE.Helpers; +using ExecutePE.Internals; namespace ExecutePE.Patchers { diff --git a/Payload_Type/apollo/apollo/agent_code/ExecutePE/Patchers/ExitPatcher.cs b/Payload_Type/apollo/apollo/agent_code/ExecutePE/Patchers/ExitPatcher.cs index b0ea9306..d35f6aa9 100644 --- a/Payload_Type/apollo/apollo/agent_code/ExecutePE/Patchers/ExitPatcher.cs +++ b/Payload_Type/apollo/apollo/agent_code/ExecutePE/Patchers/ExitPatcher.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using ExecutePE.Helpers; +using ExecutePE.Internals; namespace ExecutePE.Patchers { diff --git a/Payload_Type/apollo/apollo/agent_code/ExecutePE/Patchers/IATHooks.cs b/Payload_Type/apollo/apollo/agent_code/ExecutePE/Patchers/IATHooks.cs index 5346cf9d..464b8b74 100644 --- a/Payload_Type/apollo/apollo/agent_code/ExecutePE/Patchers/IATHooks.cs +++ b/Payload_Type/apollo/apollo/agent_code/ExecutePE/Patchers/IATHooks.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Runtime.InteropServices; using ApolloInterop.Utils; +using ExecutePE.Internals; namespace ExecutePE.Patchers { From 994566d3290b94291e2b74bd8792efd5e39cde46 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20=C5=81ugowski?= Date: Sat, 2 May 2026 09:03:49 +0200 Subject: [PATCH 2/4] Fix for missing _disposed variable update. --- Payload_Type/apollo/apollo/agent_code/ExecutePE/RunPE.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Payload_Type/apollo/apollo/agent_code/ExecutePE/RunPE.cs b/Payload_Type/apollo/apollo/agent_code/ExecutePE/RunPE.cs index 622d5ecb..18c15a12 100644 --- a/Payload_Type/apollo/apollo/agent_code/ExecutePE/RunPE.cs +++ b/Payload_Type/apollo/apollo/agent_code/ExecutePE/RunPE.cs @@ -1938,6 +1938,7 @@ public void Dispose() protected virtual void Dispose(bool disposing) { RestoreCommandLine(); + _disposed = true; return; } From 8060ab6b8c1818fbbd38ccb87f89f7b984210769 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20=C5=81ugowski?= Date: Sat, 2 May 2026 10:37:39 +0200 Subject: [PATCH 3/4] Fix for handling CRT output and valid restore stdout and stderr. --- .../ExecutePE/Helpers/StdHandleRedirector.cs | 137 ++++++++++++++---- .../ExecutePE/Internals/NativeDeclarations.cs | 18 ++- 2 files changed, 124 insertions(+), 31 deletions(-) diff --git a/Payload_Type/apollo/apollo/agent_code/ExecutePE/Helpers/StdHandleRedirector.cs b/Payload_Type/apollo/apollo/agent_code/ExecutePE/Helpers/StdHandleRedirector.cs index 2b29be1d..02a03c75 100644 --- a/Payload_Type/apollo/apollo/agent_code/ExecutePE/Helpers/StdHandleRedirector.cs +++ b/Payload_Type/apollo/apollo/agent_code/ExecutePE/Helpers/StdHandleRedirector.cs @@ -6,6 +6,8 @@ using System.Threading.Tasks; using System.Threading; using ApolloInterop.Classes.Events; +using System.Text; +using Microsoft.Win32.SafeHandles; namespace ExecutePE.Helpers { @@ -19,6 +21,11 @@ class StdHandleRedirector : IDisposable private IntPtr _oldStdout; private IntPtr _oldStderr; + private int _osfHandle; + private int _oldOsfOut; + private int _oldOsfErr; + IntPtr _stdoutClientHandle; + private Encoding _oldEncoding; private event EventHandler _stdoutHandler; @@ -43,22 +50,76 @@ public StdHandleRedirector(EventHandler stdoutHandler) private void Initialize() { + SetupNamePipes(); + DuplicateHandlesAndEncoding(); + SetupRedirection(); + } + private void DuplicateHandlesAndEncoding() { + _oldEncoding = (Encoding)Console.OutputEncoding.Clone(); + DuplicateHandle( + GetCurrentProcess(), + GetStdHandle(StdHandle.Stdout), + GetCurrentProcess(), + out _oldStdout, + 0, + false, + DuplicateOptions.DuplicateSameAccess + ); + DuplicateHandle( + GetCurrentProcess(), + GetStdHandle(StdHandle.Stderr), + GetCurrentProcess(), + out _oldStderr, + 0, + false, + DuplicateOptions.DuplicateSameAccess + ); + + IntPtr pipeWriteHandle = stdoutClientStream.SafePipeHandle.DangerousGetHandle(); + DuplicateHandle( + GetCurrentProcess(), + pipeWriteHandle, + GetCurrentProcess(), + out _stdoutClientHandle, + 0, + false, + DuplicateOptions.DuplicateSameAccess + ); + + _oldOsfOut = _dup(1); + _oldOsfErr = _dup(2); + } + + private void SetupNamePipes() { string stdoutGuid = Guid.NewGuid().ToString(); - stdoutServerStream = new NamedPipeServerStream(stdoutGuid, PipeDirection.InOut, 100, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); stdoutServerStream.BeginWaitForConnection(new AsyncCallback(stdoutServerStream.EndWaitForConnection), stdoutServerStream); stdoutClientStream = new NamedPipeClientStream("127.0.0.1", stdoutGuid, PipeDirection.InOut, PipeOptions.Asynchronous); stdoutClientStream.Connect(); + } + + private void SetupRedirection() + { + var stdoutServerFileHandle = new SafeFileHandle( + stdoutServerStream.SafePipeHandle.DangerousGetHandle(), + ownsHandle: false + ); + stdoutReader = new FileStream(stdoutServerFileHandle, FileAccess.Read); + + SetStdHandle(StdHandle.Stdout, _stdoutClientHandle); + SetStdHandle(StdHandle.Stderr, _stdoutClientHandle); - stdoutReader = new FileStream(stdoutServerStream.SafePipeHandle.DangerousGetHandle(), FileAccess.Read); + _osfHandle = _open_osfhandle(_stdoutClientHandle.ToInt32(), _O_TEXT); + if (_osfHandle == 0) + throw new Exception("_open_osfhandle failed"); - _oldStdout = GetStdHandle(StdHandles.Stdout); - _oldStderr = GetStdHandle(StdHandles.Stderr); + if (_dup2(_osfHandle, 1) != 0) + throw new Exception("_dup2 stdout failed"); - SetStdHandle(StdHandles.Stdout, stdoutClientStream.SafePipeHandle.DangerousGetHandle()); - SetStdHandle(StdHandles.Stderr, stdoutClientStream.SafePipeHandle.DangerousGetHandle()); + if (_dup2(_osfHandle, 2) != 0) + throw new Exception("_dup2 stderr failed"); } private void ReadFileStreamAsync(FileStream stream, EventHandler eventhandler) @@ -96,23 +157,23 @@ private void ReadFileStreamAsync(FileStream stream, EventHandler 0) - { - newstr = new byte[n]; - Array.Copy(tmp, newstr, n); - eventhandler?.Invoke(this, new StringDataEventArgs(Console.OutputEncoding.GetString(newstr))); - } - else - { - break; - } - } while (n > 0); + } while (!_cts.IsCancellationRequested || n > 0); + + //do + //{ + // tmp = new byte[szBuf]; + // n = stream.Read(tmp, 0, szBuf); + // if (n > 0) + // { + // newstr = new byte[n]; + // Array.Copy(tmp, newstr, n); + // eventhandler?.Invoke(this, new StringDataEventArgs(Console.OutputEncoding.GetString(newstr))); + // } + // else + // { + // break; + // } + //} while (n > 0); } private void ReadStdoutAsync() @@ -122,20 +183,38 @@ private void ReadStdoutAsync() public void Dispose() { - SetStdHandle(StdHandles.Stderr, _oldStderr); - SetStdHandle(StdHandles.Stdout, _oldStdout); - + Console.Out.Flush(); + Console.Error.Flush(); + fflush(IntPtr.Zero); stdoutClientStream.Flush(); + stdoutServerStream.Flush(); - stdoutClientStream.Close(); + if (_dup2(_oldOsfOut, 1) != 0) + throw new Exception("_dup2 stdout failed"); - _cts.Cancel(); + if (_dup2(_oldOsfErr, 2) != 0) + throw new Exception("_dup2 stderr failed"); + SetStdHandle(StdHandle.Stderr, _oldStderr); + SetStdHandle(StdHandle.Stdout, _oldStdout); + Console.SetOut(new StreamWriter(Console.OpenStandardOutput(), _oldEncoding) + { + AutoFlush = true + }); + + Console.SetError(new StreamWriter(Console.OpenStandardError(), _oldEncoding) + { + AutoFlush = true + }); + _close(_oldOsfOut); + _close(_oldOsfErr); + _close(_osfHandle); + stdoutClientStream.Close(); + _cts.Cancel(); Task.WaitAll(new Task[] { _stdoutReadTask }); - stdoutServerStream.Close(); } } diff --git a/Payload_Type/apollo/apollo/agent_code/ExecutePE/Internals/NativeDeclarations.cs b/Payload_Type/apollo/apollo/agent_code/ExecutePE/Internals/NativeDeclarations.cs index a998d612..eebe6160 100644 --- a/Payload_Type/apollo/apollo/agent_code/ExecutePE/Internals/NativeDeclarations.cs +++ b/Payload_Type/apollo/apollo/agent_code/ExecutePE/Internals/NativeDeclarations.cs @@ -37,6 +37,8 @@ internal enum StdHandle internal const uint IMAGE_SCN_MEM_READ = 0x40000000; internal const uint IMAGE_SCN_MEM_WRITE = 0x80000000; + internal const int _O_TEXT = 0x4000; + [StructLayout(LayoutKind.Sequential)] internal struct IMAGE_BASE_RELOCATION { @@ -137,9 +139,9 @@ internal static extern IntPtr VirtualAlloc(IntPtr lpStartAddr, uint size, uint f [DllImport("kernel32.dll", SetLastError = true)] internal static extern bool DuplicateHandle( IntPtr hSourceProcessHandle, - SafeFileHandle hSourceHandle, + IntPtr hSourceHandle, IntPtr hTargetProcessHandle, - ref SafeFileHandle lpTargetHandle, + out IntPtr lpTargetHandle, uint dwDesiredAccess, bool bInheritHandle, DuplicateOptions dwOptions @@ -187,5 +189,17 @@ internal struct PROCESS_BASIC_INFORMATION internal UIntPtr UniqueProcessId; internal UIntPtr InheritedFromUniqueProcessId; } + + [DllImport("ucrtbase.dll", CallingConvention = CallingConvention.Cdecl)] + internal static extern int _open_osfhandle(int osfhandle, int flags); + [DllImport("ucrtbase.dll", CallingConvention = CallingConvention.Cdecl)] + internal static extern int _dup2(int fd1, int fd2); + [DllImport("ucrtbase.dll", CallingConvention = CallingConvention.Cdecl)] + internal static extern int _dup(int fd); + [DllImport("ucrtbase.dll", CallingConvention = CallingConvention.Cdecl)] + internal static extern int _close(int fd); + [DllImport("ucrtbase.dll", CallingConvention = CallingConvention.Cdecl)] + internal static extern int fflush(IntPtr stream); + } } \ No newline at end of file From 025e59efc795ec2e123f259e50f59bd69ee7d463 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20=C5=81ugowski?= Date: Sat, 2 May 2026 12:38:18 +0200 Subject: [PATCH 4/4] Removed unused elements. Changed consts to enums. --- .../agent_code/ExecutePE/Helpers/Utils.cs | 6 +- .../ExecutePE/Internals/NativeDeclarations.cs | 115 +++++------------- .../agent_code/ExecutePE/Patchers/IATHooks.cs | 4 +- .../agent_code/ExecutePE/Patchers/PEMapper.cs | 18 +-- 4 files changed, 47 insertions(+), 96 deletions(-) diff --git a/Payload_Type/apollo/apollo/agent_code/ExecutePE/Helpers/Utils.cs b/Payload_Type/apollo/apollo/agent_code/ExecutePE/Helpers/Utils.cs index ef7197ba..bff4a25b 100644 --- a/Payload_Type/apollo/apollo/agent_code/ExecutePE/Helpers/Utils.cs +++ b/Payload_Type/apollo/apollo/agent_code/ExecutePE/Helpers/Utils.cs @@ -15,7 +15,7 @@ internal static class Utils Marshal.Copy(pFunc, originalBytes, 0, patchBytes.Length); var result = NativeDeclarations.VirtualProtect(pFunc, (UIntPtr)patchBytes.Length, - NativeDeclarations.PAGE_EXECUTE_READWRITE, out var oldProtect); + NativeDeclarations.MemoryProtectionConstant.PAGE_EXECUTE_READWRITE, out var oldProtect); if (!result) { return null; @@ -32,7 +32,7 @@ internal static class Utils internal static bool PatchAddress(IntPtr pAddress, IntPtr newValue) { var result = NativeDeclarations.VirtualProtect(pAddress, (UIntPtr)IntPtr.Size, - NativeDeclarations.PAGE_EXECUTE_READWRITE, out var oldProtect); + NativeDeclarations.MemoryProtectionConstant.PAGE_EXECUTE_READWRITE, out var oldProtect); if (!result) { return false; @@ -49,7 +49,7 @@ internal static bool PatchAddress(IntPtr pAddress, IntPtr newValue) internal static bool ZeroOutMemory(IntPtr start, int length) { - var result = NativeDeclarations.VirtualProtect(start, (UIntPtr)length, NativeDeclarations.PAGE_READWRITE, + var result = NativeDeclarations.VirtualProtect(start, (UIntPtr)length, NativeDeclarations.MemoryProtectionConstant.PAGE_READWRITE, out var oldProtect); if (!result) { diff --git a/Payload_Type/apollo/apollo/agent_code/ExecutePE/Internals/NativeDeclarations.cs b/Payload_Type/apollo/apollo/agent_code/ExecutePE/Internals/NativeDeclarations.cs index eebe6160..9f0cb789 100644 --- a/Payload_Type/apollo/apollo/agent_code/ExecutePE/Internals/NativeDeclarations.cs +++ b/Payload_Type/apollo/apollo/agent_code/ExecutePE/Internals/NativeDeclarations.cs @@ -21,14 +21,28 @@ internal enum StdHandle Stdout = -11, Stderr = -12 } - internal const uint PAGE_EXECUTE_READWRITE = 0x40; - internal const uint PAGE_READWRITE = 0x04; - internal const uint PAGE_EXECUTE_READ = 0x20; - internal const uint PAGE_EXECUTE = 0x10; - internal const uint PAGE_EXECUTE_WRITECOPY = 0x80; - internal const uint PAGE_NOACCESS = 0x01; - internal const uint PAGE_READONLY = 0x02; - internal const uint PAGE_WRITECOPY = 0x08; + + internal enum X86BaseRelocationType : byte + { + IMAGE_REL_BASED_ABSOLUTE = 0, + IMAGE_REL_BASED_HIGH = 1, + IMAGE_REL_BASED_LOW = 2, + IMAGE_REL_BASED_HIGHLOW = 3, + IMAGE_REL_BASED_HIGHADJ = 4, + IMAGE_REL_BASED_DIR64 = 10, + } + + internal enum MemoryProtectionConstant : uint + { + PAGE_EXECUTE_READWRITE = 0x40, + PAGE_READWRITE = 0x04, + PAGE_EXECUTE_READ = 0x20, + PAGE_EXECUTE = 0x10, + PAGE_EXECUTE_WRITECOPY = 0x80, + PAGE_NOACCESS = 0x01, + PAGE_READONLY = 0x02, + PAGE_WRITECOPY = 0x08 + } internal const uint MEM_COMMIT = 0x1000; internal const uint MEM_RELEASE = 0x00008000; @@ -59,14 +73,15 @@ public static IMAGE_BASE_RELOCATION Parse(byte[] b) } } - internal enum X86BaseRelocationType : byte + [StructLayout(LayoutKind.Sequential)] + internal struct PROCESS_BASIC_INFORMATION { - IMAGE_REL_BASED_ABSOLUTE = 0, - IMAGE_REL_BASED_HIGH = 1, - IMAGE_REL_BASED_LOW = 2, - IMAGE_REL_BASED_HIGHLOW = 3, - IMAGE_REL_BASED_HIGHADJ = 4, - IMAGE_REL_BASED_DIR64 = 10, + internal uint ExitStatus; + internal IntPtr PebAddress; + internal UIntPtr AffinityMask; + internal int BasePriority; + internal UIntPtr UniqueProcessId; + internal UIntPtr InheritedFromUniqueProcessId; } [DllImport("kernel32.dll")] @@ -76,53 +91,16 @@ internal enum X86BaseRelocationType : byte [DllImport("kernel32.dll")] internal static extern uint GetLastError(); - [DllImport("kernel32.dll", SetLastError = true)] - internal static extern SafeFileHandle CreateNamedPipeA( - string lpName, - long dwOpenMode, - long dwPipeMode, - int nMaxInstances, - int nOutBufferSize, - int nInBufferSize, - int nDefaultTimeout, - SECURITY_ATTRIBUTES lpSecurityAttributes); - - [DllImport("Kernel32.dll", SetLastError = true)] - internal static extern SafeFileHandle CreateFileA( - string lpFileName, - long dwDesiredAccess, - long dwShareMode, - SECURITY_ATTRIBUTES lpSecurityAttributes, - long dwCreationDisposition, - long dwFlagsAndAttributes, - IntPtr hTemplateFile); - [DllImport("kernel32.dll", SetLastError = true)] internal static extern IntPtr GetStdHandle(StdHandle nStdHandle); - [StructLayout(LayoutKind.Sequential)] - internal struct SECURITY_ATTRIBUTES - { - internal int nLength; - internal byte* lpSecurityDescriptor; - internal int bInheritHandle; - } - - [DllImport("kernel32.dll", SetLastError = true)] - internal static extern bool ReadFile(IntPtr hFile, [Out] byte[] lpBuffer, - uint nNumberOfBytesToRead, out uint lpNumberOfBytesRead, IntPtr lpOverlapped); - - [DllImport("kernel32.dll")] - internal static extern bool CreatePipe(out SafeFileHandle hReadPipe, out SafeFileHandle hWritePipe, - ref SECURITY_ATTRIBUTES lpPipeAttributes, uint nSize); - [DllImport("ntdll.dll", SetLastError = true)] internal static extern int NtQueryInformationProcess(IntPtr processHandle, int processInformationClass, IntPtr processInformation, uint processInformationLength, IntPtr returnLength); [DllImport("kernel32")] internal static extern IntPtr VirtualAlloc(IntPtr lpStartAddr, uint size, uint flAllocationType, - uint flProtect); + MemoryProtectionConstant flProtect); [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern IntPtr LoadLibrary(string lpFileName); @@ -154,42 +132,15 @@ DuplicateOptions dwOptions internal static extern bool CloseHandle(IntPtr hObject); [DllImport("kernel32.dll")] - internal static extern bool ClosePipe(IntPtr hPipe); - - [DllImport("kernel32")] - internal static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, - IntPtr param, uint dwCreationFlags, IntPtr lpThreadId); - - [DllImport("kernel32.dll")] - internal static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, - out uint lpFlOldProtect); + internal static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, MemoryProtectionConstant flNewProtect, + out MemoryProtectionConstant lpFlOldProtect); [DllImport("kernel32.dll", CharSet = CharSet.Auto)] internal static extern IntPtr GetModuleHandle(string lpModuleName); - - [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] - internal static extern bool AllocConsole(); - - [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] - internal static extern bool AttachConsole(int pid); [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] internal static extern bool VirtualFree(IntPtr pAddress, uint size, uint freeType); - [DllImport("kernel32")] - internal static extern uint WaitForSingleObject(IntPtr hHandle, uint dwMilliseconds); - - [StructLayout(LayoutKind.Sequential)] - internal struct PROCESS_BASIC_INFORMATION - { - internal uint ExitStatus; - internal IntPtr PebAddress; - internal UIntPtr AffinityMask; - internal int BasePriority; - internal UIntPtr UniqueProcessId; - internal UIntPtr InheritedFromUniqueProcessId; - } - [DllImport("ucrtbase.dll", CallingConvention = CallingConvention.Cdecl)] internal static extern int _open_osfhandle(int osfhandle, int flags); [DllImport("ucrtbase.dll", CallingConvention = CallingConvention.Cdecl)] diff --git a/Payload_Type/apollo/apollo/agent_code/ExecutePE/Patchers/IATHooks.cs b/Payload_Type/apollo/apollo/agent_code/ExecutePE/Patchers/IATHooks.cs index 464b8b74..bad09780 100644 --- a/Payload_Type/apollo/apollo/agent_code/ExecutePE/Patchers/IATHooks.cs +++ b/Payload_Type/apollo/apollo/agent_code/ExecutePE/Patchers/IATHooks.cs @@ -109,7 +109,7 @@ public bool ApplyHook(IntPtr iatAddress, IntPtr originalFunction) IntPtr.Zero, (uint)_hookBytes.Count, NativeDeclarations.MEM_COMMIT, - NativeDeclarations.PAGE_READWRITE + NativeDeclarations.MemoryProtectionConstant.PAGE_READWRITE ); if (hookMemory == null) @@ -124,7 +124,7 @@ public bool ApplyHook(IntPtr iatAddress, IntPtr originalFunction) if (!NativeDeclarations.VirtualProtect( hookMemory, (UIntPtr)_hookBytes.Count, - NativeDeclarations.PAGE_EXECUTE_READ, + NativeDeclarations.MemoryProtectionConstant.PAGE_EXECUTE_READ, out _) ) { diff --git a/Payload_Type/apollo/apollo/agent_code/ExecutePE/Patchers/PEMapper.cs b/Payload_Type/apollo/apollo/agent_code/ExecutePE/Patchers/PEMapper.cs index f695c087..2a2a1d5b 100644 --- a/Payload_Type/apollo/apollo/agent_code/ExecutePE/Patchers/PEMapper.cs +++ b/Payload_Type/apollo/apollo/agent_code/ExecutePE/Patchers/PEMapper.cs @@ -15,7 +15,7 @@ public void MapPEIntoMemory(byte[] unpacked, out PELoader peLoader, out long cur { _pe = peLoader = new PELoader(unpacked); _codebase = NativeDeclarations.VirtualAlloc(IntPtr.Zero, _pe.OptionalHeader64.SizeOfImage, - NativeDeclarations.MEM_COMMIT, NativeDeclarations.PAGE_READWRITE); + NativeDeclarations.MEM_COMMIT, NativeDeclarations.MemoryProtectionConstant.PAGE_READWRITE); currentBase = _codebase.ToInt64(); int relocTableFileOffset = 0; @@ -67,7 +67,7 @@ public void MapPEIntoMemory(byte[] unpacked, out PELoader peLoader, out long cur ); var y = NativeDeclarations.VirtualAlloc((IntPtr)(currentBase + _pe.ImageSectionHeaders[i].VirtualAddress), - sectionSize, NativeDeclarations.MEM_COMMIT, NativeDeclarations.PAGE_READWRITE); + sectionSize, NativeDeclarations.MEM_COMMIT, NativeDeclarations.MemoryProtectionConstant.PAGE_READWRITE); if (y == null) { var sectionName = new string(_pe.ImageSectionHeaders[i].Name); @@ -176,31 +176,31 @@ internal void SetPagePermissions() var read = ((uint)_pe.ImageSectionHeaders[i].Characteristics & NativeDeclarations.IMAGE_SCN_MEM_READ) != 0; var write = ((uint)_pe.ImageSectionHeaders[i].Characteristics & NativeDeclarations.IMAGE_SCN_MEM_WRITE) != 0; - var protection = NativeDeclarations.PAGE_EXECUTE_READWRITE; + var protection = NativeDeclarations.MemoryProtectionConstant.PAGE_EXECUTE_READWRITE; if (execute && read && write) { - protection = NativeDeclarations.PAGE_EXECUTE_READWRITE; + protection = NativeDeclarations.MemoryProtectionConstant.PAGE_EXECUTE_READWRITE; } else if (!execute && read && write) { - protection = NativeDeclarations.PAGE_READWRITE; + protection = NativeDeclarations.MemoryProtectionConstant.PAGE_READWRITE; } else if (!write && execute && read) { - protection = NativeDeclarations.PAGE_EXECUTE_READ; + protection = NativeDeclarations.MemoryProtectionConstant.PAGE_EXECUTE_READ; } else if (!execute && !write && read) { - protection = NativeDeclarations.PAGE_READONLY; + protection = NativeDeclarations.MemoryProtectionConstant.PAGE_READONLY; } else if (execute && !read && !write) { - protection = NativeDeclarations.PAGE_EXECUTE; + protection = NativeDeclarations.MemoryProtectionConstant.PAGE_EXECUTE; } else if (!execute && !read && !write) { - protection = NativeDeclarations.PAGE_NOACCESS; + protection = NativeDeclarations.MemoryProtectionConstant.PAGE_NOACCESS; } NativeDeclarations.VirtualProtect((IntPtr)(_codebase.ToInt64() + _pe.ImageSectionHeaders[i].VirtualAddress),