diff --git a/AntiCrack-DotNet/AntiCrack-DotNet.csproj b/AntiCrack-DotNet/AntiCrack-DotNet.csproj index 43983fa..877f7bc 100644 --- a/AntiCrack-DotNet/AntiCrack-DotNet.csproj +++ b/AntiCrack-DotNet/AntiCrack-DotNet.csproj @@ -30,7 +30,7 @@ true - x64 + x86 true full false @@ -52,6 +52,14 @@ true false + + LocalIntranet + + + false + + + @@ -68,6 +76,8 @@ + + diff --git a/AntiCrack-DotNet/AntiCrack-DotNet.csproj.user b/AntiCrack-DotNet/AntiCrack-DotNet.csproj.user new file mode 100644 index 0000000..d82a293 --- /dev/null +++ b/AntiCrack-DotNet/AntiCrack-DotNet.csproj.user @@ -0,0 +1,16 @@ + + + + true + + + publish\ + + + + + + en-US + false + + \ No newline at end of file diff --git a/AntiCrack-DotNet/AntiDebug.cs b/AntiCrack-DotNet/AntiDebug.cs index 190b6c9..209df93 100644 --- a/AntiCrack-DotNet/AntiDebug.cs +++ b/AntiCrack-DotNet/AntiDebug.cs @@ -4,6 +4,9 @@ using System.Threading; using System.Diagnostics; using System.Runtime.InteropServices; +using System.Windows.Forms; +using System.Net; +using System.Security.Cryptography; namespace AntiCrack_DotNet { @@ -62,8 +65,8 @@ internal sealed class AntiDebug [DllImport("kernelbase.dll", SetLastError = true)] private static extern int QueryFullProcessImageNameA(SafeHandle hProcess, uint Flags, byte[] lpExeName, Int32[] lpdwSize); - [DllImport("user32.dll", SetLastError = true)] - private static extern IntPtr GetForegroundWindow(); + [DllImport("win32u.dll", SetLastError = true)] + private static extern IntPtr NtUserGetForegroundWindow(); [DllImport("user32.dll", SetLastError = true)] private static extern int GetWindowTextLengthA(IntPtr HWND); @@ -93,13 +96,19 @@ internal sealed class AntiDebug /// /// Attempts to close an invalid handle to detect debugger presence. + /// specifies if we should use syscall to call the WinAPI functions. /// /// Returns true if an exception is caught, indicating no debugger, otherwise false. - public static bool NtCloseAntiDebug_InvalidHandle() + public static bool NtCloseAntiDebug_InvalidHandle(bool Syscall) { try { - NtClose((IntPtr)0x1231222L); + int RandomInt = new Random().Next(int.MinValue, int.MaxValue); + IntPtr RandomIntPtr = new IntPtr(RandomInt); + if (Syscall) + Syscalls.SyscallNtClose(RandomIntPtr); + else + NtClose(RandomIntPtr); return false; } catch @@ -110,17 +119,22 @@ public static bool NtCloseAntiDebug_InvalidHandle() /// /// Attempts to close a protected handle to detect debugger presence. + /// specifies if we should use syscall to call the WinAPI functions. /// /// Returns true if an exception is caught, indicating no debugger, otherwise false. - public static bool NtCloseAntiDebug_ProtectedHandle() + public static bool NtCloseAntiDebug_ProtectedHandle(bool Syscall) { - IntPtr hMutex = CreateMutexA(IntPtr.Zero, false, new Random().Next(0, 9999999).ToString()); + string RandomMutexName = new Random().Next(int.MinValue, int.MaxValue).ToString(); + IntPtr hMutex = CreateMutexA(IntPtr.Zero, false, RandomMutexName); uint HANDLE_FLAG_PROTECT_FROM_CLOSE = 0x00000002; SetHandleInformation(hMutex, HANDLE_FLAG_PROTECT_FROM_CLOSE, HANDLE_FLAG_PROTECT_FROM_CLOSE); bool Result = false; try { - NtClose(hMutex); + if (Syscall) + Syscalls.SyscallNtClose(hMutex); + else + NtClose(hMutex); Result = false; } catch @@ -153,13 +167,20 @@ public static bool IsDebuggerPresentCheck() } /// - /// Checks if the process has debug flags set using NtQueryInformationProcess. + /// Checks if the process has debug flags set using NtQueryInformationProcess + /// specifies if we should use syscall to call the WinAPI functions. /// /// Returns true if debug flags are set, otherwise false. - public static bool NtQueryInformationProcessCheck_ProcessDebugFlags() + public static bool NtQueryInformationProcessCheck_ProcessDebugFlags(bool Syscall) { uint ProcessDebugFlags = 0; - NtQueryInformationProcess(Process.GetCurrentProcess().SafeHandle, 0x1F, out ProcessDebugFlags, sizeof(uint), 0); + uint Class = 0x1F; + uint Size = sizeof(uint); + uint Result = 0; + if (Syscall) + Syscalls.SyscallNtQueryInformationProcess(Process.GetCurrentProcess().SafeHandle, Class, out ProcessDebugFlags, Size, out Result); + else + NtQueryInformationProcess(Process.GetCurrentProcess().SafeHandle, 0x1F, out ProcessDebugFlags, sizeof(uint), 0); if (ProcessDebugFlags == 0) return true; return false; @@ -167,15 +188,20 @@ public static bool NtQueryInformationProcessCheck_ProcessDebugFlags() /// /// Checks if the process has a debug port using NtQueryInformationProcess. + /// specifies if we should use syscalls to call the WinAPI functions.. /// /// Returns true if a debug port is detected, otherwise false. - public static bool NtQueryInformationProcessCheck_ProcessDebugPort() + public static bool NtQueryInformationProcessCheck_ProcessDebugPort(bool Syscall) { uint DebuggerPresent = 0; uint Size = sizeof(uint); if (Environment.Is64BitProcess) Size = sizeof(uint) * 2; - NtQueryInformationProcess(Process.GetCurrentProcess().SafeHandle, 7, out DebuggerPresent, Size, 0); + uint Result = 0; + if(Syscall) + Syscalls.SyscallNtQueryInformationProcess(Process.GetCurrentProcess().SafeHandle, 7, out DebuggerPresent, Size, out Result); + else + NtQueryInformationProcess(Process.GetCurrentProcess().SafeHandle, 7, out DebuggerPresent, Size, 0); if (DebuggerPresent != 0) return true; return false; @@ -183,15 +209,20 @@ public static bool NtQueryInformationProcessCheck_ProcessDebugPort() /// /// Checks if the process has a debug object handle using NtQueryInformationProcess. + /// specifies if we should use syscall to call the WinAPI functions. /// /// Returns true if a debug object handle is detected, otherwise false. - public static bool NtQueryInformationProcessCheck_ProcessDebugObjectHandle() + public static bool NtQueryInformationProcessCheck_ProcessDebugObjectHandle(bool Syscall) { IntPtr hDebugObject = IntPtr.Zero; uint Size = sizeof(uint); if (Environment.Is64BitProcess) Size = sizeof(uint) * 2; - NtQueryInformationProcess(Process.GetCurrentProcess().SafeHandle, 0x1E, out hDebugObject, Size, 0); + + if (Syscall) + Syscalls.SyscallNtQueryInformationProcess(Process.GetCurrentProcess().SafeHandle, 0x1E, out hDebugObject, Size, 0); + else + NtQueryInformationProcess(Process.GetCurrentProcess().SafeHandle, 0x1E, out hDebugObject, Size, 0); if (hDebugObject != IntPtr.Zero) return true; return false; @@ -221,18 +252,31 @@ public static string AntiDebugAttach() /// Returns true if a known debugger window is detected, otherwise false. public static bool FindWindowAntiDebug() { + string[] BadWindowNames = { "x32dbg", "x64dbg", "windbg", "ollydbg", "dnspy", "immunity debugger", "hyperdbg", "cheat engine", "cheatengine", "ida" }; Process[] GetProcesses = Process.GetProcesses(); foreach (Process GetWindow in GetProcesses) { - string[] BadWindowNames = { "x32dbg", "x64dbg", "windbg", "ollydbg", "dnspy", "immunity debugger", "hyperdbg", "cheat engine", "cheatengine", "ida" }; - foreach (string BadWindows in BadWindowNames) + try { - if (GetWindow.MainWindowTitle.ToLower().Contains(BadWindows)) + if (GetWindow.MainWindowHandle != IntPtr.Zero) { - GetWindow.Close(); - return true; + string title = GetWindow.MainWindowTitle; + if (string.IsNullOrEmpty(title)) continue; + + foreach (string BadWindows in BadWindowNames) + { + if (title.IndexOf(BadWindows, StringComparison.OrdinalIgnoreCase) >= 0) + { + GetWindow.Close(); + return true; + } + } } } + catch + { + continue; + } } return false; } @@ -241,10 +285,10 @@ public static bool FindWindowAntiDebug() /// Checks if the foreground window belongs to a known debugger. /// /// Returns true if a known debugger window is detected, otherwise false. - public static bool GetForegroundWindowAntiDebug() + public static bool NtUserGetForegroundWindowAntiDebug() { string[] BadWindowNames = { "x32dbg", "x64dbg", "windbg", "ollydbg", "dnspy", "immunity debugger", "hyperdbg", "debug", "debugger", "cheat engine", "cheatengine", "ida" }; - IntPtr HWND = GetForegroundWindow(); + IntPtr HWND = NtUserGetForegroundWindow(); if (HWND != IntPtr.Zero) { int WindowLength = GetWindowTextLengthA(HWND); @@ -254,7 +298,7 @@ public static bool GetForegroundWindowAntiDebug() GetWindowTextA(HWND, WindowName, WindowLength + 1); foreach (string BadWindows in BadWindowNames) { - if (WindowName.ToString().ToLower().Contains(BadWindows)) + if (Utils.Contains(WindowName.ToString().ToLower(), BadWindows)) { return true; } @@ -353,16 +397,21 @@ public static bool HardwareRegistersBreakpointsDetection() { Structs.CONTEXT Context = new Structs.CONTEXT(); Context.ContextFlags = CONTEXT_DEBUG_REGISTERS; - IntPtr CurrentThread = GetCurrentThread(); - if (GetThreadContext(CurrentThread, ref Context)) + foreach (ProcessThread Threads in Process.GetCurrentProcess().Threads) { - if ((Context.Dr1 != 0x00 || Context.Dr2 != 0x00 || Context.Dr3 != 0x00 || Context.Dr4 != 0x00 || Context.Dr5 != 0x00 || Context.Dr6 != 0x00 || Context.Dr7 != 0x00)) + uint THREAD_GET_CONTEXT = 0x0008; + uint THREAD_QUERY_INFORMATION = 0x0040; + IntPtr hThread = OpenThread(THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, false, Threads.Id); + if (GetThreadContext(hThread, ref Context)) { - NtClose(CurrentThread); - return true; + if ((Context.Dr1 != 0x00 || Context.Dr2 != 0x00 || Context.Dr3 != 0x00 || Context.Dr6 != 0x00 || Context.Dr7 != 0x00)) + { + NtClose(hThread); + return true; + } } + NtClose(hThread); } - NtClose(CurrentThread); return false; } @@ -386,15 +435,17 @@ private static string CleanPath(string Path) /// /// Checks if the parent process is a debugger by querying process information. + /// specifies if we should use syscall to call the WinAPI functions. /// /// Returns true if the parent process is a debugger, otherwise false. - public static bool ParentProcessAntiDebug() + public static bool ParentProcessAntiDebug(bool Syscall) { try { Structs.PROCESS_BASIC_INFORMATION PBI = new Structs.PROCESS_BASIC_INFORMATION(); uint ProcessBasicInformation = 0; - if (NtQueryInformationProcess(Process.GetCurrentProcess().SafeHandle, ProcessBasicInformation, ref PBI, (uint)Marshal.SizeOf(typeof(Structs.PROCESS_BASIC_INFORMATION)), 0) == 0) + uint Result = Syscall ? Syscalls.SyscallNtQueryInformationProcess(Process.GetCurrentProcess().SafeHandle, ProcessBasicInformation, ref PBI, (uint)Marshal.SizeOf(typeof(Structs.PROCESS_BASIC_INFORMATION)), 0) : NtQueryInformationProcess(Process.GetCurrentProcess().SafeHandle, ProcessBasicInformation, ref PBI, (uint)Marshal.SizeOf(typeof(Structs.PROCESS_BASIC_INFORMATION)), 0); + if (Result == 0) { int ParentPID = PBI.InheritedFromUniqueProcessId.ToInt32(); if (ParentPID != 0) @@ -432,7 +483,8 @@ public static bool NtSetDebugFilterStateAntiDebug() return true; } - delegate int ExecutionDelegate(); + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int ExecutionDelegate(); /// /// Uses page guard to detect debugger presence by executing a function pointer. @@ -471,5 +523,4 @@ public static bool PageGuardAntiDebug() return false; } } - -} +} \ No newline at end of file diff --git a/AntiCrack-DotNet/AntiDllInjection.cs b/AntiCrack-DotNet/AntiDllInjection.cs index c229987..e4525ad 100644 --- a/AntiCrack-DotNet/AntiDllInjection.cs +++ b/AntiCrack-DotNet/AntiDllInjection.cs @@ -23,50 +23,6 @@ internal sealed class AntiDllInjection #endregion - - /// - /// Patches the LoadLibraryA function to prevent DLL injection. - /// - /// Returns "Success" if the patching was successful, otherwise "Failed". - public static string PatchLoadLibraryA() - { - IntPtr KernelModule = GetModuleHandle("kernelbase.dll"); - IntPtr LoadLibraryA = GetProcAddress(KernelModule, "LoadLibraryA"); - byte[] HookedCode = { 0xC2, 0x04, 0x00 }; - bool Status = WriteProcessMemory(Process.GetCurrentProcess().SafeHandle, LoadLibraryA, HookedCode, 3, 0); - if (Status) - return "Success"; - return "Failed"; - } - - /// - /// Patches the LoadLibraryW function to prevent DLL injection. - /// - /// Returns "Success" if the patching was successful, otherwise "Failed". - public static string PatchLoadLibraryW() - { - IntPtr KernelModule = GetModuleHandle("kernelbase.dll"); - IntPtr LoadLibraryW = GetProcAddress(KernelModule, "LoadLibraryW"); - byte[] HookedCode = { 0xC2, 0x04, 0x00 }; - bool Status = WriteProcessMemory(Process.GetCurrentProcess().SafeHandle, LoadLibraryW, HookedCode, 3, 0); - if (Status) - return "Success"; - return "Failed"; - } - - /// - /// Enables the binary image signature mitigation policy to only allow Microsoft-signed binaries. - /// - /// Returns "Success" if the policy was set successfully, otherwise "Failed". - public static string BinaryImageSignatureMitigationAntiDllInjection() - { - Structs.PROCESS_MITIGATION_BINARY_SIGNATURE_POLICY OnlyMicrosoftBinaries = new Structs.PROCESS_MITIGATION_BINARY_SIGNATURE_POLICY(); - OnlyMicrosoftBinaries.MicrosoftSignedOnly = 1; - if (SetProcessMitigationPolicy(8, ref OnlyMicrosoftBinaries, Marshal.SizeOf(typeof(Structs.PROCESS_MITIGATION_BINARY_SIGNATURE_POLICY)))) - return "Success"; - return "Failed"; - } - /// /// Checks if there are any injected libraries in the current process. /// @@ -98,7 +54,7 @@ public static string SetDllLoadPolicy() { MicrosoftSignedOnly = 1 }; - if (SetProcessMitigationPolicy(0x10, ref policy, Marshal.SizeOf(policy))) + if (SetProcessMitigationPolicy(8, ref policy, Marshal.SizeOf(policy))) return "Success"; return "Failed"; } diff --git a/AntiCrack-DotNet/AntiVirtualization.cs b/AntiCrack-DotNet/AntiVirtualization.cs index 1bfb557..5d3f683 100644 --- a/AntiCrack-DotNet/AntiVirtualization.cs +++ b/AntiCrack-DotNet/AntiVirtualization.cs @@ -14,11 +14,23 @@ internal sealed class AntiVirtualization #region WinApi + [DllImport("ntdll.dll", SetLastError = true, CharSet = CharSet.Unicode)] + private static extern void RtlInitUnicodeString(out Structs.UNICODE_STRING DestinationString, string SourceString); + + [DllImport("ntdll.dll", SetLastError = true, CharSet = CharSet.Ansi)] + private static extern void RtlUnicodeStringToAnsiString(out Structs.ANSI_STRING DestinationString, Structs.UNICODE_STRING UnicodeString, bool AllocateDestinationString); + + [DllImport("ntdll.dll", SetLastError = true)] + private static extern uint LdrGetDllHandleEx(ulong Flags, [MarshalAs(UnmanagedType.LPWStr)] string DllPath, [MarshalAs(UnmanagedType.LPWStr)] string DllCharacteristics, Structs.UNICODE_STRING LibraryName, ref IntPtr DllHandle); + [DllImport("kernelbase.dll", SetLastError = true)] - private static extern IntPtr GetModuleHandle(string lib); + private static extern IntPtr GetModuleHandleA(string Library); [DllImport("kernelbase.dll", SetLastError = true)] - private static extern IntPtr GetProcAddress(IntPtr ModuleHandle, string Function); + private static extern IntPtr GetProcAddress(IntPtr hModule, string Function); + + [DllImport("ntdll.dll", SetLastError = true, CharSet = CharSet.Ansi)] + private static extern uint LdrGetProcedureAddressForCaller(IntPtr Module, Structs.ANSI_STRING ProcedureName, ushort ProcedureNumber, out IntPtr FunctionHandle, ulong Flags, IntPtr CallBack); [DllImport("kernelbase.dll", SetLastError = true)] private static extern bool WriteProcessMemory(SafeHandle hProcess, IntPtr BaseAddress, byte[] Buffer, uint size, int NumOfBytes); @@ -40,7 +52,7 @@ internal sealed class AntiVirtualization /// True if Sandboxie is detected, otherwise false. public static bool IsSandboxiePresent() { - if (GetModuleHandle("SbieDll.dll").ToInt32() != 0) + if (Utils.LowLevelGetModuleHandle("SbieDll.dll").ToInt32() != 0) return true; return false; } @@ -51,7 +63,7 @@ public static bool IsSandboxiePresent() /// True if Comodo Sandbox is detected, otherwise false. public static bool IsComodoSandboxPresent() { - if (GetModuleHandle("cmdvrt32.dll").ToInt32() != 0 || GetModuleHandle("cmdvrt64.dll").ToInt32() != 0) + if (Utils.LowLevelGetModuleHandle("cmdvrt32.dll").ToInt32() != 0 || Utils.LowLevelGetModuleHandle("cmdvrt64.dll").ToInt32() != 0) return true; return false; } @@ -62,7 +74,7 @@ public static bool IsComodoSandboxPresent() /// True if Qihoo 360 Sandbox is detected, otherwise false. public static bool IsQihoo360SandboxPresent() { - if (GetModuleHandle("SxIn.dll").ToInt32() != 0) + if (Utils.LowLevelGetModuleHandle("SxIn.dll").ToInt32() != 0) return true; return false; } @@ -73,7 +85,7 @@ public static bool IsQihoo360SandboxPresent() /// True if Cuckoo Sandbox is detected, otherwise false. public static bool IsCuckooSandboxPresent() { - if (GetModuleHandle("cuckoomon.dll").ToInt32() != 0) + if (Utils.LowLevelGetModuleHandle("cuckoomon.dll").ToInt32() != 0) return true; return false; } @@ -100,8 +112,8 @@ public static bool IsEmulationPresent() /// True if Wine is detected, otherwise false. public static bool IsWinePresent() { - IntPtr ModuleHandle = GetModuleHandle("kernel32.dll"); - if (GetProcAddress(ModuleHandle, "wine_get_unix_file_name").ToInt32() != 0) + IntPtr ModuleHandle = Utils.LowLevelGetModuleHandle("kernel32.dll"); + if (Utils.LowLevelGetProcAddress(ModuleHandle, "wine_get_unix_file_name").ToInt32() != 0) return true; return false; } @@ -120,7 +132,7 @@ public static bool CheckForVMwareAndVirtualBox() { string ManufacturerString = Item["Manufacturer"].ToString().ToLower(); string ModelName = Item["Model"].ToString(); - if ((ManufacturerString == "microsoft corporation" && ModelName.ToUpperInvariant().Contains("VIRTUAL") || ManufacturerString.Contains("vmware"))) + if ((ManufacturerString == "microsoft corporation" && Utils.Contains(ModelName.ToUpperInvariant(), "VIRTUAL") || Utils.Contains(ManufacturerString, "vmware"))) { return true; } @@ -141,7 +153,7 @@ public static bool CheckForKVM() { foreach (string BadDrivers in BadDriversList) { - if (Drivers.Contains(BadDrivers)) + if (Utils.Contains(Drivers, BadDrivers)) { return true; } @@ -163,7 +175,7 @@ public static bool CheckForHyperV() string[] Services = { "vmbus", "VMBusHID", "hyperkbd" }; foreach (string ServicesToCheck in Services) { - if (CompareServicesNames.ServiceName.Contains(ServicesToCheck)) + if (Utils.Contains(CompareServicesNames.ServiceName, ServicesToCheck)) return true; } } @@ -266,40 +278,6 @@ public static bool PortConnectionAntiVM() return false; } - /// - /// Attempts to crash Sandboxie if detected. - /// - public static void CrashingSandboxie() - { - if (!Environment.Is64BitProcess) - { - byte[] UnHookedCode = { 0xB8, 0x26, 0x00, 0x00, 0x00 }; - IntPtr NtdllModule = GetModuleHandle("ntdll.dll"); - IntPtr NtOpenProcess = GetProcAddress(NtdllModule, "NtOpenProcess"); - WriteProcessMemory(Process.GetCurrentProcess().SafeHandle, NtOpenProcess, UnHookedCode, 5, 0); - try - { - Process[] GetProcesses = Process.GetProcesses(); - foreach (Process ProcessesHandle in GetProcesses) - { - bool DoingSomethingWithHandle = false; - try - { - IsProcessCritical(ProcessesHandle.SafeHandle, ref DoingSomethingWithHandle); - } - catch - { - continue; - } - } - } - catch - { - - } - } - } - /// /// Checks for VM-related device names. /// @@ -337,7 +315,7 @@ public static bool CheckForParallels() { foreach (string BadDrivers in BadDriversList) { - if (Drivers.Contains(BadDrivers)) + if (Utils.Contains(Drivers, BadDrivers)) { return true; } @@ -358,7 +336,7 @@ public static bool TriageCheck() foreach (var item in searcher.Get()) { string model = item["Model"].ToString(); - if (model.Contains("DADY HARDDISK") || model.Contains("QEMU HARDDISK")) + if (Utils.Contains(model, "DADY HARDDISK") || Utils.Contains(model, "QEMU HARDDISK")) { return true; } @@ -410,7 +388,7 @@ public static bool CheckForQemu() { foreach (string BadDrivers in BadDriversList) { - if (Drivers.Contains(BadDrivers)) + if (Utils.Contains(Drivers, BadDrivers)) { return true; } diff --git a/AntiCrack-DotNet/HooksDetection.cs b/AntiCrack-DotNet/HooksDetection.cs index 14bdaa1..1dd5a39 100644 --- a/AntiCrack-DotNet/HooksDetection.cs +++ b/AntiCrack-DotNet/HooksDetection.cs @@ -12,63 +12,6 @@ public sealed class HooksDetection { public static object ProcessMethod { get; private set; } - #region WinApi - - [DllImport("ntdll.dll", SetLastError = true, CharSet = CharSet.Unicode)] - private static extern void RtlInitUnicodeString(out Structs.UNICODE_STRING DestinationString, string SourceString); - - [DllImport("ntdll.dll", SetLastError = true, CharSet = CharSet.Ansi)] - private static extern void RtlUnicodeStringToAnsiString(out Structs.ANSI_STRING DestinationString, Structs.UNICODE_STRING UnicodeString, bool AllocateDestinationString); - - [DllImport("ntdll.dll", SetLastError = true)] - private static extern uint LdrGetDllHandleEx(ulong Flags, [MarshalAs(UnmanagedType.LPWStr)] string DllPath, [MarshalAs(UnmanagedType.LPWStr)] string DllCharacteristics, Structs.UNICODE_STRING LibraryName, ref IntPtr DllHandle); - - [DllImport("kernelbase.dll", SetLastError = true)] - private static extern IntPtr GetModuleHandleA(string Library); - - [DllImport("kernelbase.dll", SetLastError = true)] - private static extern IntPtr GetProcAddress(IntPtr hModule, string Function); - - [DllImport("ntdll.dll", SetLastError = true, CharSet = CharSet.Ansi)] - private static extern uint LdrGetProcedureAddressForCaller(IntPtr Module, Structs.ANSI_STRING ProcedureName, ushort ProcedureNumber, out IntPtr FunctionHandle, ulong Flags, IntPtr CallBack); - - #endregion - - /// - /// Gets the handle of a specified module using low-level functions. - /// - /// The name of the library to get the handle for. - /// The handle to the module. - private static IntPtr LowLevelGetModuleHandle(string Library) - { - if (IntPtr.Size == 4) - return GetModuleHandleA(Library); - IntPtr hModule = IntPtr.Zero; - Structs.UNICODE_STRING UnicodeString = new Structs.UNICODE_STRING(); - RtlInitUnicodeString(out UnicodeString, Library); - LdrGetDllHandleEx(0, null, null, UnicodeString, ref hModule); - return hModule; - } - - /// - /// Gets the address of a specified function using low-level functions. - /// - /// The handle to the module. - /// The name of the function to get the address for. - /// The address of the function. - private static IntPtr LowLevelGetProcAddress(IntPtr hModule, string Function) - { - if (IntPtr.Size == 4) - return GetProcAddress(hModule, Function); - IntPtr FunctionHandle = IntPtr.Zero; - Structs.UNICODE_STRING UnicodeString = new Structs.UNICODE_STRING(); - Structs.ANSI_STRING AnsiString = new Structs.ANSI_STRING(); - RtlInitUnicodeString(out UnicodeString, Function); - RtlUnicodeStringToAnsiString(out AnsiString, UnicodeString, true); - LdrGetProcedureAddressForCaller(hModule, AnsiString, 0, out FunctionHandle, 0, IntPtr.Zero); - return FunctionHandle; - } - /// /// Reads a byte from a specified memory address. /// @@ -101,7 +44,7 @@ public static bool DetectHooksOnCommonWinAPIFunctions() string[] CommonWin32uFunctions = { "NtUserBlockInput", "NtUserFindWindowEx", "NtUserQueryWindow", "NtUserGetForegroundWindow" }; foreach (string Library in Libraries) { - IntPtr hModule = LowLevelGetModuleHandle(Library); + IntPtr hModule = Utils.LowLevelGetModuleHandle(Library); if (hModule != IntPtr.Zero) { switch (Library) @@ -112,7 +55,7 @@ public static bool DetectHooksOnCommonWinAPIFunctions() { foreach (string WinAPIFunction in CommonKernelLibFunctions) { - IntPtr Function = LowLevelGetProcAddress(hModule, WinAPIFunction); + IntPtr Function = Utils.LowLevelGetProcAddress(hModule, WinAPIFunction); byte FunctionByte = InternalReadByte(Function); if (FunctionByte == 0x90 || FunctionByte == 0xE9) { @@ -132,7 +75,7 @@ public static bool DetectHooksOnCommonWinAPIFunctions() { foreach (string WinAPIFunction in CommonKernelLibFunctions) { - IntPtr Function = LowLevelGetProcAddress(hModule, WinAPIFunction); + IntPtr Function = Utils.LowLevelGetProcAddress(hModule, WinAPIFunction); byte FunctionByte = InternalReadByte(Function); if (FunctionByte == 255 || FunctionByte == 0x90 || FunctionByte == 0xE9) { @@ -152,7 +95,7 @@ public static bool DetectHooksOnCommonWinAPIFunctions() { foreach (string WinAPIFunction in CommonNtdllFunctions) { - IntPtr Function = LowLevelGetProcAddress(hModule, WinAPIFunction); + IntPtr Function = Utils.LowLevelGetProcAddress(hModule, WinAPIFunction); byte FunctionByte = InternalReadByte(Function); if (FunctionByte == 255 || FunctionByte == 0x90 || FunctionByte == 0xE9) { @@ -172,7 +115,7 @@ public static bool DetectHooksOnCommonWinAPIFunctions() { foreach (string WinAPIFunction in CommonUser32Functions) { - IntPtr Function = LowLevelGetProcAddress(hModule, WinAPIFunction); + IntPtr Function = Utils.LowLevelGetProcAddress(hModule, WinAPIFunction); byte FunctionByte = InternalReadByte(Function); if (FunctionByte == 0x90 || FunctionByte == 0xE9) { @@ -192,7 +135,7 @@ public static bool DetectHooksOnCommonWinAPIFunctions() { foreach (string WinAPIFunction in CommonWin32uFunctions) { - IntPtr Function = LowLevelGetProcAddress(hModule, WinAPIFunction); + IntPtr Function = Utils.LowLevelGetProcAddress(hModule, WinAPIFunction); byte FunctionByte = InternalReadByte(Function); if (FunctionByte == 255 || FunctionByte == 0x90 || FunctionByte == 0xE9) { @@ -215,19 +158,19 @@ public static bool DetectHooksOnCommonWinAPIFunctions() /// /// Detects inline hooks on specified functions within a module. /// - /// The name of the module to check for hooks. - /// The list of functions to check for hooks. + /// The name of the module to check for hooks. + /// The list of functions to check for hooks. /// Returns true if hooks are detected, otherwise false. - public static bool DetectInlineHooks(string moduleName, string[] functions) + public static bool DetectInlineHooks(string ModuleName, string[] Functions) { - if (moduleName != null && functions != null) + if (ModuleName != null && Functions != null) { try { - foreach (string function in functions) + foreach (string function in Functions) { - IntPtr hModule = LowLevelGetModuleHandle(moduleName); - IntPtr Function = LowLevelGetProcAddress(hModule, function); + IntPtr hModule = Utils.LowLevelGetModuleHandle(ModuleName); + IntPtr Function = Utils.LowLevelGetProcAddress(hModule, function); byte FunctionByte = InternalReadByte(Function); if (FunctionByte == 255 || FunctionByte == 0x90 || FunctionByte == 0xE9) { @@ -240,7 +183,11 @@ public static bool DetectInlineHooks(string moduleName, string[] functions) return false; } - public static bool IsModule(IntPtr Address) + /// + /// Detects if an address is a module or not. + /// + /// Returns true if there's no module, otherwise false. + private static bool IsNotModule(IntPtr Address) { foreach (ProcessModule module in Process.GetCurrentProcess().Modules) { @@ -341,7 +288,7 @@ public static bool DetectCLRHooks() byte FirstByte = InternalReadByte(FP); if (FirstByte == 0xE9 || FirstByte == 255) { - if(IsModule(FP)) + if(IsNotModule(FP)) return true; } } @@ -352,7 +299,7 @@ public static bool DetectCLRHooks() byte FirstByte = InternalReadByte(FP); if (FirstByte == 0xE9 || FirstByte == 255) { - if (IsModule(FP)) + if (IsNotModule(FP)) return true; } } @@ -363,7 +310,7 @@ public static bool DetectCLRHooks() byte FirstByte = InternalReadByte(FP); if (FirstByte == 0xE9 || FirstByte == 255) { - if (IsModule(FP)) + if (IsNotModule(FP)) return true; } } @@ -374,7 +321,7 @@ public static bool DetectCLRHooks() byte FirstByte = InternalReadByte(FP); if (FirstByte == 0xE9 || FirstByte == 255) { - if (IsModule(FP)) + if (IsNotModule(FP)) return true; } } @@ -385,7 +332,7 @@ public static bool DetectCLRHooks() byte FirstByte = InternalReadByte(FP); if (FirstByte == 0xE9 || FirstByte == 255) { - if (IsModule(FP)) + if (IsNotModule(FP)) return true; } } @@ -396,7 +343,7 @@ public static bool DetectCLRHooks() byte FirstByte = InternalReadByte(FP); if (FirstByte == 0xE9 || FirstByte == 255) { - if (IsModule(FP)) + if (IsNotModule(FP)) return true; } } @@ -411,7 +358,7 @@ public static bool DetectCLRHooks() byte FirstByte = InternalReadByte(FP); if (FirstByte == 0xE9 || FirstByte == 255) { - if (IsModule(FP)) + if (IsNotModule(FP)) return true; } } @@ -426,4 +373,4 @@ public static bool DetectCLRHooks() } } -} +} \ No newline at end of file diff --git a/AntiCrack-DotNet/OtherChecks.cs b/AntiCrack-DotNet/OtherChecks.cs index 648a048..824bf64 100644 --- a/AntiCrack-DotNet/OtherChecks.cs +++ b/AntiCrack-DotNet/OtherChecks.cs @@ -4,6 +4,7 @@ using System.Windows.Forms; using System.Runtime.InteropServices; using Microsoft.Win32; +using static AntiCrack_DotNet.Structs; namespace AntiCrack_DotNet { @@ -20,23 +21,20 @@ public sealed class OtherChecks [DllImport("ntdll.dll", SetLastError = true)] private static extern uint NtQuerySystemInformation(uint SystemInformationClass, ref Structs.SYSTEM_SECUREBOOT_INFORMATION SystemInformation, uint SystemInformationLength, out uint ReturnLength); - [DllImport("QCall", CharSet = CharSet.Unicode)] - [SecurityCritical] - [SuppressUnmanagedCodeSecurity] - private static extern void GetExecutingAssembly(uint stackMark, IntPtr retAssembly); - #endregion /// /// Checks if unsigned drivers are allowed on the system. + /// specifies if we should use syscall to call the WinAPI functions. /// /// Returns true if unsigned drivers are allowed, otherwise false. - public static bool IsUnsignedDriversAllowed() + public static bool IsUnsignedDriversAllowed(bool Syscall) { uint SystemCodeIntegrityInformation = 0x67; Structs.SYSTEM_CODEINTEGRITY_INFORMATION CodeIntegrityInfo = new Structs.SYSTEM_CODEINTEGRITY_INFORMATION(); CodeIntegrityInfo.Length = (uint)Marshal.SizeOf(typeof(Structs.SYSTEM_CODEINTEGRITY_INFORMATION)); uint ReturnLength = 0; + uint result = Syscall ? Syscalls.SyscallNtQuerySystemInformation(SystemCodeIntegrityInformation, ref CodeIntegrityInfo, (uint)Marshal.SizeOf(CodeIntegrityInfo), out ReturnLength) : NtQuerySystemInformation(SystemCodeIntegrityInformation, ref CodeIntegrityInfo, (uint)Marshal.SizeOf(CodeIntegrityInfo), out ReturnLength); if (NtQuerySystemInformation(SystemCodeIntegrityInformation, ref CodeIntegrityInfo, (uint)Marshal.SizeOf(CodeIntegrityInfo), out ReturnLength) >= 0 && ReturnLength == (uint)Marshal.SizeOf(CodeIntegrityInfo)) { uint CODEINTEGRITY_OPTION_ENABLED = 0x01; @@ -50,15 +48,17 @@ public static bool IsUnsignedDriversAllowed() /// /// Checks if test-signed drivers are allowed on the system. + /// specifies if we should use syscall to call the WinAPI functions. /// /// Returns true if test-signed drivers are allowed, otherwise false. - public static bool IsTestSignedDriversAllowed() + public static bool IsTestSignedDriversAllowed(bool Syscall) { uint SystemCodeIntegrityInformation = 0x67; Structs.SYSTEM_CODEINTEGRITY_INFORMATION CodeIntegrityInfo = new Structs.SYSTEM_CODEINTEGRITY_INFORMATION(); CodeIntegrityInfo.Length = (uint)Marshal.SizeOf(typeof(Structs.SYSTEM_CODEINTEGRITY_INFORMATION)); uint ReturnLength = 0; - if (NtQuerySystemInformation(SystemCodeIntegrityInformation, ref CodeIntegrityInfo, (uint)Marshal.SizeOf(CodeIntegrityInfo), out ReturnLength) >= 0 && ReturnLength == (uint)Marshal.SizeOf(CodeIntegrityInfo)) + uint result = Syscall ? Syscalls.SyscallNtQuerySystemInformation(SystemCodeIntegrityInformation, ref CodeIntegrityInfo, (uint)Marshal.SizeOf(CodeIntegrityInfo), out ReturnLength) : NtQuerySystemInformation(SystemCodeIntegrityInformation, ref CodeIntegrityInfo, (uint)Marshal.SizeOf(CodeIntegrityInfo), out ReturnLength); + if (result >= 0 && ReturnLength == (uint)Marshal.SizeOf(CodeIntegrityInfo)) { uint CODEINTEGRITY_OPTION_TESTSIGN = 0x02; if ((CodeIntegrityInfo.CodeIntegrityOptions & CODEINTEGRITY_OPTION_TESTSIGN) == CODEINTEGRITY_OPTION_TESTSIGN) @@ -71,16 +71,18 @@ public static bool IsTestSignedDriversAllowed() /// /// Checks if kernel debugging is enabled on the system. + /// specifies if we should use syscall to call the WinAPI functions. /// /// Returns true if kernel debugging is enabled, otherwise false. - public static bool IsKernelDebuggingEnabled() + public static bool IsKernelDebuggingEnabled(bool Syscall) { uint SystemKernelDebuggerInformation = 0x23; Structs.SYSTEM_KERNEL_DEBUGGER_INFORMATION KernelDebugInfo = new Structs.SYSTEM_KERNEL_DEBUGGER_INFORMATION(); KernelDebugInfo.KernelDebuggerEnabled = false; KernelDebugInfo.KernelDebuggerNotPresent = true; uint ReturnLength = 0; - if (NtQuerySystemInformation(SystemKernelDebuggerInformation, ref KernelDebugInfo, (uint)Marshal.SizeOf(KernelDebugInfo), out ReturnLength) >= 0 && ReturnLength == (uint)Marshal.SizeOf(KernelDebugInfo)) + uint result = Syscall ? Syscalls.SyscallNtQuerySystemInformation(SystemKernelDebuggerInformation, ref KernelDebugInfo, (uint)Marshal.SizeOf(KernelDebugInfo), out ReturnLength) : NtQuerySystemInformation(SystemKernelDebuggerInformation, ref KernelDebugInfo, (uint)Marshal.SizeOf(KernelDebugInfo), out ReturnLength); + if (result >= 0 && ReturnLength == (uint)Marshal.SizeOf(KernelDebugInfo)) { if (KernelDebugInfo.KernelDebuggerEnabled || !KernelDebugInfo.KernelDebuggerNotPresent) { @@ -92,16 +94,18 @@ public static bool IsKernelDebuggingEnabled() /// /// Checks if Secure Boot is enabled on the system. + /// specifies if we should use syscall to call the WinAPI functions. /// /// Returns true if Secure Boot is enabled, otherwise false. - public static bool IsSecureBootEnabled() + public static bool IsSecureBootEnabled(bool Syscall) { uint SystemSecureBootInformation = 0x91; Structs.SYSTEM_SECUREBOOT_INFORMATION SecureBoot = new Structs.SYSTEM_SECUREBOOT_INFORMATION(); SecureBoot.SecureBootCapable = false; SecureBoot.SecureBootEnabled = false; uint ReturnLength = 0; - if (NtQuerySystemInformation(SystemSecureBootInformation, ref SecureBoot, (uint)Marshal.SizeOf(SecureBoot), out ReturnLength) >= 0) + uint result = Syscall ? Syscalls.SyscallNtQuerySystemInformation(SystemSecureBootInformation, ref SecureBoot, (uint)Marshal.SizeOf(SecureBoot), out ReturnLength) : NtQuerySystemInformation(SystemSecureBootInformation, ref SecureBoot, (uint)Marshal.SizeOf(SecureBoot), out ReturnLength); + if (result >= 0) { if (!SecureBoot.SecureBootCapable) return false; diff --git a/AntiCrack-DotNet/Program.cs b/AntiCrack-DotNet/Program.cs index 33e2dcc..2e4a306 100644 --- a/AntiCrack-DotNet/Program.cs +++ b/AntiCrack-DotNet/Program.cs @@ -1,4 +1,7 @@ using System; +using System.Diagnostics; +using System.Threading; +using Microsoft.Win32; namespace AntiCrack_DotNet { @@ -17,7 +20,6 @@ public static void SetTitle(string title) { Console.Title = title; } - public static void DisplayHeader(string header) { Console.ForegroundColor = ConsoleColor.Cyan; @@ -69,25 +71,54 @@ public static void DisplayResult(string text, string result, string info = "") Console.WriteLine($"{result} {info}"); Console.ForegroundColor = ConsoleColor.White; } + + public static void SyscallPrompt() + { + string Arch = IntPtr.Size == 8 ? "[x64 Environment]" : "[x86 Environment]"; + SetTitle($"AntiCrack DotNet {Arch} | Syscall Mode: Undetermined"); + Console.Write("Do you want to use syscalls for some of the detections? (Y/N): "); + string Response = Console.ReadLine().ToLower(); + if (Response == "y" || Response == "yes") + { + syscall = true; + SetTitle($"AntiCrack DotNet {Arch} | Syscall Mode: {syscall}"); + Console.Clear(); + Syscalls.InitSyscallList(); + Syscalls.BuildNumber = Syscalls.GetBuildNumber(true, true).ToLower(); + if (!Syscalls.IsBuildNumberSaved()) + { + Console.ForegroundColor = ConsoleColor.DarkRed; + Console.WriteLine("your system build number is not saved, we will try to dynamically get the syscalls and work with what we got."); + Console.ForegroundColor = ConsoleColor.White; + } + } + else + { + SetTitle($"AntiCrack DotNet {Arch} | Syscall Mode: {syscall}"); + Console.Clear(); + } + } } + private static bool syscall = false; + private static void ExecuteAntiDebuggingTricks() { ConsoleConfig.DisplayHeader("Executing Anti Debugging Tricks"); - ConsoleConfig.DisplayResult("GetForegroundWindow (Looking For Bad Active Debugger Window): ", AntiDebug.GetForegroundWindowAntiDebug(), "Checks if a debugger window is in the foreground."); + ConsoleConfig.DisplayResult("NtUserGetForegroundWindow (Looking For Bad Active Debugger Window): ", AntiDebug.NtUserGetForegroundWindowAntiDebug(), "Checks if a debugger window is in the foreground."); ConsoleConfig.DisplayResult("Debugger.IsAttached: ", AntiDebug.DebuggerIsAttached(), "Checks if a managed debugger is attached."); ConsoleConfig.DisplayResult("Hide Threads From Debugger..... ", AntiDebug.HideThreadsAntiDebug(), "Attempts to hide threads from the debugger."); ConsoleConfig.DisplayResult("IsDebuggerPresent: ", AntiDebug.IsDebuggerPresentCheck(), "Checks if a debugger is present."); ConsoleConfig.DisplayResult("NtSetDebugFilterState Check: ", AntiDebug.NtSetDebugFilterStateAntiDebug(), "Sets the debug filter state."); ConsoleConfig.DisplayResult("Page Guard Breakpoints Detection Check: ", AntiDebug.PageGuardAntiDebug(), "Detects page guard breakpoints."); - ConsoleConfig.DisplayResult("NtQueryInformationProcess ProcessDebugFlags: ", AntiDebug.NtQueryInformationProcessCheck_ProcessDebugFlags(), "Queries process debug flags."); - ConsoleConfig.DisplayResult("NtQueryInformationProcess ProcessDebugPort: ", AntiDebug.NtQueryInformationProcessCheck_ProcessDebugPort(), "Queries process debug port."); - ConsoleConfig.DisplayResult("NtQueryInformationProcess ProcessDebugObjectHandle: ", AntiDebug.NtQueryInformationProcessCheck_ProcessDebugObjectHandle(), "Queries process debug object handle."); - ConsoleConfig.DisplayResult("NtClose (Invalid Handle): ", AntiDebug.NtCloseAntiDebug_InvalidHandle(), "Tests NtClose with an invalid handle."); - ConsoleConfig.DisplayResult("NtClose (Protected Handle): ", AntiDebug.NtCloseAntiDebug_ProtectedHandle(), "Tests NtClose with a protected handle."); - ConsoleConfig.DisplayResult("Parent Process (Checking if the parent process is cmd.exe or explorer.exe): ", AntiDebug.ParentProcessAntiDebug(), "Checks if the parent process is a known process."); + ConsoleConfig.DisplayResult("NtQueryInformationProcess ProcessDebugFlags: ", AntiDebug.NtQueryInformationProcessCheck_ProcessDebugFlags(syscall), "Queries process debug flags."); + ConsoleConfig.DisplayResult("NtQueryInformationProcess ProcessDebugPort: ", AntiDebug.NtQueryInformationProcessCheck_ProcessDebugPort(syscall), "Queries process debug port."); + ConsoleConfig.DisplayResult("NtQueryInformationProcess ProcessDebugObjectHandle: ", AntiDebug.NtQueryInformationProcessCheck_ProcessDebugObjectHandle(syscall), "Queries process debug object handle."); + ConsoleConfig.DisplayResult("NtClose (Invalid Handle): ", AntiDebug.NtCloseAntiDebug_InvalidHandle(syscall), "Tests NtClose with an invalid handle."); + ConsoleConfig.DisplayResult("NtClose (Protected Handle): ", AntiDebug.NtCloseAntiDebug_ProtectedHandle(syscall), "Tests NtClose with a protected handle."); + ConsoleConfig.DisplayResult("Parent Process (Checking if the parent process is cmd.exe or explorer.exe): ", AntiDebug.ParentProcessAntiDebug(syscall), "Checks if the parent process is a known process."); ConsoleConfig.DisplayResult("Hardware Registers Breakpoints Detection: ", AntiDebug.HardwareRegistersBreakpointsDetection(), "Detects hardware register breakpoints."); - ConsoleConfig.DisplayResult("FindWindow (Looking For Bad Debugger Windows): ", AntiDebug.FindWindowAntiDebug(), "Finds windows with debugger-related titles."); + //ConsoleConfig.DisplayResult("FindWindow (Looking For Bad Debugger Windows): ", AntiDebug.FindWindowAntiDebug(), "Finds windows with debugger-related titles."); ConsoleConfig.DisplayResult("GetTickCount Anti Debug: ", "Skipped", "Unreliable for real anti-debug use."); ConsoleConfig.DisplayResult("OutputDebugString Anti Debug: ", "Skipped", "Unreliable for real anti-debug use."); ConsoleConfig.DisplayResult("Trying To Crash Non-Managed Debuggers with a Debugger Breakpoint..... ", "Skipped"); @@ -117,17 +148,13 @@ private static void ExecuteAntiVirtualizationTricks() ConsoleConfig.DisplayResult("Checking For Known Bad VM File Locations: ", AntiVirtualization.BadVMFilesDetection(), "Detects known bad VM file locations."); ConsoleConfig.DisplayResult("Checking For Known Bad Process Names: ", AntiVirtualization.BadVMProcessNames(), "Detects known bad VM process names."); ConsoleConfig.DisplayResult("Checking For Ports (useful to detect VMs which have no ports connected): ", AntiVirtualization.PortConnectionAntiVM(), "Checks for VM port connections."); - Console.WriteLine("Trying To Crash Sandboxie if Present......"); ConsoleConfig.DisplayResult("Checking for devices created by VMs or Sandboxes: ", AntiVirtualization.CheckDevices(), "Checks for VM or sandbox devices."); - AntiVirtualization.CrashingSandboxie(); ConsoleConfig.DisplayFooter(); } private static void ExecuteAntiDllInjectionTricks() { ConsoleConfig.DisplayHeader("Executing Anti DLL Injection Tricks"); - ConsoleConfig.DisplayResult("Patching LoadLibraryA To Prevent DLL Injection..... ", AntiDllInjection.PatchLoadLibraryA(), "Patches LoadLibraryA to prevent DLL injection."); - ConsoleConfig.DisplayResult("Patching LoadLibraryW To Prevent DLL Injection..... ", AntiDllInjection.PatchLoadLibraryW(), "Patches LoadLibraryW to prevent DLL injection."); ConsoleConfig.DisplayResult("Taking Advantage of Binary Image Signature Mitigation Policy to Prevent Non-Microsoft Binaries From Being Injected..... ", AntiDllInjection.SetDllLoadPolicy(), "Enforces binary image signature mitigation policy."); ConsoleConfig.DisplayResult("Checking if any injected libraries are present (simple DLL path whitelist check): ", AntiDllInjection.IsInjectedLibrary(), "Checks for injected libraries."); ConsoleConfig.DisplayFooter(); @@ -136,10 +163,10 @@ private static void ExecuteAntiDllInjectionTricks() private static void ExecuteOtherDetectionTricks() { ConsoleConfig.DisplayHeader("Executing Other Detection Tricks"); - ConsoleConfig.DisplayResult("Detecting if Unsigned Drivers are Allowed to Load: ", OtherChecks.IsUnsignedDriversAllowed(), "Checks if unsigned drivers are allowed."); - ConsoleConfig.DisplayResult("Detecting if Test-Signed Drivers are Allowed to Load: ", OtherChecks.IsTestSignedDriversAllowed(), "Checks if test-signed drivers are allowed."); - ConsoleConfig.DisplayResult("Detecting if Kernel Debugging is Enabled on the System: ", OtherChecks.IsKernelDebuggingEnabled(), "Checks if kernel debugging is enabled."); - ConsoleConfig.DisplayResult("Detecting if Secure Boot is Enabled on the System: ", OtherChecks.IsSecureBootEnabled(), "Checks if secure boot is enabled."); + ConsoleConfig.DisplayResult("Detecting if Unsigned Drivers are Allowed to Load: ", OtherChecks.IsUnsignedDriversAllowed(syscall), "Checks if unsigned drivers are allowed."); + ConsoleConfig.DisplayResult("Detecting if Test-Signed Drivers are Allowed to Load: ", OtherChecks.IsTestSignedDriversAllowed(syscall), "Checks if test-signed drivers are allowed."); + ConsoleConfig.DisplayResult("Detecting if Kernel Debugging is Enabled on the System: ", OtherChecks.IsKernelDebuggingEnabled(syscall), "Checks if kernel debugging is enabled."); + ConsoleConfig.DisplayResult("Detecting if Secure Boot is Enabled on the System: ", OtherChecks.IsSecureBootEnabled(syscall), "Checks if secure boot is enabled."); ConsoleConfig.DisplayResult("Detecting if Virtualization-Based Security is Enabled: ", OtherChecks.IsVirtualizationBasedSecurityEnabled(), "Checks if VBS is enabled."); ConsoleConfig.DisplayResult("Detecting if Memory Integrity Protection is Enabled: ", OtherChecks.IsMemoryIntegrityEnabled(), "Checks if Memory Integrity is enabled."); ConsoleConfig.DisplayResult("Detecting if the current assembly has been invoked by another one: ", OtherChecks.IsInovkedAssembly(), "Checks if assembly has been invoked."); @@ -157,8 +184,7 @@ private static void ExecuteHooksDetectionTricks() public static void Main(string[] args) { ConsoleConfig.SetDefaultColors(); - ConsoleConfig.SetTitle("AntiCrack DotNet"); - + ConsoleConfig.SyscallPrompt(); while (true) { ExecuteAntiDebuggingTricks(); diff --git a/AntiCrack-DotNet/Properties/AssemblyInfo.cs b/AntiCrack-DotNet/Properties/AssemblyInfo.cs index 969b812..96f3710 100644 --- a/AntiCrack-DotNet/Properties/AssemblyInfo.cs +++ b/AntiCrack-DotNet/Properties/AssemblyInfo.cs @@ -6,11 +6,11 @@ // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AntiCrack-DotNet")] -[assembly: AssemblyDescription("")] +[assembly: AssemblyDescription("Anti-Cracking Techniques made by AdvDebug on GitHub.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("AdvDebug")] [assembly: AssemblyProduct("AntiCrack-DotNet")] -[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyCopyright("Copyright © 2024")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] @@ -32,5 +32,5 @@ // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyVersion("1.2.7.0")] +[assembly: AssemblyFileVersion("1.2.7.0")] diff --git a/AntiCrack-DotNet/Structs.cs b/AntiCrack-DotNet/Structs.cs index 19aa777..ebb068f 100644 --- a/AntiCrack-DotNet/Structs.cs +++ b/AntiCrack-DotNet/Structs.cs @@ -3,7 +3,7 @@ namespace AntiCrack_DotNet { - internal sealed class Structs + public sealed class Structs { [StructLayout(LayoutKind.Sequential)] public struct CONTEXT @@ -15,12 +15,18 @@ public struct CONTEXT public uint P5Home; public uint P6Home; public long ContextFlags; + public IntPtr MxCsr; + public IntPtr SegCs; + public IntPtr SegDs; + public IntPtr SegEs; + public IntPtr SegFs; + public IntPtr SegGs; + public IntPtr SegSs; + public IntPtr EFlags; public uint Dr0; public uint Dr1; public uint Dr2; public uint Dr3; - public uint Dr4; - public uint Dr5; public uint Dr6; public uint Dr7; } @@ -98,5 +104,22 @@ public struct SYSTEM_INFO public ushort ProcessorLevel; public ushort ProcessorRevision; } + + [StructLayout(LayoutKind.Sequential)] + public struct OSVERSIONINFOEX + { + public int dwOSVersionInfoSize; + public int dwMajorVersion; + public int dwMinorVersion; + public int dwBuildNumber; + public int dwPlatformId; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] + public string szCSDVersion; + public ushort wServicePackMajor; + public ushort wServicePackMinor; + public ushort wSuiteMask; + public byte wProductType; + public byte wReserved; + } } } \ No newline at end of file diff --git a/AntiCrack-DotNet/Syscalls.cs b/AntiCrack-DotNet/Syscalls.cs new file mode 100644 index 0000000..2b641f8 --- /dev/null +++ b/AntiCrack-DotNet/Syscalls.cs @@ -0,0 +1,573 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.Eventing.Reader; +using System.IO; +using System.Linq; +using System.Management; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Remoting.Messaging; +using System.Security.Cryptography; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using Microsoft.Win32; +using static AntiCrack_DotNet.Structs; + +namespace AntiCrack_DotNet +{ + public sealed class Syscalls + { + #region WinApi + + [DllImport("ntdll.dll", SetLastError = true)] + private static extern uint NtAllocateVirtualMemory(IntPtr ProcessHandle, ref IntPtr BaseAddress, uint ZeroBits, ref uint RegionSize, uint AllocationType, uint Protect); + + [DllImport("kernelbase.dll", SetLastError = true)] + private static extern bool VirtualFree(IntPtr lpAddress, uint dwSize, uint dwFreeType); + + [DllImport("ntdll.dll", SetLastError = true, CharSet = CharSet.Unicode)] + private static extern void RtlInitUnicodeString(out Structs.UNICODE_STRING DestinationString, string SourceString); + + [DllImport("ntdll.dll", SetLastError = true, CharSet = CharSet.Ansi)] + private static extern void RtlUnicodeStringToAnsiString(out Structs.ANSI_STRING DestinationString, Structs.UNICODE_STRING UnicodeString, bool AllocateDestinationString); + + [DllImport("ntdll.dll", SetLastError = true)] + private static extern uint LdrGetDllHandleEx(ulong Flags, [MarshalAs(UnmanagedType.LPWStr)] string DllPath, [MarshalAs(UnmanagedType.LPWStr)] string DllCharacteristics, Structs.UNICODE_STRING LibraryName, ref IntPtr DllHandle); + + [DllImport("ntdll.dll", SetLastError = true, CharSet = CharSet.Ansi)] + private static extern uint LdrGetProcedureAddressForCaller(IntPtr Module, Structs.ANSI_STRING ProcedureName, ushort ProcedureNumber, out IntPtr FunctionHandle, ulong Flags, IntPtr CallBack); + + [DllImport("kernelbase.dll", SetLastError = true)] + private static extern IntPtr GetModuleHandleA(string Library); + + [DllImport("kernelbase.dll", SetLastError = true)] + private static extern IntPtr GetProcAddress(IntPtr hModule, string Function); + + [DllImport("ntdll.dll", SetLastError = true)] + private static extern int RtlGetVersion(ref Structs.OSVERSIONINFOEX versionInfo); + + #endregion + + #region Utils + + /// + /// Searches for the syscall number from the function bytes. + /// + /// the bytes to search for the syscall. + /// The syscall byte. + public static byte ExtractSyscallByte(byte[] bytes) + { + for (int i = 0; i < bytes.Length; i++) + { + if (bytes[i] == 0xB8) + { + return bytes[i + 1]; + } + } + return 0; + } + + private class Syscall + { + public string Name { get; set; } + public List<(string BuildNumber, byte SyscallNumber)> BuildNumber { get; set; } + } + + private static List syscalls = new List(); + + /// + /// Initializes the build numbers along with syscalls. + /// + public static void InitSyscallList() + { + syscalls = new List + { + new Syscall + { + Name = "NtClose", + BuildNumber = new List<(string, byte)> + { + ("7601", 0xF), + ("9200", 0xF), + ("9600", 0xF), + ("10240", 0xF), + ("10586", 0xF), + ("14393", 0xF), + ("15063", 0xF), + ("16299", 0xF), + ("17134", 0xF), + ("17763", 0xF), + ("18362", 0xF), + ("18363", 0xF), + ("19041", 0xF), + ("19042", 0xF), + ("19043", 0xF), + ("19044", 0xF), + ("19045", 0xF), + ("22621", 0xF), + ("22631", 0xF), + ("25915", 0xF), + ("26000", 0xF) + } + }, + new Syscall + { + Name = "NtQueryInformationProcess", + BuildNumber = new List<(string, byte)> + { + ("7601", 0x16), + ("9200", 0x17), + ("9600", 0x18), + ("10240", 0x19), + ("10586", 0x19), + ("14393", 0x19), + ("15063", 0x19), + ("16299", 0x19), + ("17134", 0x19), + ("17763", 0x19), + ("18362", 0x19), + ("18363", 0x19), + ("19041", 0x19), + ("19042", 0x19), + ("19043", 0x19), + ("19044", 0x19), + ("19045", 0x19), + ("22621", 0x19), + ("22631", 0x19), + ("25915", 0x19), + ("26000", 0x19) + } + }, + new Syscall + { + Name = "NtQuerySystemInformation", + BuildNumber = new List<(string DisplayVersion, byte SyscallNumber)> + { + ("7601", 0x33), + ("9200", 0x34), + ("9600", 0x35), + ("10240", 0x36), + ("10586", 0x36), + ("14393", 0x36), + ("15063", 0x36), + ("16299", 0x36), + ("17134", 0x36), + ("17763", 0x36), + ("18362", 0x36), + ("18363", 0x36), + ("19041", 0x36), + ("19042", 0x36), + ("19043", 0x36), + ("19044", 0x36), + ("19045", 0x36), + ("22621", 0x36), + ("22631", 0x36), + ("25915", 0x36), + ("26000", 0x36) + } + } + }; + } + + /// + /// Searches for the return value from the function bytes. + /// + /// the bytes to search for the ret value. + /// The return value byte. + public static byte ExtractSyscallRetValue(byte[] bytes) + { + for (int i = 0; i < bytes.Length; i++) + { + if (bytes[i] == 0xC2) + { + return bytes[i + 1]; + } + } + return 0; + } + + /// + /// Checks to see if the build number is already saved. + /// + /// An indicator to see if the build number is saved or not. + public static bool IsBuildNumberSaved() + { + foreach (Syscall GetSyscalls in syscalls) + { + for (int i = 0; i < GetSyscalls.BuildNumber.Count; i++) + { + if (GetSyscalls.BuildNumber[i].BuildNumber.ToLower() == BuildNumber) + { + return true; + } + } + } + return false; + } + + public static string BuildNumber = null; + + /// + /// Searches for the build number in registry. + /// + /// The build number. + private static string GetWindowsBuildNumberReg() + { + try + { + using (RegistryKey CurrentKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion")) + { + if (CurrentKey != null) + { + object value = CurrentKey.GetValue("CurrentBuildNumber"); + return value.ToString(); + } + } + } + catch + { + return null; + } + return null; + } + + /// + /// Searches for build number in WMI. + /// + /// The build number. + private static string GetWindowsBuildNumberWMI() + { + try + { + using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem")) + { + foreach (ManagementObject os in searcher.Get()) + { + object build = os["BuildNumber"]; + return build.ToString(); + } + } + } + catch + { + return null; + } + return null; + } + + + /// + /// Gets the build number using RtlGetVersion WinAPI. + /// + /// The build number. + private static string GetWindowsBuildNumberWinAPI() + { + OSVERSIONINFOEX VI = new OSVERSIONINFOEX(); + VI.dwOSVersionInfoSize = Marshal.SizeOf(typeof(OSVERSIONINFOEX)); + int status = RtlGetVersion(ref VI); + if (status == 0) + { + return VI.dwBuildNumber.ToString(); + } + return null; + } + + + /// + /// Searches for the return value from the function bytes. + /// + /// returns if the build numbers have been tampered with. + private static bool IsTampered(string WinAPI, string WMI, string Registry) + { + bool isMatch = (WinAPI == WMI) && (WMI == Registry); + return !isMatch; + } + + /// + /// Searches for the return value from the function bytes. + /// + /// The most suitable build number. + public static string GetMostMatching(string WinAPI, string WMI, string Registry) + { + if (Tampered) + { + if (WinAPI == WMI) + { + return WinAPI; + } + else if (WinAPI == Registry) + { + return WinAPI; + } + else if (WMI == Registry) + { + return WMI; + } + else + { + return WinAPI; + } + } + else + { + return WinAPI; + } + } + + private static bool ShowedBefore = false; + public static bool Tampered = false; + + /// + /// Gets the system build number. + /// + /// Exit if we found that the build number was tampered with. + /// Only print a console message that says that the function was tampered with. ExitOnBuildNumberTamper also needs to be enabled for this but the process won't die. + /// The current system build number. + public static string GetBuildNumber(bool ExitOnBuildNumberTamper, bool OnlyShowOnTamper) + { + string WinAPI = GetWindowsBuildNumberWinAPI(); + string WMI = GetWindowsBuildNumberWMI(); + string Registry = GetWindowsBuildNumberReg(); + if (ExitOnBuildNumberTamper && IsTampered(WinAPI, WMI, Registry)) + { + Tampered = true; + if (OnlyShowOnTamper) + { + if (!ShowedBefore) + { + Console.ForegroundColor = ConsoleColor.DarkRed; + Console.WriteLine("\nThe build number may have been tampered with. We will try to identify the most appropriate build number based on other detections and proceed with it, but there is a risk of incorrect syscalls..."); + Console.ForegroundColor = ConsoleColor.White; + ShowedBefore = true; + } + } + else + { + Environment.Exit(0); + unsafe + { + int* ptr = null; + *ptr = 42; + } + throw new Exception(new Random().Next(int.MinValue, int.MaxValue).ToString()); + } + } + return GetMostMatching(WinAPI, WMI, Registry); + } + + /// + /// Prepares the syscall code for the function provided. + /// + /// the function library name. + /// the function to get it's syscall code for. + /// An allocated memory to the syscall code. + public static IntPtr SyscallCode(string Library, string Function) + { + try + { + bool Extract = true; + byte SyscallNumber = 0x0; + foreach (Syscall GetSyscalls in syscalls) + { + if (GetSyscalls.Name.ToLower() == Function.ToLower()) + { + for (int i = 0; i < GetSyscalls.BuildNumber.Count; i++) + { + if (GetSyscalls.BuildNumber[i].BuildNumber.ToLower() == BuildNumber) + { + Extract = false; + SyscallNumber = GetSyscalls.BuildNumber[i].SyscallNumber; + break; + } + } + } + } + IntPtr hModule = Utils.LowLevelGetModuleHandle(Library); + IntPtr Address = Utils.LowLevelGetProcAddress(hModule, Function); + if (Address != IntPtr.Zero) + { + byte[] FunctionCode = new byte[40]; + Utils.CopyMem(FunctionCode, Address); + if (Extract) + { + SyscallNumber = ExtractSyscallByte(FunctionCode); + } + if (SyscallNumber != 0) + { + byte[] Code = new byte[40]; + if (IntPtr.Size == 8) + { + Code = new byte[] { 0x49, 0x89, 0xCA, 0xB8, SyscallNumber, 0x00, 0x00, 0x00, 0x0F, 0x05, 0xC3 }; + } + else + { + byte RetValue = ExtractSyscallRetValue(Code); + Code = new byte[] { 0xB8, SyscallNumber, 0x00, 0x00, 0x00, 0x64, 0xFF, 0x15, 0xC0, 0x00, 0x00, 0x00, 0xC2, RetValue, 0x00 }; + } + IntPtr Allocated = IntPtr.Zero; + uint Length = (uint)Code.Length; + uint Status = NtAllocateVirtualMemory(new IntPtr(-1), ref Allocated, 0, ref Length, 0x1000, PAGE_EXECUTE_READWRITE); + if (Status == 0) + { + unsafe + { + fixed (byte* source = Code) + { + Buffer.MemoryCopy(source, (void*)Allocated, Code.Length, Code.Length); + } + } + return Allocated; + } + } + } + return IntPtr.Zero; + } + catch + { + //this shouldn't happen in normal conditions + Environment.Exit(0); + unsafe + { + int* ptr = null; + *ptr = 42; + } + return IntPtr.Zero; + } + } + #endregion + + #region Syscalls Delegates + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate uint SysNtQueryInformationProcess(SafeHandle hProcess, uint ProcessInfoClass, out uint ProcessInfo, uint nSize, out uint ReturnLength); + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate uint SysNtQueryInformationProcess2(SafeHandle hProcess, uint ProcessInfoClass, out IntPtr ProcessInfo, uint nSize, uint ReturnLength); + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate uint SysNtQueryInformationProcess3(SafeHandle hProcess, uint ProcessInfoClass, ref Structs.PROCESS_BASIC_INFORMATION ProcessInfo, uint nSize, uint ReturnLength); + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate bool SysNtClose(IntPtr Handle); + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate uint SysNtQuerySystemInformation(uint SystemInformationClass, ref Structs.SYSTEM_CODEINTEGRITY_INFORMATION SystemInformation, uint SystemInformationLength, out uint ReturnLength); + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate uint SysNtQuerySystemInformation2(uint SystemInformationClass, ref Structs.SYSTEM_KERNEL_DEBUGGER_INFORMATION SystemInformation, uint SystemInformationLength, out uint ReturnLength); + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate uint SysNtQuerySystemInformation3(uint SystemInformationClass, ref Structs.SYSTEM_SECUREBOOT_INFORMATION SystemInformation, uint SystemInformationLength, out uint ReturnLength); + + #endregion + + #region Syscalls + + private static uint PAGE_EXECUTE_READWRITE = 0x40; + private static uint MEM_RELEASE = 0x00008000; + + public static uint SyscallNtQueryInformationProcess(SafeHandle hProcess, uint ProcessInfoClass, out uint ProcessInfo, uint nSize, out uint ReturnLength) + { + ProcessInfo = 0; + ReturnLength = 0; + IntPtr Syscall = SyscallCode("ntdll.dll", "NtQueryInformationProcess"); + if (Syscall != IntPtr.Zero) + { + SysNtQueryInformationProcess Executed = (SysNtQueryInformationProcess)Marshal.GetDelegateForFunctionPointer(Syscall, typeof(SysNtQueryInformationProcess)); + uint Result = Executed(hProcess, ProcessInfoClass, out ProcessInfo, nSize, out ReturnLength); + VirtualFree(Syscall, 0, MEM_RELEASE); + return Result; + } + return 0; + } + + public static uint SyscallNtQueryInformationProcess(SafeHandle hProcess, uint ProcessInfoClass, out IntPtr ProcessInfo, uint nSize, uint ReturnLength) + { + ProcessInfo = IntPtr.Zero; + ReturnLength = 0; + IntPtr Syscall = SyscallCode("ntdll.dll", "NtQueryInformationProcess"); + if (Syscall != IntPtr.Zero) + { + SysNtQueryInformationProcess2 Executed = (SysNtQueryInformationProcess2)Marshal.GetDelegateForFunctionPointer(Syscall, typeof(SysNtQueryInformationProcess2)); + uint Result = Executed(hProcess, ProcessInfoClass, out ProcessInfo, nSize, ReturnLength); + VirtualFree(Syscall, 0, MEM_RELEASE); + return Result; + } + return 0; + } + + public static uint SyscallNtQueryInformationProcess(SafeHandle hProcess, uint ProcessInfoClass, ref Structs.PROCESS_BASIC_INFORMATION ProcessInfo, uint nSize, uint ReturnLength) + { + ProcessInfo = new PROCESS_BASIC_INFORMATION(); + ReturnLength = 0; + IntPtr Syscall = SyscallCode("ntdll.dll", "NtQueryInformationProcess"); + if (Syscall != IntPtr.Zero) + { + SysNtQueryInformationProcess3 Executed = (SysNtQueryInformationProcess3)Marshal.GetDelegateForFunctionPointer(Syscall, typeof(SysNtQueryInformationProcess3)); + uint Result = Executed(hProcess, ProcessInfoClass, ref ProcessInfo, nSize, ReturnLength); + VirtualFree(Syscall, 0, MEM_RELEASE); + return Result; + } + return 0; + } + + public static bool SyscallNtClose(IntPtr Handle) + { + IntPtr Syscall = SyscallCode("ntdll.dll", "NtClose"); + if (Syscall != IntPtr.Zero) + { + SysNtClose Executed = (SysNtClose)Marshal.GetDelegateForFunctionPointer(Syscall, typeof(SysNtClose)); + bool Result = Executed(Handle); + VirtualFree(Syscall, 0, MEM_RELEASE); + return Result; + } + return false; + } + + public static uint SyscallNtQuerySystemInformation(uint SystemInformationClass, ref Structs.SYSTEM_CODEINTEGRITY_INFORMATION SystemInformation, uint SystemInformationLength, out uint ReturnLength) + { + ReturnLength = 0; + IntPtr Syscall = SyscallCode("ntdll.dll", "NtQuerySystemInformation"); + if (Syscall != IntPtr.Zero) + { + SysNtQuerySystemInformation Executed = (SysNtQuerySystemInformation)Marshal.GetDelegateForFunctionPointer(Syscall, typeof(SysNtQuerySystemInformation)); + uint Result = Executed(SystemInformationClass, ref SystemInformation, SystemInformationLength, out ReturnLength); + VirtualFree(Syscall, 0, MEM_RELEASE); + return Result; + } + return 0; + } + + public static uint SyscallNtQuerySystemInformation(uint SystemInformationClass, ref Structs.SYSTEM_KERNEL_DEBUGGER_INFORMATION SystemInformation, uint SystemInformationLength, out uint ReturnLength) + { + ReturnLength = 0; + IntPtr Syscall = SyscallCode("ntdll.dll", "NtQuerySystemInformation"); + if (Syscall != IntPtr.Zero) + { + SysNtQuerySystemInformation2 Executed = (SysNtQuerySystemInformation2)Marshal.GetDelegateForFunctionPointer(Syscall, typeof(SysNtQuerySystemInformation2)); + uint Result = Executed(SystemInformationClass, ref SystemInformation, SystemInformationLength, out ReturnLength); + VirtualFree(Syscall, 0, MEM_RELEASE); + return Result; + } + return 0; + } + + public static uint SyscallNtQuerySystemInformation(uint SystemInformationClass, ref Structs.SYSTEM_SECUREBOOT_INFORMATION SystemInformation, uint SystemInformationLength, out uint ReturnLength) + { + ReturnLength = 0; + IntPtr Syscall = SyscallCode("ntdll.dll", "NtQuerySystemInformation"); + if (Syscall != IntPtr.Zero) + { + SysNtQuerySystemInformation3 Executed = (SysNtQuerySystemInformation3)Marshal.GetDelegateForFunctionPointer(Syscall, typeof(SysNtQuerySystemInformation3)); + uint Result = Executed(SystemInformationClass, ref SystemInformation, SystemInformationLength, out ReturnLength); + VirtualFree(Syscall, 0, MEM_RELEASE); + return Result; + } + return 0; + } + #endregion + } +} \ No newline at end of file diff --git a/AntiCrack-DotNet/Utils.cs b/AntiCrack-DotNet/Utils.cs new file mode 100644 index 0000000..f8cff70 --- /dev/null +++ b/AntiCrack-DotNet/Utils.cs @@ -0,0 +1,122 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Management; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Win32; +using System.Threading; +using static AntiCrack_DotNet.Structs; +using System.Collections; +using System.Text.RegularExpressions; + +namespace AntiCrack_DotNet +{ + public sealed class Utils + { + #region WinApi + + [DllImport("ntdll.dll", SetLastError = true, CharSet = CharSet.Unicode)] + private static extern void RtlInitUnicodeString(out Structs.UNICODE_STRING DestinationString, string SourceString); + + [DllImport("ntdll.dll", SetLastError = true, CharSet = CharSet.Ansi)] + private static extern void RtlUnicodeStringToAnsiString(out Structs.ANSI_STRING DestinationString, Structs.UNICODE_STRING UnicodeString, bool AllocateDestinationString); + + [DllImport("ntdll.dll", SetLastError = true)] + private static extern uint LdrGetDllHandleEx(ulong Flags, [MarshalAs(UnmanagedType.LPWStr)] string DllPath, [MarshalAs(UnmanagedType.LPWStr)] string DllCharacteristics, Structs.UNICODE_STRING LibraryName, ref IntPtr DllHandle); + + [DllImport("kernelbase.dll", SetLastError = true)] + private static extern IntPtr GetModuleHandleA(string Library); + + [DllImport("kernelbase.dll", SetLastError = true)] + private static extern IntPtr GetProcAddress(IntPtr hModule, string Function); + + [DllImport("ntdll.dll", SetLastError = true, CharSet = CharSet.Ansi)] + private static extern uint LdrGetProcedureAddressForCaller(IntPtr Module, Structs.ANSI_STRING ProcedureName, ushort ProcedureNumber, out IntPtr FunctionHandle, ulong Flags, IntPtr CallBack); + + #endregion + + /// + /// Gets the handle of a specified module using low-level functions. + /// + /// The name of the library to get the handle for. + /// The handle to the module. + public static IntPtr LowLevelGetModuleHandle(string Library) + { + if (IntPtr.Size == 4) + return GetModuleHandleA(Library); + IntPtr hModule = IntPtr.Zero; + Structs.UNICODE_STRING UnicodeString = new Structs.UNICODE_STRING(); + RtlInitUnicodeString(out UnicodeString, Library); + LdrGetDllHandleEx(0, null, null, UnicodeString, ref hModule); + return hModule; + } + + /// + /// Gets the address of a specified function using low-level functions. + /// + /// The handle to the module. + /// The name of the function to get the address for. + /// The address of the function. + public static IntPtr LowLevelGetProcAddress(IntPtr hModule, string Function) + { + if (IntPtr.Size == 4) + return GetProcAddress(hModule, Function); + IntPtr FunctionHandle = IntPtr.Zero; + Structs.UNICODE_STRING UnicodeString = new Structs.UNICODE_STRING(); + Structs.ANSI_STRING AnsiString = new Structs.ANSI_STRING(); + RtlInitUnicodeString(out UnicodeString, Function); + RtlUnicodeStringToAnsiString(out AnsiString, UnicodeString, true); + LdrGetProcedureAddressForCaller(hModule, AnsiString, 0, out FunctionHandle, 0, IntPtr.Zero); + return FunctionHandle; + } + + /// + /// copies memory from a byte array to an IntPtr. + /// + /// The IntPtr destination in which the data will be copied to. + /// The byte array source in which the data will be copied from. + public static void CopyMem(IntPtr dst, byte[] src) + { + unsafe + { + fixed (byte* source = src) + { + Buffer.MemoryCopy(source, (void*)dst, src.Length, src.Length); + } + } + } + + /// + /// copies memory from an IntPtr to a byte array. + /// + /// The byte array destination in which the data will be copied to. + /// The IntPtr source in which the data will be copied from. + public static void CopyMem(byte[] dst, IntPtr src) + { + unsafe + { + fixed (byte* destination = dst) + { + Buffer.MemoryCopy((void*)src, destination, dst.Length, dst.Length); + } + } + } + + /// + /// Sees if the main string contains the second string. + /// + /// Main string to see if it contains the second string. + /// The second string that will be searched for. + /// An indicator if the Main string have the Second string in it. + public static bool Contains(string Main, string Second) + { + if (Main.IndexOf(Second, StringComparison.OrdinalIgnoreCase) >= 0) + { + return true; + } + return false; + } + } +}