Exemplo n.º 1
0
    static public bool SkipUacEnable(string taskName, bool is_enable)
    {
        try
        {
            TaskScheduler.TaskScheduler service = new TaskScheduler.TaskScheduler();
            service.Connect();
            ITaskFolder folder = service.GetFolder(@"\"); // root
            if (is_enable)
            {
                string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
                string appPath = Path.GetDirectoryName(exePath);

                ITaskDefinition task = service.NewTask(0);
                task.RegistrationInfo.Author = "WuMgr";
                task.Principal.RunLevel      = _TASK_RUNLEVEL.TASK_RUNLEVEL_HIGHEST;

                task.Settings.AllowHardTerminate         = false;
                task.Settings.StartWhenAvailable         = false;
                task.Settings.DisallowStartIfOnBatteries = false;
                task.Settings.StopIfGoingOnBatteries     = false;
                task.Settings.MultipleInstances          = _TASK_INSTANCES_POLICY.TASK_INSTANCES_PARALLEL;
                task.Settings.ExecutionTimeLimit         = "PT0S";

                IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC);
                action.Path             = exePath;
                action.WorkingDirectory = appPath;
                action.Arguments        = "-NoUAC $(Arg0)";

                IRegisteredTask registered_task = folder.RegisterTaskDefinition(taskName, task, (int)_TASK_CREATION.TASK_CREATE_OR_UPDATE, null, null, _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN);

                if (registered_task == null)
                {
                    return(false);
                }

                // Note: if we run as UWP we need to adjust the file permissions for this workaround to work
                if (UwpFunc.IsRunningAsUwp())
                {
                    if (!FileOps.TakeOwn(exePath))
                    {
                        return(false);
                    }

                    FileSecurity ac = File.GetAccessControl(exePath);
                    ac.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.ReadAndExecute, AccessControlType.Allow));
                    File.SetAccessControl(exePath, ac);
                }
            }
            else
            {
                folder.DeleteTask(taskName, 0);
            }
        }
        catch (Exception err)
        {
            AppLog.Exception(err);
            return(false);
        }
        return(true);
    }
