Ejemplo n.º 1
0
        List <VulpesSMARTInfo> LoadData(string MachineID, SQLLib sql)
        {
            List <VulpesSMARTInfo> lst = new List <VulpesSMARTInfo>();

            SqlDataReader dr = sql.ExecSQLReader("Select * from SMARTData WHERE MachineID=@id", new SQLParam("@id", MachineID));

            while (dr.Read())
            {
                VulpesSMARTInfo s = new VulpesSMARTInfo();
                sql.LoadIntoClass(dr, s);
                lst.Add(s);
            }
            dr.Close();

            foreach (VulpesSMARTInfo sm in lst)
            {
                sm.Attributes = new Dictionary <int, VulpesSMARTAttribute>();

                dr = sql.ExecSQLReader("Select * from SMARTDataAttributes WHERE MachineID=@id AND PnPDeviceID=@pnp",
                                       new SQLParam("@id", MachineID),
                                       new SQLParam("@pnp", sm.PNPDeviceID));
                while (dr.Read())
                {
                    VulpesSMARTAttribute attr = new VulpesSMARTAttribute();
                    sql.LoadIntoClass(dr, attr);
                    sm.Attributes.Add(attr.ID, attr);
                }
                dr.Close();
            }
            return(lst);
        }
Ejemplo n.º 2
0
        public RESTStatus ListPolicies(SQLLib sql, object dummy, NetworkConnectionInfo ni, NameValueCollection QueryString)
        {
            if (ni.HasAcl(ACLFlags.ChangeServerSettings) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;
                return(RESTStatus.Denied);
            }

            if (QueryString["MachineID"] != null && QueryString["Grouping"] != null)
            {
                ni.Error   = "Invalid data";
                ni.ErrorID = ErrorFlags.InvalidData;
                return(RESTStatus.Fail);
            }

            PolicyList       = new PolicyObjectList();
            PolicyList.Items = new List <PolicyObject>();

            bool AllPolicies = true;
            bool WithData    = false;
            int  tmp;

            int.TryParse(QueryString["AllPolicies"] == null ? "1" : QueryString["AllPolicies"], out tmp);
            AllPolicies = tmp == 1 ? true : false;
            int.TryParse(QueryString["WithData"] == null ? "0" : QueryString["WithData"], out tmp);
            WithData = tmp == 1 ? true : false;

            lock (ni.sqllock)
            {
                SqlDataReader dr = null;
                if (AllPolicies == true)
                {
                    dr = sql.ExecSQLReader("select * from Policies order by Name");
                }
                else
                {
                    dr = sql.ExecSQLReader("select * from Policies where " + (QueryString["Grouping"] == null ? " Grouping is null AND " : " Grouping=@grouping AND ") +
                                           (QueryString["MachineID"] == null ? " MachineID is null " : " MachineID=@machineid ") + " order by Name",
                                           new SQLParam("@machineid", QueryString["MachineID"]),
                                           new SQLParam("@grouping", QueryString["Grouping"]));
                }

                while (dr.Read())
                {
                    PolicyList.Items.Add(LoadPolicyDB(dr, WithData, false));
                }
                dr.Close();
            }

            return(RESTStatus.Success);
        }
Ejemplo n.º 3
0
        public RESTStatus GetStartupItems(SQLLib sql, object dummy, NetworkConnectionInfo ni, string id)
        {
            if (ni.HasAcl(ACLFlags.ChangeServerSettings) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;
                return(RESTStatus.Denied);
            }

            StartupsRep       = new ListStartupItemReport();
            StartupsRep.Items = new List <StartupItemFull>();

            lock (ni.sqllock)
            {
                SqlDataReader dr;
                if (string.IsNullOrWhiteSpace(id) == true)
                {
                    dr = sql.ExecSQLReader("select * from Startups inner join ComputerAccounts on ComputerAccounts.MachineID=Startups.MachineID left outer join UsersList on UsersList.SID=HKCUUser AND UsersList.MachineID=Startups.MachineID order by Location,[Key]");
                }
                else
                {
                    if (Computers.MachineExists(sql, id) == false)
                    {
                        ni.Error   = "Invalid data";
                        ni.ErrorID = ErrorFlags.InvalidData;
                        return(RESTStatus.NotFound);
                    }

                    dr = sql.ExecSQLReader("select * from Startups inner join ComputerAccounts on ComputerAccounts.MachineID=Startups.MachineID left outer join UsersList on UsersList.SID=HKCUUser AND UsersList.MachineID=Startups.MachineID WHERE ComputerAccounts.MachineID=@m order by Location,[Key]",
                                           new SQLParam("@m", id));
                }

                while (dr.Read())
                {
                    StartupItemFull ar = new StartupItemFull();
                    ar.Computername = Convert.ToString(dr["Computername"]);
                    ar.DT           = SQLLib.GetDTUTC(dr["DT"]);
                    ar.HKCUUser     = Convert.ToString(dr["HKCUUser"]);
                    ar.MachineID    = Convert.ToString(dr["MachineID"]);
                    ar.Username     = Convert.ToString(dr["Username"]);
                    ar.Item         = Convert.ToString(dr["Item"]);
                    ar.Key          = Convert.ToString(dr["Key"]);
                    ar.Location     = Convert.ToString(dr["Location"]);

                    StartupsRep.Items.Add(ar);
                }
                dr.Close();
            }

            return(RESTStatus.Success);
        }
Ejemplo n.º 4
0
        public RESTStatus GetGroupDetails(SQLLib sql, object dummy, NetworkConnectionInfo ni, Int64 id)
        {
            if (ni.HasAcl(ACLFlags.ChangeServerSettings) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;
                return(RESTStatus.Denied);
            }

            lock (ni.sqllock)
            {
                if (GroupExsits(sql, id) == false)
                {
                    ni.Error   = "Invalid data";
                    ni.ErrorID = ErrorFlags.InvalidID;
                    return(RESTStatus.NotFound);
                }
            }

            lock (ni.sqllock)
            {
                SqlDataReader dr = sql.ExecSQLReader("SELECT * FROM Grouping WHERE ID=@id", new SQLParam("@id", id));
                while (dr.Read())
                {
                    GroupElement          = new GroupElement();
                    GroupElement.ID       = Convert.ToInt64(dr["ID"]);
                    GroupElement.Name     = Convert.ToString(dr["Name"]);
                    GroupElement.ParentID = dr["ParentID"] is DBNull ? (Int64?)null : Convert.ToInt64(dr["ParentID"]);
                }
                dr.Close();
            }

            return(RESTStatus.Success);
        }
Ejemplo n.º 5
0
        public RESTStatus GetGroups(SQLLib sql, object dummy, NetworkConnectionInfo ni, Int64 id)
        {
            if (ni.HasAcl(ACLFlags.ChangeServerSettings) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;
                return(RESTStatus.Denied);
            }

            GroupList      = new GroupElementList();
            GroupList.List = new List <GroupElement>();

            lock (ni.sqllock)
            {
                SqlDataReader dr = sql.ExecSQLReader("select * from Grouping WHERE ParentID=@p order by Name",
                                                     new SQLParam("@p", id));
                while (dr.Read())
                {
                    GroupElement ge = new GroupElement();
                    ge.ID       = Convert.ToInt64(dr["ID"]);
                    ge.Name     = Convert.ToString(dr["Name"]);
                    ge.ParentID = dr["ParentID"] is DBNull ? (Int64?)null : Convert.ToInt64(dr["ParentID"]);
                    GroupList.List.Add(ge);
                }
                dr.Close();
            }

            return(RESTStatus.Success);
        }
