public NetworkMonitor() { LastUpdate = MiscFunc.GetTickCount64(); try { InitEtw(); //AppLog.Debug("Successfully initialized NetworkMonitorETW"); } catch { Priv10Logger.LogError("Failed to initialized NetworkMonitorETW"); } regWatchers = new RegistryMonitor[] { new RegistryMonitor(RegistryHive.LocalMachine, @"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces"), new RegistryMonitor(RegistryHive.LocalMachine, @"SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters\Interfaces"), new RegistryMonitor(RegistryHive.LocalMachine, @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkList\Profiles") // firewall profile configuration }; foreach (var regWatcher in regWatchers) { regWatcher.RegChanged += new EventHandler(OnRegChanged); regWatcher.Start(); } }
void OnFinished(object sender, HttpTask.FinishedEventArgs args) { DomainBlocklist Blocklist; ListLock.EnterReadLock(); Blocklists.TryGetValue(mCurTask.DlUrl, out Blocklist); ListLock.ExitReadLock(); if (Blocklist != null) { Blocklist.LastUpdate = DateTime.Now; if (!args.Cancelled) { if (!args.Success) { Blocklist.Status = "Download Error"; // todo localize Priv10Logger.LogError("Blocklist download failed: {0}; Reason: {1}", mCurTask.DlUrl, args.GetError()); if (mCurTask.DlName != null && File.Exists(mCurTask.DlPath + @"\" + mCurTask.DlName)) { Priv10Logger.LogWarning("An older version of the Blocklist is present and will be used."); } } else { Blocklist.Status = "Downloaded"; // todo localize } } } PendingDownloads.Remove(mCurTask.DlUrl); mCurTask = null; DownloadNextFile(); }
public static bool Restart(bool RunAs = false /*, bool bService = false*/) { /*if (bService && Priv10Service.IsInstalled()) * { * Priv10Service.Terminate(); * Priv10Service.Startup(); * }*/ string arguments = "\"" + string.Join("\" \"", args) + "\""; ProcessStartInfo startInfo = new ProcessStartInfo(exePath, arguments); startInfo.UseShellExecute = true; if (RunAs) { startInfo.Verb = "runas"; } try { Process.Start(startInfo); Environment.Exit(-1); return(true); } catch { //MessageBox.Show(Translate.fmt("msg_admin_req", mName), mName); Priv10Logger.LogWarning("Failed to restart Application"); return(false); } }
public int CleanUp(bool ExtendedCleanup = false) { int Count = 0; foreach (Program prog in Programs.Values.ToList()) { bool Remove = !prog.Exists(); if (ExtendedCleanup && prog.Rules.Count == 0 && prog.Sockets.Count == 0) { Remove = true; } if (Remove) { // remove all rules for this program, if there are any foreach (var guid in prog.Rules.Keys.ToList()) { App.engine.FirewallManager.RemoveRule(guid); } Programs.Remove(prog.ID); Priv10Logger.LogInfo("CleanUp Removed program: {0}", prog.ID.FormatString()); Count++; } } return(Count); }
public bool RemoveRule(FirewallRule rule) { NetFwRule FwRule; if (!Rules.TryGetValue(rule.guid, out FwRule)) { return(true); // tne rule is already gone } try { // Note: if this is not set to null renam may fail as well as other sets :/ FwRule.Entry.EdgeTraversalOptions = (int)NET_FW_EDGE_TRAVERSAL_TYPE_.NET_FW_EDGE_TRAVERSAL_TYPE_DENY; // Note: the removal is done byname, howeever multiple rules may have the same name, WTF, so we set a temporary unique name FwRule.Entry.Name = "***_to_be_deleted_***"; // todo add rand string NetFwPolicy.Rules.Remove(FwRule.Entry.Name); Rules.Remove(rule.guid); } catch (Exception err) { Priv10Logger.LogError("Failed to Remove rule: " + err.Message); return(false); } return(true); }
protected override void OnStart(string[] args) { Priv10Logger.LogInfo("priv10 Service starting"); Thread thread = new Thread(new ThreadStart(Run)); thread.IsBackground = true; thread.SetApartmentState(ApartmentState.STA); // needed for tweaks thread.Start(); //Priv10Logger.LogInfo("priv10 Service started"); }
public ProcessMonitor() { try { InitEtw(); //AppLog.Debug("Successfully initialized ProcessMonitorEtw"); } catch { Priv10Logger.LogError("Failed to initialized ProcessMonitorEtw"); } }
public DnsQueryWatcher() { try { InitEtw(); //AppLog.Debug("Successfully initialized DnsInspectorETW"); } catch { Priv10Logger.LogError("Failed to initialized DnsInspectorETW"); } }
protected override void OnStop() { try { Priv10Logger.LogInfo("priv10 Service stopping..."); App.engine.Stop(); Priv10Logger.LogInfo("priv10 Service stopped"); } catch { } base.OnStop(); }
public bool Load() { if (!File.Exists(App.dataPath + @"\DnsBlockList.xml")) { return(false); } ListLock.EnterWriteLock(); try { XmlDocument xDoc = new XmlDocument(); xDoc.Load(App.dataPath + @"\DnsBlockList.xml"); double fileVersion = 0.0; double.TryParse(xDoc.DocumentElement.GetAttribute("Version"), out fileVersion); if (fileVersion != xmlVersion) { Priv10Logger.LogError("Failed to load DNS Blocklist, unknown file version {0}, expected {1}", fileVersion, xmlVersion); return(false); } foreach (XmlNode node in xDoc.DocumentElement.ChildNodes) { if (node.Name == "Blocklists") { LoadList(node); } else if (node.Name == "Whitelist") { LoadList(node, Lists.Whitelist); } else if (node.Name == "Blacklist") { LoadList(node, Lists.Blacklist); } } } catch (Exception err) { AppLog.Exception(err); return(false); } finally { ListLock.ExitWriteLock(); } return(true); }
public int LoadBlockList(string BlockListPath) { int count = 0; int success = 0; try { var lines = File.ReadAllLines(BlockListPath); var entries = lines.Where(l => TestLine(l)).Select(l => (ParseLine(l))); foreach (var entry in entries) { count++; if (entry == null) { continue; } //IPAddress ip = IPAddress.Any; //if (!IPAddress.TryParse(entry.Address, out ip)) // continue; // Note: some blocklists use 120.0.0.1 as target, but we want always 0.0.0.0 Domain domain = new Domain(entry.Domain); Add(new ResourceRecord(domain, new byte[0], RecordType.ANY, RecordClass.IN, ttl)); success++; } } catch (Exception err) { AppLog.Exception(err); } if (success == 0) { Priv10Logger.LogError("Failed to load blocklist: {0}", Path.GetFileName(BlockListPath)); } else if (success < count) { Priv10Logger.LogWarning("Loaded {1} DNS blocklist entries from {0}, {2} entries were invalid", Path.GetFileName(BlockListPath), success, count - success); } else { Priv10Logger.LogInfo("Loaded {1} DNS blocklist entries from {0}", Path.GetFileName(BlockListPath), success); } return(success); }
public bool UpdateRule(FirewallRule rule) { bool bAdd = (rule.guid == null); try { NetFwRule FwRule; if (bAdd) { FwRule = new NetFwRule() { Entry = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule")), Rule = rule } } ; else if (!Rules.TryGetValue(rule.guid, out FwRule)) { Priv10Logger.LogError("Failed Updating rule: ruls is not longer present"); return(false); } else { FwRule.Rule = rule; } if (!SaveRule(rule, FwRule.Entry)) { return(false); } if (bAdd) { NetFwPolicy.Rules.Add(FwRule.Entry); rule.Index = RuleCounter++; rule.guid = Guid.NewGuid().ToString("B"); Rules.Add(rule.guid, FwRule); } } catch (Exception err) { Priv10Logger.LogError("Failed to Write rule: " + err.Message); return(false); } return(true); }
public bool Init() { try { string strBindIP = App.GetConfig("DNSProxy", "BindIP", ""); IPAddress BindIP = IPAddress.IPv6Any; if (strBindIP.Length > 0) { IPAddress.TryParse(strBindIP, out BindIP); } udp = new UdpClient(BindIP.AddressFamily); if (BindIP.AddressFamily == AddressFamily.InterNetworkV6) { udp.Client.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false); // Also accept IPv4 } udp.Client.Bind(new IPEndPoint(BindIP, App.GetConfigInt("DNSProxy", "Port", DEFAULT_PORT))); udp.Client.SendTimeout = UDP_TIMEOUT; } catch { Priv10Logger.LogError("Failed to start DNS server"); return(false); } if (!blockList.Load()) { Priv10Logger.LogError("Restoring default blocklist list, as loading from file failed!"); blockList.AddDefaultLists(); } blockList.LoadBlockLists(); SetupUpstreamDNS(); run = true; thread = new Thread(new ThreadStart(Run)); thread.IsBackground = true; thread.Name = "DnsProxy"; thread.Start(); ConfigureSystemDNS(); return(true); }
private void OnDnsQueryWatched(object sender, DnsQueryWatcher.DnsEvent Event) { foreach (IPAddress remoteAddress in Event.RemoteAddresses) { OnHostName(remoteAddress, Event.HostName, NameSources.CapturedQuery, Event.ProcessId); } List <ServiceHelper.ServiceInfo> Services = ServiceHelper.GetServicesByPID(Event.ProcessId); ProgramID ProgID = App.engine.GetProgIDbyPID(Event.ProcessId, (Services == null || Services.Count > 1) ? null : Services[0].ServiceName); if (ProgID == null) { Priv10Logger.LogWarning("Watched a DNS query '{0}' for a terminated process with id {1}", Event.HostName, Event.ProcessId); } else { Program prog = App.engine.ProgramList.FindProgram(ProgID, true, ProgramID.FuzzyModes.Any); prog?.LogDomain(Event.HostName, Event.TimeStamp); } }
private void DownloadNextFile() { if (PendingDownloads.Count == 0) { DownloadsFinished(); return; } if (mCurTask != null) { return; } string Url = PendingDownloads.FirstOrDefault(); DomainBlocklist Blocklist; ListLock.EnterReadLock(); Blocklists.TryGetValue(Url, out Blocklist); ListLock.ExitReadLock(); if (Blocklist == null) { PendingDownloads.Remove(Url); DownloadNextFile(); } mCurTask = new HttpTask(Url, App.dataPath + @"\DnsBlockLists\", Blocklist.FileName); //mCurTask.Progress += OnProgress; mCurTask.Finished += OnFinished; if (!mCurTask.Start()) { Priv10Logger.LogError("Failed to start download of blocklist: {0}", Url); PendingDownloads.Remove(Url); DownloadNextFile(); } else { Priv10Logger.LogInfo("Started downloading blocklist: {0}", Url); } }
public bool TestTweak(Tweak tweak, bool fixChanged = false) { if (!tweak.IsAvailable()) { return(false); } bool status; if (AdminFunc.IsAdministrator() || tweak.usrLevel || !App.client.IsConnected()) { status = TweakTools.TestTweak(tweak); } else { status = App.client.TestTweak(tweak); } if (tweak.Status != status) { tweak.Status = status; tweak.LastChangeTime = DateTime.Now; if (tweak.Status == false && tweak.State != Tweak.States.Unsellected) { Dictionary <string, string> Params = new Dictionary <string, string>(); Params.Add("Name", tweak.Name); Params.Add("Group", tweak.Group); Params.Add("Category", tweak.Category); TweakEventArgs.State state = TweakEventArgs.State.eChanged; if (fixChanged == true && tweak.FixFailed == false) { ApplyTweak(tweak); if (TestTweak(tweak, false) != true) { tweak.FixFailed = true; Priv10Logger.LogError(Priv10Logger.EventIDs.TweakError, Params, Priv10Logger.EventFlags.Notifications, Translate.fmt("msg_tweak_stuck", tweak.Name, tweak.Group)); } else { state = TweakEventArgs.State.eRestored; tweak.FixedCount++; Priv10Logger.LogInfo(Priv10Logger.EventIDs.TweakFixed, Params, Priv10Logger.EventFlags.Notifications, Translate.fmt("msg_tweak_fixed", tweak.Name, tweak.Group)); } } else { Priv10Logger.LogWarning(Priv10Logger.EventIDs.TweakChanged, Params, Priv10Logger.EventFlags.AppLogEntries, Translate.fmt("msg_tweak_un_done", tweak.Name, tweak.Group)); } if (state == TweakEventArgs.State.eChanged) { TweakChanged?.Invoke(this, new TweakEventArgs() { tweak = tweak, state = state }); } } } return(status); }
public bool Load(string FilePath, Dictionary <string, TweakPresets.Category> Categorys) { if (!File.Exists(FilePath)) { return(false); } try { XmlDocument xDoc = new XmlDocument(); xDoc.Load(FilePath); double fileVersion = 0.0; double.TryParse(xDoc.DocumentElement.GetAttribute("Version"), out fileVersion); #if false if (fileVersion != xmlVersion) { if (fileVersion != 0 && fileVersion < xmlVersion) { FileOps.MoveFile(FilePath, App.dataPath + @"\Tweaks_old.xml", true); Priv10Logger.LogWarning(App.EventIDs.AppWarning, null, App.EventFlags.Notifications, Translate.fmt("msg_tweaks_updated", App.dataPath + @"\Tweaks_old.xml")); } else { Priv10Logger.LogError("Failed to load tweaklist, unknown file version {0}, expected {1}", fileVersion, xmlVersion); } return(false); } #endif int TotalCount = 0; int ErrorCount = 0; foreach (XmlNode node in xDoc.DocumentElement.ChildNodes) { TotalCount++; Tweak tweak = new Tweak(); if (!tweak.Load(node)) { ErrorCount++; continue; } TweakPresets.Category tweak_cat; if (!Categorys.TryGetValue(tweak.Category, out tweak_cat)) { tweak_cat = new TweakPresets.Category(tweak.Category); Categorys.Add(tweak.Category, tweak_cat); } tweak_cat.Add(tweak); } #if false if (ErrorCount != 0) { Priv10Logger.LogError("Failed to load {0} tweak entries out of {1}", ErrorCount, TotalCount); } Priv10Logger.LogInfo("TweakManager loaded {0} entries", TotalCount - ErrorCount); #endif } catch (Exception err) { AppLog.Exception(err); return(false); } return(true); }
public static bool SaveRule(FirewallRule rule, INetFwRule2 entry) { try { entry.EdgeTraversalOptions = (int)NET_FW_EDGE_TRAVERSAL_TYPE_.NET_FW_EDGE_TRAVERSAL_TYPE_DENY; INetFwRule3 entry3 = entry as INetFwRule3; entry.ApplicationName = rule.BinaryPath; entry.serviceName = rule.ServiceTag; if (entry3 != null) { entry3.LocalAppPackageId = rule.AppSID; } /* * switch (rule.ProgID.Type) * { * case ProgramID.Types.Global: * entry.ApplicationName = null; * break; * case ProgramID.Types.System: * entry.ApplicationName = "System"; * break; * default: * if (rule.ProgID.Path != null && rule.ProgID.Path.Length > 0) * entry.ApplicationName = rule.ProgID.Path; * break; * } * * if (rule.ProgID.Type == ProgramID.Types.App) * entry3.LocalAppPackageId = rule.ProgID.GetPackageSID(); * else * entry3.LocalAppPackageId = null; * * if (rule.ProgID.Type == ProgramID.Types.Service) * entry.serviceName = rule.ProgID.GetServiceId(); * else * entry.serviceName = null; */ entry.Name = rule.Name; entry.Grouping = rule.Grouping; entry.Description = rule.Description; entry.Enabled = rule.Enabled; switch (rule.Direction) { case FirewallRule.Directions.Inbound: entry.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN; break; case FirewallRule.Directions.Outboun: entry.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT; break; } switch (rule.Action) { case FirewallRule.Actions.Allow: entry.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW; break; case FirewallRule.Actions.Block: entry.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK; break; } entry.Profiles = rule.Profile; if (rule.Interface == (int)FirewallRule.Interfaces.All) { entry.InterfaceTypes = "All"; } else { List <string> interfaces = new List <string>(); if ((rule.Interface & (int)FirewallRule.Interfaces.Lan) != 0) { interfaces.Add("Lan"); } if ((rule.Interface & (int)FirewallRule.Interfaces.Wireless) != 0) { interfaces.Add("Wireless"); } if ((rule.Interface & (int)FirewallRule.Interfaces.RemoteAccess) != 0) { interfaces.Add("RemoteAccess"); } entry.InterfaceTypes = string.Join(",", interfaces.ToArray().Reverse()); } // Note: if this is not cleared protocol change may trigger an exception if (entry.LocalPorts != null) { entry.LocalPorts = null; } if (entry.RemotePorts != null) { entry.RemotePorts = null; } if (entry.IcmpTypesAndCodes != null) { entry.IcmpTypesAndCodes = null; } // Note: protocol must be set early enough or other sets will cause errors! entry.Protocol = rule.Protocol; switch (rule.Protocol) { case (int)FirewallRule.KnownProtocols.ICMP: case (int)FirewallRule.KnownProtocols.ICMPv6: entry.IcmpTypesAndCodes = rule.GetIcmpTypesAndCodes(); break; case (int)FirewallRule.KnownProtocols.TCP: case (int)FirewallRule.KnownProtocols.UDP: entry.LocalPorts = rule.LocalPorts; entry.RemotePorts = rule.RemotePorts; break; } if (rule.EdgeTraversal != (int)NET_FW_EDGE_TRAVERSAL_TYPE_.NET_FW_EDGE_TRAVERSAL_TYPE_DEFER_TO_USER) { entry.LocalAddresses = rule.LocalAddresses; entry.RemoteAddresses = rule.RemoteAddresses; } entry.EdgeTraversalOptions = rule.EdgeTraversal; if (entry3 != null) { /* * string s0 = entry3.LocalAppPackageId // 8 * string s1 = entry3.RemoteUserAuthorizedList; // 7 * string s2 = entry3.RemoteMachineAuthorizedList; // 7 * string s3 = entry3.LocalUserAuthorizedList; // 8 * string s4 = entry3.LocalUserOwner; // 8 * int i1 = entry3.SecureFlags; // ?? */ } } catch (Exception err) { Priv10Logger.LogError("Firewall Rule Commit failed {0}", err.ToString()); return(false); } return(true); }
public static bool LoadRule(FirewallRule rule, INetFwRule2 entry) { try { INetFwRule3 entry3 = entry as INetFwRule3; rule.BinaryPath = entry.ApplicationName; rule.ServiceTag = entry.serviceName; if (entry3 != null) { rule.AppSID = entry3.LocalAppPackageId; } // Note: while LocalAppPackageId and serviceName can be set at the same timea universall App can not be started as a service ProgramID progID; if (entry.ApplicationName != null && entry.ApplicationName.Equals("System", StringComparison.OrdinalIgnoreCase)) { progID = ProgramID.NewID(ProgramID.Types.System); } // Win10 else if (entry3 != null && entry3.LocalAppPackageId != null) { if (entry.serviceName != null) { throw new ArgumentException("Firewall paremeter conflict"); } progID = ProgramID.NewAppID(entry3.LocalAppPackageId, entry.ApplicationName); } // else if (entry.serviceName != null) { progID = ProgramID.NewSvcID(entry.serviceName, entry.ApplicationName); } else if (entry.ApplicationName != null) { progID = ProgramID.NewProgID(entry.ApplicationName); } else // if nothing is configured than its a global roule { progID = ProgramID.NewID(ProgramID.Types.Global); } rule.ProgID = Priv10Engine.AdjustProgID(progID); // https://docs.microsoft.com/en-us/windows/desktop/api/netfw/nn-netfw-inetfwrule rule.Name = entry.Name; rule.Grouping = entry.Grouping; rule.Description = entry.Description; //rule.ProgramPath = entry.ApplicationName; //rule.ServiceName = entry.serviceName; rule.Enabled = entry.Enabled; switch (entry.Direction) { case NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN: rule.Direction = FirewallRule.Directions.Inbound; break; case NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT: rule.Direction = FirewallRule.Directions.Outboun; break; } switch (entry.Action) { case NET_FW_ACTION_.NET_FW_ACTION_ALLOW: rule.Action = FirewallRule.Actions.Allow; break; case NET_FW_ACTION_.NET_FW_ACTION_BLOCK: rule.Action = FirewallRule.Actions.Block; break; } rule.Profile = entry.Profiles; if (entry.InterfaceTypes.Equals("All", StringComparison.OrdinalIgnoreCase)) { rule.Interface = (int)FirewallRule.Interfaces.All; } else { rule.Interface = 0; if (entry.InterfaceTypes.IndexOf("Lan", StringComparison.OrdinalIgnoreCase) != -1) { rule.Interface |= (int)FirewallRule.Interfaces.Lan; } if (entry.InterfaceTypes.IndexOf("Wireless", StringComparison.OrdinalIgnoreCase) != -1) { rule.Interface |= (int)FirewallRule.Interfaces.Wireless; } if (entry.InterfaceTypes.IndexOf("RemoteAccess", StringComparison.OrdinalIgnoreCase) != -1) { rule.Interface |= (int)FirewallRule.Interfaces.RemoteAccess; } } rule.Protocol = entry.Protocol; /*The localAddrs parameter consists of one or more comma-delimited tokens specifying the local addresses from which the application can listen for traffic. "*" is the default value. Valid tokens include: * * "*" indicates any local address. If present, this must be the only token included. * "Defaultgateway" * "DHCP" * "WINS" * "LocalSubnet" indicates any local address on the local subnet. This token is not case-sensitive. * A subnet can be specified using either the subnet mask or network prefix notation. If neither a subnet mask not a network prefix is specified, the subnet mask defaults to 255.255.255.255. * A valid IPv6 address. * An IPv4 address range in the format of "start address - end address" with no spaces included. * An IPv6 address range in the format of "start address - end address" with no spaces included.*/ switch (rule.Protocol) { case (int)FirewallRule.KnownProtocols.ICMP: case (int)FirewallRule.KnownProtocols.ICMPv6: rule.SetIcmpTypesAndCodes(entry.IcmpTypesAndCodes); break; case (int)FirewallRule.KnownProtocols.TCP: case (int)FirewallRule.KnownProtocols.UDP: // , separated number or range 123-456 rule.LocalPorts = entry.LocalPorts; rule.RemotePorts = entry.RemotePorts; break; } rule.LocalAddresses = entry.LocalAddresses; rule.RemoteAddresses = entry.RemoteAddresses; // https://docs.microsoft.com/de-de/windows/desktop/api/icftypes/ne-icftypes-net_fw_edge_traversal_type_ //EdgeTraversal = (int)(Entry.EdgeTraversal ? NET_FW_EDGE_TRAVERSAL_TYPE_.NET_FW_EDGE_TRAVERSAL_TYPE_ALLOW : NET_FW_EDGE_TRAVERSAL_TYPE_.NET_FW_EDGE_TRAVERSAL_TYPE_DENY); rule.EdgeTraversal = entry.EdgeTraversalOptions; if (entry3 != null) { /* * string s0 = entry3.LocalAppPackageId // 8 * string s1 = entry3.RemoteUserAuthorizedList; // 7 * string s2 = entry3.RemoteMachineAuthorizedList; // 7 * string s3 = entry3.LocalUserAuthorizedList; // 8 * string s4 = entry3.LocalUserOwner; // 8 * int i1 = entry3.SecureFlags; // ?? */ } } catch (Exception err) { Priv10Logger.LogError("Reading Firewall Rule failed {0}", err.ToString()); return(false); } return(true); }
public static void Main(string[] args) { App.args = args; HasConsole = WinConsole.Initialize(TestArg("-console")); if (TestArg("-dbg_wait")) { MessageBox.Show("Waiting for debugger. (press ok when attached)"); } if (TestArg("-dbg_log")) { AppDomain.CurrentDomain.FirstChanceException += FirstChanceExceptionHandler; } StartModes startMode = StartModes.Normal; // Normal GUI Mode if (TestArg("-svc")) { startMode = StartModes.Service; } else if (TestArg("-engine")) { startMode = StartModes.Engine; } Log = new AppLog(Key); AppLog.ExceptionLogID = (long)Priv10Logger.EventIDs.Exception; AppLog.ExceptionCategory = (short)Priv10Logger.EventFlags.DebugEvents; // When running as worker we need the windows event log if (!Log.UsingEventLog()) { Log.SetupEventLog(Key); } // load current version exePath = Process.GetCurrentProcess().MainModule.FileName; //System.Reflection.Assembly.GetExecutingAssembly().Location; //*FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(exePath); //Version = fvi.FileMajorPart + "." + fvi.FileMinorPart; //if (fvi.FileBuildPart != 0) // Version += "." + fvi.FileBuildPart; //if (fvi.FilePrivatePart != 0) // Version += (char)('a' + (fvi.FilePrivatePart - 1)); appPath = Path.GetDirectoryName(exePath); dataPath = appPath + @"\Data"; if (File.Exists(GetINIPath())) // if an ini exists in the app path, its considdered to be a portable run { isPortable = true; AppLog.Debug("Portable Mode"); } else { string progData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); if (progData == null) { progData = @"C:\ProgramData"; } dataPath = progData + "\\" + Key; } AppLog.Debug("Config Directory: {0}", dataPath); if (!Directory.Exists(dataPath)) { Directory.CreateDirectory(dataPath); } if (AdminFunc.IsAdministrator()) { FileOps.SetAnyDirSec(dataPath); } Priv10Logger.LogInfo("PrivateWin10 Service Process Started, Mode {0}.", startMode.ToString()); // setup custom assembly resolution for x86/x64 synamic compatybility AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolveHandler; // is the process starting as a service/worker? if (startMode != StartModes.Normal) { engine = new Priv10Engine(); if (startMode == StartModes.Service) { using (Priv10Service svc = new Priv10Service()) ServiceBase.Run(svc); } else { engine.Run(); } return; } }
public bool Load() { if (!File.Exists(App.dataPath + @"\Programs.xml")) { return(false); } try { XmlDocument xDoc = new XmlDocument(); xDoc.Load(App.dataPath + @"\Programs.xml"); double fileVersion = 0.0; double.TryParse(xDoc.DocumentElement.GetAttribute("Version"), out fileVersion); if (fileVersion != xmlVersion) { Priv10Logger.LogError("Failed to load programlist, unknown file version {0}, expected {1}", fileVersion, xmlVersion); return(false); } int TotalCount = 0; int ErrorCount = 0; foreach (XmlNode node in xDoc.DocumentElement.ChildNodes) { TotalCount++; ProgramSet entry = new ProgramSet(); if (!entry.LoadSet(node)) { ErrorCount++; continue; } foreach (Program prog in entry.Programs.Values.ToList()) { // COMPAT: merge "duplicates" Program knownProg; if (App.engine.ProgramList.Programs.TryGetValue(prog.ID, out knownProg)) { foreach (var rule in prog.Rules) { knownProg.Rules.Add(rule.Key, rule.Value); } entry.Programs.Remove(prog.ID); } else { Programs.Add(prog.ID, prog); } } if (entry.Programs.Count > 0) { ProgramSets.Add(entry.guid, entry); } } if (ErrorCount != 0) { Priv10Logger.LogError("Failed to load {0} program entry out of {1}", ErrorCount, TotalCount); } Priv10Logger.LogInfo("ProgramList loaded {0} entries", TotalCount - ErrorCount); } catch (Exception err) { AppLog.Exception(err); return(false); } return(true); }
public bool Load(XmlNode entryNode) { foreach (XmlNode node in entryNode.ChildNodes) { if (node.Name == "ID") { ProgramID id = new ProgramID(); if (id.Load(node)) { // COMPAT: remove service tag ID = FirewallRuleEx.AdjustProgID(id); } } else if (node.Name == "Description") { Description = node.InnerText; } else if (node.Name == "ReceivedBytes") { UInt64.TryParse(node.InnerText, out OldDownload); } else if (node.Name == "SentBytes") { UInt64.TryParse(node.InnerText, out OldUpload); } else if (node.Name == "FwRules") { foreach (XmlNode childNode in node.ChildNodes) { FirewallRuleEx rule = new FirewallRuleEx(); rule.ProgID = ID; // todo: remove later, load loads this amyways if (rule.Load(childNode) && !Rules.ContainsKey(rule.guid)) { // COMPAT: update entry, old version did not save these data separatly //if (ID.Type != ProgramID.Types.Global && (rule.BinaryPath == null && rule.ServiceTag == null && rule.AppSID == null)) // rule.SetProgID(ID); Rules.Add(rule.guid, rule); } else { Priv10Logger.LogError("Failed to load Firewall RuleEx {0} in {1}", rule.Name != null ? rule.Name : "[un named]", this.Description); } } } else if (node.Name == "DnsLog") { foreach (XmlNode childNode in node.ChildNodes) { DnsEntry Entry = new DnsEntry(ID); if (Entry.Load(childNode) && !DnsLog.ContainsKey(Entry.HostName)) { DnsLog.Add(Entry.HostName, Entry); } else { Priv10Logger.LogError("Failed to load DnsLog Entry in {0}", this.Description); } } } else { AppLog.Debug("Unknown Program Value, '{0}':{1}", node.Name, node.InnerText); } } if (Description == null || Description.Substring(0, 2) == "@{") { Description = GetDescription(); } return(ID != null); }
private void DownloadsFinished() { LoadBlockLists(); Priv10Logger.LogInfo("Filished Updating blocklists"); }