Ejemplo n.º 1
0
        static void PolicyThread()
        {
            Int64 NextRunTime = RegistryData.LastSyncPolicies;
            Int64 CurrentTime;

            while (StopThreads == false)
            {
                CurrentTime = CommonUtilities.DTtoINT(DateTime.Now);

                if (InvokePolicy == true)
                {
                    InvokePolicy = false;
                    NextRunTime  = CommonUtilities.DTtoINT(DateTime.Now.AddMinutes(-1));
                }

                if (CurrentTime < NextRunTime)
                {
                    Thread.Sleep(1000);
                    continue;
                }

                lock (LockLock3)
                {
                    if (LockPolicyUpdate == true)
                    {
                        Thread.Sleep(1000);
                        continue;
                    }
                    LockPolicyUpdate = true;
                }

                try
                {
                    SyncPolicy.DoSyncPolicy();

                    #region Prevent criss cross with reportings wait until done!
                    do
                    {
                        lock (LockLock1)
                        {
                            if (LockReportingUpdate1 == true)
                            {
                                if (StopThreads == true)
                                {
                                    LockReportingUpdate1 = false;
                                    break;
                                }
                                Thread.Sleep(1000);
                                continue;
                            }
                            LockReportingUpdate1 = true;
                            break;
                        }
                    } while (true);

                    #endregion

                    if (StopThreads == false)
                    {
                        SyncPolicy.ApplyPolicy(SyncPolicy.ApplyPolicyFunction.ApplySystem);
                    }

                    #region Prevent criss cross with reportings wait until done!
                    lock (LockLock1)
                    {
                        LockReportingUpdate1 = false;
                    }
                    #endregion
                }
                catch (Exception ee)
                {
                    Debug.WriteLine(ee.ToString());
                    FoxEventLog.WriteEventLog("Servere error while syncing / applying policies: " + ee.ToString(), EventLogEntryType.Error);
                }
                Int64 Tim = RegistryData.LastSyncPoliciesWaitTime;
                if (Tim < 1)
                {
                    Tim = 5;
                }

                NextRunTime = CommonUtilities.DTtoINT(DateTime.Now.AddMinutes(Tim));
                RegistryData.LastSyncPolicies = NextRunTime;

                lock (LockLock3)
                {
                    LockPolicyUpdate = false;
                }
            }
        }
Ejemplo n.º 2
0
        static WindowsLic GetWindowsLicense()
        {
            WindowsLic lic = new WindowsLic();

            try
            {
                ManagementScope Scope;
                Scope = new ManagementScope("\\\\.\\root\\CIMV2", null);

                Scope.Connect();
                ObjectQuery        Query = new ObjectQuery("SELECT * FROM SoftwareLicensingProduct Where PartialProductKey<>null AND ApplicationId='55c92734-d682-4d71-983e-d6ec3f16059f' AND LicenseIsAddon=False");
                EnumerationOptions eo    = new EnumerationOptions();
                eo.Timeout = new TimeSpan(0, 0, 3, 0);
                ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query, eo);

                foreach (ManagementObject WmiObject in Searcher.Get())
                {
                    lic.Name                 = (String)WmiObject["Name"];
                    lic.Description          = (String)WmiObject["Description"];
                    lic.GracePeriodRemaining = (UInt32)WmiObject["GracePeriodRemaining"];
                    lic.PartialProductKey    = (String)WmiObject["PartialProductKey"];
                    lic.ProductKeyID         = (String)WmiObject["ProductKeyID"];
                    try
                    {
                        lic.ProductKeyID2 = (String)WmiObject["ProductKeyID2"];
                    }
                    catch
                    {
                        lic.ProductKeyID2 = "";
                    }
                    lic.LicenseFamily = (String)WmiObject["LicenseFamily"];
                    try
                    {
                        lic.ProductKeyChannel = (String)WmiObject["ProductKeyChannel"];
                    }
                    catch
                    {
                        lic.ProductKeyChannel = "";
                    }
                    lic.LicenseStatus = (UInt32)WmiObject["LicenseStatus"];
                    switch ((UInt32)WmiObject["LicenseStatus"])
                    {
                    case 0:
                        lic.LicenseStatusText = "Unlicensed"; break;

                    case 1:
                        lic.LicenseStatusText = "Licensed"; break;

                    case 2:
                        lic.LicenseStatusText = "Out-Of-Box Grace Period"; break;

                    case 3:
                        lic.LicenseStatusText = "Out-Of-Tolerance Grace Period"; break;

                    case 4:
                        lic.LicenseStatusText = "On-Genuine Grace Period"; break;

                    case 5:
                        lic.LicenseStatusText = "Notification"; break;

                    default:
                        lic.LicenseStatusText = lic.LicenseStatus.ToString(); break;
                    }
                }
            }
            catch (ManagementException ee)
            {
                if (ee.ErrorCode == ManagementStatus.CallCanceled || ee.ErrorCode == ManagementStatus.Timedout)
                {
                    //drop message silently
                    Debug.WriteLine(ee.ToString());
                    return(null);
                }
                else
                {
                    Debug.WriteLine(ee.ToString());
                    FoxEventLog.WriteEventLog("Cannot get Windows License Info " + ee.ToString(), System.Diagnostics.EventLogEntryType.Error);
                    return(null);
                }
            }
            catch (Exception ee)
            {
                Debug.WriteLine(ee.ToString());
                FoxEventLog.WriteEventLog("Cannot get Windows License Info " + ee.ToString(), System.Diagnostics.EventLogEntryType.Error);
                return(null);
            }
            return(lic);
        }