Ejemplo n.º 6
0
        public static ComputerData GetComputerDetail(SQLLib sql, string MachineID)
        {
            if (MachineExists(sql, MachineID) == false)
            {
                return(null);
            }

            SqlDataReader dr = sql.ExecSQLReader(@"
                WITH GroupingRecursive(ID, Name, ParentID, LEVEL, Path) AS
                (SELECT ID, name, ParentID, 0 AS LEVEL,
                CAST(name AS nvarchar(max)) AS treepath
                FROM Grouping
                WHERE ParentID IS NULL
                UNION ALL
                SELECT d.ID, d.Name, d.ParentID,
                GroupingRecursive.LEVEL + 1 AS LEVEL,
                CAST(GroupingRecursive.Path + '\' +
                CAST(d.Name AS nvarchar(max)) AS NVARCHAR(max)) AS treepath
                FROM Grouping as d
                INNER JOIN GroupingRecursive
                ON GroupingRecursive.ID = d.ParentID)
                select *,(SELECT Path FROM GroupingRecursive WHERE ID=ComputerAccounts.Grouping) as Path from ComputerAccounts WHERE MachineID=@id order by ComputerName",
                                                 new SQLParam("@id", MachineID));
            ComputerData cd = null;

            while (dr.Read())
            {
                cd = new ComputerData();
                PutComputerData(dr, ref cd);
            }
            dr.Close();

            return(cd);
        }
Ejemplo n.º 7
0
        public RESTStatus GetSTask(SQLLib sql, object dummy, NetworkConnectionInfo ni, Int64 id)
        {
            if (ni.HasAcl(ACLFlags.ChangeServerSettings) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;
                return(RESTStatus.Denied);
            }

            lock (ni.sqllock)
            {
                SqlDataReader dr = sql.ExecSQLReader("select * from SimpleTasks WHERE ID=@id", new SQLParam("@id", id));
                if (dr.HasRows == false)
                {
                    dr.Close();
                    return(RESTStatus.NotFound);
                }

                SimpleTask = new SimpleTask();

                while (dr.Read())
                {
                    sql.LoadIntoClass(dr, SimpleTask);
                }
                dr.Close();
            }

            return(RESTStatus.Success);
        }
Ejemplo n.º 8
0
        public RESTStatus GetPackages(SQLLib sql, object dummy, NetworkConnectionInfo ni)
        {
            if (ni.HasAcl(ACLFlags.ChangeServerSettings) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;
                return(RESTStatus.Denied);
            }

            PackageDataList       = new PackageDataList();
            PackageDataList.Items = new List <FoxSDC_Common.PackageData>();

            lock (ni.sqllock)
            {
                SqlDataReader dr = sql.ExecSQLReader("Select * FROM Packages");

                while (dr.Read())
                {
                    PackageData pd = new PackageData();
                    sql.LoadIntoClass(dr, pd);
                    PackageDataList.Items.Add(pd);
                }

                dr.Close();
            }
            return(RESTStatus.Success);
        }
Ejemplo n.º 9
0
        public RESTStatus GetPackage(SQLLib sql, object dummy, NetworkConnectionInfo ni, Int64 id)
        {
            if (ni.HasAcl(ACLFlags.ChangeServerSettings) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;
                return(RESTStatus.Denied);
            }

            lock (ni.sqllock)
            {
                if (PackageExists(sql, id) == false)
                {
                    ni.Error   = "Invalid data";
                    ni.ErrorID = ErrorFlags.InvalidID;
                    return(RESTStatus.NotFound);
                }
            }

            lock (ni.sqllock)
            {
                SqlDataReader dr = sql.ExecSQLReader("Select * FROM Packages WHERE ID=@id",
                                                     new SQLParam("@id", id));
                dr.Read();

                PackageData = new PackageData();
                sql.LoadIntoClass(dr, PackageData);
                dr.Close();
            }
            return(RESTStatus.Success);
        }
Ejemplo n.º 10
0
        public RESTStatus GetWindowsLicData(SQLLib sql, object dummy, NetworkConnectionInfo ni, string id)
        {
            if (ni.HasAcl(ACLFlags.ChangeServerSettings) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;
                return(RESTStatus.Denied);
            }

            if (string.IsNullOrWhiteSpace(id) == true)
            {
                ni.Error   = "Missing Data";
                ni.ErrorID = ErrorFlags.InvalidData;
                return(RESTStatus.Fail);
            }

            lock (ni.sqllock)
            {
                if (Computers.MachineExists(sql, id) == false)
                {
                    ni.Error   = "Invalid MachineID";
                    ni.ErrorID = ErrorFlags.InvalidValue;
                    return(RESTStatus.Fail);
                }
            }

            lock (ni.sqllock)
            {
                SqlDataReader dr = sql.ExecSQLReader("SELECT * FROM WindowsLic WHERE MachineID=@m",
                                                     new SQLParam("@m", id));
                if (dr.HasRows == false)
                {
                    dr.Close();
                    ni.Error   = "No Data";
                    ni.ErrorID = ErrorFlags.NoData;
                    return(RESTStatus.Fail);
                }

                WindowsLicData = new WindowsLic();
                dr.Read();

                WindowsLicData.Description          = Convert.ToString(dr["Description"]);
                WindowsLicData.GracePeriodRemaining = Convert.ToInt64(dr["GracePeriodRemaining"]);
                WindowsLicData.LicenseFamily        = Convert.ToString(dr["LicenseFamily"]);
                WindowsLicData.LicenseStatus        = Convert.ToInt64(dr["LicenseStatus"]);
                WindowsLicData.LicenseStatusText    = Convert.ToString(dr["LicenseStatusText"]);
                WindowsLicData.MachineID            = Convert.ToString(dr["MachineID"]);
                WindowsLicData.Name = Convert.ToString(dr["Name"]);
                WindowsLicData.PartialProductKey = Convert.ToString(dr["PartialProductKey"]);
                WindowsLicData.ProductKeyChannel = Convert.ToString(dr["ProductKeyChannel"]);
                WindowsLicData.ProductKeyID      = Convert.ToString(dr["ProductKeyID"]);
                WindowsLicData.ProductKeyID2     = Convert.ToString(dr["ProductKeyID2"]);
                WindowsLicData.Reported          = SQLLib.GetDTUTC(dr["Reported"]);

                dr.Close();
            }

            return(RESTStatus.Success);
        }
