// *** 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.Line("Error in {0}: {1}", MiscFunc.GetCurrentMethod(), err.Message);
            }
            return(false);
        }
        static public bool BlockFile(string path, bool UnDo = false)
        {
            try
            {
                path = Environment.ExpandEnvironmentVariables(path);
                if (!FileOps.TakeOwn(path))
                {
                    return(false);
                }

                FileSecurity ac = File.GetAccessControl(path);
                if (UnDo)
                {
                    AuthorizationRuleCollection rules = ac.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier)); // get as SID not string
                    foreach (FileSystemAccessRule rule in rules)
                    {
                        ac.RemoveAccessRule(rule);
                    }
                }
                else
                {
                    ac.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(FileOps.SID_World), FileSystemRights.ExecuteFile, AccessControlType.Deny));
                }
                File.SetAccessControl(path, ac);
                return(true);
            }
            catch (Exception err)
            {
                AppLog.Line("Error in {0}: {1}", MiscFunc.GetCurrentMethod(), err.Message);
            }
            return(false);
        }
        static public bool DisableService(string name, bool UnDo = false)
        {
            bool ret = false;
            ServiceController svc = new ServiceController(name); // Windows Update Service

            try
            {
                if (UnDo)
                {
                    if (svc.Status != ServiceControllerStatus.Running)
                    {
                        ServiceHelper.ChangeStartMode(name, ServiceHelper.ServiceBootFlag.DemandStart);
                        //svc.Start();
                    }
                }
                else
                {
                    if (svc.Status == ServiceControllerStatus.Running)
                    {
                        svc.Stop();
                    }
                    ServiceHelper.ChangeStartMode(name, ServiceHelper.ServiceBootFlag.Disabled);
                }
                ret = true;
            }
            catch (Exception err)
            {
                AppLog.Line("Error in {0}: {1}", MiscFunc.GetCurrentMethod(), err.Message);
            }
            svc.Close();
            return(ret);
        }
        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.Line("Error in {0}: {1}", MiscFunc.GetCurrentMethod(), err.Message);
            }
            return(false);
        }
Пример #5
0
        public bool SetAuditPol(Auditing audit)
        {
            //MiscFunc.Exec("auditpol.exe", "/set /subcategory:{0CCE9226-69AE-11D9-BED3-505054503030} /failure:enable /success:enable");
            try
            {
                AuditPol.AUDIT_POLICY_INFORMATION pol = AuditPol.GetSystemPolicy("0CCE9226-69AE-11D9-BED3-505054503030");
                switch (audit)
                {
                case Auditing.All: pol.AuditingInformation = AuditPol.AUDIT_POLICY_INFORMATION_TYPE.Success | AuditPol.AUDIT_POLICY_INFORMATION_TYPE.Failure; break;

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

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

                case Auditing.Off: pol.AuditingInformation = AuditPol.AUDIT_POLICY_INFORMATION_TYPE.None; break;
                }
                TokenManipulator.AddPrivilege(TokenManipulator.SE_SECURITY_NAME);
                // Note: without SeSecurityPrivilege this fails silently
                AuditPol.SetSystemPolicy(pol);
                TokenManipulator.RemovePrivilege(TokenManipulator.SE_SECURITY_NAME);
            }
            catch (Exception err)
            {
                AppLog.Line("Error in {0}: {1}", MiscFunc.GetCurrentMethod(), err.Message);
                return(false);
            }
            return(true);
        }
Пример #6
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.Line("Error in {0}: {1}", MiscFunc.GetCurrentMethod(), err.Message);
     }
     return("");
 }