Ejemplo n.º 3
0
        public static bool DoSyncPolicy()
        {
            RequestCertPolicyID        = 0;
            RequestCertPolicyMessageID = 0;
            RequestCertPolicyCERData   = null;

            List <Int64> ProcessedPolicies = new List <long>();

            Network net;

            net = Utilities.ConnectNetwork(9);
            if (net == null)
            {
                return(false);
            }

            Status.UpdateMessage(9, "Downloading client settings");
            FoxEventLog.VerboseWriteEventLog("Downloading client settings", System.Diagnostics.EventLogEntryType.Information);
            ClientSettings settings = net.GetClientSettings();

            if (settings != null)
            {
                RegistryData.AdministratorName = settings.AdministratorName;
                RegistryData.MessageDisclaimer = settings.MessageDisclaimer;
            }

            Status.UpdateMessage(9, "Downloading policies");
            FoxEventLog.VerboseWriteEventLog("Downloading policies", System.Diagnostics.EventLogEntryType.Information);
            PolicyObjectListSigned    policieslistsigned = net.GetPoliciesForComputer();
            List <PolicyObjectSigned> policies           = policieslistsigned == null ? null : policieslistsigned.Items;

            if (policies == null)
            {
                FoxEventLog.VerboseWriteEventLog("Downloading policies - nix", System.Diagnostics.EventLogEntryType.Information);
                Status.UpdateMessage(9);
                net.CloseConnection();
                return(true);
            }

            if (FilesystemData.LoadedCertificates.Count > 0)
            {
                bool SignatureOK = false;
                foreach (FilesystemCertificateData cer in FilesystemData.LoadedCertificates)
                {
                    if (Certificates.Verify(policieslistsigned, cer.Certificate) == true)
                    {
                        SignatureOK = true;
                        break;
                    }
                }
                if (SignatureOK == false)
                {
                    FoxEventLog.WriteEventLog("Invalid signature for PolicyList - no policies will be processed.", System.Diagnostics.EventLogEntryType.Error);
                    net.CloseConnection();
                    return(true);
                }
            }
            if (RegistryData.Verbose == 1)
            {
                string data = "Got policy:\r\n";
                foreach (PolicyObjectSigned obj in policies)
                {
                    data += obj.Policy.Name + " [ID: " + obj.Policy.ID + " VER: " + obj.Policy.Version + "]\r\n";
                }
                FoxEventLog.VerboseWriteEventLog("Downloading policies " + data, System.Diagnostics.EventLogEntryType.Information);
            }

            if (FilesystemData.LoadedCertificates.Count > 0)
            {
                foreach (PolicyObjectSigned obj in policies)
                {
                    if (ApplicationCertificate.Verify(obj) == false)
                    {
                        FoxEventLog.WriteEventLog("One or more policies were tampered - no policies will be processed.", System.Diagnostics.EventLogEntryType.Error);
                        net.CloseConnection();
                        return(true);
                    }
                }
            }

            #region Certificate Checks

            foreach (PolicyObjectSigned obj in policies)
            {
                if (obj.Policy.Type == PolicyIDs.SignCertificate)
                {
                    if (FilesystemData.ContainsPolicy(obj.Policy, false, false) == true)
                    {
                        continue;
                    }
                    PolicyObjectSigned objj = net.GetPolicyObjectSigned(obj.Policy.ID);
                    //do not verify signing here - that won't work! - Fox
                    PolicySigningCertificates Cert = JsonConvert.DeserializeObject <PolicySigningCertificates>(objj.Policy.Data);
                    if (FilesystemData.ContainsLoadedCert(Convert.FromBase64String(Cert.UUCerFile)) == true)
                    {
                        continue;
                    }
                    bool sig = Certificates.Verify(Convert.FromBase64String(Cert.UUCerFile), Convert.FromBase64String(Cert.UUSignFile), InternalCertificate.Main);
                    if (sig == false)
                    {
                        RequestCertPolicyID      = objj.Policy.ID;
                        RequestCertPolicyCERData = Convert.FromBase64String(Cert.UUCerFile);
                        string CN = Certificates.GetCN(Convert.FromBase64String(Cert.UUCerFile));
                        if (CN == null)
                        {
                            FoxEventLog.WriteEventLog("Invalid certificate from server (Policy ID=" + objj.Policy.ID.ToString() + " Name=" + objj.Policy.Name + ")", System.Diagnostics.EventLogEntryType.Error);
                            continue;
                        }
                        Status.RequestCertificateConfirm("The certificate with " + CN + " is not signed by Vulpes. This may that someone tampered the connection, or a false certificate is installed on the server.\nDo you want to continue, and trust this certificate?", RequestCertPolicyID);
                        RequestCertPolicyMessageID = Status.MessageID;
                        FoxEventLog.WriteEventLog("Got unsinged certificate (Policy ID=" + objj.Policy.ID.ToString() + " Name=" + objj.Policy.Name + " " + CN + ")", System.Diagnostics.EventLogEntryType.Warning);
                    }
                    else
                    {
                        string CN = Certificates.GetCN(Convert.FromBase64String(Cert.UUCerFile));
                        if (CN == null)
                        {
                            FoxEventLog.WriteEventLog("Invalid (Vulpes signed) certificate from server (Policy ID=" + objj.Policy.ID.ToString() + " Name=" + objj.Policy.Name + ")", System.Diagnostics.EventLogEntryType.Error);
                            continue;
                        }
                        FilesystemData.InstallCertificate(Convert.FromBase64String(Cert.UUCerFile));
                    }
                }
            }

            #endregion

            if (FilesystemData.LoadedCertificates.Count > 0)
            {
                foreach (PolicyObjectSigned obj in policies)
                {
                    if (FilesystemData.ContainsPolicy(obj.Policy, false, false) == true)
                    {
                        if (ProcessedPolicies.Contains(obj.Policy.ID) == false)
                        {
                            ProcessedPolicies.Add(obj.Policy.ID);
                        }
                        FilesystemData.UpdatePolicyOrder(obj.Policy, obj.Policy.Order);
                        continue;
                    }

                    PolicyObjectSigned objj = net.GetPolicyObjectSigned(obj.Policy.ID);
                    if (objj == null)
                    {
                        FoxEventLog.WriteEventLog("No data for policy - not applying (Policy ID=" + obj.Policy.ID.ToString() + " Name=" + obj.Policy.Name + ")", System.Diagnostics.EventLogEntryType.Error);
                        continue;
                    }
                    if (ApplicationCertificate.Verify(objj) == false)
                    {
                        FoxEventLog.WriteEventLog("Policy was tampered - not applying (Policy ID=" + objj.Policy.ID.ToString() + " Name=" + objj.Policy.Name + ")", System.Diagnostics.EventLogEntryType.Error);
                        continue;
                    }

                    if (FilesystemData.InstallPolicy(objj.Policy, obj.Policy.Order) == false)
                    {
                        continue;
                    }
                    if (ProcessedPolicies.Contains(obj.Policy.ID) == false)
                    {
                        ProcessedPolicies.Add(obj.Policy.ID);
                    }
                }

                List <LoadedPolicyObject> RemovePol = new List <LoadedPolicyObject>();

                foreach (LoadedPolicyObject lobj in FilesystemData.LoadedPolicyObjects)
                {
                    if (ProcessedPolicies.Contains(lobj.PolicyObject.ID) == false)
                    {
                        RemovePol.Add(lobj);
                    }
                }

                foreach (LoadedPolicyObject lobj in RemovePol)
                {
                    FilesystemData.DeletePolicy(lobj);
                }
            }

            net.CloseConnection();

            if (RequestCertPolicyID == 0)
            {
                Status.UpdateMessage(9);
            }

            FoxEventLog.VerboseWriteEventLog("Downloading policies - DONE", System.Diagnostics.EventLogEntryType.Information);
            return(true);
        }
Ejemplo n.º 4
0
        public static bool ApplyPolicy(ApplyPolicyFunction applymethod)
        {
            if (ActivePolicy == null)
            {
                ActivePolicy = new List <LoadedPolicyObject>();
            }

            FilesystemData.ReOrderPolicies();

            foreach (Type type in GetTypesWithHelpAttribute(Assembly.GetExecutingAssembly()))
            {
                PolicyObjectAttr po       = type.GetCustomAttribute <PolicyObjectAttr>();
                IPolicyClass     instance = (IPolicyClass)Activator.CreateInstance(type);
                try
                {
                    instance.PreApplyPolicy();
                }
                catch (Exception ee)
                {
                    Debug.WriteLine(ee.ToString());
                    FoxEventLog.WriteEventLog("SEH Error while finalising policy - Type 0x" + po.PolicyType.ToString("X"), System.Diagnostics.EventLogEntryType.Error);
                }
            }

            if (FilesystemData.UpdatePolicies != null)
            {
                foreach (KeyValuePair <LoadedPolicyObject, LoadedPolicyObject> kvp in FilesystemData.UpdatePolicies)
                {
                    foreach (Type type in GetTypesWithHelpAttribute(Assembly.GetExecutingAssembly()))
                    {
                        PolicyObjectAttr po = type.GetCustomAttribute <PolicyObjectAttr>();
                        if (po.PolicyType == kvp.Key.PolicyObject.Type)
                        {
                            IPolicyClass instance = (IPolicyClass)Activator.CreateInstance(type);
                            try
                            {
                                instance.UpdatePolicy(kvp.Key, kvp.Value);
                            }
                            catch (Exception ee)
                            {
                                Debug.WriteLine(ee.ToString());
                                FoxEventLog.WriteEventLog("SEH Error while updating policy - (Policy ID=" + kvp.Value.PolicyObject.ID.ToString() + " Name=" + kvp.Value.PolicyObject.Name + ")", System.Diagnostics.EventLogEntryType.Error);
                            }
                            break;
                        }
                    }
                }
            }

            List <LoadedPolicyObject> RemovePol = new List <LoadedPolicyObject>();

            foreach (LoadedPolicyObject a in ActivePolicy)
            {
                bool PolicyFound = false;
                foreach (LoadedPolicyObject b in FilesystemData.LoadedPolicyObjects)
                {
                    if (a.PolicyObject.ID == b.PolicyObject.ID &&
                        a.PolicyObject.Type == b.PolicyObject.Type)
                    {
                        PolicyFound = true;
                        break;
                    }
                }
                if (PolicyFound == false)
                {
                    RemovePol.Add(a);
                }
            }

            foreach (LoadedPolicyObject a in RemovePol)
            {
                foreach (Type type in GetTypesWithHelpAttribute(Assembly.GetExecutingAssembly()))
                {
                    PolicyObjectAttr po = type.GetCustomAttribute <PolicyObjectAttr>();
                    if (po.PolicyType == a.PolicyObject.Type)
                    {
                        IPolicyClass instance = (IPolicyClass)Activator.CreateInstance(type);
                        try
                        {
                            instance.RemovePolicy(a);
                        }
                        catch (Exception ee)
                        {
                            Debug.WriteLine(ee.ToString());
                            FoxEventLog.WriteEventLog("SEH Error while removing policy - (Policy ID=" + a.PolicyObject.ID.ToString() + " Name=" + a.PolicyObject.Name + ")", System.Diagnostics.EventLogEntryType.Error);
                        }
                        ActivePolicy.Remove(a);
                        break;
                    }
                }
            }

            RemovePol = new List <LoadedPolicyObject>(); //empty out

            foreach (LoadedPolicyObject a in FilesystemData.LoadedPolicyObjects)
            {
                bool PolicyFound = false;
                foreach (LoadedPolicyObject b in ActivePolicy)
                {
                    if (a.PolicyObject.ID == b.PolicyObject.ID &&
                        a.PolicyObject.Version == b.PolicyObject.Version &&
                        a.PolicyObject.Type == b.PolicyObject.Type)
                    {
                        PolicyFound = true;
                        break;
                    }
                }
                if (PolicyFound == false)
                {
                    bool CanProcessPolicy     = false;
                    bool FoundPolicyProcessor = false;

                    foreach (Type type in GetTypesWithHelpAttribute(Assembly.GetExecutingAssembly()))
                    {
                        PolicyObjectAttr po = type.GetCustomAttribute <PolicyObjectAttr>();
                        if (po.PolicyType == a.PolicyObject.Type)
                        {
                            IPolicyClass instance = (IPolicyClass)Activator.CreateInstance(type);
                            try
                            {
                                instance.ApplyPolicy(a);
                            }
                            catch (Exception ee)
                            {
                                Debug.WriteLine(ee.ToString());
                                FoxEventLog.WriteEventLog("SEH Error while applying policy - (Policy ID=" + a.PolicyObject.ID.ToString() + " Name=" + a.PolicyObject.Name + ")", System.Diagnostics.EventLogEntryType.Error);
                            }
                            CanProcessPolicy     = true;
                            FoundPolicyProcessor = true;
                            break;
                        }
                    }

                    if (CanProcessPolicy == true || FoundPolicyProcessor == true)
                    {
                        ActivePolicy.Add(a);
                    }

                    if (FoundPolicyProcessor == false)
                    {
                        FoxEventLog.WriteEventLog("Don't know how to process policy type 0x" + a.PolicyObject.Type.ToString("X") + " - (Policy ID=" + a.PolicyObject.ID.ToString() + " Name=" + a.PolicyObject.Name + ")", System.Diagnostics.EventLogEntryType.Warning);
                    }
                }
            }

            foreach (LoadedPolicyObject a in ActivePolicy)
            {
                foreach (Type type in GetTypesWithHelpAttribute(Assembly.GetExecutingAssembly()))
                {
                    PolicyObjectAttr po = type.GetCustomAttribute <PolicyObjectAttr>();
                    if (po.PolicyType == a.PolicyObject.Type)
                    {
                        IPolicyClass instance = (IPolicyClass)Activator.CreateInstance(type);
                        try
                        {
                            instance.ApplyOrdering(a, a.PolicyObject.Order);
                        }
                        catch (Exception ee)
                        {
                            Debug.WriteLine(ee.ToString());
                            FoxEventLog.WriteEventLog("SEH Error while reordering polcy - Type 0x" + po.PolicyType.ToString("X"), System.Diagnostics.EventLogEntryType.Error);
                        }
                    }
                }
            }

            foreach (Type type in GetTypesWithHelpAttribute(Assembly.GetExecutingAssembly()))
            {
                PolicyObjectAttr po       = type.GetCustomAttribute <PolicyObjectAttr>();
                IPolicyClass     instance = (IPolicyClass)Activator.CreateInstance(type);
                try
                {
                    switch (applymethod)
                    {
                    case ApplyPolicyFunction.ApplySystem:
                        instance.FinaliseApplyPolicy();
                        break;

                    case ApplyPolicyFunction.ApplyUser:
                        instance.FinaliseApplyPolicyUserPart();
                        break;

                    case ApplyPolicyFunction.Uninstall:
                        instance.FinaliseUninstallProgramm();
                        break;
                    }
                }
                catch (Exception ee)
                {
                    Debug.WriteLine(ee.ToString());
                    FoxEventLog.WriteEventLog("SEH Error while finalising policy (applymethod=" + applymethod.ToString() + ") - Type 0x" + po.PolicyType.ToString("X"), System.Diagnostics.EventLogEntryType.Error);
                }
            }

            FilesystemData.UpdatePolicies = null;

            if (applymethod == ApplyPolicyFunction.ApplySystem)
            {
                string ApplyUserSettingsApp = ProgramAgent.AppPath + "FoxSDC_ApplyUserSettings.exe";

                if (File.Exists(ApplyUserSettingsApp) == false)
                {
                    FoxEventLog.WriteEventLog("The file " + ApplyUserSettingsApp + " does not exist. User settings are not applied properly.", EventLogEntryType.Error);
                }
                else
                {
#if !DEBUG
                    if (ProgramAgent.CPP.VerifyEXESignature(ApplyUserSettingsApp) == false)
                    {
                        FoxEventLog.WriteEventLog("The file " + ApplyUserSettingsApp + " cannot be verified. User settings are not applied properly.", EventLogEntryType.Error);
                    }
                    else
#endif
                    {
                        try
                        {
                            Process.Start(ApplyUserSettingsApp, ""); //NT_AUTHORITY\SYSTEM
                        }
                        catch
                        {
                        }

                        try
                        {
                            ProgramAgent.CPP.StartAppAsUser(ApplyUserSettingsApp, ""); //all other logged in users
                        }
                        catch
                        {
                        }
                    }
                }
            }
            return(true);
        }
