Example #1
0
        public static List <PolicyObject> GetPolicyForComputerInternal(SQLLib sql, string MachineID)
        {
            PolicyObjectList PolicyListSigned = new PolicyObjectList();

            PolicyListSigned.Items = new List <PolicyObject>();

            SqlDataReader dr;

            dr = sql.ExecSQLReader("SELECT * FROM Policies WHERE MachineID=@m AND Enabled=1",
                                   new SQLParam("@m", MachineID));
            while (dr.Read())
            {
                PolicyObject obj = LoadPolicyDB(dr, false, false);
                PolicyListSigned.Items.Add(obj);
            }
            dr.Close();

            Int64? GroupID = null;
            object sqlo    = sql.ExecSQLScalar("select Grouping from ComputerAccounts where MachineID=@m", new SQLParam("@m", MachineID));

            if (sqlo is DBNull || sqlo == null)
            {
                GroupID = null;
            }
            else
            {
                GroupID = Convert.ToInt64(sqlo);
            }

            do
            {
                dr = sql.ExecSQLReader("SELECT * FROM Policies WHERE " + (GroupID == null ? "Grouping is NULL" : "Grouping=@g") + " AND Enabled=1 AND MachineID is NULL",
                                       new SQLParam("@g", GroupID));
                while (dr.Read())
                {
                    PolicyObject obj = LoadPolicyDB(dr, false, false);
                    PolicyListSigned.Items.Add(obj);
                }
                dr.Close();

                if (GroupID != null)
                {
                    sqlo = sql.ExecSQLScalar("select ParentID FROM Grouping WHERE ID=@g", new SQLParam("@g", GroupID));
                    if (sqlo is DBNull || sqlo == null)
                    {
                        GroupID = null;
                    }
                    else
                    {
                        GroupID = Convert.ToInt64(sqlo);
                    }
                }
                else
                {
                    break;
                }
            } while (true);

            PolicyListSigned.Items.Reverse();
            Int64 Count = 1;

            foreach (PolicyObject p in PolicyListSigned.Items)
            {
                p.Order = Count;
                Count++;
            }

            #region Resolve Linked Policies for client

            for (int i = 0; i < PolicyListSigned.Items.Count; i++)
            {
                PolicyObject pol = PolicyListSigned.Items[i];
                if (pol.Type == PolicyIDs.LinkedPolicy)
                {
                    List <Int64> RunningIDs = new List <Int64>();

                    PolicyObject po = pol;

                    while (true)
                    {
                        if (RunningIDs.Contains(po.ID) == true)
                        {
                            FoxEventLog.WriteEventLog("Policy ID " + pol.ID.ToString() + " (" + pol.Name + ") creates a loop!", System.Diagnostics.EventLogEntryType.Warning);
                            break;
                        }

                        RunningIDs.Add(po.ID);

                        Int64 PolID;
                        po.Data = Convert.ToString(sql.ExecSQLScalar("SELECT DataBlob FROM Policies WHERE ID=@id",
                                                                     new SQLParam("@id", po.ID)));
                        if (Int64.TryParse(po.Data, out PolID) == false)
                        {
                            FoxEventLog.WriteEventLog("Cannot read data of policy ID " + po.ID.ToString() + " (" + po.Name + ") for linking.", System.Diagnostics.EventLogEntryType.Warning);
                            break;
                        }

                        if (Policies.PolicyExsits(sql, PolID) == false)
                        {
                            FoxEventLog.WriteEventLog("Policy ID " + PolID.ToString() + " referencing from " + po.ID.ToString() + " (" + po.Name + ") does not exist.", System.Diagnostics.EventLogEntryType.Warning);
                            break;
                        }

                        if (Convert.ToInt32(sql.ExecSQLScalar("SELECT Enabled FROM Policies WHERE ID=@id", new SQLParam("@id", PolID))) != 1)
                        {
                            break;
                        }

                        dr = sql.ExecSQLReader("SELECT * FROM Policies WHERE ID=@id",
                                               new SQLParam("@id", PolID));
                        dr.Read();
                        po = LoadPolicyDB(dr, false, false);
                        dr.Close();
                        if (po == null)
                        {
                            FoxEventLog.WriteEventLog("Cannot read policy ID for linking " + PolID.ToString(), System.Diagnostics.EventLogEntryType.Warning);
                            break;
                        }
                        if (po.Type != PolicyIDs.LinkedPolicy)
                        {
                            pol = po;
                            PolicyListSigned.Items[i] = po;
                            break;
                        }
                    }
                }
            }

            #endregion

            return(PolicyListSigned.Items);
        }
Example #2
0
        public RESTStatus ReportStatups(SQLLib sql, ListStartupItems StartupList, NetworkConnectionInfo ni)
        {
            if (ni.HasAcl(ACLFlags.ComputerLogin) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;
                return(RESTStatus.Denied);
            }

            StartupList.MachineID = ni.Username;

            lock (ni.sqllock)
            {
                if (Convert.ToInt32(sql.ExecSQLScalar("SELECT COUNT(*) FROM ComputerAccounts WHERE MachineID=@m",
                                                      new SQLParam("@m", StartupList.MachineID))) == 0)
                {
                    ni.Error   = "Invalid MachineID";
                    ni.ErrorID = ErrorFlags.InvalidValue;
                    return(RESTStatus.Denied);
                }
            }

            if (StartupList.Items == null)
            {
                ni.Error   = "Invalid Items";
                ni.ErrorID = ErrorFlags.InvalidValue;
                return(RESTStatus.Fail);
            }
            if (StartupList.SIDUsers == null)
            {
                StartupList.SIDUsers = new List <string>();
            }

            foreach (StartupItem rep in StartupList.Items)
            {
                if (string.IsNullOrWhiteSpace(rep.Location) == true)
                {
                    ni.Error   = "Invalid Items";
                    ni.ErrorID = ErrorFlags.InvalidValue;
                    return(RESTStatus.Fail);
                }
                if (string.IsNullOrWhiteSpace(rep.Key) == true)
                {
                    ni.Error   = "Invalid Items";
                    ni.ErrorID = ErrorFlags.InvalidValue;
                    return(RESTStatus.Fail);
                }

                if (string.IsNullOrWhiteSpace(rep.HKCUUser) == true)
                {
                    rep.HKCUUser = "";
                }
                if (string.IsNullOrWhiteSpace(rep.Item) == true)
                {
                    rep.Item = "";
                }
            }

            List <StartupItem> Installed = new List <StartupItem>();
            List <StartupItem> Reported  = StartupList.Items;

            lock (ni.sqllock)
            {
                SqlDataReader dr = sql.ExecSQLReader("SELECT * FROM Startups WHERE MachineID=@id", new SQLParam("@id", StartupList.MachineID));
                while (dr.Read())
                {
                    StartupItem ar = new StartupItem();
                    ar.Location = Convert.ToString(dr["Location"]);
                    ar.Key      = Convert.ToString(dr["Key"]);
                    ar.Item     = Convert.ToString(dr["Item"]);
                    ar.HKCUUser = Convert.ToString(dr["HKCUUser"]);
                    if (string.IsNullOrWhiteSpace(ar.HKCUUser) == true)
                    {
                        ar.HKCUUser = "";
                    }

                    Installed.Add(ar);
                }
                dr.Close();
            }

            List <StartupItem> Updated   = new List <StartupItem>();
            List <StartupItem> Unchanged = new List <StartupItem>();
            List <StartupItem> Removed   = new List <StartupItem>();
            List <StartupItem> Added     = new List <StartupItem>();

            foreach (StartupItem inst in Installed)
            {
                inst.Location = inst.Location.Trim();
                inst.Key      = inst.Key.Trim();
                inst.Item     = inst.Item.Trim();
                inst.HKCUUser = inst.HKCUUser.Trim();

                bool Found = false;
                foreach (StartupItem rep in Reported)
                {
                    rep.Location = rep.Location.Trim();
                    rep.Key      = rep.Key.Trim();
                    rep.Item     = rep.Item.Trim();
                    rep.HKCUUser = rep.HKCUUser.Trim();

                    if (rep.Location.ToLower() == inst.Location.ToLower() && rep.Key == inst.Key && rep.HKCUUser == inst.HKCUUser)
                    {
                        if (rep.Item.ToLower() == inst.Item.ToLower())
                        {
                            Unchanged.Add(rep);
                            Found = true;
                            break;
                        }
                        else
                        {
                            Updated.Add(rep);
                            Found = true;
                            break;
                        }
                    }
                }
                if (Found == false)
                {
                    if (inst.HKCUUser != "" && StartupList.SIDUsers.Contains(inst.HKCUUser, StringComparer.InvariantCultureIgnoreCase) == false)
                    {
                        //likely that this user is not logged on or such
                        Unchanged.Add(inst);
                    }
                    else
                    {
                        Removed.Add(inst);
                    }
                }
            }

            foreach (StartupItem inst in Reported)
            {
                bool Found = false;
                foreach (StartupItem rep in Installed)
                {
                    if (rep.Key.ToLower() == inst.Key.ToLower() && rep.Location == inst.Location && rep.HKCUUser == inst.HKCUUser)
                    {
                        Found = true;
                        break;
                    }
                }
                if (Found == false)
                {
                    Added.Add(inst);
                }
            }

            lock (ni.sqllock)
            {
                try
                {
                    sql.BeginTransaction();
                    sql.SEHError = true;
                    foreach (StartupItem ar in Removed)
                    {
                        sql.ExecSQL("DELETE FROM Startups WHERE MachineID=@id AND [Key]=@key AND Location=@location AND HKCUUser=@user",
                                    new SQLParam("@id", StartupList.MachineID),
                                    new SQLParam("@key", ar.Key),
                                    new SQLParam("@user", ar.HKCUUser),
                                    new SQLParam("@location", ar.Location));
                    }
                    foreach (StartupItem ar in Updated)
                    {
                        sql.ExecSQL(@"UPDATE Startups SET
                            Item=@item,
                            DT=@DT
                            WHERE MachineID=@id AND [Key]=@key AND Location=@location AND HKCUUser=@user",
                                    new SQLParam("@id", StartupList.MachineID),
                                    new SQLParam("@key", ar.Key),
                                    new SQLParam("@user", ar.HKCUUser),
                                    new SQLParam("@location", ar.Location),
                                    new SQLParam("@item", ar.Item),
                                    new SQLParam("@DT", DateTime.UtcNow));
                    }
                    foreach (StartupItem ar in Added)
                    {
                        sql.InsertMultiData("Startups",
                                            new SQLData("MachineID", StartupList.MachineID),
                                            new SQLData("Item", ar.Item),
                                            new SQLData("Location", ar.Location),
                                            new SQLData("Key", ar.Key),
                                            new SQLData("HKCUUser", ar.HKCUUser),
                                            new SQLData("DT", DateTime.UtcNow));
                    }
                    sql.CommitTransaction();
                }
                catch (Exception ee)
                {
                    sql.RollBackTransaction();
                    FoxEventLog.WriteEventLog("DB Error: Cannot update Startups: " + ee.ToString(), System.Diagnostics.EventLogEntryType.Error);
                    return(RESTStatus.ServerError);
                }
                finally
                {
                    sql.SEHError = false;
                }
            }

            StartupLst l = new StartupLst();

            l.Added     = Added;
            l.Removed   = Removed;
            l.Unchanged = Unchanged;
            l.Updated   = Updated;
            l.MachineID = StartupList.MachineID;
            Thread t = new Thread(new ParameterizedThreadStart(new DReportingThread(ReportingThread)));

            t.Start(l);

            return(RESTStatus.Created);
        }