Пример #7
0
        private void OnConnection(object obj, EventRecordWrittenEventArgs arg)
        {
            if (arg.EventRecord == null)
            {
                return;
            }
            try
            {
                int    processId = MiscFunc.parseInt(arg.EventRecord.Properties[0].Value.ToString());
                string path      = arg.EventRecord.Properties[1].Value.ToString();

                Actions action = Actions.Undefined;
                if (arg.EventRecord.Id == (int)EventIDs.Blocked)
                {
                    action = Actions.Block;
                }
                else if (arg.EventRecord.Id == (int)EventIDs.Allowed)
                {
                    action = Actions.Allow;
                }

                string     direction_str = arg.EventRecord.Properties[2].Value.ToString();
                Directions direction     = Directions.Unknown;
                if (direction_str == "%%14592")
                {
                    direction = Directions.Inbound;
                }
                else if (direction_str == "%%14593")
                {
                    direction = Directions.Outboun;
                }
                string src_ip    = arg.EventRecord.Properties[3].Value.ToString();
                int    src_port  = MiscFunc.parseInt(arg.EventRecord.Properties[4].Value.ToString());
                string dest_ip   = arg.EventRecord.Properties[5].Value.ToString();
                int    dest_port = MiscFunc.parseInt(arg.EventRecord.Properties[6].Value.ToString());
                int    protocol  = MiscFunc.parseInt(arg.EventRecord.Properties[7].Value.ToString());

                ProgramList.ID id = GetIDforEntry(path, processId);
                if (id == null)
                {
                    return;
                }

                Program.LogEntry entry = new Program.LogEntry(id, action, direction, src_ip, src_port, dest_ip, dest_port, protocol, processId, DateTime.Now);

                entry.Profile = GetCurrentProfiles();

                App.engine.LogActivity(entry);
            }
            catch (Exception err)
            {
                AppLog.Line("Error in {0}: {1}", MiscFunc.GetCurrentMethod(), err.Message);
            }
        }
 static public bool SetRegistryTweak(string path, string name, object value, bool usrLevel = false)
 {
     try
     {
         var subKey = (usrLevel ? Registry.CurrentUser : Registry.LocalMachine).CreateSubKey(path, true);
         SetRegistryValue(subKey, name, value);
         return(true);
     }
     catch (Exception err)
     {
         AppLog.Line("Error in {0}: {1}", MiscFunc.GetCurrentMethod(), err.Message);
     }
     return(false);
 }
        // *** 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.Line("Error in {0}: {1}", MiscFunc.GetCurrentMethod(), err.Message);
            }
            return(false);
        }
        // *** Services ***

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

            try
            {
                ret = svc.StartType != ServiceStartMode.Disabled;
            }
            catch (Exception err)
            {
                AppLog.Line("Error in {0}: {1}", MiscFunc.GetCurrentMethod(), err.Message);
            }
            svc.Close();
            return(ret);
        }
Пример #11
0
        public T RemoteExec <T>(string fx, object args, T defRet)
        {
            try
            {
                if (clientPipe == null && !Connect())
                {
                    throw new Exception("Connection Failed");
                }

                return((T)(clientPipe.RemoteExec(fx, args)));
            }
            catch (Exception err)
            {
                AppLog.Line("Error in {0}: {1}", MiscFunc.GetCurrentMethod(), err.Message);
                return(defRet);
            }
        }
 static public bool SetGPOTweak(string path, string name, object value, bool usrLevel = false)
 {
     try
     {
         var gpo    = new ComputerGroupPolicyObject();
         var key    = gpo.GetRootRegistryKey(usrLevel ? GroupPolicySection.User : GroupPolicySection.Machine);
         var subKey = key.CreateSubKey(path);
         SetRegistryValue(subKey, name, value);
         gpo.Save();
         return(true);
     }
     catch (Exception err)
     {
         AppLog.Line("Error in {0}: {1}", MiscFunc.GetCurrentMethod(), err.Message);
     }
     return(false);
 }
Пример #13
0
        public bool Uninstall()
        {
            try
            {
                if (ServiceHelper.ServiceIsInstalled(ServiceName))
                {
                    if (ServiceHelper.GetServiceStatus(ServiceName) == ServiceHelper.ServiceState.Running)
                    {
                        ServiceHelper.StopService(ServiceName);
                    }

                    ServiceHelper.Uninstall(ServiceName);
                }
                return(true);
            }
            catch (Exception err)
            {
                AppLog.Line("Error in {0}: {1}", MiscFunc.GetCurrentMethod(), err.Message);
            }
            return(false);
        }
        // *** Tasks ***

        static public List <string> EnumTasks(string path)
        {
            List <string> list = new List <string>();

            try
            {
                TaskScheduler.TaskScheduler service = new TaskScheduler.TaskScheduler();
                service.Connect();
                ITaskFolder folder = service.GetFolder(path);

                foreach (IRegisteredTask task in folder.GetTasks((int)_TASK_ENUM_FLAGS.TASK_ENUM_HIDDEN))
                {
                    list.Add(task.Name);
                }
            }
            catch (Exception err)
            {
                AppLog.Line("Error in {0}: {1}", MiscFunc.GetCurrentMethod(), err.Message);
                return(null);
            }
            return(list);
        }