Exemplo n.º 2
0
 public static string parsePath(string path)
 {
     try
     {
         if (path.Contains(@"\device\mup\"))
         {
             return(@"\" + path.Substring(11, path.Length - 11));
         }
         string[] strArray = path.Split(new char[1] {
             '\\'
         }, StringSplitOptions.RemoveEmptyEntries);
         string vol = @"\" + strArray[0] + @"\" + strArray[1];
         path = path.Replace(vol, GetDriveLetter(vol));
         if (path.Contains('~'))
         {
             path = Path.GetFullPath(path);
         }
         return(path);
     }
     catch (Exception err)
     {
         AppLog.Exception(err);
     }
     return("");
 }
Exemplo n.º 3
0
    static public bool MoveFile(string from, string to, bool Overwrite = false)
    {
        try
        {
            if (File.Exists(to))
            {
                if (!Overwrite)
                {
                    return(false);
                }
                File.Delete(to);
            }

            File.Move(from, to);

            if (File.Exists(from))
            {
                return(false);
            }
        }
        catch (Exception err)
        {
            AppLog.Exception(err);
            return(false);
        }
        return(true);
    }
Exemplo n.º 4
0
        public bool SetAuditPolicy(Auditing audit)
        {
            try
            {
                AuditPolicy.AUDIT_POLICY_INFORMATION pol = AuditPolicy.GetSystemPolicy(FirewallEventPolicyID);
                switch (audit)
                {
                case Auditing.All: pol.AuditingInformation = AuditPolicy.AUDIT_POLICY_INFORMATION_TYPE.Success | AuditPolicy.AUDIT_POLICY_INFORMATION_TYPE.Failure; break;

                case Auditing.Blocked: pol.AuditingInformation = AuditPolicy.AUDIT_POLICY_INFORMATION_TYPE.Failure; break;

                case Auditing.Allowed: pol.AuditingInformation = AuditPolicy.AUDIT_POLICY_INFORMATION_TYPE.Success; break;

                case Auditing.Off: pol.AuditingInformation = AuditPolicy.AUDIT_POLICY_INFORMATION_TYPE.None; break;
                }
                TokenManipulator.AddPrivilege(TokenManipulator.SE_SECURITY_NAME);
                // Note: without SeSecurityPrivilege this fails silently
                AuditPolicy.SetSystemPolicy(pol);
                TokenManipulator.RemovePrivilege(TokenManipulator.SE_SECURITY_NAME);
            }
            catch (Exception err)
            {
                AppLog.Exception(err);
                return(false);
            }
            return(true);
        }
Exemplo n.º 5
0
        // *** Files ***

        static public bool IsFileBlocked(string path)
        {
            try
            {
                path = Environment.ExpandEnvironmentVariables(path);

                if (!File.Exists(path))
                {
                    return(true);
                }

                FileSecurity ac = File.GetAccessControl(path);
                AuthorizationRuleCollection rules = ac.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier)); // get as SID not string
                foreach (FileSystemAccessRule rule in rules)
                {
                    if (rule.AccessControlType != AccessControlType.Deny)
                    {
                        continue;
                    }
                    if (!rule.IdentityReference.Value.Equals(FileOps.SID_World))
                    {
                        continue;
                    }
                    if ((rule.FileSystemRights & FileSystemRights.ExecuteFile) != 0)
                    {
                        return(true);
                    }
                }
            }
            catch (Exception err)
            {
                AppLog.Exception(err);
            }
            return(false);
        }
Exemplo n.º 6
0
        // *** Services ***

        static public bool IsServiceEnabled(string name)
        {
            bool ret = false;

            /*ServiceController svc = new ServiceController(name);
             * try
             * {
             *  ret = svc.StartType != ServiceStartMode.Disabled; // only present in .NET 4.6.1 and abive
             * }
             * catch (Exception err)
             * {
             *  AppLog.Exception(err);
             * }
             * svc.Close();*/
            try
            {
                /*var svcInfo = ServiceHelper.GetServiceInfo(name);
                 * ret = svcInfo.StartType != (uint)ServiceStartMode.Disabled;*/
                RegistryKey reg = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\services\" + name, false);
                if (reg != null)
                {
                    ret = (int)reg.GetValue("Start") != (int)ServiceStartMode.Disabled;
                }
            }
            catch (Exception err)
            {
                AppLog.Exception(err);
            }
            return(ret);
        }
Exemplo n.º 7
0
        static public bool DisableTask(string path, string name, bool UnDo = false)
        {
            if (name == "*")
            {
                List <string> names = EnumTasks(path);
                if (names == null)
                {
                    return(false);
                }
                foreach (string found in names)
                {
                    if (!DisableTask(path, found, UnDo))
                    {
                        return(false);
                    }
                }
                return(true);
            }

            try
            {
                TaskScheduler.TaskScheduler service = new TaskScheduler.TaskScheduler();
                service.Connect();
                ITaskFolder     folder = service.GetFolder(path);
                IRegisteredTask task   = folder.GetTask(name);
                task.Enabled = UnDo ? true : false; // todo have old state saved
                return(true);
            }
            catch (Exception err)
            {
                AppLog.Exception(err);
            }
            return(false);
        }
Exemplo n.º 8
0
        static public bool DisableService(string name)
        {
            bool ret = false;
            ServiceController svc = new ServiceController(name); // Windows Update Service

            try
            {
                if (svc.Status == ServiceControllerStatus.Running)
                {
                    svc.Stop();
                }

                // backup original value
                RegistryKey reg   = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\services\" + name, true);
                var         value = reg.GetValue("Start");
                reg.SetValue("OldStart", value);

                ServiceHelper.ChangeStartMode(name, ServiceHelper.ServiceBootFlag.Disabled);

                ret = true;
            }
            catch (Exception err)
            {
                AppLog.Exception(err);
            }
            svc.Close();
            return(ret);
        }
Exemplo n.º 9
0
        static public bool EnableService(string name)
        {
            bool ret = false;
            ServiceController svc = new ServiceController(name); // Windows Update Service

            try
            {
                RegistryKey reg   = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\services\" + name, true);
                var         value = reg.GetValue("OldStart");
                if (value != null)
                {
                    ServiceHelper.ChangeStartMode(name, (ServiceHelper.ServiceBootFlag)((int)value));
                    //svc.Start();
                    reg.DeleteValue("OldStart");
                }
                else // fall back
                {
                    ServiceHelper.ChangeStartMode(name, ServiceHelper.ServiceBootFlag.DemandStart);
                }

                ret = true;
            }
            catch (Exception err)
            {
                AppLog.Exception(err);
            }
            svc.Close();
            return(ret);
        }
Exemplo n.º 10
0
    public static T FindChild <T>(DependencyObject parentObj) where T : DependencyObject
    {
        if (parentObj == null)
        {
            return(null);
        }

        try
        {
            if (parentObj is T)
            {
                return(parentObj as T);
            }

            for (int i = 0; i < System.Windows.Media.VisualTreeHelper.GetChildrenCount(parentObj); i++)
            {
                T childObj = FindChild <T>(System.Windows.Media.VisualTreeHelper.GetChild(parentObj, i));
                if (childObj != null)
                {
                    return(childObj);
                }
            }
        }
        catch (Exception err)
        {
            AppLog.Exception(err);
        }
        return(null);
    }
Exemplo n.º 11
0
 public override void HandlePushNotification(string func, object args)
 {
     try
     {
         if (Application.Current == null)
         {
             return; // not ready yet
         }
         if (func == "ActivityNotification")
         {
             Application.Current.Dispatcher.BeginInvoke(new Action(() => {
                 ActivityNotification?.Invoke(this, (Priv10Engine.FwEventArgs)args);
             }));
         }
         else if (func == "ChangeNotification")
         {
             Application.Current.Dispatcher.BeginInvoke(new Action(() => {
                 ChangeNotification?.Invoke(this, (Priv10Engine.ChangeArgs)args);
             }));
         }
         else
         {
             throw new Exception("Unknown Notificacion");
         }
     }
     catch (Exception err)
     {
         AppLog.Exception(err);
     }
 }
Exemplo n.º 12
0
 public bool SetAuditPolicy(bool audit)
 {
     try
     {
         AuditPolicy.AUDIT_POLICY_INFORMATION pol = AuditPolicy.GetSystemPolicy(FirewallEventPolicyID);
         if (audit)
         {
             pol.AuditingInformation = AuditPolicy.AUDIT_POLICY_INFORMATION_TYPE.Success;
         }
         else
         {
             pol.AuditingInformation = AuditPolicy.AUDIT_POLICY_INFORMATION_TYPE.None;
         }
         TokenManipulator.AddPrivilege(TokenManipulator.SE_SECURITY_NAME);
         // Note: without SeSecurityPrivilege this fails silently
         AuditPolicy.SetSystemPolicy(pol);
         TokenManipulator.RemovePrivilege(TokenManipulator.SE_SECURITY_NAME);
     }
     catch (Exception err)
     {
         AppLog.Exception(err);
         return(false);
     }
     return(true);
 }
Exemplo n.º 13
0
        public bool SetFilteringMode(FilteringModes Mode)
        {
            try
            {
                RegistryKey subKey = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\StandardProfile", false);
                bool        DoNotAllowExceptions = subKey == null ? false : ((int)subKey.GetValue("DoNotAllowExceptions", 0) != 0);

                SetFirewallEnabled(Mode != FilteringModes.NoFiltering);
                switch (Mode)
                {
                case FilteringModes.NoFiltering:
                    break;

                case FilteringModes.BlackList:
                    SetBlockAllInboundTraffic(DoNotAllowExceptions);
                    SetDefaultOutboundAction(FirewallRule.Actions.Allow);
                    break;

                case FilteringModes.WhiteList:
                    SetBlockAllInboundTraffic(DoNotAllowExceptions);
                    SetDefaultOutboundAction(FirewallRule.Actions.Block);
                    break;
                    //case FilteringModes.BlockAll:
                    //    BlockAllTrafic();
                    //    break;
                }
            }
            catch (Exception err)
            {
                AppLog.Exception(err);
                return(false);
            }
            return(true);
        }
Exemplo n.º 14
0
        public bool SetAccessRestriction(string keyPath, bool bSet)
        {
            try
            {
                RegistryKey      subKey = Registry.LocalMachine.OpenSubKey(keyPath, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.ChangePermissions);
                RegistrySecurity keySec = subKey.GetAccessControl(AccessControlSections.Access);

                RegistryAccessRule systemRule  = new RegistryAccessRule(new SecurityIdentifier(FileOps.SID_System), RegistryRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow);
                RegistryAccessRule serviceRule = new RegistryAccessRule(FirewallServiceName, RegistryRights.ExecuteKey, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow);
                if (bSet)
                {
                    keySec.SetAccessRuleProtection(true, false);
                    keySec.AddAccessRule(systemRule);
                    keySec.AddAccessRule(serviceRule);
                }
                else
                {
                    keySec.SetAccessRuleProtection(false, false);
                    keySec.RemoveAccessRule(systemRule);
                    keySec.RemoveAccessRule(serviceRule);
                }
                subKey.SetAccessControl(keySec);

                return(true);
            }
            catch (Exception err)
            {
                AppLog.Exception(err);
            }
            return(false);
        }
Exemplo n.º 15
0
        protected FirewallEvent ReadFirewallEvent(EventRecord record)
        {
            try
            {
                var PropertyValues = ((EventLogRecord)record).GetPropertyValues(eventPropertySelector);

                FirewallEvent args = new FirewallEvent();

                args.ProcessId = (int)(UInt64)PropertyValues[(int)EventProperties.ProcessID];
                string fileName = PropertyValues[(int)EventProperties.ProcessFileName].ToString();
                args.ProcessFileName = fileName.Equals("System", StringComparison.OrdinalIgnoreCase) ? "System" : MiscFunc.parsePath(fileName);

                args.Action = FirewallRule.Actions.Undefined;

                switch ((UInt16)PropertyValues[(int)EventProperties.EventID])
                {
                case (UInt16)EventIDs.Blocked: args.Action = FirewallRule.Actions.Block; break;

                case (UInt16)EventIDs.Allowed: args.Action = FirewallRule.Actions.Allow; break;

                default: return(null);
                }

                args.Protocol  = (UInt32)PropertyValues[(int)EventProperties.Protocol];
                args.Direction = FirewallRule.Directions.Unknown;
                if (PropertyValues[(int)EventProperties.Direction].ToString() == "%%14592")
                {
                    args.Direction     = FirewallRule.Directions.Inbound;
                    args.LocalAddress  = IPAddress.Parse(PropertyValues[(int)EventProperties.DestAddress].ToString());
                    args.LocalPort     = (UInt16)MiscFunc.parseInt(PropertyValues[(int)EventProperties.DestPort].ToString());
                    args.RemoteAddress = IPAddress.Parse(PropertyValues[(int)EventProperties.SourceAddress].ToString());
                    args.RemotePort    = (UInt16)MiscFunc.parseInt(PropertyValues[(int)EventProperties.SourcePort].ToString());
                }
                else if (PropertyValues[(int)EventProperties.Direction].ToString() == "%%14593")
                {
                    args.Direction     = FirewallRule.Directions.Outboun;
                    args.LocalAddress  = IPAddress.Parse(PropertyValues[(int)EventProperties.SourceAddress].ToString());
                    args.LocalPort     = (UInt16)MiscFunc.parseInt(PropertyValues[(int)EventProperties.SourcePort].ToString());
                    args.RemoteAddress = IPAddress.Parse(PropertyValues[(int)EventProperties.DestAddress].ToString());
                    args.RemotePort    = (UInt16)MiscFunc.parseInt(PropertyValues[(int)EventProperties.DestPort].ToString());
                }
                else
                {
                    return(null); // todo log error
                }
                args.TimeStamp = record.TimeCreated != null ? (DateTime)record.TimeCreated : DateTime.Now;

                // for debug only
                //if(!FirewallRule.MatchAddress(args.RemoteAddress, "LocalSubnet") && !NetFunc.IsMultiCast(args.RemoteAddress))
                //    AppLog.Debug("Firewall Event: {0}({1}) -> {2}", args.ProcessFileName, args.ProcessId, args.RemoteAddress);

                return(args);
            }
            catch (Exception err)
            {
                AppLog.Exception(err);
            }
            return(null);
        }
Exemplo n.º 16
0
 public void OneTimeSetup()
 {
     AppLog.Log("Test log 1");
     AppLog.Error("Test error 1");
     AppLog.Log("Test log 2");
     AppLog.Debug("Test debug 1");
     AppLog.Exception(new AmbiguousMatchException(), "Test exception 1");
     AppLog.Debug("Invalid Format {0}");
 }
Exemplo n.º 17
0
        public Tuple <int, int> LoadBlockLists()
        {
            ListLock.EnterWriteLock();

            TopLevel = new Level(); // clear domain tree

            int counter = 0;
            int errors  = 0;

            var watch = System.Diagnostics.Stopwatch.StartNew();

            try
            {
                //string[] fileEntries = Directory.GetFiles(App.dataPath + @"\DnsBlockLists");
                //foreach (string fileName in fileEntries)
                foreach (DomainBlocklist blocklist in Blocklists.Values)
                {
                    if (!blocklist.Enabled)
                    {
                        continue;
                    }
                    string fileName = App.dataPath + @"\DnsBlockLists\" + blocklist.FileName;
                    if (blocklist.FileName.Length == 0 || !File.Exists(fileName))
                    {
                        continue;
                    }

                    counter++;
                    int count = LoadBlockList(fileName);
                    if (count == 0)
                    {
                        errors++;
                    }

                    blocklist.EntryCount = count;
                }
            }

            /*catch (DirectoryNotFoundException)
             * {
             *  App.LogError("Could not load blocklists from {0}", App.dataPath + @"\DnsBlockLists");
             * }*/
            catch (Exception err)
            {
                AppLog.Exception(err);
            }

            watch.Stop();
            var elapsedMs = watch.ElapsedMilliseconds;

            AppLog.Debug("LoadBlockLists took: " + elapsedMs + "ms");

            ListLock.ExitWriteLock();

            return(Tuple.Create(counter, errors));
        }
Exemplo n.º 18
0
        public bool LoadList()
        {
            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)
                {
                    App.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;
                    }

                    ProgramSets.Add(entry.guid, entry);

                    foreach (Program prog in entry.Programs.Values)
                    {
                        Programs.Add(prog.ID, prog);
                    }
                }

                if (ErrorCount != 0)
                {
                    App.LogError("Failed to load {0} program entry out of {1}", ErrorCount, TotalCount);
                }
                App.LogInfo("ProgramList loaded {0} entries", TotalCount - ErrorCount);
            }
            catch (Exception err)
            {
                AppLog.Exception(err);
                return(false);
            }
            return(true);
        }