Ejemplo n.º 11
0
        public RESTStatus ListSTasks(SQLLib sql, object dummy, NetworkConnectionInfo ni, string id)
        {
            if (ni.HasAcl(ACLFlags.ChangeServerSettings) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;
                return(RESTStatus.Denied);
            }

            lock (ni.sqllock)
            {
                SqlDataReader dr;
                if (string.IsNullOrWhiteSpace(id) == false)
                {
                    if (Computers.MachineExists(sql, id) == false)
                    {
                        ni.Error   = "Access denied";
                        ni.ErrorID = ErrorFlags.InvalidData;
                        return(RESTStatus.NotFound);
                    }

                    dr = sql.ExecSQLReader("select SimpleTasks.*,ComputerName from SimpleTasks inner join ComputerAccounts on ComputerAccounts.MachineID=SimpleTasks.MachineID where SimpleTasks.MachineID=@m order by MachineID,Name",
                                           new SQLParam("@m", id));
                }
                else
                {
                    dr = sql.ExecSQLReader("select SimpleTasks.*,ComputerName from SimpleTasks inner join ComputerAccounts on ComputerAccounts.MachineID=SimpleTasks.MachineID order by MachineID,Name");
                }

                SimpleList      = new SimpleTaskLiteList();
                SimpleList.List = new List <SimpleTaskLite>();

                while (dr.Read())
                {
                    SimpleTaskLite d = new SimpleTaskLite();
                    sql.LoadIntoClass(dr, d);
                    SimpleList.List.Add(d);
                }
                dr.Close();
            }

            return(RESTStatus.Success);
        }
Ejemplo n.º 12
0
        public RESTStatus ListDiskData(SQLLib sql, object dummy, NetworkConnectionInfo ni, string id)
        {
            if (ni.HasAcl(ACLFlags.ChangeServerSettings) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;
                return(RESTStatus.Denied);
            }

            lock (ni.sqllock)
            {
                SqlDataReader dr;
                if (string.IsNullOrWhiteSpace(id) == false)
                {
                    if (Computers.MachineExists(sql, id) == false)
                    {
                        ni.Error   = "Access denied";
                        ni.ErrorID = ErrorFlags.InvalidData;
                        return(RESTStatus.NotFound);
                    }

                    dr = sql.ExecSQLReader("select DiskData.*,ComputerName from DiskData inner join ComputerAccounts on ComputerAccounts.MachineID=DiskData.MachineID where diskData.MachineID=@m order by MachineID,Caption",
                                           new SQLParam("@m", id));
                }
                else
                {
                    dr = sql.ExecSQLReader("select DiskData.*,ComputerName from DiskData inner join ComputerAccounts on ComputerAccounts.MachineID=DiskData.MachineID order by MachineID,Caption");
                }

                LstDiskData       = new ListDiskDataReport();
                LstDiskData.Items = new List <DiskDataReport>();

                while (dr.Read())
                {
                    DiskDataReport d = new DiskDataReport();
                    sql.LoadIntoClass(dr, d);
                    LstDiskData.Items.Add(d);
                }
                dr.Close();
            }

            return(RESTStatus.Success);
        }
Ejemplo n.º 13
0
        public static PolicyObject GetPolicy(SQLLib sql, Int64 ID)
        {
            PolicyObject  PolicyObj = null;
            SqlDataReader dr        = sql.ExecSQLReader("select * from Policies where ID=@id", new SQLParam("@id", ID));

            while (dr.Read())
            {
                PolicyObj = LoadPolicyDB(dr, true, false);
            }
            dr.Close();
            return(PolicyObj);
        }
Ejemplo n.º 14
0
        public RESTStatus GetComputerDetail(SQLLib sql, object dummy, NetworkConnectionInfo ni, string id)
        {
            if (ni.HasAcl(ACLFlags.ChangeServerSettings) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;
                return(RESTStatus.Denied);
            }

            lock (ni.sqllock)
            {
                if (MachineExists(sql, id) == false)
                {
                    ni.Error   = "Invalid data";
                    ni.ErrorID = ErrorFlags.InvalidData;
                    return(RESTStatus.NotFound);
                }
            }

            lock (ni.sqllock)
            {
                SqlDataReader dr = sql.ExecSQLReader(@"
                WITH GroupingRecursive(ID, Name, ParentID, LEVEL, Path) AS
                (SELECT ID, name, ParentID, 0 AS LEVEL,
                CAST(name AS nvarchar(max)) AS treepath
                FROM Grouping
                WHERE ParentID IS NULL
                UNION ALL
                SELECT d.ID, d.Name, d.ParentID,
                GroupingRecursive.LEVEL + 1 AS LEVEL,
                CAST(GroupingRecursive.Path + '\' +
                CAST(d.Name AS nvarchar(max)) AS NVARCHAR(max)) AS treepath
                FROM Grouping as d
                INNER JOIN GroupingRecursive
                ON GroupingRecursive.ID = d.ParentID)
                select *,(SELECT Path FROM GroupingRecursive WHERE ID=ComputerAccounts.Grouping) as Path from ComputerAccounts WHERE MachineID=@id order by ComputerName",
                                                     new SQLParam("@id", id));
                ComputerData cd = null;
                while (dr.Read())
                {
                    cd = new ComputerData();
                    PutComputerData(dr, ref cd);
                }
                dr.Close();
                ComputerDataInfo = cd;
            }

            return(RESTStatus.Success);
        }
Ejemplo n.º 15
0
        public RESTStatus ListRKData(SQLLib sql, object dummy, NetworkConnectionInfo ni, string id)
        {
            if (ni.HasAcl(ACLFlags.ChangeServerSettings) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;
                return(RESTStatus.Denied);
            }

            if (string.IsNullOrWhiteSpace(id) == true)
            {
                ni.Error   = "Invalid data";
                ni.ErrorID = ErrorFlags.InvalidData;
                return(RESTStatus.NotFound);
            }

            lock (ni.sqllock)
            {
                if (Computers.MachineExists(sql, id) == false)
                {
                    ni.Error   = "Invalid data";
                    ni.ErrorID = ErrorFlags.InvalidData;
                    return(RESTStatus.NotFound);
                }
            }

            LstRKData           = new BitlockerRKList();
            LstRKData.List      = new List <BitlockerRK>();
            LstRKData.MachineID = id;

            lock (ni.sqllock)
            {
                SqlDataReader dr = sql.ExecSQLReader("SELECT * FROM BitlockerRK WHERE MachineID=@m",
                                                     new SQLParam("@m", id));
                while (dr.Read())
                {
                    BitlockerRK rk = new BitlockerRK();
                    rk.DeviceID    = Convert.ToString(dr["DeviceID"]);
                    rk.DriveLetter = Convert.ToString(dr["DriveLetter"]);
                    rk.Reported    = SQLLib.GetDTUTC(dr["Reported"]);
                    rk.Keys        = JsonConvert.DeserializeObject <List <BitlockerRKKeyElement> >(Convert.ToString(dr["Keys"]));
                    LstRKData.List.Add(rk);
                }
                dr.Close();
            }

            return(RESTStatus.Success);
        }