Пример #15
0
 public void HandlePushNotification(string func, object args)
 {
     try
     {
         if (func == "ActivityNotification")
         {
             NotifyActivity(GetArg <Guid>(args, 0), GetArg <Program.LogEntry>(args, 1));
         }
         else if (func == "ChangeNotification")
         {
             NotifyChange(GetArg <Guid>(args, 0));
         }
         else
         {
             throw new Exception("Unknown Notificacion");
         }
     }
     catch (Exception err)
     {
         AppLog.Line("Error in {0}: {1}", MiscFunc.GetCurrentMethod(), err.Message);
     }
 }
        static public bool IsTaskEnabled(string path, string name)
        {
            if (name == "*")
            {
                List <string> names = EnumTasks(path);
                if (names == null)
                {
                    return(true); // we dont know so just in case
                }
                foreach (string found in names)
                {
                    if (IsTaskEnabled(path, found))
                    {
                        return(true);
                    }
                }
                return(false);
            }

            try
            {
                TaskScheduler.TaskScheduler service = new TaskScheduler.TaskScheduler();
                service.Connect();
                ITaskFolder     folder = service.GetFolder(path);
                IRegisteredTask task   = folder.GetTask(name);
                return(task.Enabled);
            }
            catch (FileNotFoundException)
            {
                return(false);
            }
            catch (Exception err)
            {
                AppLog.Line("Error in {0}: {1}", MiscFunc.GetCurrentMethod(), err.Message);
            }
            return(true); // we dont know so just in case
        }
Пример #17
0
        public bool Install(bool start = false)
        {
            try
            {
                if (!ServiceHelper.ServiceIsInstalled(ServiceName))
                {
                    ServiceHelper.Install(ServiceName, App.mName, "\"" + App.exePath + "\" -svc");
                }

                ServiceHelper.ChangeStartMode(ServiceName, ServiceHelper.ServiceBootFlag.AutoStart);

                if (start)
                {
                    ServiceHelper.StartService(ServiceName);
                }

                return(true);
            }
            catch (Exception err)
            {
                AppLog.Line("Error in {0}: {1}", MiscFunc.GetCurrentMethod(), err.Message);
            }
            return(false);
        }
Пример #18
0
 public Auditing GetAuditPol()
 {
     try
     {
         AuditPol.AUDIT_POLICY_INFORMATION pol = AuditPol.GetSystemPolicy("0CCE9226-69AE-11D9-BED3-505054503030");
         if ((pol.AuditingInformation & AuditPol.AUDIT_POLICY_INFORMATION_TYPE.Success) != 0 && (pol.AuditingInformation & AuditPol.AUDIT_POLICY_INFORMATION_TYPE.Failure) != 0)
         {
             return(Auditing.All);
         }
         if ((pol.AuditingInformation & AuditPol.AUDIT_POLICY_INFORMATION_TYPE.Success) != 0)
         {
             return(Auditing.Allowed);
         }
         if ((pol.AuditingInformation & AuditPol.AUDIT_POLICY_INFORMATION_TYPE.Failure) != 0)
         {
             return(Auditing.Blocked);
         }
     }
     catch (Exception err)
     {
         AppLog.Line("Error in {0}: {1}", MiscFunc.GetCurrentMethod(), err.Message);
     }
     return(Auditing.Off);
 }
Пример #19
0
 public bool WatchConnections(bool enable = true)
 {
     try
     {
         if (enable)
         {
             mEventWatcher = new EventLogWatcher(new EventLogQuery("Security", PathType.LogName, "*[System[(Level=4 or Level=0) and (EventID=" + (int)EventIDs.Blocked + " or EventID=" + (int)EventIDs.Allowed + ")]] and *[EventData[Data[@Name='LayerRTID']>='48']]"));
             mEventWatcher.EventRecordWritten += new EventHandler <EventRecordWrittenEventArgs>(OnConnection);
             mEventWatcher.Enabled             = true;
         }
         else
         {
             mEventWatcher.EventRecordWritten -= new EventHandler <EventRecordWrittenEventArgs>(OnConnection);
             mEventWatcher.Dispose();
             mEventWatcher = null;
         }
     }
     catch (Exception err)
     {
         AppLog.Line("Error in {0}: {1}", MiscFunc.GetCurrentMethod(), err.Message);
         return(false);
     }
     return(true);
 }