Ejemplo n.º 5
0
        static bool CollectEVT2(string Book)
        {
            try
            {
                EventLogSession session = new EventLogSession();

                bool Found = false;
                foreach (string logName in session.GetLogNames())
                {
                    if (Book == logName)
                    {
                        Found = true;
                        break;
                    }
                }

                if (Found == false)
                {
                    return(true);
                }

                EventLogReader evt = new EventLogReader(Book);

                EventRecord log;
                while ((log = evt.ReadEvent()) != null)
                {
                    EventLogReport ev = new EventLogReport();

                    ev.Category       = "(" + log.Id + ")";
                    ev.CategoryNumber = log.Id;
                    ev.Data           = new byte[0];
                    ev.EventLog       = Book;
                    switch (log.LevelDisplayName.ToLower())
                    {
                    case "information":
                        ev.EventLogType = (int)EventLogEntryType.Information; break;

                    case "warning":
                        ev.EventLogType = (int)EventLogEntryType.Warning; break;

                    case "error":
                        ev.EventLogType = (int)EventLogEntryType.Error; break;

                    default:
                        ev.EventLogType = (int)EventLogEntryType.Information; break;
                    }
                    ev.InstanceID             = log.Id;
                    ev.LogID                  = "";
                    ev.MachineID              = SystemInfos.SysInfo.MachineID;
                    ev.Message                = MakeNiceXML(log.ToXml());
                    ev.Source                 = log.ProviderName;
                    ev.TimeGenerated          = log.TimeCreated == null?DateTime.Now: log.TimeCreated.Value;
                    ev.TimeWritten            = log.TimeCreated == null ? DateTime.Now : log.TimeCreated.Value;
                    ev.JSONReplacementStrings = "[]";
                    CommonUtilities.CalcEventLogID(ev);
                    HasEVTLogs.Add(ev.LogID);
                    lst.Add(ev);
                }
            }
            catch
            {
                FoxEventLog.WriteEventLog("Cannot collect EventLog " + Book, EventLogEntryType.Error);
            }
            return(true);
        }
Ejemplo n.º 6
0
        static public bool InstallPolicy(PolicyObject data, Int64 Order)
        {
            if (data == null)
            {
                return(false);
            }
            data.Order = Order;
            string PoliciesFolder = SystemInfos.ProgramData + "Policies\\";
            string Filename       = data.ID.ToString("X8") + "-" + Guid.NewGuid().ToString();

            byte[] pol  = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data));
            byte[] sign = ApplicationCertificate.Sign(pol);
            if (sign == null)
            {
                FoxEventLog.WriteEventLog("Cannot sign policy for saving", System.Diagnostics.EventLogEntryType.Error);
                return(false);
            }

            //do we have that policy loaded?... - overwrite that (and store it to an Update Dict)
            if (LoadedPolicyObjects == null)
            {
                LoadedPolicyObjects = new List <LoadedPolicyObject>();
            }

            foreach (LoadedPolicyObject loadedpol in LoadedPolicyObjects)
            {
                if (loadedpol.PolicyObject.ID != data.ID)
                {
                    continue;
                }

                if (UpdatePolicies == null)
                {
                    UpdatePolicies = new Dictionary <LoadedPolicyObject, LoadedPolicyObject>();
                }
                UpdatePolicies.Add(
                    new LoadedPolicyObject()
                {
                    Filename     = loadedpol.Filename,
                    SignFilename = loadedpol.SignFilename,
                    PolicyObject = new PolicyObject()
                    {
                        Condition      = loadedpol.PolicyObject.Condition,
                        DataAddtions1  = loadedpol.PolicyObject.DataAddtions1,
                        DataAddtions2  = loadedpol.PolicyObject.DataAddtions2,
                        DataAddtions3  = loadedpol.PolicyObject.DataAddtions3,
                        DataAddtions4  = loadedpol.PolicyObject.DataAddtions4,
                        DataAddtions5  = loadedpol.PolicyObject.DataAddtions5,
                        Data           = loadedpol.PolicyObject.Data,
                        DT             = loadedpol.PolicyObject.DT,
                        Enabled        = loadedpol.PolicyObject.Enabled,
                        Grouping       = loadedpol.PolicyObject.Grouping,
                        ID             = loadedpol.PolicyObject.ID,
                        MachineID      = loadedpol.PolicyObject.MachineID,
                        Name           = loadedpol.PolicyObject.Name,
                        Order          = loadedpol.PolicyObject.Order,
                        TimeStampCheck = loadedpol.PolicyObject.TimeStampCheck,
                        Type           = loadedpol.PolicyObject.Type,
                        Version        = loadedpol.PolicyObject.Version
                    }
                }
                    ,
                    new LoadedPolicyObject()
                {
                    PolicyObject = data,
                    Filename     = loadedpol.Filename,
                    SignFilename = loadedpol.SignFilename
                });

                loadedpol.PolicyObject = data;

                try
                {
                    File.WriteAllBytes(loadedpol.Filename, pol);
                }
                catch
                {
                    FoxEventLog.WriteEventLog("Cannot save policy", System.Diagnostics.EventLogEntryType.Error);
                    return(false);
                }

                try
                {
                    File.WriteAllBytes(loadedpol.SignFilename, sign);
                }
                catch
                {
                    try
                    {
                        File.Delete(loadedpol.Filename);
                    }
                    catch
                    {
                    }
                    FoxEventLog.WriteEventLog("Cannot save policy signature", System.Diagnostics.EventLogEntryType.Error);
                    return(false);
                }

                return(true);
            }

            //no? create the file

            LoadedPolicyObject lobj = new LoadedPolicyObject();

            lobj.PolicyObject = data;
            lobj.Filename     = PoliciesFolder + Filename + ".pol";
            lobj.SignFilename = PoliciesFolder + Filename + ".sign";

            try
            {
                File.WriteAllBytes(lobj.Filename, pol);
            }
            catch
            {
                FoxEventLog.WriteEventLog("Cannot save policy", System.Diagnostics.EventLogEntryType.Error);
                return(false);
            }

            try
            {
                File.WriteAllBytes(lobj.SignFilename, sign);
            }
            catch
            {
                try
                {
                    File.Delete(lobj.Filename);
                }
                catch
                {
                }
                FoxEventLog.WriteEventLog("Cannot save policy signature", System.Diagnostics.EventLogEntryType.Error);
                return(false);
            }

            LoadedPolicyObjects.Add(lobj);

            return(true);
        }