Ejemplo n.º 16
0
        public RESTStatus ListDevicesFilters(SQLLib sql, object dummy, NetworkConnectionInfo ni, string id)
        {
            if (ni.HasAcl(ACLFlags.ChangeServerSettings) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;
                return(RESTStatus.Denied);
            }

            if (string.IsNullOrWhiteSpace(id) == true)
            {
                ni.Error   = "Invalid data";
                ni.ErrorID = ErrorFlags.InvalidData;
                return(RESTStatus.NotFound);
            }

            lock (ni.sqllock)
            {
                if (Computers.MachineExists(sql, id) == false)
                {
                    ni.Error   = "Invalid data";
                    ni.ErrorID = ErrorFlags.InvalidData;
                    return(RESTStatus.NotFound);
                }
            }

            LstFltData           = new FilterDriverList();
            LstFltData.List      = new List <FilterDriver>();
            LstFltData.MachineID = id;

            lock (ni.sqllock)
            {
                SqlDataReader dr = sql.ExecSQLReader("SELECT * FROM DevicesFilter WHERE MachineID=@mid", new SQLParam("@mid", id));
                while (dr.Read())
                {
                    FilterDriver n = new FilterDriver();
                    n.ClassGUID   = Convert.ToString(dr["ClassGUID"]);
                    n.ServiceName = Convert.ToString(dr["ServiceName"]);
                    n.Type        = Convert.ToInt32(dr["Type"]);
                    LstFltData.List.Add(n);
                }
                dr.Close();
            }

            return(RESTStatus.Success);
        }
Ejemplo n.º 17
0
        public RESTStatus GetPackageSigned(SQLLib sql, object dummy, NetworkConnectionInfo ni, Int64 id)
        {
            if (ni.HasAcl(ACLFlags.ComputerLogin) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;
                return(RESTStatus.Denied);
            }

            lock (ni.sqllock)
            {
                if (PackageExists(sql, id) == false)
                {
                    ni.Error   = "Invalid data";
                    ni.ErrorID = ErrorFlags.InvalidID;
                    return(RESTStatus.NotFound);
                }
            }

            PackageData pp = null;

            lock (ni.sqllock)
            {
                SqlDataReader dr = sql.ExecSQLReader("Select * FROM Packages WHERE ID=@id",
                                                     new SQLParam("@id", id));
                dr.Read();

                pp = new PackageData();
                sql.LoadIntoClass(dr, pp);
                dr.Close();
            }

            PackageDataSigned         = new PackageDataSigned();
            PackageDataSigned.Package = pp;
            if (Certificates.Sign(PackageDataSigned, SettingsManager.Settings.UseCertificate) == false)
            {
                FoxEventLog.WriteEventLog("Cannot sign package element with Certificate " + SettingsManager.Settings.UseCertificate, System.Diagnostics.EventLogEntryType.Warning);
                ni.Error   = "Cannot sign package element with Certificate " + SettingsManager.Settings.UseCertificate;
                ni.ErrorID = ErrorFlags.CannotSign;
                return(RESTStatus.ServerError);
            }

            return(RESTStatus.Success);
        }
Ejemplo n.º 18
0
        public RESTStatus GetPolicyObjectSigned(SQLLib sql, object dummy, NetworkConnectionInfo ni, Int64 id)
        {
            if (ni.HasAcl(ACLFlags.ComputerLogin) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;
                return(RESTStatus.Denied);
            }

            lock (ni.sqllock)
            {
                if (Policies.PolicyExsits(sql, id) == false)
                {
                    ni.Error   = "Invalid data";
                    ni.ErrorID = ErrorFlags.InvalidData;
                    return(RESTStatus.NotFound);
                }
            }

            lock (ni.sqllock)
            {
                SqlDataReader dr = sql.ExecSQLReader("select * from Policies where ID=@id", new SQLParam("@id", id));
                while (dr.Read())
                {
                    PolicyObj = LoadPolicyDB(dr, true, true);
                }
                dr.Close();
            }

            PolicyObjectSigned objs = new PolicyObjectSigned();

            objs.Policy = PolicyObj;
            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;
                return(RESTStatus.ServerError);
            }

            PolicyObjSigned = objs;

            return(RESTStatus.Success);
        }
Ejemplo n.º 19
0
        public RESTStatus GetSTaskSigned(SQLLib sql, object dummy, NetworkConnectionInfo ni)
        {
            if (ni.HasAcl(ACLFlags.ComputerLogin) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;
                return(RESTStatus.Denied);
            }

            SimpleTask SimpleTask;

            lock (ni.sqllock)
            {
                SqlDataReader dr = sql.ExecSQLReader("select top 1 * from SimpleTasks WHERE MachineID=@id AND GETUTCDATE()>isnull(execafter,'2010-01-01') ORDER BY ID asc",
                                                     new SQLParam("@id", ni.Username));
                if (dr.HasRows == false)
                {
                    dr.Close();
                    return(RESTStatus.NoContent);
                }

                SimpleTask = new SimpleTask();

                while (dr.Read())
                {
                    sql.LoadIntoClass(dr, SimpleTask);
                }
                dr.Close();
            }

            STaskDataSigned       = new SimpleTaskDataSigned();
            STaskDataSigned.STask = SimpleTask;
            if (Certificates.Sign(STaskDataSigned, SettingsManager.Settings.UseCertificate) == false)
            {
                FoxEventLog.WriteEventLog("Cannot sign STask Data with Certificate " + SettingsManager.Settings.UseCertificate, System.Diagnostics.EventLogEntryType.Warning);
                ni.Error   = "Cannot sign STask Data with Certificate " + SettingsManager.Settings.UseCertificate;
                ni.ErrorID = ErrorFlags.CannotSign;
                return(RESTStatus.ServerError);
            }

            return(RESTStatus.Success);
        }
Ejemplo n.º 20
0
        public RESTStatus GetEventLogSources(SQLLib sql, object dummy, NetworkConnectionInfo ni)
        {
            if (ni.HasAcl(ACLFlags.ChangeServerSettings) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;
                return(RESTStatus.Denied);
            }

            EventLogSources       = new NetStringList();
            EventLogSources.Items = new List <string>();

            lock (EventSourcesLock)
            {
                if (EventSourcesCacheDT.AddHours(1) < DateTime.UtcNow)
                {
                    EventSourcesCache.Clear();
                    lock (ni.sqllock)
                    {
                        SqlDataReader dr = sql.ExecSQLReader("select distinct Source from EventLog order by Source");
                        while (dr.Read())
                        {
                            EventSourcesCache.Add(Convert.ToString(dr["Source"]));
                        }
                        dr.Close();
                    }
                    EventSourcesCacheDT = DateTime.UtcNow;
                }
            }

            lock (EventSourcesLock)
            {
                EventLogSources.Items = EventSourcesCache;
            }

            return(RESTStatus.Success);
        }
Ejemplo n.º 21
0
        public static List <byte[]> GetPolicyCertificates(SQLLib sql)
        {
            List <byte[]> lst = new List <byte[]>();

            SqlDataReader dr = sql.ExecSQLReader("select DataBlob from Policies where Type=3 and Enabled=1");

            while (dr.Read())
            {
                string data = Convert.ToString(dr["DataBlob"]);
                PolicyPackageCertificates cer = null;
                try
                {
                    cer = JsonConvert.DeserializeObject <PolicyPackageCertificates>(data);
                }
                catch
                {
                }
                if (cer == null)
                {
                    continue;
                }
                if (cer.UUCerFile == null || cer.UUCerFile == "")
                {
                    continue;
                }
                try
                {
                    lst.Add(Convert.FromBase64String(cer.UUCerFile));
                }
                catch
                {
                }
            }
            dr.Close();

            return(lst);
        }