Exemplo n.º 19
0
    public static ImageSource GetIcon(string path, double size)
    {
        string key = path + "@" + size.ToString();

        ImageSource image = null;

        IconCacheLock.EnterReadLock();
        bool bFound = IconCache.TryGetValue(key, out image);

        IconCacheLock.ExitReadLock();
        if (bFound)
        {
            return(image);
        }

        try
        {
            var pathIndex = TextHelpers.Split2(path, "|");

            IconExtractor extractor = new IconExtractor(pathIndex.Item1);
            int           index     = MiscFunc.parseInt(pathIndex.Item2);
            if (index < extractor.Count)
            {
                image = ToImageSource(extractor.GetIcon(index, new System.Drawing.Size((int)size, (int)size)));
            }

            if (image == null)
            {
                if (File.Exists(MiscFunc.NtOsKrnlPath)) // if running in WOW64 this does not exist
                {
                    image = ToImageSource(Icon.ExtractAssociatedIcon(MiscFunc.NtOsKrnlPath));
                }
                else // fall back to an other icon
                {
                    image = ToImageSource(Icon.ExtractAssociatedIcon(MiscFunc.Shell32Path));
                }
            }

            image.Freeze();
        }
        catch (Exception err)
        {
            AppLog.Exception(err);
        }

        IconCacheLock.EnterWriteLock();
        if (!IconCache.ContainsKey(key))
        {
            IconCache.Add(key, image);
        }
        IconCacheLock.ExitWriteLock();
        return(image);
    }