Ejemplo n.º 7
0
        static public void LoadLocalPackages()
        {
            string PackagesFolder = SystemInfos.ProgramData + "Packages\\";

            if (Directory.Exists(PackagesFolder) == false)
            {
                Directory.CreateDirectory(PackagesFolder);
            }
            if (LocalPackages == null)
            {
                LocalPackages = new List <PackagesToInstall>();
            }
            try
            {
                if (File.Exists(PackagesFolder + "List.json") == true && File.Exists(PackagesFolder + "List.sign") == true)
                {
                    byte[] list = File.ReadAllBytes(PackagesFolder + "List.json");
                    byte[] sign = File.ReadAllBytes(PackagesFolder + "List.sign");
                    if (ApplicationCertificate.Verify(list, sign) == false)
                    {
                        File.Delete(PackagesFolder + "List.json");
                        File.Delete(PackagesFolder + "List.sign");
                        FoxEventLog.WriteEventLog("Package list signature is invalid: deleting the files!", EventLogEntryType.Warning);
                        LocalPackages = new List <PackagesToInstall>();
                    }
                    else
                    {
                        LocalPackages = JsonConvert.DeserializeObject <List <PackagesToInstall> >(Encoding.UTF8.GetString(list));
                    }
                }
            }
            catch (Exception ee)
            {
                Debug.WriteLine(ee.ToString());
                FoxEventLog.WriteEventLog("Error decoding package list data", EventLogEntryType.Warning);
                LocalPackages = new List <PackagesToInstall>();
            }

            try
            {
                foreach (PackagesToInstall pkg in LocalPackages)
                {
                    if (pkg.Filename != null)
                    {
                        if (File.Exists(PackagesFolder + pkg.Filename) == false)
                        {
                            FoxEventLog.WriteEventLog("Referenced package " + pkg.Filename + " does not exist", EventLogEntryType.Warning);
                            pkg.Filename = null;
                        }
                    }
                    if (pkg.MetaFilename != null)
                    {
                        if (File.Exists(PackagesFolder + pkg.MetaFilename) == false)
                        {
                            FoxEventLog.WriteEventLog("Referenced meta package " + pkg.Filename + " does not exist", EventLogEntryType.Warning);
                            pkg.MetaFilename = null;
                        }
                    }
                }

                List <PackagesToInstall> RemovePackages = new List <PackagesToInstall>();
                foreach (PackagesToInstall pkg in LocalPackages)
                {
                    if (pkg.MetaFilename == null)
                    {
                        RemovePackages.Add(pkg);
                    }
                }

                foreach (PackagesToInstall pkg in RemovePackages)
                {
                    LocalPackages.Remove(pkg);
                    if (pkg.MetaFilename != null)
                    {
                        File.Delete(PackagesFolder + pkg.MetaFilename);
                    }
                    if (pkg.Filename != null)
                    {
                        File.Delete(PackagesFolder + pkg.Filename);
                    }
                }
            }
            catch (Exception ee)
            {
                Debug.WriteLine(ee.ToString());
                FoxEventLog.WriteEventLog("Error processing package list data", EventLogEntryType.Error);
                LocalPackages = new List <PackagesToInstall>();
            }
        }
Ejemplo n.º 8
0
        public static bool InvokeRunAsUser(string Filename, string Args, string Username, string Password, int SessionID, out DataHRunasUserResult ores, out Int64 W32Res)
        {
            ores   = null;
            W32Res = 0xe9;
            DataHRunasUserTODO d = new DataHRunasUserTODO();

            d.Filename = Filename;
            d.Args     = Args;
            d.Username = Username;
            d.Password = Password;

            Process2ProcessComm p2p = new Process2ProcessComm();

            p2p.SetTODO("RUNUSER", d);
            if (p2p.StartPipe() == false)
            {
                FoxEventLog.WriteEventLog("Cannot start P2PC for RUNUSER " + p2p.GetGUID(), EventLogEntryType.Error);
                return(false);
            }

            if (SessionID == 0)
            {
                try
                {
                    Process proc = new Process();
                    proc.StartInfo.FileName        = Assembly.GetExecutingAssembly().Location;
                    proc.StartInfo.Arguments       = "-pipeaction " + p2p.GetGUID();
                    proc.StartInfo.UseShellExecute = false;
                    proc.Start();
                    proc.WaitForExit();
                }
                catch (Win32Exception ee)
                {
                    W32Res = 0x00000000FFFFFFFF & ee.NativeErrorCode;
                    Debug.WriteLine(ee.ToString());
                    FoxEventLog.WriteEventLog("Cannot start P2PC for SYS RUNUSER " + p2p.GetGUID(), EventLogEntryType.Error);
                    return(false);
                }
                catch (Exception ee)
                {
                    W32Res = 0x8000ffff;
                    Debug.WriteLine(ee.ToString());
                    FoxEventLog.WriteEventLog("Cannot start P2PC for SYS RUNUSER " + p2p.GetGUID(), EventLogEntryType.Error);
                    return(false);
                }
            }
            else
            {
                if (ProgramAgent.CPP.StartAppAsUserWait(Assembly.GetExecutingAssembly().Location, "-pipeaction " + p2p.GetGUID(), SessionID) == false)
                {
                    W32Res = ProgramAgent.CPP.WGetLastError();
                    FoxEventLog.WriteEventLog("Cannot start P2PC Process for RUNUSER " + p2p.GetGUID() + " Error: 0x" + ProgramAgent.CPP.WGetLastError().ToString("X"), EventLogEntryType.Error);
                    p2p.ClosePipe();
                    return(false);
                }
            }

            ores = p2p.GetResult <DataHRunasUserResult>();
            p2p.ClosePipe();
            if (ores == null)
            {
                FoxEventLog.WriteEventLog("P2PC didn't return any data for RUNUSER " + p2p.GetGUID(), EventLogEntryType.Error);
                return(false);
            }

            return(true);
        }