Ejemplo n.º 22
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);
        }
Ejemplo n.º 23
0
        public RESTStatus ReportBitlockerRK(SQLLib sql, BitlockerRKList BitLockerRK, NetworkConnectionInfo ni)
        {
            if (ni.HasAcl(ACLFlags.ComputerLogin) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;
                return(RESTStatus.Denied);
            }

            BitLockerRK.MachineID = ni.Username;

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

            if (BitLockerRK.List == null)
            {
                BitLockerRK.List = new List <BitlockerRK>();
            }

            if (BitLockerRK.List.Count == 0)
            {
                return(RESTStatus.Success);
            }

            List <string> DiskIDs = new List <string>();
            SqlDataReader dr      = sql.ExecSQLReader("SELECT DeviceID FROM BitlockerRK WHERE MachineID=@m",
                                                      new SQLParam("@m", BitLockerRK.MachineID));

            while (dr.Read())
            {
                DiskIDs.Add(Convert.ToString(dr["DeviceID"]).ToLower());
            }
            dr.Close();

            foreach (BitlockerRK disk in BitLockerRK.List)
            {
                if (disk.Keys == null)
                {
                    continue;
                }
                if (disk.Keys.Count == 0)
                {
                    continue;
                }
                disk.Reported = DateTime.UtcNow;
                if (disk.DeviceID == null)
                {
                    continue;
                }

                string RKs = JsonConvert.SerializeObject(disk.Keys);

                if (DiskIDs.Contains(disk.DeviceID.ToLower()) == true)
                {
                    lock (ni.sqllock)
                    {
                        sql.ExecSQL("DELETE FROM BitLockerRK WHERE MachineID=@m AND DeviceID=@d",
                                    new SQLParam("@m", BitLockerRK.MachineID),
                                    new SQLParam("@d", disk.DeviceID));
                    }
                }
                lock (ni.sqllock)
                {
                    sql.InsertMultiData("BitLockerRK",
                                        new SQLData("MachineID", BitLockerRK.MachineID),
                                        new SQLData("DeviceID", disk.DeviceID),
                                        new SQLData("DriveLetter", disk.DriveLetter == null ? "" : disk.DriveLetter),
                                        new SQLData("Keys", RKs),
                                        new SQLData("Reported", DateTime.UtcNow));
                }
            }

            return(RESTStatus.Success);
        }
Ejemplo n.º 24
0
        public RESTStatus ReportEventLog(SQLLib sql, ListEventLogReport EventLogList, NetworkConnectionInfo ni)
        {
            if (ni.HasAcl(ACLFlags.ComputerLogin) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;
                return(RESTStatus.Denied);
            }

            EventLogList.MachineID = ni.Username;

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

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

            if (EventLogList.Items.Count == 0)
            {
                return(RESTStatus.Created);
            }

            DateTime DT = DateTime.Now;

            foreach (EventLogReport ar in EventLogList.Items)
            {
                if (NullTest.Test(ar) == false)
                {
                    ni.Error   = "Invalid Items";
                    ni.ErrorID = ErrorFlags.InvalidValue;
                    return(RESTStatus.Fail);
                }
                CommonUtilities.CalcEventLogID(ar);
            }

            List <SQLParam> sqlparams = new List <SQLParam>();

            sqlparams.Add(new SQLParam("@id", EventLogList.MachineID));
            int    count = 1;
            string vars  = "";

            foreach (EventLogReport ar in EventLogList.Items)
            {
                sqlparams.Add(new SQLParam("@p" + count.ToString(), ar.LogID));
                vars += "@p" + count.ToString() + ",";
                count++;
            }
            if (vars.EndsWith(",") == true)
            {
                vars = vars.Substring(0, vars.Length - 1);
            }

            List <string> LogIDinDB = new List <string>();

            lock (ni.sqllock)
            {
                SqlDataReader dr = sql.ExecSQLReader("SELECT LogID FROM EventLog WHERE MachineID=@id and LogID in (" + vars + ")", sqlparams.ToArray());
                while (dr.Read())
                {
                    LogIDinDB.Add(Convert.ToString(dr["LogID"]));
                }
                dr.Close();
            }

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

            foreach (EventLogReport ar in EventLogList.Items)
            {
                if (LogIDinDB.Contains(ar.LogID) == true)
                {
                    RemoveEVL.Add(ar);
                    continue;
                }
                if (SettingsManager.Settings.KeepEventLogDays > 0)
                {
                    if (ar.TimeGenerated < DateTime.UtcNow.AddDays(0 - SettingsManager.Settings.KeepEventLogDays))
                    {
                        RemoveEVL.Add(ar);
                        continue;
                    }
                }
            }

            foreach (EventLogReport ar in RemoveEVL)
            {
                EventLogList.Items.Remove(ar);
            }

            List <EventLogReportFull> car = new List <EventLogReportFull>();

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

                    foreach (EventLogReport ar in EventLogList.Items)
                    {
                        EventLogReportFull arr = new EventLogReportFull();
                        ClassCopy.CopyClassData(ar, arr);
                        arr.Reported  = DateTime.UtcNow;
                        arr.MachineID = EventLogList.MachineID;
                        List <SQLData> d = sql.InsertFromClassPrep(arr);
                        foreach (SQLData dd in d)
                        {
                            if (dd.Column == "ID")
                            {
                                dd.Data = DBNull.Value;
                                break;
                            }
                        }
                        car.Add(arr);
                        sql.InsertFromClass("EventLog", arr);
                    }
                    sql.CommitTransaction();
                }
                catch (Exception ee)
                {
                    sql.RollBackTransaction();
                    FoxEventLog.WriteEventLog("DB Error: Cannot insert data to EventLog: " + ee.ToString() + "\r\n\r\nJSON: " +
                                              JsonConvert.SerializeObject(car, Formatting.Indented), System.Diagnostics.EventLogEntryType.Error);
                    return(RESTStatus.ServerError);
                }
                finally
                {
                    sql.SEHError = false;
                }
            }

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

            t.Start(car);

            return(RESTStatus.Created);
        }