Example #3
0
        void ReportingThread(object AddRemoveProgramsListO)
        {
            try
            {
                using (SQLLib sql = SQLTest.ConnectSQL("Fox SDC Server for AddRemovePrograms Data"))
                {
                    if (sql == null)
                    {
                        FoxEventLog.WriteEventLog("Cannot connect to SQL Server for AddRemovePrograms Reporting!", System.Diagnostics.EventLogEntryType.Error);
                        return;
                    }

                    AddRemoveProgramsLst AddRemoveProgramsList = (AddRemoveProgramsLst)AddRemoveProgramsListO;
                    ComputerData         computerdata          = Computers.GetComputerDetail(sql, AddRemoveProgramsList.MachineID);
                    if (computerdata == null)
                    {
                        FoxEventLog.WriteEventLog("Cannot get any computer data for AddRemovePrograms Reporting!", System.Diagnostics.EventLogEntryType.Error);
                        return;
                    }

                    List <PolicyObject>        Pol             = Policies.GetPolicyForComputerInternal(sql, AddRemoveProgramsList.MachineID);
                    Dictionary <string, Int64> AlreadyReported = new Dictionary <string, long>();
                    foreach (PolicyObject PolO in Pol)
                    {
                        if (PolO.Type != PolicyIDs.ReportingPolicy)
                        {
                            continue;
                        }
                        ReportingPolicyElement RepElementRoot = JsonConvert.DeserializeObject <ReportingPolicyElement>(Policies.GetPolicy(sql, PolO.ID).Data);
                        if (RepElementRoot.Type != ReportingPolicyType.AddRemovePrograms)
                        {
                            continue;
                        }
                        if (RepElementRoot.ReportToAdmin == null)
                        {
                            RepElementRoot.ReportToAdmin = false;
                        }
                        if (RepElementRoot.ReportToClient == null)
                        {
                            RepElementRoot.ReportToClient = false;
                        }
                        if (RepElementRoot.UrgentForAdmin == null)
                        {
                            RepElementRoot.UrgentForAdmin = false;
                        }
                        if (RepElementRoot.UrgentForClient == null)
                        {
                            RepElementRoot.UrgentForClient = false;
                        }
                        if (RepElementRoot.ReportToAdmin == false && RepElementRoot.ReportToClient == false && RepElementRoot.UrgentForAdmin == false && RepElementRoot.UrgentForClient == false)
                        {
                            continue;
                        }

                        foreach (string Element in RepElementRoot.ReportingElements)
                        {
                            ReportingPolicyElementAddRemovePrograms arprep = JsonConvert.DeserializeObject <ReportingPolicyElementAddRemovePrograms>(Element);
                            if (arprep.NotifyOnAdd == false && arprep.NotifyOnRemove == false && arprep.NotifyOnUpdate == false)
                            {
                                continue;
                            }

                            if (arprep.NotifyOnAdd == true)
                            {
                                foreach (AddRemoveApp ar in GetFilteredData(AddRemoveProgramsList.Added, computerdata, arprep))
                                {
                                    ReportThings(sql, AddRemoveProgramsList.MachineID, "Add", ar, ref AlreadyReported, RepElementRoot);
                                }
                            }

                            if (arprep.NotifyOnUpdate == true)
                            {
                                foreach (AddRemoveApp ar in GetFilteredData(AddRemoveProgramsList.Updated, computerdata, arprep))
                                {
                                    ReportThings(sql, AddRemoveProgramsList.MachineID, "Update", ar, ref AlreadyReported, RepElementRoot);
                                }
                            }

                            if (arprep.NotifyOnRemove == true)
                            {
                                foreach (AddRemoveApp ar in GetFilteredData(AddRemoveProgramsList.Removed, computerdata, arprep))
                                {
                                    ReportThings(sql, AddRemoveProgramsList.MachineID, "Remove", ar, ref AlreadyReported, RepElementRoot);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ee)
            {
                FoxEventLog.WriteEventLog("SEH in AddRemovePrograms Reporting " + ee.ToString(), System.Diagnostics.EventLogEntryType.Error);
            }
        }
Example #4
0
        public RESTStatus GetPolicyForComputer(SQLLib sql, object dummy, NetworkConnectionInfo ni)
        {
            if (ni.HasAcl(ACLFlags.ComputerLogin) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;
                return(RESTStatus.Denied);
            }

            PolicyListSigned       = new PolicyObjectListSigned();
            PolicyListSigned.Items = new List <PolicyObjectSigned>();

            string MachineID = ni.Username;

            lock (ni.sqllock)
            {
                SqlDataReader dr = sql.ExecSQLReader("SELECT * FROM Policies WHERE MachineID=@m AND Enabled=1 AND Type not in (" + PolicyIDs.HiddenPoliciesSQLINClause + ")",
                                                     new SQLParam("@m", MachineID));
                while (dr.Read())
                {
                    PolicyObject       obj  = LoadPolicyDB(dr, false, true);
                    PolicyObjectSigned objs = new PolicyObjectSigned();
                    objs.Policy = obj;
                    if (Certificates.Sign(objs, SettingsManager.Settings.UseCertificate) == false)
                    {
                        FoxEventLog.WriteEventLog("Cannot sign policy with Certificate " + SettingsManager.Settings.UseCertificate, System.Diagnostics.EventLogEntryType.Warning);
                        ni.Error   = "Cannot sign policy with Certificate " + SettingsManager.Settings.UseCertificate;
                        ni.ErrorID = ErrorFlags.CannotSign;
                        dr.Close();
                        return(RESTStatus.ServerError);
                    }
                    PolicyListSigned.Items.Add(objs);
                }
                dr.Close();
            }

            Int64? GroupID = null;
            object sqlo    = sql.ExecSQLScalar("select Grouping from ComputerAccounts where MachineID=@m", new SQLParam("@m", MachineID));

            if (sqlo is DBNull || sqlo == null)
            {
                GroupID = null;
            }
            else
            {
                GroupID = Convert.ToInt64(sqlo);
            }

            do
            {
                lock (ni.sqllock)
                {
                    SqlDataReader dr = sql.ExecSQLReader("SELECT * FROM Policies WHERE " + (GroupID == null ? "Grouping is NULL" : "Grouping=@g") + " AND Enabled=1 AND Type NOT IN (" + PolicyIDs.HiddenPoliciesSQLINClause + ") AND MachineID is NULL",
                                                         new SQLParam("@g", GroupID));
                    while (dr.Read())
                    {
                        PolicyObject       obj  = LoadPolicyDB(dr, false, true);
                        PolicyObjectSigned objs = new PolicyObjectSigned();
                        objs.Policy = obj;
                        PolicyListSigned.Items.Add(objs);
                    }
                    dr.Close();
                }

                if (GroupID != null)
                {
                    lock (ni.sqllock)
                    {
                        sqlo = sql.ExecSQLScalar("select ParentID FROM Grouping WHERE ID=@g", new SQLParam("@g", GroupID));
                    }

                    if (sqlo is DBNull || sqlo == null)
                    {
                        GroupID = null;
                    }
                    else
                    {
                        GroupID = Convert.ToInt64(sqlo);
                    }
                }
                else
                {
                    break;
                }
            } while (true);

            PolicyListSigned.Items.Reverse();
            Int64 Count = 1;

            foreach (PolicyObjectSigned p in PolicyListSigned.Items)
            {
                p.Policy.Order = Count;
                Count++;
                if (Certificates.Sign(p, SettingsManager.Settings.UseCertificate) == false)
                {
                    FoxEventLog.WriteEventLog("Cannot sign policy with Certificate " + SettingsManager.Settings.UseCertificate, System.Diagnostics.EventLogEntryType.Warning);
                    ni.Error   = "Cannot sign policy with Certificate " + SettingsManager.Settings.UseCertificate;
                    ni.ErrorID = ErrorFlags.CannotSign;
                    return(RESTStatus.ServerError);
                }
            }

            List <PolicyObjectSigned> RemoveFromList = new List <PolicyObjectSigned>();

            #region Resolve Linked Policies for client

            for (int i = 0; i < PolicyListSigned.Items.Count; i++)
            {
                PolicyObjectSigned pol = PolicyListSigned.Items[i];
                if (pol.Policy.Type == PolicyIDs.LinkedPolicy)
                {
                    List <Int64> RunningIDs = new List <Int64>();

                    PolicyObject po = pol.Policy;

                    while (true)
                    {
                        if (RunningIDs.Contains(po.ID) == true)
                        {
                            FoxEventLog.WriteEventLog("Policy ID " + pol.Policy.ID.ToString() + " (" + pol.Policy.Name + ") creates a loop!", System.Diagnostics.EventLogEntryType.Warning);
                            break;
                        }

                        RunningIDs.Add(po.ID);

                        lock (ni.sqllock)
                        {
                            po.Data = Convert.ToString(sql.ExecSQLScalar("SELECT DataBlob FROM Policies WHERE ID=@id",
                                                                         new SQLParam("@id", po.ID)));
                        }

                        Int64 PolID;
                        if (Int64.TryParse(po.Data, out PolID) == false)
                        {
                            FoxEventLog.WriteEventLog("Cannot read data of policy ID " + po.ID.ToString() + " (" + po.Name + ") for linking.", System.Diagnostics.EventLogEntryType.Warning);
                            break;
                        }

                        lock (ni.sqllock)
                        {
                            if (Policies.PolicyExsits(sql, PolID) == false)
                            {
                                FoxEventLog.WriteEventLog("Policy ID " + PolID.ToString() + " referencing from " + po.ID.ToString() + " (" + po.Name + ") does not exist.", System.Diagnostics.EventLogEntryType.Warning);
                                break;
                            }
                        }

                        lock (ni.sqllock)
                        {
                            if (Convert.ToInt32(sql.ExecSQLScalar("SELECT Enabled FROM Policies WHERE ID=@id", new SQLParam("@id", PolID))) != 1)
                            {
                                break;
                            }
                        }

                        lock (ni.sqllock)
                        {
                            SqlDataReader dr = sql.ExecSQLReader("SELECT * FROM Policies WHERE ID=@id",
                                                                 new SQLParam("@id", PolID));
                            dr.Read();
                            po = LoadPolicyDB(dr, false, true);
                            dr.Close();
                        }

                        if (po == null)
                        {
                            FoxEventLog.WriteEventLog("Cannot read policy ID for linking " + PolID.ToString(), System.Diagnostics.EventLogEntryType.Warning);
                            break;
                        }

                        if (po.Type != PolicyIDs.LinkedPolicy)
                        {
                            if (PolicyIDs.HiddenPolicies.Contains(po.Type) == true)
                            {
                                pol.Policy    = null;
                                pol.Signature = null;
                                break;
                            }
                            else
                            {
                                pol.Policy    = po;
                                pol.Signature = null;
                                break;
                            }
                        }
                    }

                    if (pol.Policy != null)
                    {
                        if (Certificates.Sign(pol, SettingsManager.Settings.UseCertificate) == false)
                        {
                            FoxEventLog.WriteEventLog("Cannot sign policy with Certificate " + SettingsManager.Settings.UseCertificate, System.Diagnostics.EventLogEntryType.Warning);
                            ni.Error   = "Cannot sign policy with Certificate " + SettingsManager.Settings.UseCertificate;
                            ni.ErrorID = ErrorFlags.CannotSign;
                            return(RESTStatus.ServerError);
                        }
                    }
                    else
                    {
                        RemoveFromList.Add(pol);
                    }
                }
            }

            foreach (PolicyObjectSigned pos in RemoveFromList)
            {
                PolicyListSigned.Items.Remove(pos);
            }

            #endregion

            if (Certificates.Sign(PolicyListSigned, SettingsManager.Settings.UseCertificate) == false)
            {
                FoxEventLog.WriteEventLog("Cannot sign policy list with Certificate " + SettingsManager.Settings.UseCertificate, System.Diagnostics.EventLogEntryType.Warning);
                ni.Error   = "Cannot sign policy list with Certificate " + SettingsManager.Settings.UseCertificate;
                ni.ErrorID = ErrorFlags.CannotSign;
                return(RESTStatus.ServerError);
            }

            return(RESTStatus.Success);
        }
Example #5
0
        public RESTStatus ComputerLogin(SQLLib sql, ComputerLogon logon, NetworkConnectionInfo ni, string IPAddress)
        {
            Err = new ErrorInfo();

            if (logon == null)
            {
                Err.Error   = "Faulty data";
                Err.ErrorID = (int)ErrorFlags.FaultyData;
                return(RESTStatus.Fail);
            }

            if (NullTest.Test(logon) == false)
            {
                Err.Error   = "Invalid data";
                Err.ErrorID = (int)ErrorFlags.InvalidData;
                return(RESTStatus.Fail);
            }

            if (logon.SysInfo != null)
            {
                if (logon.SysInfo.BIOSType == null)
                {
                    logon.SysInfo.BIOSType = "N/A";
                }
                if (logon.SysInfo.CPUName == null)
                {
                    logon.SysInfo.CPUName = "N/A";
                }
                if (logon.SysInfo.SecureBootState == null)
                {
                    logon.SysInfo.SecureBootState = "N/A";
                }
                if (logon.SysInfo.ComputerModel == null)
                {
                    logon.SysInfo.ComputerModel = "N/A";
                }
                if (logon.SysInfo.ComputerModel.Trim() == "")
                {
                    logon.SysInfo.ComputerModel = "N/A";
                }
                if (logon.SysInfo.SystemRoot == null)
                {
                    logon.SysInfo.SystemRoot = "C:\\Windows";
                }
                if (logon.SysInfo.SUSID == null)
                {
                    logon.SysInfo.SUSID = "";
                }
                if (logon.SysInfo.SUSID.Trim() == "")
                {
                    logon.SysInfo.SUSID = Consts.NullGUID;
                }
                if (logon.SysInfo.LegacyUCID == null)
                {
                    logon.SysInfo.LegacyUCID = Consts.NullUCID;
                }
            }

            if (NullTest.Test(logon.SysInfo, "IsMeteredConnection", "RunningInWindowsPE") == false)
            {
                Err.Error   = "Invalid data";
                Err.ErrorID = (int)ErrorFlags.InvalidData;
                return(RESTStatus.Fail);
            }

            if (string.IsNullOrWhiteSpace(logon.Password) == true || string.IsNullOrWhiteSpace(logon.Username) == true)
            {
                Err.Error   = "Invalid data";
                Err.ErrorID = (int)ErrorFlags.InvalidData;
                return(RESTStatus.Fail);
            }

            if (NullTest.TestBlankString(logon.SysInfo, "IsMeteredConnection", "RunningInWindowsPE") == false)
            {
                Err.Error   = "Invalid data";
                Err.ErrorID = (int)ErrorFlags.InvalidData;
                return(RESTStatus.Fail);
            }

            Guid testguid;

            if (Guid.TryParse(logon.Username, out testguid) == false)
            {
                Err.Error   = "Invalid username";
                Err.ErrorID = (int)ErrorFlags.InvalidUsername;
                return(RESTStatus.Fail);
            }

            if (Guid.TryParse(logon.Password, out testguid) == false)
            {
                Err.Error   = "Invalid password";
                Err.ErrorID = (int)ErrorFlags.InvalidPassword;
                return(RESTStatus.Fail);
            }

            if (logon.SysInfo.UCID.Trim().Length != 32)
            {
                Err.Error   = "Invalid UCID";
                Err.ErrorID = (int)ErrorFlags.InvalidValue;
                return(RESTStatus.Fail);
            }

            if (logon.ContractID == null)
            {
                logon.ContractID = "";
            }
            if (logon.ContractPassword == null)
            {
                logon.ContractPassword = "";
            }

            if (Fox_LicenseGenerator.SDCLicensing.ValidLicense == false)
            {
                FoxEventLog.WriteEventLog("Licensing error: no valid license found. Client login are rejected.", EventLogEntryType.Warning);
                Err.Error   = "Licensing error";
                Err.ErrorID = (int)ErrorFlags.LicensingError;
                return(RESTStatus.Fail);
            }

            if (Fox_LicenseGenerator.SDCLicensing.TestExpiry() == false)
            {
                FoxEventLog.WriteEventLog("Licensing error: license expired. Client login are rejected.", EventLogEntryType.Warning);
                Err.Error   = "Licensing error";
                Err.ErrorID = (int)ErrorFlags.LicensingError;
                return(RESTStatus.Fail);
            }

            if (Settings.Default.UseContract == true)
            {
                if (logon.ContractID == "")
                {
                    Err.Error   = "Invalid Contract Data";
                    Err.ErrorID = (int)ErrorFlags.FaultyContractData;
                    return(RESTStatus.Fail);
                }
                if (logon.ContractPassword == "")
                {
                    Err.Error   = "Invalid Contract Data";
                    Err.ErrorID = (int)ErrorFlags.FaultyContractData;
                    return(RESTStatus.Fail);
                }
            }

            logon.Username          = logon.Username.Trim().ToUpper();
            logon.SysInfo.MachineID = logon.SysInfo.MachineID.Trim().ToUpper();

            if (logon.Username != logon.SysInfo.MachineID)
            {
                Err.Error   = "Invalid Username/MachineID";
                Err.ErrorID = (int)ErrorFlags.InvalidValue;
                return(RESTStatus.Fail);
            }

            string newID = NetworkConnection.NewSession();

            ni = NetworkConnection.GetSession(newID);
            if (NetworkConnectionProcessor.InitNi(ni) == false)
            {
                NetworkConnection.DeleteSession(newID);
                Err.Error   = "System Error";
                Err.ErrorID = (int)ErrorFlags.SystemError;
                return(RESTStatus.ServerError);
            }
            sql = ni.sql;

            ni.Permissions = 0;
            ni.Error       = "";
            ni.ErrorID     = ErrorFlags.NoError;

            if (Fox_LicenseGenerator.SDCLicensing.NumComputers != null)
            {
                Int64 Computers = Convert.ToInt64(sql.ExecSQLScalar("select count(*) from ComputerAccounts where Accepted=1"));
                if (Computers > Fox_LicenseGenerator.SDCLicensing.NumComputers.Value)
                {
                    NetworkConnection.DeleteSession(newID);
                    FoxEventLog.WriteEventLog("Licensing error: too many computers are accepted. Client login are rejected.\n" +
                                              "Lic=" + Fox_LicenseGenerator.SDCLicensing.NumComputers.Value.ToString() + " Listed=" + Computers.ToString(),
                                              EventLogEntryType.Warning);
                    Err.Error   = "Licensing error";
                    Err.ErrorID = (int)ErrorFlags.LicensingError;
                    return(RESTStatus.Fail);
                }
            }

            if (Settings.Default.UseContract == true)
            {
                if (Convert.ToInt32(sql.ExecSQLScalar("SELECT Count(*) FROM Contracts WHERE ContractID=@id AND ContractPassword=@pw AND Disabled=0",
                                                      new SQLParam("@id", logon.ContractID),
                                                      new SQLParam("@pw", logon.ContractPassword))) == 0)
                {
                    NetworkConnection.DeleteSession(newID);
                    Err.Error   = "Invalid/Disabled Contract Data";
                    Err.ErrorID = (int)ErrorFlags.FaultyContractData;
                    return(RESTStatus.Fail);
                }
            }

            if (Convert.ToInt32(sql.ExecSQLScalar("SELECT COUNT(*) FROM ComputerAccounts WHERE MachineID=@m",
                                                  new SQLParam("@m", logon.Username))) == 0)
            {
                if (Convert.ToInt32(sql.ExecSQLScalar("SELECT COUNT(*) FROM ComputerAccounts WHERE UCID=@u",
                                                      new SQLParam("@u", logon.SysInfo.UCID.Trim()))) > 0)
                {
                    NetworkConnection.DeleteSession(newID);
                    Err.Error   = "UCID used for a different machine";
                    Err.ErrorID = (int)ErrorFlags.UCIDissues;
                    return(RESTStatus.Fail);
                }

                if (Settings.Default.UseContract == true)
                {
                    object o = sql.ExecSQLScalar("Select MaxComputers FROM Contracts WHERE ContractID=@cid", new SQLParam("@cid", logon.ContractID));
                    if (!(o is DBNull))
                    {
                        int i;
                        if (int.TryParse(o.ToString(), out i) == true)
                        {
                            int cnt = Convert.ToInt32(sql.ExecSQL("Select count(*) FROM ComputerAccounts WHERE ContractID=@cid", new SQLParam("@cid", logon.ContractID)));
                            if (cnt + 1 > i)
                            {
                                NetworkConnection.DeleteSession(newID);
                                Err.Error   = "Number of computers exhausted";
                                Err.ErrorID = (int)ErrorFlags.ContractNumComputersExhausted;
                                return(RESTStatus.Fail);
                            }
                        }
                    }
                }

                sql.InsertMultiData("ComputerAccounts",
                                    new SQLData("MachineID", logon.SysInfo.MachineID),
                                    new SQLData("UCID", logon.SysInfo.UCID),
                                    new SQLData("Password", logon.Password),
                                    new SQLData("Is64Bit", logon.SysInfo.Is64Bit),
                                    new SQLData("OSName", logon.SysInfo.OSName),
                                    new SQLData("OSVerMaj", logon.SysInfo.OSVerMaj),
                                    new SQLData("OSVerMin", logon.SysInfo.OSVerMin),
                                    new SQLData("OSVerBuild", logon.SysInfo.OSVerBuild),
                                    new SQLData("OSSuite", logon.SysInfo.OSSuite),
                                    new SQLData("IsTSE", logon.SysInfo.IsTSE),
                                    new SQLData("CPU", logon.SysInfo.CPU),
                                    new SQLData("ComputerModel", logon.SysInfo.ComputerModel),
                                    new SQLData("ComputerName", logon.SysInfo.ComputerName),
                                    new SQLData("Language", logon.SysInfo.Language),
                                    new SQLData("DisplayLanguage", logon.SysInfo.DisplayLanguage),
                                    new SQLData("AgentVersion", logon.SysInfo.AgentVersion),
                                    new SQLData("AgentVersionID", logon.SysInfo.AgentVersionID),
                                    new SQLData("OSVerType", logon.SysInfo.OSVerType),
                                    new SQLData("RunningInHypervisor", logon.SysInfo.RunningInHypervisor),
                                    new SQLData("BIOS", logon.SysInfo.BIOS),
                                    new SQLData("BIOSType", logon.SysInfo.BIOSType),
                                    new SQLData("NumberOfLogicalProcessors", logon.SysInfo.NumberOfLogicalProcessors),
                                    new SQLData("NumberOfProcessors", logon.SysInfo.NumberOfProcessors),
                                    new SQLData("TotalPhysicalMemory", logon.SysInfo.TotalPhysicalMemory),
                                    new SQLData("CPUName", logon.SysInfo.CPUName),
                                    new SQLData("SecureBootState", logon.SysInfo.SecureBootState),
                                    new SQLData("IPAddress", IPAddress),
                                    new SQLData("SystemRoot", logon.SysInfo.SystemRoot),
                                    new SQLData("SUSID", logon.SysInfo.SUSID),
                                    new SQLData("MeteredConnection", logon.SysInfo.IsMeteredConnection),
                                    new SQLData("RunningInWindowsPE", logon.SysInfo.RunningInWindowsPE),
                                    new SQLData("ContractID", Settings.Default.UseContract == true ? (object)logon.ContractID : DBNull.Value));

                Err.Error   = "Not accepted (computer registered)";
                Err.ErrorID = (int)ErrorFlags.NotAccepted;
                NetworkConnection.DeleteSession(newID);
                return(RESTStatus.Fail);
            }

            if (Convert.ToInt32(sql.ExecSQLScalar("SELECT COUNT(*) FROM ComputerAccounts WHERE MachineID=@m AND UCID=@ucid",
                                                  new SQLParam("@m", logon.Username),
                                                  new SQLParam("@ucid", logon.SysInfo.UCID.Trim()))) == 0)
            {
                #region Remove in future
                if (logon.SysInfo.LegacyUCID != Consts.NullUCID && logon.SysInfo.LegacyUCID.Trim().Length == 32)
                {
                    if (Convert.ToInt32(sql.ExecSQLScalar("SELECT COUNT(*) FROM ComputerAccounts WHERE UCID=@u AND MachineID=@m AND Password=@p",
                                                          new SQLParam("@u", logon.SysInfo.LegacyUCID.Trim()),
                                                          new SQLParam("@p", logon.Password),
                                                          new SQLParam("@m", logon.Username))) > 0)
                    {
                        sql.ExecSQL("UPDATE ComputerAccounts SET UCID=@nu WHERE UCID=@u AND MachineID=@m",
                                    new SQLParam("@nu", logon.SysInfo.UCID.Trim()),
                                    new SQLParam("@u", logon.SysInfo.LegacyUCID.Trim()),
                                    new SQLParam("@m", logon.Username));

                        FoxEventLog.WriteEventLog("UCID changed:\nMachineID: " + logon.Username + "\nName: " + logon.SysInfo.ComputerName + "\nLUCID: " + logon.SysInfo.LegacyUCID + "\nUCID: " + logon.SysInfo.UCID, EventLogEntryType.Warning);

                        Err.Error   = "UCID changed!";
                        Err.ErrorID = (int)ErrorFlags.NotAccepted;
                        NetworkConnection.DeleteSession(newID);
                        return(RESTStatus.Fail);
                    }
                }
                #endregion

                Err.Error   = "MachineID & UCID do not match";
                Err.ErrorID = (int)ErrorFlags.MachineUCIDmissmatch;
                NetworkConnection.DeleteSession(newID);
                return(RESTStatus.Fail);
            }

            if (Convert.ToInt32(sql.ExecSQLScalar("SELECT COUNT(*) FROM ComputerAccounts WHERE MachineID=@m AND Password=@p",
                                                  new SQLParam("@m", logon.Username),
                                                  new SQLParam("@p", logon.Password))) == 0)
            {
                Err.Error   = "Invalid password";
                Err.ErrorID = (int)ErrorFlags.InvalidPassword;
                NetworkConnection.DeleteSession(newID);
                return(RESTStatus.Fail);
            }

            if (Settings.Default.UseContract == true)
            {
                string CurrentContractID = Convert.ToString(sql.ExecSQLScalar("SELECT ContractID FROM ComputerAccounts WHERE MachineID=@m",
                                                                              new SQLParam("@m", logon.Username)));
                if (CurrentContractID == null)
                {
                    CurrentContractID = "";
                }
                if (CurrentContractID != "")
                {
                    if (CurrentContractID.Trim().ToLower() != logon.ContractID.Trim().ToLower())
                    {
                        Err.Error   = "Invalid Contract Data";
                        Err.ErrorID = (int)ErrorFlags.FaultyContractData;
                        NetworkConnection.DeleteSession(newID);
                        return(RESTStatus.Fail);
                    }
                }

                object   dt;
                DateTime dtt;

                dt = sql.ExecSQLScalar("Select ValidFrom FROM Contracts WHERE ContractID=@cid", new SQLParam("@cid", CurrentContractID));
                if (!(dt is DBNull))
                {
                    try
                    {
                        dtt = SQLLib.GetDTUTC(dt);
                        if (DateTime.UtcNow < dtt)
                        {
                            Err.Error   = "Contract not started / expired";
                            Err.ErrorID = (int)ErrorFlags.ContractNotStarted_Expired;
                            NetworkConnection.DeleteSession(newID);
                            return(RESTStatus.Fail);
                        }
                    }
                    catch
                    {
                        Err.Error   = "Invalid Contract Data";
                        Err.ErrorID = (int)ErrorFlags.FaultyContractData;
                        NetworkConnection.DeleteSession(newID);
                        return(RESTStatus.Fail);
                    }
                }

                dt = sql.ExecSQLScalar("Select ValidTo FROM Contracts WHERE ContractID=@cid", new SQLParam("@cid", CurrentContractID));
                if (!(dt is DBNull))
                {
                    try
                    {
                        dtt = SQLLib.GetDTUTC(dt);
                        if (dtt < DateTime.UtcNow)
                        {
                            Err.Error   = "Contract not started / expired";
                            Err.ErrorID = (int)ErrorFlags.ContractNotStarted_Expired;
                            NetworkConnection.DeleteSession(newID);
                            return(RESTStatus.Fail);
                        }
                    }
                    catch
                    {
                        Err.Error   = "Invalid Contract Data";
                        Err.ErrorID = (int)ErrorFlags.FaultyContractData;
                        NetworkConnection.DeleteSession(newID);
                        return(RESTStatus.Fail);
                    }
                }
            }
            else
            {
                logon.ContractID       = "";
                logon.ContractPassword = "";
            }

            sql.ExecSQL("UPDATE ComputerAccounts SET BIOS=@BIOS, OSVerType=@OSVerType, Is64Bit = @Is64Bit,OSName = @OSName,OSVerMaj = @OSVerMaj," +
                        "OSVerMin = @OSVerMin,OSVerBuild = @OSVerBuild,OSSuite = @OSSuite,IsTSE = @IsTSE,CPU = @CPU,ComputerModel = @ComputerModel,ComputerName = @ComputerName," +
                        "Language = @Language,DisplayLanguage = @DisplayLanguage,MachineID = @MachineID,LastUpdated = getutcdate(), AgentVersion=@AgentVersion, AgentVersionID=@AgentVersionID," +
                        "RunningInHypervisor=@RunningInHypervisor, ContractID=@ContractID, IPAddress=@IPAddress,BIOSType=@BIOSType, NumberOfLogicalProcessors=@NumberOfLogicalProcessors, " +
                        "NumberOfProcessors=@NumberOfProcessors, TotalPhysicalMemory=@TotalPhysicalMemory, CPUName=@CPUName, SecureBootState=@SecureBootState, " +
                        "SystemRoot=@SystemRoot,SUSID=@SUSID,MeteredConnection=@meteredconnection, " +
                        "RunningInWindowsPE=@RunningInWindowsPE " +
                        "    WHERE MachineID = @MachineID",
                        new SQLParam("@Is64Bit", logon.SysInfo.Is64Bit),
                        new SQLParam("@OSName", logon.SysInfo.OSName),
                        new SQLParam("@OSVerMaj", logon.SysInfo.OSVerMaj),
                        new SQLParam("@OSVerMin", logon.SysInfo.OSVerMin),
                        new SQLParam("@OSVerBuild", logon.SysInfo.OSVerBuild),
                        new SQLParam("@OSSuite", logon.SysInfo.OSSuite),
                        new SQLParam("@IsTSE", logon.SysInfo.IsTSE),
                        new SQLParam("@CPU", logon.SysInfo.CPU),
                        new SQLParam("@ComputerModel", logon.SysInfo.ComputerModel),
                        new SQLParam("@ComputerName", logon.SysInfo.ComputerName),
                        new SQLParam("@Language", logon.SysInfo.Language),
                        new SQLParam("@DisplayLanguage", logon.SysInfo.DisplayLanguage),
                        new SQLParam("@MachineID", logon.Username),
                        new SQLParam("@AgentVersionID", logon.SysInfo.AgentVersionID),
                        new SQLParam("@AgentVersion", logon.SysInfo.AgentVersion),
                        new SQLParam("@OSVerType", logon.SysInfo.OSVerType),
                        new SQLParam("@RunningInHypervisor", logon.SysInfo.RunningInHypervisor),
                        new SQLParam("@BIOS", logon.SysInfo.BIOS),
                        new SQLParam("@BIOSType", logon.SysInfo.BIOSType),
                        new SQLParam("@NumberOfLogicalProcessors", logon.SysInfo.NumberOfLogicalProcessors),
                        new SQLParam("@NumberOfProcessors", logon.SysInfo.NumberOfProcessors),
                        new SQLParam("@TotalPhysicalMemory", logon.SysInfo.TotalPhysicalMemory),
                        new SQLParam("@CPUName", logon.SysInfo.CPUName),
                        new SQLParam("@SecureBootState", logon.SysInfo.SecureBootState),
                        new SQLParam("@IPAddress", IPAddress),
                        new SQLParam("@SystemRoot", logon.SysInfo.SystemRoot),
                        new SQLParam("@SUSID", logon.SysInfo.SUSID),
                        new SQLParam("@meteredconnection", logon.SysInfo.IsMeteredConnection),
                        new SQLParam("@RunningInWindowsPE", logon.SysInfo.RunningInWindowsPE),
                        new SQLParam("@ContractID", Settings.Default.UseContract == true ? (object)logon.ContractID : DBNull.Value));

            sql.ExecSQL("UPDATE ComputerAccounts SET LastUpdated=getutcdate() WHERE MachineID=@m",
                        new SQLParam("@m", logon.Username));

            int Acceptance = Convert.ToInt32(sql.ExecSQLScalar("SELECT Accepted FROM ComputerAccounts WHERE MachineID=@m",
                                                               new SQLParam("@m", logon.Username)));

            switch (Acceptance)
            {
            case 1:     //OK
                break;

            default:
                Err.Error   = "Not accepted";
                Err.ErrorID = (int)ErrorFlags.NotAccepted;
                NetworkConnection.DeleteSession(newID);
                return(RESTStatus.Fail);
            }

            ni.Username           = logon.Username;
            ni.Name               = logon.SysInfo.ComputerName;
            ni.EMail              = "";
            ni.MustChangePassword = false;
            ni.LoggedIn           = false;
            ni.ComputerLoggedIn   = true;
            ni.Permissions        = (Int64)ACLFlags.ComputerLogin;
            Debug.WriteLine("Computer: " + ni.Name + " logged in");
            Err.Error   = "OK:" + newID;
            Err.ErrorID = (int)ErrorFlags.NoError;
            return(RESTStatus.Success);
        }
Example #6
0
        public RESTStatus ReportAddRemovePrograms(SQLLib sql, ListAddRemoveApps AddRemoveList, NetworkConnectionInfo ni)
        {
            if (ni.HasAcl(ACLFlags.ComputerLogin) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;
                return(RESTStatus.Denied);
            }

            AddRemoveList.MachineID = ni.Username;

            lock (ni.sqllock)
            {
                if (Convert.ToInt32(sql.ExecSQLScalar("SELECT COUNT(*) FROM ComputerAccounts WHERE MachineID=@m",
                                                      new SQLParam("@m", AddRemoveList.MachineID))) == 0)
                {
                    ni.Error   = "Invalid MachineID";
                    ni.ErrorID = ErrorFlags.InvalidValue;
                    return(RESTStatus.Denied);
                }
            }

            if (AddRemoveList.Items == null)
            {
                ni.Error   = "Invalid Items";
                ni.ErrorID = ErrorFlags.InvalidValue;
                return(RESTStatus.Fail);
            }
            if (AddRemoveList.SIDUsers == null)
            {
                AddRemoveList.SIDUsers = new List <string>();
            }

            foreach (AddRemoveApp rep in AddRemoveList.Items)
            {
                if (rep.ProductID == null)
                {
                    rep.ProductID = "";
                }
                if (rep.Name == null)
                {
                    rep.Name = "";
                }
                if (rep.DisplayVersion == null)
                {
                    rep.DisplayVersion = "";
                }
                if (rep.UninstallString == null)
                {
                    rep.UninstallString = "";
                }
                if (rep.Language == null)
                {
                    rep.Language = "";
                }
                if (rep.DisplayLanguage == null)
                {
                    rep.DisplayLanguage = "";
                }
                if (rep.HKCUUser == null)
                {
                    rep.HKCUUser = "";
                }

                rep.ProductID       = rep.ProductID.Trim();
                rep.Name            = rep.Name.Trim();
                rep.DisplayVersion  = rep.DisplayVersion.Trim();
                rep.UninstallString = rep.UninstallString.Trim();
                rep.Language        = rep.Language.Trim();
                rep.DisplayLanguage = rep.DisplayLanguage.Trim();
                rep.HKCUUser        = rep.HKCUUser.Trim();
            }

            List <AddRemoveApp> Installed = new List <AddRemoveApp>();
            List <AddRemoveApp> Reported  = AddRemoveList.Items;

            lock (ni.sqllock)
            {
                SqlDataReader dr = sql.ExecSQLReader("SELECT * FROM AddRemovePrograms WHERE MachineID=@id", new SQLParam("@id", AddRemoveList.MachineID));
                while (dr.Read())
                {
                    AddRemoveApp ar = new AddRemoveApp();
                    ar.DisplayLanguage   = Convert.ToString(dr["DisplayLanguage"]);
                    ar.DisplayVersion    = Convert.ToString(dr["DisplayVersion"]);
                    ar.IsMSI             = Convert.ToBoolean(dr["IsMSI"]);
                    ar.IsWOWBranch       = Convert.ToBoolean(dr["IsWOWBranch"]);
                    ar.IsSystemComponent = Convert.ToBoolean(dr["IsSystemComponent"]);
                    ar.Language          = Convert.ToString(dr["Language"]);
                    ar.MachineID         = Convert.ToString(dr["MachineID"]);
                    ar.Name            = Convert.ToString(dr["Name"]);
                    ar.ProductID       = Convert.ToString(dr["ProductID"]);
                    ar.UninstallString = Convert.ToString(dr["UninstallString"]);
                    ar.VersionMajor    = Convert.ToInt32(dr["VersionMajor"]);
                    ar.VersionMinor    = Convert.ToInt32(dr["VersionMinor"]);
                    ar.HKCUUser        = Convert.ToString(dr["HKCUUser"]);
                    if (string.IsNullOrWhiteSpace(ar.HKCUUser) == true)
                    {
                        ar.HKCUUser = "";
                    }

                    Installed.Add(ar);
                }
                dr.Close();
            }

            List <AddRemoveApp> Updated   = new List <AddRemoveApp>();
            List <AddRemoveApp> Unchanged = new List <AddRemoveApp>();
            List <AddRemoveApp> Removed   = new List <AddRemoveApp>();
            List <AddRemoveApp> Added     = new List <AddRemoveApp>();

            foreach (AddRemoveApp inst in Installed)
            {
                if (inst.ProductID == null)
                {
                    inst.ProductID = "";
                }
                if (inst.Name == null)
                {
                    inst.Name = "";
                }
                if (inst.DisplayVersion == null)
                {
                    inst.DisplayVersion = "";
                }
                if (inst.UninstallString == null)
                {
                    inst.UninstallString = "";
                }
                if (inst.Language == null)
                {
                    inst.Language = "";
                }
                if (inst.DisplayLanguage == null)
                {
                    inst.DisplayLanguage = "";
                }

                inst.ProductID       = inst.ProductID.Trim();
                inst.Name            = inst.Name.Trim();
                inst.DisplayVersion  = inst.DisplayVersion.Trim();
                inst.UninstallString = inst.UninstallString.Trim();
                inst.Language        = inst.Language.Trim();
                inst.DisplayLanguage = inst.DisplayLanguage.Trim();
                inst.HKCUUser        = inst.HKCUUser.Trim();

                bool Found = false;
                foreach (AddRemoveApp rep in Reported)
                {
                    if (rep.ProductID.ToLower() == inst.ProductID.ToLower() && rep.IsWOWBranch == inst.IsWOWBranch && rep.HKCUUser == inst.HKCUUser)
                    {
                        if (rep.IsMSI == inst.IsMSI && rep.IsSystemComponent == inst.IsSystemComponent && rep.Name.ToLower() == inst.Name.ToLower() &&
                            rep.DisplayVersion.ToLower() == inst.DisplayVersion.ToLower() && inst.UninstallString.ToLower() == rep.UninstallString.ToLower() &&
                            rep.VersionMajor == inst.VersionMajor && rep.VersionMinor == inst.VersionMinor && rep.Language.ToLower() == inst.Language.ToLower() &&
                            rep.DisplayLanguage.ToLower() == inst.DisplayLanguage.ToLower())
                        {
                            Unchanged.Add(rep);
                            Found = true;
                            break;
                        }
                        else
                        {
                            Updated.Add(rep);
                            Found = true;
                            break;
                        }
                    }
                }
                if (Found == false)
                {
                    if (inst.HKCUUser != "" && AddRemoveList.SIDUsers.Contains(inst.HKCUUser, StringComparer.InvariantCultureIgnoreCase) == false)
                    {
                        //likely that this user is not logged on or such
                        Unchanged.Add(inst);
                    }
                    else
                    {
                        Removed.Add(inst);
                    }
                }
            }

            foreach (AddRemoveApp inst in Reported)
            {
                bool Found = false;
                foreach (AddRemoveApp rep in Installed)
                {
                    if (rep.ProductID.ToLower() == inst.ProductID.ToLower() && rep.IsWOWBranch == inst.IsWOWBranch && rep.HKCUUser == inst.HKCUUser)
                    {
                        Found = true;
                        break;
                    }
                }
                if (Found == false)
                {
                    Added.Add(inst);
                }
            }

            lock (ni.sqllock)
            {
                try
                {
                    sql.BeginTransaction();
                    sql.SEHError = true;
                    foreach (AddRemoveApp ar in Removed)
                    {
                        sql.ExecSQL("DELETE FROM AddRemovePrograms WHERE MachineID=@id AND IsWOWBranch=@wow AND ProductID=@prod AND HKCUUser=@user",
                                    new SQLParam("@id", AddRemoveList.MachineID),
                                    new SQLParam("@prod", ar.ProductID),
                                    new SQLParam("@user", ar.HKCUUser),
                                    new SQLParam("@wow", ar.IsWOWBranch));
                    }
                    foreach (AddRemoveApp ar in Updated)
                    {
                        sql.ExecSQL(@"UPDATE AddRemovePrograms SET
                            IsMSI=@IsMSI,
                            IsSystemComponent=@IsSystemComponent,
                            Name=@Name,
                            DisplayVersion=@DisplayVersion,
                            UninstallString=@UninstallString,
                            VersionMajor=@VersionMajor,
                            VersionMinor=@VersionMinor,
                            Language=@Language,
                            DisplayLanguage=@DisplayLanguage,
                            DT=@DT
                            WHERE MachineID=@id AND IsWOWBranch=@wow AND ProductID=@prod AND HKCUUser=@user",
                                    new SQLParam("@id", AddRemoveList.MachineID),
                                    new SQLParam("@prod", ar.ProductID),
                                    new SQLParam("@wow", ar.IsWOWBranch),
                                    new SQLParam("@IsMSI", ar.IsMSI),
                                    new SQLParam("@IsSystemComponent", ar.IsSystemComponent),
                                    new SQLParam("@Name", ar.Name.Trim()),
                                    new SQLParam("@DisplayVersion", ar.DisplayVersion),
                                    new SQLParam("@UninstallString", ar.UninstallString),
                                    new SQLParam("@VersionMajor", ar.VersionMajor),
                                    new SQLParam("@VersionMinor", ar.VersionMinor),
                                    new SQLParam("@Language", ar.Language),
                                    new SQLParam("@DisplayLanguage", ar.DisplayLanguage),
                                    new SQLParam("@user", ar.HKCUUser),
                                    new SQLParam("@DT", DateTime.UtcNow));
                    }
                    foreach (AddRemoveApp ar in Added)
                    {
                        sql.InsertMultiData("AddRemovePrograms",
                                            new SQLData("MachineID", AddRemoveList.MachineID),
                                            new SQLData("ProductID", ar.ProductID),
                                            new SQLData("IsWOWBranch", ar.IsWOWBranch),
                                            new SQLData("IsMSI", ar.IsMSI),
                                            new SQLData("IsSystemComponent", ar.IsSystemComponent),
                                            new SQLData("Name", ar.Name.Trim()),
                                            new SQLData("DisplayVersion", ar.DisplayVersion),
                                            new SQLData("UninstallString", ar.UninstallString),
                                            new SQLData("VersionMajor", ar.VersionMajor),
                                            new SQLData("VersionMinor", ar.VersionMinor),
                                            new SQLData("Language", ar.Language),
                                            new SQLData("DisplayLanguage", ar.DisplayLanguage),
                                            new SQLData("HKCUUser", ar.HKCUUser),
                                            new SQLData("DT", DateTime.UtcNow));
                    }
                    sql.CommitTransaction();
                }
                catch (Exception ee)
                {
                    sql.RollBackTransaction();
                    FoxEventLog.WriteEventLog("DB Error: Cannot update AddRemovePrograms: " + ee.ToString(), System.Diagnostics.EventLogEntryType.Error);
                    return(RESTStatus.ServerError);
                }
                finally
                {
                    sql.SEHError = false;
                }
            }

            AddRemoveProgramsLst l = new AddRemoveProgramsLst();

            l.Added     = Added;
            l.Removed   = Removed;
            l.Unchanged = Unchanged;
            l.Updated   = Updated;
            l.MachineID = AddRemoveList.MachineID;
            Thread t = new Thread(new ParameterizedThreadStart(new DReportingThread(ReportingThread)));

            t.Start(l);

            return(RESTStatus.Created);
        }
Example #7
0
        static void ReadVersions()
        {
            string AppPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            if (AppPath.EndsWith("\\") == false)
            {
                AppPath += "\\";
            }
            AppPath += "Packages\\";

            string NormalUpdate = AppPath + "SDCA.foxpkg";
            string EarlyUpdate  = AppPath + "SDCA-Early.foxpkg";

            string Error;

            if (File.Exists(NormalUpdate) == false)
            {
                FoxEventLog.WriteEventLog("No client updates will be provided. The file " + NormalUpdate + " is missing.",
                                          System.Diagnostics.EventLogEntryType.Error);
                CurrentVersion = CurrentEarlyVersion = null;
                return;
            }

            PackageInstaller pkg = new PackageInstaller();
            PKGStatus        status;
            PKGRecieptData   receipt;

            Int64?NormalVersion = null;
            Int64?EarlyVersion  = null;

            try
            {
                if (pkg.InstallPackage(NormalUpdate, null, PackageInstaller.InstallMode.TestPackageOnly, false, out Error, out status, out receipt) == false)
                {
                    FoxEventLog.WriteEventLog("No client updates will be provided. The file " + NormalUpdate + " is invalid / invalid signatures.",
                                              System.Diagnostics.EventLogEntryType.Error);
                    CurrentVersion = CurrentEarlyVersion = null;
                    return;
                }

                if (pkg.PackageInfo(NormalUpdate, null, out Error) == false)
                {
                    FoxEventLog.WriteEventLog("No client updates will be provided. The file " + NormalUpdate + " is invalid / invalid info.",
                                              System.Diagnostics.EventLogEntryType.Error);
                    CurrentVersion = CurrentEarlyVersion = null;
                    return;
                }

                if (pkg.PackageInfoData.PackageID != "Vulpes-SDCA1-Update")
                {
                    FoxEventLog.WriteEventLog("No client updates will be provided. The file " + NormalUpdate + " is has an invalid identifier.",
                                              System.Diagnostics.EventLogEntryType.Error);
                    CurrentVersion = CurrentEarlyVersion = null;
                    return;
                }
            }
            catch
            {
                NormalVersion       = null;
                EarlyVersion        = null;
                CurrentVersion      = NormalVersion;
                CurrentEarlyVersion = EarlyVersion;
                FoxEventLog.WriteEventLog("Update packages contains errors. No updates will be provided.", System.Diagnostics.EventLogEntryType.Error);
                return;
            }

            NormalVersion = pkg.PackageInfoData.VersionID;

            if (File.Exists(EarlyUpdate) == true)
            {
                if (pkg.InstallPackage(EarlyUpdate, null, PackageInstaller.InstallMode.TestPackageOnly, false, out Error, out status, out receipt) == true)
                {
                    if (pkg.PackageInfo(EarlyUpdate, null, out Error) == true)
                    {
                        if (pkg.PackageInfoData.PackageID == "Vulpes-SDCA1-Update")
                        {
                            EarlyVersion = pkg.PackageInfoData.VersionID;

                            if (EarlyVersion < NormalVersion)
                            {
                                FoxEventLog.WriteEventLog("The version ID of the file " + EarlyUpdate + " is older than the normal version - not deploying.",
                                                          System.Diagnostics.EventLogEntryType.Warning);
                                EarlyVersion = null;
                            }
                            else
                            {
                                FoxEventLog.WriteEventLog("The file " + EarlyUpdate + " will be deployed along with the normal updates.",
                                                          System.Diagnostics.EventLogEntryType.Information);
                            }
                        }
                    }
                }
            }

            CurrentVersion      = NormalVersion;
            CurrentEarlyVersion = EarlyVersion;

            FoxEventLog.WriteEventLog("The Agent update system is working normally.\r\nVersion: " + CurrentVersion.ToString() + "\r\nEarly Version: " + CurrentEarlyVersion.ToString(), System.Diagnostics.EventLogEntryType.Information);
        }
Example #8
0
        void ReportingThread(object SimpleTaskO)
        {
            try
            {
                using (SQLLib sql = SQLTest.ConnectSQL("Fox SDC Server for SimpleTask Result Data"))
                {
                    if (sql == null)
                    {
                        FoxEventLog.WriteEventLog("Cannot connect to SQL Server for SimpleTask Result Reporting!", System.Diagnostics.EventLogEntryType.Error);
                        return;
                    }
                    SimpleTaskResult SimpleTask = (SimpleTaskResult)SimpleTaskO;

                    List <PolicyObject>        Pol             = Policies.GetPolicyForComputerInternal(sql, SimpleTask.MachineID);
                    Dictionary <string, Int64> AlreadyReported = new Dictionary <string, long>();
                    foreach (PolicyObject PolO in Pol)
                    {
                        if (PolO.Type != PolicyIDs.ReportingPolicy)
                        {
                            continue;
                        }
                        ReportingPolicyElement RepElementRoot = JsonConvert.DeserializeObject <ReportingPolicyElement>(Policies.GetPolicy(sql, PolO.ID).Data);
                        if (RepElementRoot.Type != ReportingPolicyType.SimpleTaskCompleted)
                        {
                            continue;
                        }
                        if (RepElementRoot.ReportToAdmin == null)
                        {
                            RepElementRoot.ReportToAdmin = false;
                        }
                        if (RepElementRoot.ReportToClient == null)
                        {
                            RepElementRoot.ReportToClient = false;
                        }
                        if (RepElementRoot.UrgentForAdmin == null)
                        {
                            RepElementRoot.UrgentForAdmin = false;
                        }
                        if (RepElementRoot.UrgentForClient == null)
                        {
                            RepElementRoot.UrgentForClient = false;
                        }
                        if (RepElementRoot.ReportToAdmin == false && RepElementRoot.ReportToClient == false && RepElementRoot.UrgentForAdmin == false &&
                            RepElementRoot.UrgentForClient == false)
                        {
                            continue;
                        }

                        foreach (string Element in RepElementRoot.ReportingElements)
                        {
                            ReportingPolicyElementSimpleTaskCompleted arprep = JsonConvert.DeserializeObject <ReportingPolicyElementSimpleTaskCompleted>(Element);

                            ReportThings(sql, SimpleTask.MachineID, "Completed", SimpleTask, ref AlreadyReported, RepElementRoot);
                        }
                    }
                }
            }
            catch (Exception ee)
            {
                FoxEventLog.WriteEventLog("SEH in SimpleTask Result Reporting " + ee.ToString(), System.Diagnostics.EventLogEntryType.Error);
            }
        }
Example #9
0
        public static bool TestServer(out string ErrorReason, bool SkipSomeSanityChecks = false)
        {
            ErrorReason = "";

            SQLLib sql = null;

            try
            {
                if (Settings.Default.DBType.ToLower() == "mssql")
                {
                    if (Settings.Default.DBServer == "" || Settings.Default.DBDB == "")
                    {
                        ErrorReason = "Servername / DB missing";
                        return(false);
                    }
                    sql = new SQLLib();
                    sql.SqlCommandTimeout = 0; //waiting .... :-)
                    sql.ApplicationName   = "Fox SDC Server [test/update connection]";
                    sql.ConnectionPooling = false;
                    sql.SEHError          = true;
                    if (sql.ConnectDatabase(Settings.Default.DBServer, Settings.Default.DBDB, true) == false)
                    {
                        ErrorReason = "Cannot connect to the SQL Server";
                        return(false);
                    }
                }
                if (Settings.Default.DBType.ToLower() == "localdb")
                {
                    if (Settings.Default.DBLocalPath == "")
                    {
                        ErrorReason = "LocalDB path missing";
                        return(false);
                    }
                    sql = new SQLLib();
                    sql.SqlCommandTimeout = 0; //waiting .... :-)
                    sql.ApplicationName   = "Fox SDC Server [test/update connection]";
                    sql.ConnectionPooling = false;
                    sql.SEHError          = true;
                    if (sql.ConnectLocalDatabase(Settings.Default.DBLocalPath) == false)
                    {
                        ErrorReason = "Cannot connect to the SQL Server";
                        return(false);
                    }
                }
            }
            catch (Exception ee)
            {
                ErrorReason = "Cannot connect to the SQL Server [SEH]\n" + ee.ToString();
                Debug.WriteLine(ee.ToString());
                return(false);
            }

            if (sql == null)
            {
                ErrorReason = "sql==null //is the SQL Profile properly defined in registry?\n";
                return(false);
            }

            string ServerVersion = Convert.ToString(sql.ExecSQLScalar("SELECT SERVERPROPERTY('productversion')"));
            string ServerVPart   = ServerVersion.Split('.')[0].Trim();
            int    ServerVPartI  = 0;

            if (int.TryParse(ServerVPart, out ServerVPartI) == false)
            {
                sql.CloseConnection();
                ErrorReason = "Cannot read SQL Version";
                return(false);
            }
            if (ServerVPartI < 11)
            {
                sql.CloseConnection();
                ErrorReason = "Unsupported SQL Version - Minimum V.11 (SQL 2012)";
            }

            try
            {
                sql.ExecSQL("SELECT * FROM Config");
            }
            catch
            {
                sql.CloseConnection();
                ErrorReason = "Cannot SELECT Table CONFIG.";
                return(false);
            }

            try
            {
                if (Convert.ToString(sql.ExecSQLScalar("SELECT Value FROM Config WHERE [Key]='ID'")) != "FOXSDCv1")
                {
                    sql.CloseConnection();
                    ErrorReason = "Invalid ID in Config Table";
                    return(false);
                }
            }
            catch
            {
                sql.CloseConnection();
                ErrorReason = "Cannot SELECT Table CONFIG. (ID)";
                return(false);
            }

            while (DBUpdate.UpdateDB(sql) == false)
            {
                ;
            }

            sql.SEHError = true;

            try
            {
                if (Convert.ToInt32(sql.ExecSQLScalar("SELECT Value FROM Config WHERE [Key]='Version'")) != Program.DBVersion)
                {
                    sql.CloseConnection();
                    ErrorReason = "Invalid Version in Config Table";
                    return(false);
                }
            }
            catch
            {
                sql.CloseConnection();
                ErrorReason = "Cannot SELECT Table CONFIG. (Version)";
                return(false);
            }

            if (Convert.ToInt32(sql.ExecSQLScalar("SELECT COUNT(*) FROM Users WHERE Username='******'")) == 0)
            {
                FoxEventLog.WriteEventLog("Creating user ROOT", EventLogEntryType.Warning);
                sql.InsertMultiData("Users",
                                    new SQLData("Username", "root"),
                                    new SQLData("Name", "Root User"),
                                    new SQLData("Password", DefaultPasswordHash),
                                    new SQLData("Permissions", AllPermissions),
                                    new SQLData("MustChangePassword", 1));
            }
            if (Convert.ToInt32(sql.ExecSQLScalar("SELECT COUNT(*) FROM Users WHERE Username='******' AND Permissions=@p", new SQLParam("@p", AllPermissions))) == 0)
            {
                FoxEventLog.WriteEventLog("Fixing user ROOT", EventLogEntryType.Warning);
                sql.ExecSQL("UPDATE Users SET Permissions=@p WHERE Username='******'", new SQLParam("@p", AllPermissions));
            }

            try
            {
                Guid g;
                if (Guid.TryParse(Convert.ToString(sql.ExecSQLScalar("SELECT Value FROM Config WHERE [Key]='GUID'")), out g) == false)
                {
                    FoxEventLog.WriteEventLog("Creating GUID", EventLogEntryType.Warning);
                    sql.ExecSQL("DELETE FROM Config WHERE [Key]='GUID'");
                    sql.ExecSQL("INSERT INTO Config VALUES ('GUID', @g)", new SQLParam("@g", Guid.NewGuid().ToString()));
                }
            }
            catch (Exception ee)
            {
                Debug.WriteLine(ee.ToString());
                ErrorReason = "Cannot verify GUID";
                return(false);
            }


            SettingsManager.LoadSettings(sql);

            //try
            //{
            //    string ret = Convert.ToString(sql.ExecSQLScalar("select dbo.FoxCreateSerial(1, 1)"));
            //}
            //catch (Exception ee)
            //{
            //    Debug.WriteLine(ee.ToString());
            //    ErrorReason = "Cannot execute FUNCTIONs in SQL";
            //    return (false);
            //}

            sql.CloseConnection();
            ErrorReason = "";
            return(true);
        }
Example #10
0
        void ReportingThread(object SmartDataListO)
        {
            try
            {
                using (SQLLib sql = SQLTest.ConnectSQL("Fox SDC Server for SMART Device Data"))
                {
                    if (sql == null)
                    {
                        FoxEventLog.WriteEventLog("Cannot connect to SQL Server for SMART Device Reporting!", System.Diagnostics.EventLogEntryType.Error);
                        return;
                    }
                    SmartDataLst SmartDataList = (SmartDataLst)SmartDataListO;
                    ComputerData computerdata  = Computers.GetComputerDetail(sql, SmartDataList.MachineID);
                    if (computerdata == null)
                    {
                        FoxEventLog.WriteEventLog("Cannot get any computer data for SMART Device Reporting!", System.Diagnostics.EventLogEntryType.Error);
                        return;
                    }

                    List <PolicyObject>        Pol             = Policies.GetPolicyForComputerInternal(sql, SmartDataList.MachineID);
                    Dictionary <string, Int64> AlreadyReported = new Dictionary <string, long>();
                    foreach (PolicyObject PolO in Pol)
                    {
                        if (PolO.Type != PolicyIDs.ReportingPolicy)
                        {
                            continue;
                        }
                        ReportingPolicyElement RepElementRoot = JsonConvert.DeserializeObject <ReportingPolicyElement>(Policies.GetPolicy(sql, PolO.ID).Data);
                        if (RepElementRoot.Type != ReportingPolicyType.SMART)
                        {
                            continue;
                        }
                        if (RepElementRoot.ReportToAdmin == null)
                        {
                            RepElementRoot.ReportToAdmin = false;
                        }
                        if (RepElementRoot.ReportToClient == null)
                        {
                            RepElementRoot.ReportToClient = false;
                        }
                        if (RepElementRoot.UrgentForAdmin == null)
                        {
                            RepElementRoot.UrgentForAdmin = false;
                        }
                        if (RepElementRoot.UrgentForClient == null)
                        {
                            RepElementRoot.UrgentForClient = false;
                        }
                        if (RepElementRoot.ReportToAdmin == false && RepElementRoot.ReportToClient == false && RepElementRoot.UrgentForAdmin == false &&
                            RepElementRoot.UrgentForClient == false)
                        {
                            continue;
                        }

                        foreach (string Element in RepElementRoot.ReportingElements)
                        {
                            ReportingPolicyElementSMART arprep = JsonConvert.DeserializeObject <ReportingPolicyElementSMART>(Element);
                            if (arprep.NotifyOnAdd == false && arprep.NotifyOnRemove == false && arprep.NotifyOnUpdate == false &&
                                arprep.NotifyOnError == false)
                            {
                                continue;
                            }

                            if (arprep.NotifyOnAdd == true)
                            {
                                foreach (VulpesSMARTInfo ar in SmartDataList.Added)
                                {
                                    ReportThings(sql, SmartDataList.MachineID, "Add", ar, ref AlreadyReported, RepElementRoot);
                                }
                            }

                            if (arprep.NotifyOnUpdate == true)
                            {
                                foreach (VulpesSMARTInfo ar in SmartDataList.Updated)
                                {
                                    foreach (VulpesSMARTInfo indbvsm in SmartDataList.InDB)
                                    {
                                        if (indbvsm.PNPDeviceID == ar.PNPDeviceID)
                                        {
                                            if (SMARTDescription.CompareFull(ar, indbvsm, arprep.SkipAttribUpdateReport) == false)
                                            {
                                                if (indbvsm.Attributes != null)
                                                {
                                                    List <int> UpdatedAttribs = new List <int>();
                                                    if (ar.Attributes == null)
                                                    {
                                                        ar.Attributes = new Dictionary <int, VulpesSMARTAttribute>();
                                                    }
                                                    foreach (KeyValuePair <int, VulpesSMARTAttribute> indb in indbvsm.Attributes)
                                                    {
                                                        if (ar.Attributes.ContainsKey(indb.Key) == true)
                                                        {
                                                            if (ar.Attributes[indb.Key].FailureImminent != indb.Value.FailureImminent ||
                                                                ar.Attributes[indb.Key].Flags != indb.Value.Flags ||
                                                                ar.Attributes[indb.Key].ID != indb.Value.ID ||
                                                                ar.Attributes[indb.Key].Threshold != indb.Value.Threshold ||
                                                                ar.Attributes[indb.Key].Value != indb.Value.Value ||
                                                                ar.Attributes[indb.Key].Vendordata != indb.Value.Vendordata ||
                                                                ar.Attributes[indb.Key].Worst != indb.Value.Worst)
                                                            {
                                                                UpdatedAttribs.Add(indb.Key);
                                                            }
                                                        }
                                                    }
                                                    ReportThings(sql, SmartDataList.MachineID, "Update", ar, ref AlreadyReported, RepElementRoot, UpdatedAttribs);
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            if (arprep.NotifyOnRemove == true)
                            {
                                foreach (VulpesSMARTInfo ar in SmartDataList.Removed)
                                {
                                    ReportThings(sql, SmartDataList.MachineID, "Remove", ar, ref AlreadyReported, RepElementRoot);
                                }
                            }

                            if (arprep.NotifyOnError == true)
                            {
                                foreach (VulpesSMARTInfo ar in SmartDataList.Added)
                                {
                                    if (SMARTDescription.IsInError(ar) == true)
                                    {
                                        ReportThings(sql, SmartDataList.MachineID, "Error", ar, ref AlreadyReported, RepElementRoot);
                                    }
                                }
                                foreach (VulpesSMARTInfo ar in SmartDataList.Updated)
                                {
                                    if (SMARTDescription.IsInError(ar) == true)
                                    {
                                        foreach (VulpesSMARTInfo indbvsm in SmartDataList.InDB)
                                        {
                                            if (indbvsm.PNPDeviceID == ar.PNPDeviceID)
                                            {
                                                if (SMARTDescription.CompareFullCriticalOnly(indbvsm, ar) == false)
                                                {
                                                    ReportThings(sql, SmartDataList.MachineID, "Error", ar, ref AlreadyReported, RepElementRoot);
                                                }
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ee)
            {
                FoxEventLog.WriteEventLog("SEH in SMART Data Reporting " + ee.ToString(), System.Diagnostics.EventLogEntryType.Error);
            }
        }
Example #11
0
        static void MThread()
        {
            do
            {
                using (SQLLib sql = SQLTest.ConnectSQL("Fox SDC Server for Maintenance", 0))
                {
                    if (sql == null)
                    {
                        Pause();
                        if (StopThread == true)
                        {
                            break;
                        }
                    }

                    try
                    {
                        if (SettingsManager.Settings.KeepEventLogDays > 0)
                        {
                            DateTime now = DateTime.UtcNow;
                            Int64    res = Convert.ToInt64(sql.ExecSQLScalar(@"DECLARE @Deleted_Rows INT
                            DECLARE @Deleted_Rows_Total INT
                            SET @Deleted_Rows = 1
                            SET @Deleted_Rows_Total = 0

                            WHILE (@Deleted_Rows > 0)
                            BEGIN
                                delete top (10000) from EventLog where TimeGenerated<DATEADD(day, @d, getutcdate())
                                SET @Deleted_Rows = @@ROWCOUNT
                                SET @Deleted_Rows_Total = @Deleted_Rows_Total + @Deleted_Rows
                            END

                            Select @Deleted_Rows_Total",
                                                                             new SQLParam("@d", 0 - SettingsManager.Settings.KeepEventLogDays)));
                            Int64 secs = Convert.ToInt64((DateTime.UtcNow - now).TotalSeconds);
                            FoxEventLog.WriteEventLog("Eventlog data Maintenance completed: " + res.ToString() + " entr" + (res == 1 ? "y" : "ies") + " deleted\nTime needed: " + secs + " second" + (secs == 1 ? "" : "s"), System.Diagnostics.EventLogEntryType.Information);
                        }
                        if (SettingsManager.Settings.KeepNonPresentDisks > 0)
                        {
                            DateTime now = DateTime.UtcNow;
                            int      res = sql.ExecSQLNQ("delete from DiskData where DevicePresent!=1 AND LastUpdated<DATEADD(day, @d, getutcdate())",
                                                         new SQLParam("@d", 0 - SettingsManager.Settings.KeepNonPresentDisks));
                            Int64 secs = Convert.ToInt64((DateTime.UtcNow - now).TotalSeconds);
                            FoxEventLog.WriteEventLog("Nonpresent disk data Maintenance completed: " + res.ToString() + " entr" + (res == 1 ? "y" : "ies") + " deleted\nTime needed: " + secs + " second" + (secs == 1 ? "" : "s"), System.Diagnostics.EventLogEntryType.Information);
                        }
                        if (SettingsManager.Settings.KeepReports > 0)
                        {
                            DateTime now = DateTime.UtcNow;
                            int      res = sql.ExecSQLNQ("delete from Reporting where Reported<DATEADD(day, @d, getutcdate())",
                                                         new SQLParam("@d", 0 - SettingsManager.Settings.KeepReports));
                            Int64 secs = Convert.ToInt64((DateTime.UtcNow - now).TotalSeconds);
                            FoxEventLog.WriteEventLog("Report Maintenance completed: " + res.ToString() + " entr" + (res == 1 ? "y" : "ies") + " deleted\nTime needed: " + secs + " second" + (secs == 1 ? "" : "s"), System.Diagnostics.EventLogEntryType.Information);
                        }
                        if (SettingsManager.Settings.KeepBitlockerRK > 0)
                        {
                            DateTime now = DateTime.UtcNow;
                            int      res = sql.ExecSQLNQ("delete from BitlockerRK where Reported<DATEADD(day, @d, getutcdate())",
                                                         new SQLParam("@d", 0 - SettingsManager.Settings.KeepBitlockerRK));
                            Int64 secs = Convert.ToInt64((DateTime.UtcNow - now).TotalSeconds);
                            FoxEventLog.WriteEventLog("Old BitlockerRK Maintenance completed: " + res.ToString() + " entr" + (res == 1 ? "y" : "ies") + " deleted\nTime needed: " + secs + " second" + (secs == 1 ? "" : "s"), System.Diagnostics.EventLogEntryType.Information);
                        }
                        if (SettingsManager.Settings.KeepChatLogs > 0)
                        {
                            DateTime now = DateTime.UtcNow;
                            int      res = sql.ExecSQLNQ("delete from Chats where DT<DATEADD(day, @d, getutcdate())",
                                                         new SQLParam("@d", 0 - SettingsManager.Settings.KeepChatLogs));
                            Int64 secs = Convert.ToInt64((DateTime.UtcNow - now).TotalSeconds);
                            FoxEventLog.WriteEventLog("Old Chat Logs Maintenance completed: " + res.ToString() + " entr" + (res == 1 ? "y" : "ies") + " deleted\nTime needed: " + secs + " second" + (secs == 1 ? "" : "s"), System.Diagnostics.EventLogEntryType.Information);
                        }
                    }
                    catch (Exception ee)
                    {
                        FoxEventLog.WriteEventLog("Cannot delete Eventlog data\n" + ee.ToString(), System.Diagnostics.EventLogEntryType.Error);
                    }

                    sql.CloseConnection();
                }
                Pause();
                if (StopThread == true)
                {
                    break;
                }
            } while (StopThread == false);
        }
Example #12
0
        public RESTStatus ReportDiskData(SQLLib sql, ListDiskDataReport DiskDataList, NetworkConnectionInfo ni)
        {
            if (ni.HasAcl(ACLFlags.ComputerLogin) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;
                return(RESTStatus.Denied);
            }

            DiskDataList.MachineID = ni.Username;
            lock (ni.sqllock)
            {
                if (Convert.ToInt32(sql.ExecSQLScalar("SELECT COUNT(*) FROM ComputerAccounts WHERE MachineID=@m",
                                                      new SQLParam("@m", DiskDataList.MachineID))) == 0)
                {
                    ni.Error   = "Invalid MachineID";
                    ni.ErrorID = ErrorFlags.InvalidValue;
                    return(RESTStatus.NotFound);
                }
            }

            if (DiskDataList.Items == null)
            {
                ni.Error   = "Invalid Items";
                ni.ErrorID = ErrorFlags.InvalidValue;
                return(RESTStatus.Fail);
            }

            lock (ni.sqllock)
            {
                sql.ExecSQL("UPDATE DiskData SET DevicePresent=0 WHERE MachineID=@m",
                            new SQLParam("@m", DiskDataList.MachineID));
            }
            foreach (DiskDataReport dr in DiskDataList.Items)
            {
                lock (ni.sqllock)
                {
                    sql.ExecSQL("DELETE FROM DiskData WHERE MachineID=@m AND DeviceID=@d",
                                new SQLParam("@d", dr.DeviceID),
                                new SQLParam("@m", DiskDataList.MachineID));
                }
            }

            List <List <SQLData> > bulkdata = new List <List <SQLData> >();
            DateTime DT = DateTime.Now;

            DiskDataReport cdr = null;

            lock (ni.sqllock)
            {
                try
                {
                    sql.BeginTransaction();
                    sql.SEHError = true;

                    foreach (DiskDataReport dr in DiskDataList.Items)
                    {
                        sql.InsertMultiData("DiskData",
                                            new SQLData("MachineID", dr.MachineID),
                                            new SQLData("DevicePresent", true),
                                            new SQLData("LastUpdated", DT),
                                            new SQLData("DeviceID", dr.DeviceID),
                                            new SQLData("Access", dr.Access),
                                            new SQLData("Automount", dr.Automount),
                                            new SQLData("Availability", dr.Availability),
                                            new SQLData("Capacity", dr.Capacity),
                                            new SQLData("Caption", dr.Caption),
                                            new SQLData("Compressed", dr.Compressed),
                                            new SQLData("ConfigManagerErrorCode", dr.ConfigManagerErrorCode),
                                            new SQLData("Description", dr.Description),
                                            new SQLData("DirtyBitSet", dr.DirtyBitSet),
                                            new SQLData("DriveLetter", dr.DriveLetter),
                                            new SQLData("DriveType", dr.DriveType),
                                            new SQLData("ErrorDescription", dr.ErrorDescription),
                                            new SQLData("ErrorMethodology", dr.ErrorMethodology),
                                            new SQLData("FileSystem", dr.FileSystem),
                                            new SQLData("FreeSpace", dr.FreeSpace),
                                            new SQLData("Label", dr.Label),
                                            new SQLData("LastErrorCode", dr.LastErrorCode),
                                            new SQLData("MaximumFileNameLength", dr.MaximumFileNameLength),
                                            new SQLData("Name", dr.Name),
                                            new SQLData("PNPDeviceID", dr.PNPDeviceID),
                                            new SQLData("SerialNumber", dr.SerialNumber),
                                            new SQLData("Status", dr.Status));
                    }
                    sql.CommitTransaction();
                }
                catch (Exception ee)
                {
                    sql.RollBackTransaction();
                    FoxEventLog.WriteEventLog("DB Error: Cannot insert data to DiskData: " + ee.ToString() + "\r\n\r\nJSON: " +
                                              JsonConvert.SerializeObject(cdr, Formatting.Indented), System.Diagnostics.EventLogEntryType.Error);
                    return(RESTStatus.ServerError);
                }
                finally
                {
                    sql.SEHError = false;
                }
            }

            Thread t = new Thread(new ParameterizedThreadStart(new DReportingThread(ReportingThread)));

            t.Start(DiskDataList);

            return(RESTStatus.Success);
        }
Example #13
0
        void ReportingThread(object DiskDataListO)
        {
            try
            {
                using (SQLLib sql = SQLTest.ConnectSQL("Fox SDC Server for DiskData"))
                {
                    if (sql == null)
                    {
                        FoxEventLog.WriteEventLog("Cannot connect to SQL Server for Disk Data Reporting!", System.Diagnostics.EventLogEntryType.Error);
                        return;
                    }
                    ListDiskDataReport  DiskDataList = (ListDiskDataReport)DiskDataListO;
                    List <PolicyObject> Pol          = Policies.GetPolicyForComputerInternal(sql, DiskDataList.MachineID);

                    Dictionary <string, Int64> AlreadyReported = new Dictionary <string, long>();
                    foreach (PolicyObject PolO in Pol)
                    {
                        if (PolO.Type != PolicyIDs.ReportingPolicy)
                        {
                            continue;
                        }
                        ReportingPolicyElement RepElementRoot = JsonConvert.DeserializeObject <ReportingPolicyElement>(Policies.GetPolicy(sql, PolO.ID).Data);
                        if (RepElementRoot.Type != ReportingPolicyType.Disk)
                        {
                            continue;
                        }

                        foreach (string Element in RepElementRoot.ReportingElements)
                        {
                            ReportingPolicyElementDisk diskrep = JsonConvert.DeserializeObject <ReportingPolicyElementDisk>(Element);
                            if (diskrep.DriveLetter == null)
                            {
                                continue;
                            }
                            if (diskrep.DriveLetter.Length != 1)
                            {
                                continue;
                            }

                            foreach (DiskDataReport DD in DiskDataList.Items)
                            {
                                string Drive = diskrep.DriveLetter;

                                if (diskrep.DriveLetter == "$")
                                {
                                    ComputerData d = Computers.GetComputerDetail(sql, DiskDataList.MachineID);
                                    if (d != null)
                                    {
                                        if (string.IsNullOrWhiteSpace(d.SystemRoot) == false)
                                        {
                                            Drive = d.SystemRoot.Substring(0, 1);
                                        }
                                    }
                                }

                                if (string.IsNullOrWhiteSpace(DD.DriveLetter) == true)
                                {
                                    continue;
                                }
                                if (DD.DriveLetter.ToLower().Substring(0, 1) != Drive.ToLower())
                                {
                                    continue;
                                }

                                Int64 SZLimit;

                                if (diskrep.Method == 1)
                                {
                                    SZLimit = (Int64)((100m / (decimal)DD.Capacity) * (decimal)diskrep.MinimumSize);
                                }
                                else
                                {
                                    SZLimit = diskrep.MinimumSize;
                                }

                                if (DD.FreeSpace < SZLimit)
                                {
                                    bool ReportToAdmin   = RepElementRoot.ReportToAdmin.Value;
                                    bool ReportToClient  = RepElementRoot.ReportToClient.Value;
                                    bool UrgentForAdmin  = RepElementRoot.UrgentForAdmin.Value;
                                    bool UrgentForClient = RepElementRoot.UrgentForClient.Value;

                                    if (AlreadyReported.ContainsKey(DD.DriveLetter) == true)
                                    {
                                        if ((AlreadyReported[DD.DriveLetter] & (Int64)ReportingFlags.ReportToAdmin) != 0)
                                        {
                                            ReportToAdmin = false;
                                        }
                                        if ((AlreadyReported[DD.DriveLetter] & (Int64)ReportingFlags.ReportToClient) != 0)
                                        {
                                            ReportToClient = false;
                                        }
                                        if ((AlreadyReported[DD.DriveLetter] & (Int64)ReportingFlags.UrgentForAdmin) != 0)
                                        {
                                            UrgentForAdmin = false;
                                        }
                                        if ((AlreadyReported[DD.DriveLetter] & (Int64)ReportingFlags.UrgentForClient) != 0)
                                        {
                                            UrgentForClient = false;
                                        }
                                    }

                                    if (ReportToAdmin == false && ReportToClient == false && UrgentForAdmin == false && UrgentForClient == false)
                                    {
                                        continue;
                                    }
                                    ReportingFlags Flags = (ReportToAdmin == true ? ReportingFlags.ReportToAdmin : 0) |
                                                           (ReportToClient == true ? ReportingFlags.ReportToClient : 0) |
                                                           (UrgentForAdmin == true ? ReportingFlags.UrgentForAdmin : 0) |
                                                           (UrgentForClient == true ? ReportingFlags.UrgentForClient : 0);
                                    ReportingProcessor.ReportDiskData(sql, DiskDataList.MachineID, DD.DriveLetter, SZLimit, DD.FreeSpace, DD.Capacity, Flags);
                                    if (AlreadyReported.ContainsKey(DD.DriveLetter) == true)
                                    {
                                        AlreadyReported[DD.DriveLetter] |= (Int64)Flags;
                                    }
                                    else
                                    {
                                        AlreadyReported.Add(DD.DriveLetter, (Int64)Flags);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ee)
            {
                FoxEventLog.WriteEventLog("SEH in Disk Data Reporting " + ee.ToString(), System.Diagnostics.EventLogEntryType.Error);
            }
        }