Ejemplo n.º 9
0
        static public bool LoadPolicies()
        {
            LoadedPolicyObjects = new List <LoadedPolicyObject>();
            string PoliciesFolder = SystemInfos.ProgramData + "Policies\\";

            if (Directory.Exists(PoliciesFolder) == false)
            {
                Directory.CreateDirectory(PoliciesFolder);
            }

            foreach (string file in Directory.EnumerateFiles(PoliciesFolder, "*.pol", SearchOption.TopDirectoryOnly))
            {
                string signfile = file.Substring(0, file.Length - 4) + ".sign";

                if (File.Exists(file) == false)
                {
                    if (File.Exists(signfile) == true)
                    {
                        FoxEventLog.WriteEventLog("Found lonely file \"" + file + "\" - deleting the file", System.Diagnostics.EventLogEntryType.Warning);
                        File.Delete(signfile);
                    }
                }
                else
                {
                    if (File.Exists(signfile) == false)
                    {
                        FoxEventLog.WriteEventLog("Found \"" + file + "\" but no signature - deleting the file", System.Diagnostics.EventLogEntryType.Warning);
                        File.Delete(file);
                    }
                    else
                    {
                        FileInfo fileinfo;
                        fileinfo = new FileInfo(file);
                        if (fileinfo.Length > 33554432)
                        {
                            FoxEventLog.WriteEventLog("File \"" + file + "\" too large (>32MB) - deleting the files", System.Diagnostics.EventLogEntryType.Warning);
                            File.Delete(file);
                            File.Delete(signfile);
                            continue;
                        }
                        fileinfo = new FileInfo(signfile);
                        if (fileinfo.Length > 33554432)
                        {
                            FoxEventLog.WriteEventLog("File \"" + signfile + "\" too large (>32MB) - deleting the files", System.Diagnostics.EventLogEntryType.Warning);
                            File.Delete(file);
                            File.Delete(signfile);
                            continue;
                        }

                        byte[] pol  = File.ReadAllBytes(file);
                        byte[] sign = File.ReadAllBytes(signfile);

                        if (ApplicationCertificate.Verify(pol, sign) == false)
                        {
                            FoxEventLog.WriteEventLog("File \"" + file + "\" is not proper signed - deleting the files", System.Diagnostics.EventLogEntryType.Warning);
                            File.Delete(file);
                            File.Delete(signfile);
                            continue;
                        }

                        try
                        {
                            PolicyObject obj = JsonConvert.DeserializeObject <PolicyObject>(Encoding.UTF8.GetString(pol));
                            if (ContainsPolicy(obj, true, true) == true)
                            {
                                FoxEventLog.WriteEventLog("File \"" + file + "\" is already loaded from a different file - deleting the files", System.Diagnostics.EventLogEntryType.Warning);
                                File.Delete(file);
                                File.Delete(signfile);
                                continue;
                            }
                            LoadedPolicyObject lobj = new LoadedPolicyObject();
                            lobj.PolicyObject = obj;
                            lobj.Filename     = file;
                            lobj.SignFilename = signfile;
                            LoadedPolicyObjects.Add(lobj);
                            Debug.WriteLine(file + " loaded");
                        }
                        catch
                        {
                            FoxEventLog.WriteEventLog("File \"" + file + "\" cannot be loaded properly - deleting the files", System.Diagnostics.EventLogEntryType.Warning);
                            File.Delete(file);
                            File.Delete(signfile);
                            continue;
                        }
                    }
                }
            }

            return(true);
        }
Ejemplo n.º 10
0
        static public bool LoadCertificates(bool Shutup = false)
        {
            LoadedCertificates = new List <FilesystemCertificateData>();
            string CertFolder = SystemInfos.ProgramData + "Certificates\\";

            if (Directory.Exists(CertFolder) == false)
            {
                Directory.CreateDirectory(CertFolder);
            }

            for (int i = 1; i < 100; i++)
            {
                if (File.Exists(CertFolder + "Certificate" + i.ToString("00") + ".cer") == false)
                {
                    if (File.Exists(CertFolder + "Certificate" + i.ToString("00") + ".sign") == true)
                    {
                        FoxEventLog.WriteEventLog("Found lonely file \"Certificate" + i.ToString("00") + ".sign\" - deleting the file", System.Diagnostics.EventLogEntryType.Warning);
                        File.Delete(CertFolder + "Certificate" + i.ToString("00") + ".sign");
                    }
                }
                else
                {
                    if (File.Exists(CertFolder + "Certificate" + i.ToString("00") + ".sign") == false)
                    {
                        FoxEventLog.WriteEventLog("Found \"Certificate" + i.ToString("00") + ".cer\" but no signature - deleting the file", System.Diagnostics.EventLogEntryType.Warning);
                        File.Delete(CertFolder + "Certificate" + i.ToString("00") + ".cer");
                    }
                    else
                    {
                        FileInfo file;
                        file = new FileInfo(CertFolder + "Certificate" + i.ToString("00") + ".cer");
                        if (file.Length > 5242880)
                        {
                            FoxEventLog.WriteEventLog("File \"Certificate" + i.ToString("00") + ".cer\" too large (>5MB) - deleting the files", System.Diagnostics.EventLogEntryType.Warning);
                            File.Delete(CertFolder + "Certificate" + i.ToString("00") + ".cer");
                            File.Delete(CertFolder + "Certificate" + i.ToString("00") + ".sign");
                            continue;
                        }
                        file = new FileInfo(CertFolder + "Certificate" + i.ToString("00") + ".sign");
                        if (file.Length > 5242880)
                        {
                            FoxEventLog.WriteEventLog("File \"Certificate" + i.ToString("00") + ".sign\" too large (>5MB) - deleting the files", System.Diagnostics.EventLogEntryType.Warning);
                            File.Delete(CertFolder + "Certificate" + i.ToString("00") + ".cer");
                            File.Delete(CertFolder + "Certificate" + i.ToString("00") + ".sign");
                            continue;
                        }

                        byte[] cert = File.ReadAllBytes(CertFolder + "Certificate" + i.ToString("00") + ".cer");
                        byte[] sign = File.ReadAllBytes(CertFolder + "Certificate" + i.ToString("00") + ".sign");

                        if (ApplicationCertificate.Verify(cert, sign) == false)
                        {
                            FoxEventLog.WriteEventLog("File \"Certificate" + i.ToString("00") + ".cer\" and \"Certificate" + i.ToString("00") + ".sign\" do not match - deleting the files", System.Diagnostics.EventLogEntryType.Warning);
                            File.Delete(CertFolder + "Certificate" + i.ToString("00") + ".cer");
                            File.Delete(CertFolder + "Certificate" + i.ToString("00") + ".sign");
                            continue;
                        }

                        if (ContainsLoadedCert(cert) == true)
                        {
                            FoxEventLog.WriteEventLog("File \"Certificate" + i.ToString("00") + ".cer\" this certificate is already loaded from a different file - deleting the files", System.Diagnostics.EventLogEntryType.Warning);
                            File.Delete(CertFolder + "Certificate" + i.ToString("00") + ".cer");
                            File.Delete(CertFolder + "Certificate" + i.ToString("00") + ".sign");
                            continue;
                        }

                        Debug.WriteLine(CertFolder + "Certificate" + i.ToString("00") + ".cer loaded");
                        FilesystemCertificateData fscer = new FilesystemCertificateData();
                        fscer.FSFilename  = "Certificate" + i.ToString("00") + ".cer";
                        fscer.Certificate = cert;
                        LoadedCertificates.Add(fscer);
                        if (Shutup == false)
                        {
                            FoxEventLog.WriteEventLog("Certificate " + Certificates.GetCN(cert) + " loaded", System.Diagnostics.EventLogEntryType.Information);
                        }
                    }
                }
            }

            return(true);
        }
Ejemplo n.º 11
0
        public static void AppendIntoHOSTSFile(string Entry, string IPAddress)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(Entry) == true || string.IsNullOrWhiteSpace(IPAddress) == true)
                {
                    return;
                }

                string HostsLine = IPAddress + " " + Entry + "      # from Fox SDC Agent";
                string HostsFile = Environment.ExpandEnvironmentVariables("%SYSTEMROOT%\\System32\\Drivers\\Etc\\Hosts");
                if (File.Exists(HostsFile) == false)
                {
                    File.AppendAllText(HostsFile, "\r\n" + HostsLine + "\r\n", Encoding.ASCII);
                    return;
                }

                List <string> Data       = new List <string>();
                bool          AppendLine = true;

                using (TextReader txtr = new StreamReader(File.Open(HostsFile, FileMode.Open, FileAccess.Read, FileShare.Read)))
                {
                    string Line = "";
                    while ((Line = txtr.ReadLine()) != null)
                    {
                        Data.Add(Line);

                        if (Line.Contains("#") == true)
                        {
                            Line = Line.Substring(0, Line.IndexOf('#')).Trim();
                        }
                        if (Line.Trim() == "")
                        {
                            continue;
                        }
                        string[] splitty = Line.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                        if (splitty.Length < 2)
                        {
                            continue;
                        }
                        if (splitty[0].ToLower().Trim() == IPAddress.ToLower().Trim() && //exact match - out, no changes
                            splitty[1].ToLower().Trim() == Entry.ToLower().Trim())
                        {
                            return;
                        }
                        if (splitty[1].ToLower().Trim() == Entry.ToLower().Trim()) //Name match, but not it's IP Address
                        {
                            Data.RemoveAt(Data.Count - 1);
                            Data.Add(HostsLine);
                            AppendLine = false;
                        }
                    }
                }

                if (AppendLine == false)
                {
                    File.WriteAllLines(HostsFile, Data.ToArray(), Encoding.ASCII);
                }
                else
                {
                    File.AppendAllText(HostsFile, "\r\n" + HostsLine + "\r\n", Encoding.ASCII);
                }
            }
            catch (Exception ee)
            {
                FoxEventLog.WriteEventLog("Cannot edit HOSTS file: " + ee.ToString(), System.Diagnostics.EventLogEntryType.Error);
            }
        }