Ejemplo n.º 25
0
        public RESTStatus GetEventLogs(SQLLib sql, EventLogSearch eventlogsearch, NetworkConnectionInfo ni)
        {
            if (ni.HasAcl(ACLFlags.ChangeServerSettings) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;
                return(RESTStatus.Denied);
            }

            EventLogs      = new EventLogReportFullList();
            EventLogs.Data = new List <EventLogReportFull>();

            if (eventlogsearch == null)
            {
                return(RESTStatus.Success);
            }

            if (eventlogsearch.QTY < 1)
            {
                eventlogsearch.QTY = 500;
            }

            string          SQLQuery     = "SELECT TOP " + eventlogsearch.QTY + " * FROM EventLog WHERE ";
            List <SQLParam> SQLQueryArgs = new List <SQLParam>();

            if (eventlogsearch.MachineID != null)
            {
                if (Computers.MachineExists(sql, eventlogsearch.MachineID) == false)
                {
                    ni.Error   = "Invalid Data";
                    ni.ErrorID = ErrorFlags.InvalidData;
                    return(RESTStatus.NotFound);
                }

                SQLQuery += "MachineID=@m AND ";
                SQLQueryArgs.Add(new SQLParam("@m", eventlogsearch.MachineID));
            }

            if (eventlogsearch.Source != null)
            {
                SQLQuery += "Source=@s AND ";
                SQLQueryArgs.Add(new SQLParam("@s", eventlogsearch.Source));
            }

            if (eventlogsearch.EventLogType != null)
            {
                SQLQuery += "EventLogType=@t AND ";
                SQLQueryArgs.Add(new SQLParam("@t", eventlogsearch.EventLogType));
            }

            if (eventlogsearch.FromDate != null)
            {
                SQLQuery += "TimeGenerated>=@tgf AND ";
                SQLQueryArgs.Add(new SQLParam("@tgf", eventlogsearch.FromDate));
            }

            if (eventlogsearch.ToDate != null)
            {
                SQLQuery += "TimeGenerated<=@tgt AND ";
                SQLQueryArgs.Add(new SQLParam("@tgt", eventlogsearch.ToDate));
            }

            if (eventlogsearch.EventLogBook != null)
            {
                SQLQuery += "EventLog=@evtb AND ";
                SQLQueryArgs.Add(new SQLParam("@evtb", eventlogsearch.EventLogBook));
            }

            if (eventlogsearch.CategoryNumber != null)
            {
                SQLQuery += "CategoryNumber=@catnum AND ";
                SQLQueryArgs.Add(new SQLParam("@catnum", eventlogsearch.CategoryNumber));
            }

            SQLQuery = SQLQuery.Trim();

            SQLQuery += "   1=1  ";

            SQLQuery += " ORDER BY TimeGenerated DESC";

            lock (ni.sqllock)
            {
                SqlDataReader dr = sql.ExecSQLReader(SQLQuery, SQLQueryArgs.ToArray());
                while (dr.Read())
                {
                    EventLogReportFull ev = new EventLogReportFull();
                    ev.Category               = Convert.ToString(dr["Category"]);
                    ev.CategoryNumber         = Convert.ToInt32(dr["CategoryNumber"]);
                    ev.Data                   = (byte[])dr["Data"];
                    ev.EventLog               = Convert.ToString(dr["EventLog"]);
                    ev.EventLogType           = Convert.ToInt32(dr["EventLogType"]);
                    ev.InstanceID             = Convert.ToInt64(dr["InstanceID"]);
                    ev.JSONReplacementStrings = Convert.ToString(dr["JSONReplacementStrings"]);
                    ev.LogID                  = Convert.ToString(dr["LogID"]);
                    ev.MachineID              = Convert.ToString(dr["MachineID"]);
                    ev.Message                = Convert.ToString(dr["Message"]);
                    ev.Reported               = SQLLib.GetDTUTC(dr["Reported"]);
                    ev.Source                 = Convert.ToString(dr["Source"]);
                    ev.TimeGenerated          = SQLLib.GetDTUTC(dr["TimeGenerated"]);
                    ev.TimeWritten            = SQLLib.GetDTUTC(dr["TimeWritten"]);
                    EventLogs.Data.Add(ev);
                }
                dr.Close();
            }

            return(RESTStatus.Success);
        }
Ejemplo n.º 26
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);
        }
Ejemplo n.º 27
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);
        }
Ejemplo n.º 28
0
        public RESTStatus GetAddRemovePrograms(SQLLib sql, object dummy, NetworkConnectionInfo ni, string id)
        {
            if (ni.HasAcl(ACLFlags.ChangeServerSettings) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;
                return(RESTStatus.Denied);
            }

            AddRemoveRep       = new ListAddRemoveAppsReport();
            AddRemoveRep.Items = new List <AddRemoveAppReport>();

            lock (ni.sqllock)
            {
                SqlDataReader dr;
                if (string.IsNullOrWhiteSpace(id) == true)
                {
                    dr = sql.ExecSQLReader("select * from AddRemovePrograms inner join ComputerAccounts on ComputerAccounts.MachineID=AddRemovePrograms.MachineID left outer join UsersList on UsersList.SID=HKCUUser AND UsersList.MachineID=AddRemovePrograms.MachineID order by Name,VersionMajor,VersionMinor");
                }
                else
                {
                    if (Computers.MachineExists(sql, id) == false)
                    {
                        ni.Error   = "Invalid data";
                        ni.ErrorID = ErrorFlags.InvalidData;
                        return(RESTStatus.NotFound);
                    }

                    dr = sql.ExecSQLReader("select * from AddRemovePrograms inner join ComputerAccounts on ComputerAccounts.MachineID=AddRemovePrograms.MachineID left outer join UsersList on UsersList.SID=HKCUUser AND UsersList.MachineID=AddRemovePrograms.MachineID WHERE ComputerAccounts.MachineID=@m order by Name,VersionMajor,VersionMinor",
                                           new SQLParam("@m", id));
                }

                while (dr.Read())
                {
                    AddRemoveAppReport ar = new AddRemoveAppReport();
                    ar.Computername      = Convert.ToString(dr["Computername"]);
                    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.DT       = SQLLib.GetDTUTC(dr["DT"]);
                    ar.HKCUUser = Convert.ToString(dr["HKCUUser"]);
                    ar.Username = Convert.ToString(dr["Username"]);
                    if (string.IsNullOrWhiteSpace(ar.HKCUUser) == true)
                    {
                        ar.HKCUUser = "";
                    }

                    AddRemoveRep.Items.Add(ar);
                }
                dr.Close();
            }

            return(RESTStatus.Success);
        }