Пример #20
0
 public static bool Exec(string cmd, string args, bool hidden = true)
 {
     try
     {
         Process process = new Process();
         process.StartInfo.UseShellExecute = false;
         if (hidden)
         {
             process.StartInfo.WindowStyle    = ProcessWindowStyle.Hidden;
             process.StartInfo.CreateNoWindow = true;
         }
         process.StartInfo.FileName  = cmd;
         process.StartInfo.Arguments = args;
         process.StartInfo.Verb      = "runas"; // run as admin
         process.Start();
         process.WaitForExit();
         return(true);
     }
     catch (Exception err)
     {
         AppLog.Line("Error in {0}: {1}", MiscFunc.GetCurrentMethod(), err.Message);
     }
     return(false);
 }
Пример #21
0
        public void LoadLog()
        {
            EventLog eventLog = new EventLog("Security");

            try
            {
                //for (int i = eventLog.Entries.Count-1; i > 0; i--)
                foreach (EventLogEntry logEntry in eventLog.Entries)
                {
                    //EventLogEntry entry = eventLog.Entries[i];
                    if (logEntry.InstanceId != (long)EventIDs.Allowed && logEntry.InstanceId != (long)EventIDs.Blocked)
                    {
                        continue;
                    }
                    string[] ReplacementStrings = logEntry.ReplacementStrings;

                    string     direction_str = ReplacementStrings[2];
                    Directions direction     = Directions.Unknown;
                    if (direction_str == "%%14592")
                    {
                        direction = Directions.Inbound;
                    }
                    else if (direction_str == "%%14593")
                    {
                        direction = Directions.Outboun;
                    }

                    int    processId = MiscFunc.parseInt(ReplacementStrings[0]);
                    string path      = ReplacementStrings[1];

                    ProgramList.ID id = GetIDforEntry(path, processId);
                    if (id == null)
                    {
                        return;
                    }

                    Actions action = Actions.Undefined;
                    if (logEntry.InstanceId == (int)EventIDs.Blocked)
                    {
                        action = Actions.Block;
                    }
                    else if (logEntry.InstanceId == (int)EventIDs.Allowed)
                    {
                        action = Actions.Allow;
                    }

                    string src_ip    = ReplacementStrings[3];
                    int    src_port  = MiscFunc.parseInt(ReplacementStrings[4]);
                    string dest_ip   = ReplacementStrings[5];
                    int    dest_port = MiscFunc.parseInt(ReplacementStrings[6]);
                    int    protocol  = MiscFunc.parseInt(ReplacementStrings[7]);

                    Program.LogEntry entry = new Program.LogEntry(id, action, direction, src_ip, src_port, dest_ip, dest_port, protocol, processId, logEntry.TimeGenerated);

                    App.engine.LogActivity(entry, true);
                }
            }
            catch (Exception err)
            {
                AppLog.Line("Error in {0}: {1}", MiscFunc.GetCurrentMethod(), err.Message);
            }
            eventLog.Dispose();
        }