Ejemplo n.º 12
0
        public static bool DoSyncSMART()
        {
            try
            {
                Status.UpdateMessage(1, "Collecting SMART Informations");
                Network net;
                net = Utilities.ConnectNetwork(1);
                if (net == null)
                {
                    return(false);
                }
                Status.UpdateMessage(1, "Collecting SMART Informations");

                List <VulpesSMARTInfo> SMART;
                try
                {
                    SMART = GetSMARTInfo();
                }
                catch (ManagementException ee)
                {
                    if (ee.ErrorCode == ManagementStatus.NotSupported)
                    {
                        SMART = new List <VulpesSMARTInfo>();
                        SMART.Add(new VulpesSMARTInfo()
                        {
                            Attributes              = null,
                            Caption                 = "Unsupported",
                            FirmwareRevision        = "AAAA",
                            InterfaceType           = "IDE",
                            Model                   = "Unsupported",
                            Name                    = "Unsupported",
                            PNPDeviceID             = "LEGACY\\UNSUPPORTED",
                            PredictFailure          = false,
                            SerialNumber            = "00000000000000",
                            Size                    = 1024 * 1024,
                            Status                  = "OK",
                            VendorSpecific          = null,
                            VendorSpecificThreshold = null
                        });
                    }
                    else
                    {
                        throw;
                    }
                }
                catch
                {
                    throw;
                }
                if (SMART == null)
                {
                    Status.UpdateMessage(1);
                    net.CloseConnection();
                    return(false);
                }

                Status.UpdateMessage(1, "Collecting SMART Informations (Sending data ...)");
                net.ReportSMARTInfos(SystemInfos.SysInfo.MachineID, SMART);
                net.CloseConnection();
            }
            catch (Exception ee)
            {
                Debug.WriteLine(ee.ToString());
                FoxEventLog.WriteEventLog("Servere error while syncing SMART Informations: " + ee.ToString(), EventLogEntryType.Error);
            }
            Status.UpdateMessage(1);
            return(true);
        }
Ejemplo n.º 13
0
        static bool RunUpdate()
        {
            string       pkgfile   = ProgramAgent.AppPath + "agentupdate.foxpkg";
            const string PackageID = "Vulpes-SDCA1-Update";

            net = Utilities.ConnectNetwork(-1);
            if (net == null)
            {
                return(false);
            }

            bool EarlyChannel = RegistryData.EarlyUpdates == 1 ? true : false;

            Int64?Version = net.GetAvailableAgentVersion(EarlyChannel);

            if (Version == null)
            {
                net.CloseConnection();
                return(false);
            }

            if (Version.Value <= FoxVersion.Version)
            {
                net.CloseConnection();
                return(false);
            }

            if (net.DownloadFile("api/" + (EarlyChannel == true ? "early" : "") + "update/package/1", pkgfile) == false)
            {
                net.CloseConnection();
                return(false);
            }

            net.CloseConnection();

            PackageInstaller pkgi = new PackageInstaller();
            string           Error;

            if (pkgi.PackageInfo(pkgfile, null, out Error) == false)
            {
                CommonUtilities.SpecialDeleteFile(pkgfile);
                FoxEventLog.WriteEventLog("Self-Update: Error reading package file " + pkgfile + ": " + Error, System.Diagnostics.EventLogEntryType.Error);
                return(false);
            }

            if (pkgi.PackageInfoData.PackageID != PackageID)
            {
                CommonUtilities.SpecialDeleteFile(pkgfile);
                FoxEventLog.WriteEventLog("Self-Update: PackageID mismatch on file " + pkgfile, System.Diagnostics.EventLogEntryType.Error);
                return(false);
            }

            if (pkgi.PackageInfoData.VersionID <= FoxSDC_Agent.FoxVersion.Version)
            {
                CommonUtilities.SpecialDeleteFile(pkgfile);
                FoxEventLog.WriteEventLog("Self-Update: Version on package is same or older than installed for file " + pkgfile, System.Diagnostics.EventLogEntryType.Error);
                return(false);
            }

            string UpdateApp = ProgramAgent.AppPath + "FoxSDC_Selfupdate.exe";

            FoxEventLog.WriteEventLog("Self-Update: Starting " + UpdateApp + " to update from " + FoxSDC_Agent.FoxVersion.Version.ToString() + " to " + pkgi.PackageInfoData.VersionID.ToString(), System.Diagnostics.EventLogEntryType.Information);

#if !DEBUG
            if (ProgramAgent.CPP.VerifyEXESignature(UpdateApp) == false)
            {
                FoxEventLog.WriteEventLog("The file " + UpdateApp + " cannot be verified. Update will not work.", EventLogEntryType.Error);
            }
            else
#endif
            {
                try
                {
                    Process.Start(UpdateApp);
                }
                catch
                {
                }
            }

            return(true);
        }