Ejemplo n.º 29
0
        static void RThread()
        {
            do
            {
                try
                {
                    using (SQLLib sql = SQLTest.ConnectSQL("Fox SDC Server for Reporting", 0))
                    {
                        if (sql == null)
                        {
                            Pause();
                            if (StopThread == true)
                            {
                                break;
                            }
                        }
                        string ErrorMessage;
                        if (MailSender.CheckConfig() == false)
                        {
                            Pause();
                            if (StopThread == true)
                            {
                                break;
                            }
                            continue;
                        }

                        if (string.IsNullOrWhiteSpace(SettingsManager.Settings.EMailAdminTo) == true)
                        {
                            Pause();
                            if (StopThread == true)
                            {
                                break;
                            }
                            continue;
                        }

                        SqlDataReader dr;
                        List <string> ConcernedMachineIDs;

                        #region Normal Admin Report

                        if (SettingsManager.Settings.LastScheduleRanAdmin == null)
                        {
                            SettingsManager.Settings.LastScheduleRanAdmin = DateTime.UtcNow;
                            SettingsManager.SaveApplySettings2(sql, SettingsManager.Settings);
                        }
                        else
                        {
                            DateTime?Planned = Scheduler.GetNextRunDate(SettingsManager.Settings.LastScheduleRanAdmin.Value, SettingsManager.Settings.EMailAdminScheduling);
                            if (RunAdminNow == true)
                            {
                                Planned     = DateTime.UtcNow.AddMinutes(-1);
                                RunAdminNow = false;
                            }

                            if (Planned != null)
                            {
                                if (Planned.Value < DateTime.UtcNow) //is in the past - run now (may also be a "miss")
                                {
                                    dr = sql.ExecSQLReader("Select distinct machineid from Reporting where (Flags & @f1)!=0 AND (Flags & @f2)=0",
                                                           new SQLParam("@f1", ReportingFlags.ReportToAdmin),
                                                           new SQLParam("@f2", ReportingFlags.AdminReported));

                                    ConcernedMachineIDs = new List <string>();

                                    while (dr.Read())
                                    {
                                        ConcernedMachineIDs.Add(Convert.ToString(dr["MachineID"]));
                                    }
                                    dr.Close();

                                    if (ConcernedMachineIDs.Count > 0)
                                    {
                                        byte[] PDFFile = RenderReport.RenderMachineReport(sql, ConcernedMachineIDs, null, null, ReportingFlagsPaper.ReportAdmin, "PDF");
                                        if (PDFFile == null)
                                        {
                                            FoxEventLog.WriteEventLog("Admin Report has no data.", System.Diagnostics.EventLogEntryType.Error);
                                        }
                                        else
                                        {
                                            string Text    = SettingsManager.Settings.EMailAdminText;
                                            string Subject = SettingsManager.Settings.EMailAdminSubject;
                                            Text = Text.Replace("{URGENT}", "").
                                                   Replace("{NMACHINESS}", ConcernedMachineIDs.Count == 1 ? "" : "s").
                                                   Replace("{NMACHINES}", ConcernedMachineIDs.Count.ToString());
                                            Subject = Subject.Replace("{URGENT}", "").
                                                      Replace("{NMACHINESS}", ConcernedMachineIDs.Count == 1 ? "" : "s").
                                                      Replace("{NMACHINES}", ConcernedMachineIDs.Count.ToString());
                                            if (MailSender.SendEMailAdmin(Subject, Text, new List <System.Net.Mail.Attachment> {
                                                new System.Net.Mail.Attachment(new MemoryStream(PDFFile), ReportAttachementFilename)
                                            }, System.Net.Mail.MailPriority.Normal, out ErrorMessage, SettingsManager.Settings.EMailAdminIsHTML) == false)
                                            {
                                                FoxEventLog.WriteEventLog("Cannot send Admin E-Mail: " + ErrorMessage, System.Diagnostics.EventLogEntryType.Error);
                                            }
                                        }
                                    }

                                    SettingsManager.Settings.LastScheduleRanAdmin = DateTime.UtcNow;
                                    SettingsManager.SaveApplySettings2(sql, SettingsManager.Settings);
                                }
                            }
                            else
                            {
                                //update anyways
                                SettingsManager.Settings.LastScheduleRanAdmin = DateTime.UtcNow;
                                SettingsManager.SaveApplySettings2(sql, SettingsManager.Settings);
                            }
                        }

                        #endregion

                        #region Urgent Admin

                        dr = sql.ExecSQLReader("Select distinct machineid from Reporting where (Flags & @f1)!=0 AND (Flags & @f2)=0",
                                               new SQLParam("@f1", ReportingFlags.UrgentForAdmin),
                                               new SQLParam("@f2", ReportingFlags.UrgentAdminReported));

                        ConcernedMachineIDs = new List <string>();

                        while (dr.Read())
                        {
                            ConcernedMachineIDs.Add(Convert.ToString(dr["MachineID"]));
                        }
                        dr.Close();

                        if (ConcernedMachineIDs.Count > 0)
                        {
                            byte[] PDFFile = RenderReport.RenderMachineReport(sql, ConcernedMachineIDs, null, null, ReportingFlagsPaper.UrgentAdmin, "PDF");
                            if (PDFFile == null)
                            {
                                FoxEventLog.WriteEventLog("Urgent Admin Report has no data.", System.Diagnostics.EventLogEntryType.Error);
                            }
                            else
                            {
                                string Text    = SettingsManager.Settings.EMailAdminText;
                                string Subject = SettingsManager.Settings.EMailAdminSubject;
                                Text = Text.Replace("{URGENT}", "Urgent ").
                                       Replace("{NMACHINESS}", ConcernedMachineIDs.Count == 1 ? "" : "s").
                                       Replace("{NMACHINES}", ConcernedMachineIDs.Count.ToString());
                                Subject = Subject.Replace("{URGENT}", "Urgent ").
                                          Replace("{NMACHINESS}", ConcernedMachineIDs.Count == 1 ? "" : "s").
                                          Replace("{NMACHINES}", ConcernedMachineIDs.Count.ToString());
                                if (MailSender.SendEMailAdmin(Subject, Text, new List <System.Net.Mail.Attachment> {
                                    new System.Net.Mail.Attachment(new MemoryStream(PDFFile), ReportAttachementFilename)
                                }, System.Net.Mail.MailPriority.High, out ErrorMessage, SettingsManager.Settings.EMailAdminIsHTML) == false)
                                {
                                    FoxEventLog.WriteEventLog("Cannot send Urgent Admin E-Mail: " + ErrorMessage, System.Diagnostics.EventLogEntryType.Error);
                                }
                            }
                        }

                        #endregion

                        #region Normal Client Report

                        if (Settings.Default.UseContract == true)
                        {
                            if (SettingsManager.Settings.LastScheduleRanClient == null)
                            {
                                SettingsManager.Settings.LastScheduleRanClient = DateTime.UtcNow;
                                SettingsManager.SaveApplySettings2(sql, SettingsManager.Settings);
                            }
                            else
                            {
                                DateTime?Planned = Scheduler.GetNextRunDate(SettingsManager.Settings.LastScheduleRanClient.Value, SettingsManager.Settings.EMailClientScheduling);
                                if (Planned != null)
                                {
                                    if (Planned.Value < DateTime.UtcNow) //is in the past - run now (may also be a "miss")
                                    {
                                        dr = sql.ExecSQLReader(@"select ComputerAccounts.MachineID,ComputerAccounts.ContractID,EMail from ComputerAccounts
                                        inner join Contracts on Contracts.ContractID = ComputerAccounts.ContractID
                                        where Disabled = 0 and MachineID in (Select distinct machineid from Reporting where (Flags & @f1) != 0 AND(Flags & @f2) = 0) and EMail is not null and EMail !=''",
                                                               new SQLParam("@f1", ReportingFlags.ReportToClient),
                                                               new SQLParam("@f2", ReportingFlags.ClientReported));

                                        List <ConcernedMachineIDsClient> ConcernedMachineIDC = new List <ConcernedMachineIDsClient>();
                                        List <string> ContractIDs = new List <string>();

                                        while (dr.Read())
                                        {
                                            ConcernedMachineIDsClient m = new ConcernedMachineIDsClient();
                                            m.ContractID = Convert.ToString(dr["ContractID"]);
                                            m.MachineID  = Convert.ToString(dr["MachineID"]);
                                            m.EMail      = Convert.ToString(dr["EMail"]);
                                            ConcernedMachineIDC.Add(m);
                                            if (ContractIDs.Contains(m.ContractID) == false)
                                            {
                                                ContractIDs.Add(m.ContractID);
                                            }
                                        }
                                        dr.Close();

                                        foreach (string ContractID in ContractIDs)
                                        {
                                            List <string> ConcernedMachineIDsForClient = new List <string>();
                                            string        EMail = "";
                                            foreach (ConcernedMachineIDsClient m in ConcernedMachineIDC)
                                            {
                                                if (m.ContractID == ContractID)
                                                {
                                                    ConcernedMachineIDsForClient.Add(m.MachineID);
                                                }
                                                if (string.IsNullOrWhiteSpace(EMail) == true)
                                                {
                                                    EMail = m.EMail;
                                                }
                                            }

                                            if (string.IsNullOrWhiteSpace(EMail) == true)
                                            {
                                                continue;
                                            }

                                            if (ConcernedMachineIDsForClient.Count > 0)
                                            {
                                                byte[] PDFFile = RenderReport.RenderMachineReport(sql, ConcernedMachineIDsForClient, null, null, ReportingFlagsPaper.ReportClient, "PDF");
                                                if (PDFFile == null)
                                                {
                                                    FoxEventLog.WriteEventLog("Client Report has no data.", System.Diagnostics.EventLogEntryType.Error);
                                                }
                                                else
                                                {
                                                    string Text    = SettingsManager.Settings.EMailClientText;
                                                    string Subject = SettingsManager.Settings.EMailClientSubject;
                                                    Text = Text.Replace("{URGENT}", "").
                                                           Replace("{NMACHINESS}", ConcernedMachineIDsForClient.Count == 1 ? "" : "s").
                                                           Replace("{NMACHINES}", ConcernedMachineIDsForClient.Count.ToString());
                                                    Subject = Subject.Replace("{URGENT}", "").
                                                              Replace("{NMACHINESS}", ConcernedMachineIDsForClient.Count == 1 ? "" : "s").
                                                              Replace("{NMACHINES}", ConcernedMachineIDsForClient.Count.ToString());
                                                    if (MailSender.SendEMailClient(EMail, Subject, Text, new List <System.Net.Mail.Attachment> {
                                                        new System.Net.Mail.Attachment(new MemoryStream(PDFFile), ReportAttachementFilename)
                                                    }, System.Net.Mail.MailPriority.High, out ErrorMessage, SettingsManager.Settings.EMailClientIsHTML) == false)
                                                    {
                                                        FoxEventLog.WriteEventLog("Cannot send Client E-Mail: " + ErrorMessage, System.Diagnostics.EventLogEntryType.Error);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    //update anyways
                                    SettingsManager.Settings.LastScheduleRanClient = DateTime.UtcNow;
                                    SettingsManager.SaveApplySettings2(sql, SettingsManager.Settings);
                                }
                            }
                        }

                        #endregion

                        #region Urgent Client

                        if (Settings.Default.UseContract == true)
                        {
                            dr = sql.ExecSQLReader(@"select ComputerAccounts.MachineID,ComputerAccounts.ContractID,EMail from ComputerAccounts
                                inner join Contracts on Contracts.ContractID = ComputerAccounts.ContractID
                                where Disabled = 0 and MachineID in (Select distinct machineid from Reporting where (Flags & @f1) != 0 AND(Flags & @f2) = 0) and EMail is not null and EMail !=''",
                                                   new SQLParam("@f1", ReportingFlags.UrgentForClient),
                                                   new SQLParam("@f2", ReportingFlags.UrgentClientReported));

                            List <ConcernedMachineIDsClient> ConcernedMachineIDC = new List <ConcernedMachineIDsClient>();
                            List <string> ContractIDs = new List <string>();

                            while (dr.Read())
                            {
                                ConcernedMachineIDsClient m = new ConcernedMachineIDsClient();
                                m.ContractID = Convert.ToString(dr["ContractID"]);
                                m.MachineID  = Convert.ToString(dr["MachineID"]);
                                m.EMail      = Convert.ToString(dr["EMail"]);
                                ConcernedMachineIDC.Add(m);
                                if (ContractIDs.Contains(m.ContractID) == false)
                                {
                                    ContractIDs.Add(m.ContractID);
                                }
                            }
                            dr.Close();

                            foreach (string ContractID in ContractIDs)
                            {
                                List <string> ConcernedMachineIDsForClient = new List <string>();
                                string        EMail = "";
                                foreach (ConcernedMachineIDsClient m in ConcernedMachineIDC)
                                {
                                    if (m.ContractID == ContractID)
                                    {
                                        ConcernedMachineIDsForClient.Add(m.MachineID);
                                    }
                                    if (string.IsNullOrWhiteSpace(EMail) == true)
                                    {
                                        EMail = m.EMail;
                                    }
                                }

                                if (string.IsNullOrWhiteSpace(EMail) == true)
                                {
                                    continue;
                                }

                                if (ConcernedMachineIDsForClient.Count > 0)
                                {
                                    byte[] PDFFile = RenderReport.RenderMachineReport(sql, ConcernedMachineIDsForClient, null, null, ReportingFlagsPaper.UrgentClient, "PDF");
                                    if (PDFFile == null)
                                    {
                                        FoxEventLog.WriteEventLog("Urgent Client Report has no data.", System.Diagnostics.EventLogEntryType.Error);
                                    }
                                    else
                                    {
                                        string Text    = SettingsManager.Settings.EMailClientText;
                                        string Subject = SettingsManager.Settings.EMailClientSubject;
                                        Text = Text.Replace("{URGENT}", "Urgent ").
                                               Replace("{NMACHINESS}", ConcernedMachineIDsForClient.Count == 1 ? "" : "s").
                                               Replace("{NMACHINES}", ConcernedMachineIDsForClient.Count.ToString());
                                        Subject = Subject.Replace("{URGENT}", "Urgent ").
                                                  Replace("{NMACHINESS}", ConcernedMachineIDsForClient.Count == 1 ? "" : "s").
                                                  Replace("{NMACHINES}", ConcernedMachineIDsForClient.Count.ToString());
                                        if (MailSender.SendEMailClient(EMail, Subject, Text, new List <System.Net.Mail.Attachment> {
                                            new System.Net.Mail.Attachment(new MemoryStream(PDFFile), ReportAttachementFilename)
                                        }, System.Net.Mail.MailPriority.High, out ErrorMessage, SettingsManager.Settings.EMailClientIsHTML) == false)
                                        {
                                            FoxEventLog.WriteEventLog("Cannot send Urgent Client E-Mail: " + ErrorMessage, System.Diagnostics.EventLogEntryType.Error);
                                        }
                                    }
                                }
                            }
                        }

                        #endregion
                    }
                }
                catch (Exception ee)
                {
                    FoxEventLog.WriteEventLog("Cannot process reporting data\n" + ee.ToString(), System.Diagnostics.EventLogEntryType.Error);
                }

                Pause();
                if (StopThread == true)
                {
                    break;
                }
            } while (StopThread == false);
        }
Ejemplo n.º 30
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);
        }