Exemplo n.º 20
0
 public bool StartEventWatcher()
 {
     try
     {
         mEventWatcher = new EventLogWatcher(new EventLogQuery("Security", PathType.LogName, GetQuery()));
         mEventWatcher.EventRecordWritten += new EventHandler <EventRecordWrittenEventArgs>(OnConnection);
         mEventWatcher.Enabled             = true;
     }
     catch (Exception err)
     {
         AppLog.Exception(err);
         return(false);
     }
     return(true);
 }
Exemplo n.º 21
0
        // *** GPO ***

        static public bool TestGPOTweak(string path, string name, object value, bool usrLevel = false)
        {
            try
            {
                var gpo    = new ComputerGroupPolicyObject(new GroupPolicyObjectSettings(true, true)); // read only so it does not fail without admin rights
                var key    = gpo.GetRootRegistryKey(usrLevel ? GroupPolicySection.User : GroupPolicySection.Machine);
                var subKey = key.CreateSubKey(path);
                return(CmpRegistryValue(subKey, name, value));
            }
            catch (Exception err)
            {
                AppLog.Exception(err);
            }
            return(false);
        }
Exemplo n.º 22
0
        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)
                {
                    App.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);
        }
Exemplo n.º 23
0
 public bool HasAuditPolicy()
 {
     try
     {
         AuditPolicy.AUDIT_POLICY_INFORMATION pol = AuditPolicy.GetSystemPolicy(FirewallEventPolicyID);
         if ((pol.AuditingInformation & AuditPolicy.AUDIT_POLICY_INFORMATION_TYPE.Success) != 0)
         {
             return(true);
         }
     }
     catch (Exception err)
     {
         AppLog.Exception(err);
     }
     return(false);
 }