Ejemplo n.º 14
0
        public static void SMain()
        {
#if !DEBUG
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
#endif
            FoxEventLog.RegisterEventLog();

            if (UsePipeAction == false && UseScreenAction == false && UseDNSAutoConfig == false && UseLoginRecovery == false) //Pipe Actions can also be run in user-space ...
            {
                if (IsSystemUser() != true)
                {
#if !DEBUG || DEBUGSERVICE
                    service.Stop();
#endif
                    return;
                }
            }

            if (LoadDLL() == false)
            {
#if !DEBUG || DEBUGSERVICE
                service.Stop();
#endif
                return;
            }

#if !DEBUG
            if (TestIntegrity(null) == false)
            {
                FoxEventLog.WriteEventLog("Integrity check failed!", EventLogEntryType.Error);
                service.Stop();
                return;
            }
#endif
            if (UseDNSAutoConfig == true)
            {
                try
                {
                    List <List <string> > Query = CPP.DNSQueryTXT("sdc-contract.my-vulpes-config.lu");

                    if (Query == null)
                    {
                        return;
                    }

                    string ContractID       = null;
                    string ContractPassword = null;
                    string UseOnPrem        = null;
                    string OnPremURL        = null;

                    foreach (List <string> Q in Query)
                    {
                        if (Q == null)
                        {
                            continue;
                        }

                        foreach (string QR in Q)
                        {
                            if (string.IsNullOrWhiteSpace(QR) == true)
                            {
                                continue;
                            }
                            if (QR.ToLower().StartsWith("contractid=") == true)
                            {
                                ContractID = QR.Substring(11).Trim();
                            }
                            if (QR.ToLower().StartsWith("contractpassword="******"useonprem=") == true)
                            {
                                UseOnPrem = QR.Substring(10).Trim();
                            }
                            if (QR.ToLower().StartsWith("onpremurl=") == true)
                            {
                                OnPremURL = QR.Substring(10).Trim();
                            }
                        }
                    }

                    using (RegistryKey k = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Fox\\SDC"))
                    {
                        if (string.IsNullOrWhiteSpace(ContractID) == false && string.IsNullOrWhiteSpace(ContractPassword) == false)
                        {
                            k.SetValue("ContractID", ContractID, RegistryValueKind.String);
                            k.SetValue("ContractPassword", ContractPassword, RegistryValueKind.String);
                        }

                        int UseOnPremInt;
                        if (int.TryParse(UseOnPrem, out UseOnPremInt) == true)
                        {
                            if (UseOnPremInt == 1 && string.IsNullOrWhiteSpace(OnPremURL) == false)
                            {
                                k.SetValue("UseOnPremServer", 1, RegistryValueKind.DWord);
                                k.SetValue("Server", OnPremURL, RegistryValueKind.String);
                            }
                            else
                            {
                                k.SetValue("UseOnPremServer", 0, RegistryValueKind.DWord);
                            }
                        }
                        else
                        {
                            k.SetValue("UseOnPremServer", 0, RegistryValueKind.DWord);
                        }
                    }
                }
                catch (Exception ee)
                {
                    Debug.WriteLine(ee.ToString());
                }
                return;
            }

            if (UseLoginRecovery == true)
            {
                if (SystemInfos.CollectSystemInfo() != 0)
                {
                    return;
                }

#if !DEBUG
                if (SystemInfos.SysInfo.RunningInWindowsPE == false || SystemInfos.SysInfo.RunningInWindowsPE == null)
                {
                    return;
                }
#endif

                RecoveryLogon reclogon = new RecoveryLogon();
                reclogon.UCID             = SystemInfos.SysInfo.UCID;
                reclogon.ContractID       = SystemInfos.ContractID;
                reclogon.ContractPassword = SystemInfos.ContractPassword;

                string Check = SystemInfos.SysInfo.CPUName.Trim();
                Check += SystemInfos.SysInfo.ComputerModel == "" ? "N/A" : SystemInfos.SysInfo.ComputerModel.Trim();
                Check += SystemInfos.SysInfo.BIOS == "" ? "N/A" : SystemInfos.SysInfo.BIOS.Trim();

                reclogon.MoreMachineHash = MD5Utilities.CalcMD5(Check);
                Network net = Utilities.NoConnectNetwork();

                RecoveryData rd = net.GetRecoveryLogon(reclogon);
                if (rd == null)
                {
                    return;
                }
                if (rd.Worked == false)
                {
                    return;
                }

                string Registry = "Windows Registry Editor Version 5.00\r\n\r\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\Fox\\SDC]\r\n\"ID\"=\"" + rd.MachineID + "\"\r\n\"PassID\"=\"" + rd.MachinePassword + "\"";
                try
                {
                    File.WriteAllText(Environment.ExpandEnvironmentVariables("%SYSTEMROOT%\\Fox SDC MachinePW.reg"), Registry, Encoding.Unicode);
                }
                catch
                {
                }
                return;
            }

            if (UsePipeAction == false && UseScreenAction == false)
            {
                using (RegistryKey installer = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\" + VulpesBranding.MSIGUID, false))
                {
                    if (installer == null)
                    {
                        FoxEventLog.WriteEventLog("Missing installer key in HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\" + VulpesBranding.MSIGUID + ". This can lead to erratic behavoir of the program!", EventLogEntryType.Warning);
                    }
                }

                if (CPP.SetToken() == false)
                {
                    FoxEventLog.WriteEventLog("Cannot setup token - 0x" + Marshal.GetLastWin32Error().ToString("X") + " - " + new Win32Exception(Marshal.GetLastWin32Error()).Message, System.Diagnostics.EventLogEntryType.Error);
                    return;
                }
            }

            if (UsePipeAction == true)
            {
                try
                {
                    Process2ProcessCommClient.RunPipeClient();
                }
                catch (Exception ee)
                {
                    FoxEventLog.WriteEventLog("Pipe SEH " + ee.ToString(), System.Diagnostics.EventLogEntryType.Error);
                }
                return;
            }

            if (UseScreenAction == true)
            {
                try
                {
                    if (SystemInfos.CollectSystemInfo() != 0)
                    {
                        return;
                    }
                    MainScreenSystemClient.RunPipeClient();
                }
                catch (Exception ee)
                {
                    FoxEventLog.WriteEventLog("Screen Pipe SEH " + ee.ToString(), System.Diagnostics.EventLogEntryType.Error);
                }
                return;
            }

            if (SystemInfos.CollectSystemInfo() != 0)
            {
#if !DEBUG || DEBUGSERVICE
                service.Stop();
#endif
                return;
            }

            RegistryData.InstallPath = AppPath;

            if (ApplicationCertificate.LoadCertificate() == false)
            {
                FoxEventLog.WriteEventLog("Cannot load certificate", System.Diagnostics.EventLogEntryType.Error);
#if !DEBUG || DEBUGSERVICE
                service.Stop();
#endif
                return;
            }

            if (FilesystemData.LoadCertificates() == false)
            {
#if !DEBUG || DEBUGSERVICE
                service.Stop();
#endif
                return;
            }
            if (FilesystemData.LoadPolicies() == false)
            {
#if !DEBUG || DEBUGSERVICE
                service.Stop();
#endif
                return;
            }
            FilesystemData.LoadLocalPackageData();
            FilesystemData.LoadLocalPackages();
            FilesystemData.LoadUserPackageData();
            FilesystemData.LoadEventLogList();

            SyncPolicy.ApplyPolicy(SyncPolicy.ApplyPolicyFunction.ApplySystem);

            PipeCommunicationSRV.StartPipeSrv();

            try
            {
                string p = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                if (p.EndsWith("\\") == false)
                {
                    p += "\\";
                }

                using (RegistryKey reg = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
                {
                    reg.SetValue("FoxSDCAgent", p + "FoxSDC_Agent_UI.exe", RegistryValueKind.String);
                    reg.SetValue("FoxSDCAgentApply", p + "FoxSDC_ApplyUserSettings.exe", RegistryValueKind.String);
                    reg.Close();
                }
            }
            catch
            {
            }

            try
            {
                using (RegistryKey reg = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", true))
                {
                    object o      = reg.GetValue("SoftwareSASGeneration", null);
                    int    rvalue = 0;
                    if (o != null)
                    {
                        rvalue = Convert.ToInt32(o);
                    }

                    if (rvalue != 1 && rvalue != 3)
                    {
                        reg.SetValue("SoftwareSASGeneration", 1);
                    }
                    reg.Close();
                }
            }
            catch
            {
            }

            Threads.StartAllThreads();
        }
Ejemplo n.º 15
0
        static public void LoadUserPackageData()
        {
            string PackagesFolder = SystemInfos.ProgramData + "Packages\\";

            if (Directory.Exists(PackagesFolder) == false)
            {
                Directory.CreateDirectory(PackagesFolder);
            }
            if (AvailableUserPackages == null)
            {
                AvailableUserPackages = new List <PackageIDData>();
            }
            if (UserPackagesToInstall == null)
            {
                UserPackagesToInstall = new List <PackageIDData>();
            }
            try
            {
                if (File.Exists(PackagesFolder + "AvailableUserPackages.json") == true && File.Exists(PackagesFolder + "AvailableUserPackages.sign") == true)
                {
                    byte[] list = File.ReadAllBytes(PackagesFolder + "AvailableUserPackages.json");
                    byte[] sign = File.ReadAllBytes(PackagesFolder + "AvailableUserPackages.sign");
                    if (ApplicationCertificate.Verify(list, sign) == false)
                    {
                        File.Delete(PackagesFolder + "AvailableUserPackages.json");
                        File.Delete(PackagesFolder + "AvailableUserPackages.sign");
                        FoxEventLog.WriteEventLog("AvailableUserPackages list signature is invalid: deleting the files!", EventLogEntryType.Warning);
                        AvailableUserPackages = new List <PackageIDData>();
                    }
                    else
                    {
                        AvailableUserPackages = JsonConvert.DeserializeObject <List <PackageIDData> >(Encoding.UTF8.GetString(list));
                    }
                }
            }
            catch (Exception ee)
            {
                Debug.WriteLine(ee.ToString());
                FoxEventLog.WriteEventLog("Error decoding AvailableUserPackages", EventLogEntryType.Warning);
                AvailableUserPackages = new List <PackageIDData>();
            }

            try
            {
                if (File.Exists(PackagesFolder + "UserPackagesToInstall.json") == true && File.Exists(PackagesFolder + "UserPackagesToInstall.sign") == true)
                {
                    byte[] list = File.ReadAllBytes(PackagesFolder + "UserPackagesToInstall.json");
                    byte[] sign = File.ReadAllBytes(PackagesFolder + "UserPackagesToInstall.sign");
                    if (ApplicationCertificate.Verify(list, sign) == false)
                    {
                        File.Delete(PackagesFolder + "UserPackagesToInstall.json");
                        File.Delete(PackagesFolder + "UserPackagesToInstall.sign");
                        FoxEventLog.WriteEventLog("UserPackagesToInstall list signature is invalid: deleting the files!", EventLogEntryType.Warning);
                        UserPackagesToInstall = new List <PackageIDData>();
                    }
                    else
                    {
                        UserPackagesToInstall = JsonConvert.DeserializeObject <List <PackageIDData> >(Encoding.UTF8.GetString(list));
                    }
                }
            }
            catch (Exception ee)
            {
                Debug.WriteLine(ee.ToString());
                FoxEventLog.WriteEventLog("Error decoding UserPackagesToInstall", EventLogEntryType.Warning);
                UserPackagesToInstall = new List <PackageIDData>();
            }
        }
Ejemplo n.º 16
0
        static int Main(string[] args)
        {
            Init();

            for (int i = 0; i < args.Length; i++)
            {
                if (args[i].ToLower() == "-reset")
                {
                    Console.WriteLine("Resetting");
                    FoxEventLog.WriteEventLog("RESET: Recovering from a crash", EventLogEntryType.Warning);
                    try
                    {
                        ServiceController ctrl = new ServiceController("FoxSDCA");
                        ctrl.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 5, 0));
                        ctrl.Start();
                    }
                    catch (Exception ee)
                    {
                        Console.WriteLine(ee.ToString());
                        return(-1);
                    }
                    return(0);
                }
                if (args[i].ToLower() == "-install")
                {
                    try
                    {
                        ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
                    }
                    catch (Exception ee)
                    {
                        Console.WriteLine(ee.ToString());
                        return(-1);
                    }
                    return(0);
                }
                if (args[i].ToLower() == "-pipeaction")
                {
                    if (args.Length <= i)
                    {
                        return(-1);
                    }
                    PipeGUID      = args[i + 1];
                    UsePipeAction = true;
                    i++;
                    SMain();
                    return(0);
                }
                if (args[i].ToLower() == "-screen")
                {
                    if (args.Length <= i)
                    {
                        return(-1);
                    }
                    PipeGUID        = args[i + 1];
                    UseScreenAction = true;
                    i++;
                    SMain();
                    return(0);
                }
                if (args[i].ToLower() == "-autodnsconfig")
                {
                    UseDNSAutoConfig = true;
                    i++;
                    SMain();
                    return(0);
                }
                if (args[i].ToLower() == "-recovercreds")
                {
                    UseLoginRecovery = true;
                    i++;
                    SMain();
                    return(0);
                }
            }

#if DEBUG && !DEBUGSERVICE
            SMain();
            Console.WriteLine("DEBUG: Running - Press any key . . . ");
            Console.ReadKey(true);
            Console.WriteLine("DEBUG: Stopping . . . ");
            Threads.StopAllThreads();
#else
            ServicesToRun = new ServiceBase[]
            {
                service
            };
            ServiceBase.Run(ServicesToRun);
#endif
            return(0);
        }
Ejemplo n.º 17
0
        static public bool UpdatePolicyOrder(PolicyObject obj, Int64 Order)
        {
            if (LoadedPolicyObjects == null)
            {
                LoadedPolicyObjects = new List <LoadedPolicyObject>();
            }

            foreach (LoadedPolicyObject pol in LoadedPolicyObjects)
            {
                if (pol.PolicyObject.ID != obj.ID)
                {
                    continue;
                }
                if (pol.PolicyObject.Name != obj.Name)
                {
                    continue;
                }
                if (pol.PolicyObject.Type != obj.Type)
                {
                    continue;
                }
                if (pol.PolicyObject.Version != obj.Version)
                {
                    continue;
                }
                if (pol.PolicyObject.DT != obj.DT)
                {
                    continue;
                }
                pol.PolicyObject.Order = Order;

                byte[] ppol = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(pol.PolicyObject));
                byte[] sign = ApplicationCertificate.Sign(ppol);
                if (sign == null)
                {
                    FoxEventLog.WriteEventLog("Cannot sign policy for saving", System.Diagnostics.EventLogEntryType.Error);
                    return(false);
                }


                try
                {
                    File.WriteAllBytes(pol.Filename, ppol);
                }
                catch
                {
                    FoxEventLog.WriteEventLog("Cannot save policy", System.Diagnostics.EventLogEntryType.Error);
                    return(false);
                }

                try
                {
                    File.WriteAllBytes(pol.SignFilename, sign);
                }
                catch
                {
                    try
                    {
                        File.Delete(pol.Filename);
                    }
                    catch
                    {
                    }
                    FoxEventLog.WriteEventLog("Cannot save policy signature", System.Diagnostics.EventLogEntryType.Error);
                    return(false);
                }

                break;
            }
            return(true);
        }
Ejemplo n.º 18
0
        public static bool InvokeInstallPackage(string Filename, List <byte[]> CerCertificates, InstallMode Mode, bool ZipIsMetaOnly,
                                                out string ErrorText, out PKGStatus res, out PKGRecieptData Reciept, string OtherDLL = "")
        {
            ErrorText = "Internal issues";
            res       = PKGStatus.Failed;
            Reciept   = null;

            DataHInstallPackageTODO inst = new DataHInstallPackageTODO();

            inst.Filename        = Filename;
            inst.CerCertificates = CerCertificates;
            inst.Mode            = Mode;
            inst.ZipIsMetaOnly   = ZipIsMetaOnly;
            inst.OtherDLL        = OtherDLL;

            Process2ProcessComm p2p = new Process2ProcessComm();

            p2p.SetTODO("INSTALL", inst);
            if (p2p.StartPipe() == false)
            {
                FoxEventLog.WriteEventLog("Cannot start P2PC for INSTALL " + p2p.GetGUID(), EventLogEntryType.Error);
                return(false);
            }

            Process p = new Process();

            p.StartInfo.Arguments       = "-pipeaction " + p2p.GetGUID();
            p.StartInfo.FileName        = Assembly.GetExecutingAssembly().Location;
            p.StartInfo.UseShellExecute = false;
            if (p.Start() == false)
            {
                FoxEventLog.WriteEventLog("Cannot start P2PC Process for INSTALL " + p2p.GetGUID(), EventLogEntryType.Error);
                p2p.ClosePipe();
                return(false);
            }
            p.WaitForExit();

            DataHInstallPackageResult ores = p2p.GetResult <DataHInstallPackageResult>();

            p2p.ClosePipe();
            if (ores == null)
            {
                FoxEventLog.WriteEventLog("P2PC didn't return any data for INSTALL " + p2p.GetGUID(), EventLogEntryType.Error);
                return(false);
            }

            ErrorText = ores.ErrorText;
            res       = ores.res;
            Reciept   = ores.Reciept;
            if (ores.TempDLLFilename != null)
            {
                try
                {
                    File.Delete(ores.TempDLLFilename);
                }
                catch
                {
                }
            }

            return(ores.Return);
        }
Ejemplo n.º 19
0
        public static bool DoSyncEventLog()
        {
            try
            {
                Network net;
                net = Utilities.ConnectNetwork(0);
                if (net == null)
                {
                    return(false);
                }
                net.CloseConnection();

                Status.UpdateMessage(0, "Collecting EventLog data");
                lst        = new List <EventLogReport>();
                HasEVTLogs = new HashSet <string>();

                Status.UpdateMessage(0, "Collecting EventLog data (Application)");

                if (CollectEVT("Application") == false)
                {
                    return(false);
                }

                Status.UpdateMessage(0, "Collecting EventLog data (Security)");

                if (CollectEVT("Security") == false)
                {
                    return(false);
                }

                Status.UpdateMessage(0, "Collecting EventLog data (System)");

                if (CollectEVT("System") == false)
                {
                    return(false);
                }

                if (RegistryData.EnableAdditionalEventLogs == true)
                {
                    string AdditionalBooks = RegistryData.AdditionalEventLogs;
                    if (string.IsNullOrWhiteSpace(AdditionalBooks) == false)
                    {
                        foreach (string AdditionalBook in AdditionalBooks.Split('|'))
                        {
                            if (string.IsNullOrWhiteSpace(AdditionalBook) == true)
                            {
                                continue;
                            }
                            Status.UpdateMessage(0, "Collecting EventLog data (" + AdditionalBook + ")");
                            if (CollectEVT2(AdditionalBook) == false)
                            {
                                return(false);
                            }
                        }
                    }
                }

                Status.UpdateMessage(0, "Collecting EventLog data (Processing ...)");

                HashSet <string> RM = new HashSet <string>();

                foreach (string evt in FilesystemData.SyncedEventLog)
                {
                    if (HasEVTLogs.Contains(evt) == false)
                    {
                        RM.Add(evt);
                    }
                }

                foreach (string evt in RM)
                {
                    FilesystemData.SyncedEventLog.Remove(evt);
                }

                RM.Clear();

                List <EventLogReport> REP = new List <EventLogReport>();

                net = Utilities.ConnectNetwork(0);
                if (net == null)
                {
                    return(false);
                }

                Status.UpdateMessage(0, "Collecting EventLog data (Sending data ...)");

                Int64 UploadCounter = 0;
                foreach (EventLogReport evt in lst)
                {
                    UploadCounter++;
                    if (FilesystemData.SyncedEventLog.Contains(evt.LogID) == true)
                    {
                        continue;
                    }
                    REP.Add(evt);
                    if (REP.Count > 99)
                    {
                        Status.UpdateMessage(0, "Collecting EventLog data (Sending data ... " + UploadCounter.ToString() + " of " + lst.Count.ToString() + ")");

                        if (net.ReportEventLogs(REP) == false)
                        {
                            net.CloseConnection();
                            Status.UpdateMessage(0);
                            return(false);
                        }
                        foreach (EventLogReport rep in REP)
                        {
                            FilesystemData.SyncedEventLog.Add(rep.LogID);
                        }
                        FilesystemData.WriteEventLogList();
                        REP.Clear();
                    }
                }

                if (REP.Count > 0)
                {
                    Status.UpdateMessage(0, "Collecting EventLog data (Sending data ...)");

                    if (net.ReportEventLogs(REP) == false)
                    {
                        net.CloseConnection();
                        Status.UpdateMessage(0);
                        return(false);
                    }
                    foreach (EventLogReport rep in REP)
                    {
                        FilesystemData.SyncedEventLog.Add(rep.LogID);
                    }
                    FilesystemData.WriteEventLogList();
                    REP.Clear();
                }
                lst.Clear();
                HasEVTLogs.Clear();
                net.CloseConnection();
            }
            catch (Exception ee)
            {
                Debug.WriteLine(ee.ToString());
                FoxEventLog.WriteEventLog("Servere error while syncing Event Log Data: " + ee.ToString(), EventLogEntryType.Error);
            }
            Status.UpdateMessage(0);
            return(true);
        }