Пример #22
0
    public AppInfo?GetInfo(string path, string name, string id, string sid)
    {
        string manifest = Path.Combine(path, "AppxManifest.xml");

        if (!File.Exists(manifest))
        {
            return(null);
        }

        XElement xelement;

        try
        {
            string manifestXML = File.ReadAllText(manifest);

            int startIndex = manifestXML.IndexOf("<Properties>", StringComparison.Ordinal);
            int num        = manifestXML.IndexOf("</Properties>", StringComparison.Ordinal);
            xelement = XElement.Parse(manifestXML.Substring(startIndex, num - startIndex + 13).Replace("uap:", string.Empty));
        }
        catch (Exception err)
        {
            AppLog.Line("Error in {0}: {1}", MiscFunc.GetCurrentMethod(), err.Message);
            return(null);
        }

        string displayName = name;
        string logoPath    = null;

        try
        {
            displayName = xelement.Element((XName)"DisplayName")?.Value;
            logoPath    = xelement.Element((XName)"Logo")?.Value;
        }
        catch (Exception err)
        {
            AppLog.Line("Error in {0}: {1}", MiscFunc.GetCurrentMethod(), err.Message);
        }

        try
        {
            Uri result;
            if (Uri.TryCreate(displayName, UriKind.Absolute, out result))
            {
                string pathToPri         = Path.Combine(path, "resources.pri");
                string resourceKey1      = "ms-resource://" + name + "/resources/" + ((IEnumerable <string>)result.Segments).Last <string>();
                string stringFromPriFile = MiscFunc.GetResourceStr(pathToPri, resourceKey1);
                if (!string.IsNullOrEmpty(stringFromPriFile.Trim()))
                {
                    displayName = stringFromPriFile;
                }
                else
                {
                    string str          = string.Concat(((IEnumerable <string>)result.Segments).Skip <string>(1));
                    string resourceKey2 = "ms-resource://" + name + "/" + str;
                    stringFromPriFile = MiscFunc.GetResourceStr(pathToPri, resourceKey2);
                    if (!string.IsNullOrEmpty(stringFromPriFile.Trim()))
                    {
                        displayName = stringFromPriFile;
                    }
                }
            }

            if (logoPath != null)
            {
                string path1 = Path.Combine(path, logoPath);
                if (File.Exists(path1))
                {
                    logoPath = path1;
                }
                else
                {
                    string path2 = Path.Combine(path, Path.ChangeExtension(path1, "scale-100.png"));
                    if (File.Exists(path2))
                    {
                        logoPath = path2;
                    }
                    else
                    {
                        string path3 = Path.Combine(Path.Combine(path, "en-us"), logoPath);
                        string path4 = Path.Combine(path, Path.ChangeExtension(path3, "scale-100.png"));
                        if (File.Exists(path4))
                        {
                            logoPath = path4;
                        }
                        else
                        {
                            logoPath = null;
                        }
                    }
                }
            }
        }
        catch (Exception err)
        {
            AppLog.Line("Error in {0}: {1}", MiscFunc.GetCurrentMethod(), err.Message);
        }

        return(new AppInfo()
        {
            Name = displayName, Logo = logoPath, ID = id, SID = sid
        });
    }
Пример #23
0
    public void LoadApps()
    {
        Apps.Clear();
        AppInfos.Clear();

        //packageManager.RemovePackageAsync(package.Id.FullName);

        IEnumerable <Windows.ApplicationModel.Package> packages = (IEnumerable <Windows.ApplicationModel.Package>)packageManager.FindPackages();

        // Todo: is there a better way to get this ?
        foreach (var package in packages)
        {
            string name;
            //string fullname;
            string path;
            string publisher;
            bool   isFramework;
            try
            {
                name = package.Id.Name;
                //fullname = package.Id.FullName;
                publisher   = package.Id.PublisherId;
                path        = package.InstalledLocation.Path;
                isFramework = package.IsFramework;
            }
            catch (Exception err)
            {
                AppLog.Line("Error in {0}: {1}", MiscFunc.GetCurrentMethod(), err.Message);
                continue;
            }

            string appPackageID = name.ToLower() + "_" + publisher;
            string appSID       = PackageIDToSid(appPackageID).ToLower();

            if (Apps.ContainsKey(package.InstalledLocation.Path.ToLower()))
            {
                AppLog.Line("Warning an app with the path: {0} is already listed", package.InstalledLocation.Path.ToLower());
            }
            else
            {
                Apps.Add(package.InstalledLocation.Path.ToLower(), appSID);
            }

            AppInfo?info = GetInfo(path, name, appPackageID, appSID);
            if (info != null)
            {
                AppInfo old_info;
                if (AppInfos.TryGetValue(appSID, out old_info))
                {
                    continue;
                }
                if (AppInfos.ContainsKey(appSID))
                {
                    AppLog.Line("Warning an app with the SID: {0} is already listed", appSID);
                }
                else
                {
                    AppInfos.Add(appSID, info.Value);
                }
            }
        }
    }