Exemplo n.º 24
0
        static public bool IsProperlyInstalled()
        {
            try
            {
                string binPathName = "\"" + App.appPath + "\\" + SvcBinary + "\" -svc";

                var svcConfigInfo = ServiceHelper.GetServiceInfoSafe(App.SvcName);

                return(svcConfigInfo != null && svcConfigInfo.BinaryPathName.Equals(binPathName));
            }
            catch (Exception err)
            {
                AppLog.Exception(err);
            }
            return(false);
        }
Exemplo n.º 25
0
        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)
            {
                App.LogError("Failed to load blocklist: {0}", Path.GetFileName(BlockListPath));
            }
            else if (success < count)
            {
                App.LogWarning("Loaded {1} DNS blocklist entries from {0}, {2} entries were invalid", Path.GetFileName(BlockListPath), success, count - success);
            }
            else
            {
                App.LogInfo("Loaded {1} DNS blocklist entries from {0}", Path.GetFileName(BlockListPath), success);
            }
            return(success);
        }
Exemplo n.º 26
0
 static public bool UndoGPOTweak(string path, string name, bool usrLevel = false)
 {
     try
     {
         var gpo    = new ComputerGroupPolicyObject();
         var key    = gpo.GetRootRegistryKey(usrLevel ? GroupPolicySection.User : GroupPolicySection.Machine);
         var subKey = key.CreateSubKey(path);
         subKey.DeleteValue(name, false);
         gpo.Save();
         return(true);
     }
     catch (Exception err)
     {
         AppLog.Exception(err);
     }
     return(false);
 }
Exemplo n.º 27
0
    static public bool SkipUacRun(string taskName, string[] args = null)
    {
        bool silent = true;

        try
        {
            TaskScheduler.TaskScheduler service = new TaskScheduler.TaskScheduler();
            service.Connect();
            ITaskFolder     folder = service.GetFolder(@"\"); // root
            IRegisteredTask task   = folder.GetTask(taskName);

            silent = false;
            AppLog.Debug("Trying to SkipUAC ...");

            IExecAction action = (IExecAction)task.Definition.Actions[1];
            if (action.Path.Equals(System.Reflection.Assembly.GetExecutingAssembly().Location, StringComparison.OrdinalIgnoreCase))
            {
                string arguments = args == null ? "" : ("\"" + string.Join("\" \"", args) + "\"");

                IRunningTask running_Task = task.RunEx(arguments, (int)_TASK_RUN_FLAGS.TASK_RUN_NO_FLAGS, 0, null);

                for (int i = 0; i < 5; i++)
                {
                    Thread.Sleep(250);
                    running_Task.Refresh();
                    _TASK_STATE state = running_Task.State;
                    if (state == _TASK_STATE.TASK_STATE_RUNNING || state == _TASK_STATE.TASK_STATE_READY || state == _TASK_STATE.TASK_STATE_DISABLED)
                    {
                        if (state == _TASK_STATE.TASK_STATE_RUNNING || state == _TASK_STATE.TASK_STATE_READY)
                        {
                            return(true);
                        }
                        break;
                    }
                }
            }
        }
        catch (Exception err)
        {
            if (!silent)
            {
                AppLog.Exception(err);
            }
        }
        return(false);
    }
Exemplo n.º 28
0
        // *** Registry ***

        static public bool TestRegistryTweak(string path, string name, object value, bool usrLevel = false)
        {
            try
            {
                var subKey = (usrLevel ? Registry.CurrentUser : Registry.LocalMachine).OpenSubKey(path, false);
                if (subKey == null)
                {
                    return(false);
                }
                return(CmpRegistryValue(subKey, name, value));
            }
            catch (Exception err)
            {
                AppLog.Exception(err);
            }
            return(false);
        }
Exemplo n.º 29
0
        static public bool UndoRegistryTweak(string path, string name, bool usrLevel = false)
        {
            try
            {
                var subKey = (usrLevel ? Registry.CurrentUser : Registry.LocalMachine).CreateSubKey(path);

                object value = subKey.GetValue("Old" + name);

                SetRegistryValue(subKey, name, value);

                subKey.DeleteValue("Old" + name);
                return(true);
            }
            catch (Exception err)
            {
                AppLog.Exception(err);
            }
            return(false);
        }
Exemplo n.º 30
0
 static public bool TestGPOTweak(string path, string name, object value, bool usrLevel = false)
 {
     gpoLocker.EnterReadLock();
     try
     {
         var gpo    = GetGPO(false);
         var key    = gpo.GetRootRegistryKey(usrLevel ? GroupPolicySection.User : GroupPolicySection.Machine);
         var subKey = key.CreateSubKey(path);
         return(CmpRegistryValue(subKey, name, value));
     }
     catch (Exception err)
     {
         AppLog.Exception(err);
     }
     finally
     {
         gpoLocker.ExitReadLock();
     }
     return(false);
 }