Example #1
0
        public RESTStatus ChangeCommentsComputer(SQLLib sql, NetString comments, 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 (Convert.ToInt32(sql.ExecSQLScalar("SELECT COUNT(*) FROM ComputerAccounts WHERE MachineID=@m", new SQLParam("@m", id))) == 0)
                {
                    ni.Error   = "Invalid data";
                    ni.ErrorID = ErrorFlags.InvalidData;
                    return(RESTStatus.NotFound);
                }
            }

            if (comments.Data == null)
            {
                ni.Error   = "Invalid data";
                ni.ErrorID = ErrorFlags.InvalidData;
                return(RESTStatus.Fail);
            }

            lock (ni.sqllock)
            {
                sql.ExecSQL("UPDATE ComputerAccounts SET Comments=@c WHERE MachineID=@m",
                            new SQLParam("@m", id),
                            new SQLParam("@c", comments.Data));
            }

            return(RESTStatus.NoContent);
        }
Example #2
0
        public RESTStatus DeleteGroup(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 (Convert.ToInt32(sql.ExecSQLScalar("SELECT COUNT(*) FROM Grouping WHERE ID=@id",
                                                      new SQLParam("@id", id))) == 0)
                {
                    ni.Error   = "Group does not exist";
                    ni.ErrorID = ErrorFlags.InvalidData;
                    return(RESTStatus.NotFound);
                }
            }

            try
            {
                lock (ni.sqllock)
                {
                    sql.ExecSQL("DELETE FROM Grouping WHERE ID=@id", new SQLParam("@id", id));
                }
            }
            catch
            {
                ni.Error   = "SQL Error";
                ni.ErrorID = ErrorFlags.SQLError;
                return(RESTStatus.ServerError);
            }
            return(RESTStatus.Success);
        }
Example #3
0
        public RESTStatus GetSMARTInfos(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 (Convert.ToInt32(sql.ExecSQLScalar("SELECT COUNT(*) FROM ComputerAccounts WHERE MachineID=@m",
                                                      new SQLParam("@m", id))) == 0)
                {
                    ni.Error   = "Invalid MachineID";
                    ni.ErrorID = ErrorFlags.InvalidValue;
                    return(RESTStatus.NotFound);
                }
            }

            SMARTRet           = new VulpesSMARTInfoList();
            SMARTRet.MachineID = id;
            SMARTRet.List      = LoadData(id, sql);

            return(RESTStatus.Success);
        }
Example #4
0
 public static bool MachineExists(SQLLib sql, string MachineID)
 {
     if (Convert.ToInt32(sql.ExecSQLScalar("SELECT COUNT(*) FROM ComputerAccounts WHERE MachineID=@m",
                                           new SQLParam("@m", MachineID))) == 0)
     {
         return(false);
     }
     return(true);
 }
Example #5
0
        public RESTStatus GetPackageMeta(SQLLib sql, HttpListenerRequest request, HttpListenerResponse response, object dummy, NetworkConnectionInfo ni, Int64 id)
        {
            if (ni.HasAcl(ACLFlags.ChangeServerSettings) == false && ni.HasAcl(ACLFlags.ComputerLogin) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;

                response.AddHeader("Content-Type", "text/plain; charset=UTF-8");
                response.StatusCode        = 403;
                response.StatusDescription = "Forbidden";
                byte[] data = Encoding.UTF8.GetBytes("403 - Forbidden.");
                response.ContentLength64 = data.LongLength;
                Stream output = response.OutputStream;
                output.Write(data, 0, data.Length);

                return(RESTStatus.Denied);
            }

            if (PackageExists(sql, id) == false)
            {
                ni.Error   = "Invalid data";
                ni.ErrorID = ErrorFlags.InvalidID;

                response.AddHeader("Content-Type", "text/plain; charset=UTF-8");
                response.StatusCode        = 404;
                response.StatusDescription = "Not found";
                byte[] data = Encoding.UTF8.GetBytes("404 - Not found.");
                response.ContentLength64 = data.LongLength;
                Stream output = response.OutputStream;
                output.Write(data, 0, data.Length);

                return(RESTStatus.NotFound);
            }

            string MetaFilename = Convert.ToString(sql.ExecSQLScalar("SELECT MetaFilename FROM Packages WHERE ID=@id",
                                                                     new SQLParam("@id", id)));

            if (File.Exists(Settings.Default.DataPath + MetaFilename) == false)
            {
                ni.Error   = "Cannot find local file";
                ni.ErrorID = ErrorFlags.FileSystemError;

                response.AddHeader("Content-Type", "text/plain; charset=UTF-8");
                response.StatusCode        = 500;
                response.StatusDescription = "Server Error";
                byte[] data = Encoding.UTF8.GetBytes("500 - Server Error.");
                response.ContentLength64 = data.LongLength;
                Stream output = response.OutputStream;
                output.Write(data, 0, data.Length);

                return(RESTStatus.ServerError);
            }

            Downloader.ReadFileChunked(Settings.Default.DataPath + MetaFilename, request, response);

            return(RESTStatus.Success);
        }
Example #6
0
 public static bool PolicyExsits(SQLLib sql, Int64 ID)
 {
     if (Convert.ToInt32(sql.ExecSQLScalar("SELECT COUNT(*) FROM Policies WHERE ID=@id",
                                           new SQLParam("@id", ID))) == 0)
     {
         return(false);
     }
     return(true);
 }
Example #7
0
 public static bool PackageExists(SQLLib sql, Int64 id)
 {
     if (Convert.ToInt32(sql.ExecSQLScalar("Select count(*) FROM Packages WHERE ID=@id",
                                           new SQLParam("@id", id))) == 0)
     {
         return(false);
     }
     return(true);
 }
Example #8
0
 public static bool GroupExsits(SQLLib sql, Int64 GroupID)
 {
     if (Convert.ToInt32(sql.ExecSQLScalar("SELECT COUNT(*) FROM Grouping WHERE ID=@id",
                                           new SQLParam("@id", GroupID))) == 0)
     {
         return(false);
     }
     return(true);
 }
Example #9
0
        public RESTStatus ReportDevicesFilter(SQLLib sql, FilterDriverList devices, NetworkConnectionInfo ni)
        {
            if (ni.HasAcl(ACLFlags.ComputerLogin) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;
                return(RESTStatus.Denied);
            }

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

            devices.MachineID = ni.Username;

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

            lock (ni.sqllock)
            {
                sql.ExecSQL("DELETE FROM DevicesFilter WHERE MachineID=@id", new SQLParam("@id", devices.MachineID));
            }

            if (devices.List == null)
            {
                devices.List = new List <FilterDriver>();
            }

            int Counter = 0;

            foreach (FilterDriver flt in devices.List)
            {
                lock (ni.sqllock)
                {
                    sql.InsertMultiData("DevicesFilter",
                                        new SQLData("MachineID", devices.MachineID),
                                        new SQLData("Index", Counter),
                                        new SQLData("ClassGUID", flt.ClassGUID),
                                        new SQLData("ServiceName", flt.ServiceName),
                                        new SQLData("Type", flt.Type));
                }
                Counter++;
            }

            return(RESTStatus.Success);
        }
Example #10
0
        public RESTStatus DeletePackage(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);
                }
            }

            string Filename     = null;
            string MetaFilename = null;

            lock (ni.sqllock)
            {
                Filename = Convert.ToString(sql.ExecSQLScalar("SELECT Filename FROM Packages WHERE ID=@id",
                                                              new SQLParam("@id", id)));
            }
            lock (ni.sqllock)
            {
                MetaFilename = Convert.ToString(sql.ExecSQLScalar("SELECT MetaFilename FROM Packages WHERE ID=@id",
                                                                  new SQLParam("@id", id)));
            }

            CommonUtilities.SpecialDeleteFile(Settings.Default.DataPath + Filename);
            CommonUtilities.SpecialDeleteFile(Settings.Default.DataPath + MetaFilename);

            lock (ni.sqllock)
            {
                sql.ExecSQL("DELETE FROM Packages WHERE ID=@id", new SQLParam("@id", id));
            }

            return(RESTStatus.Success);
        }
Example #11
0
 public static bool STaskExsits(SQLLib sql, Int64 ID, string MID)
 {
     if (Convert.ToInt32(sql.ExecSQLScalar("SELECT COUNT(*) FROM SimpleTasks WHERE ID=@id AND MachineID=@mid",
                                           new SQLParam("@id", ID),
                                           new SQLParam("@mid", MID))) == 0)
     {
         return(false);
     }
     return(true);
 }
Example #12
0
        static bool GetBool(SQLLib sql, string SettingsName, bool DefaultValue = false)
        {
            string s = Convert.ToString(sql.ExecSQLScalar("SELECT Value FROM Config WHERE [Key]=@sn",
                                                          new SQLParam("@sn", SettingsName)));

            if (s == null)
            {
                return(DefaultValue);
            }
            return(s.Trim() == "1" ? true : false);
        }
Example #13
0
        static string GetString(SQLLib sql, string SettingsName, String DefaultValue = "")
        {
            object oo = sql.ExecSQLScalar("SELECT Value FROM Config WHERE [Key]=@sn",
                                          new SQLParam("@sn", SettingsName));

            if (oo == null)
            {
                return(DefaultValue);
            }
            return(Convert.ToString(oo));
        }
Example #14
0
        public RESTStatus ReportWindowsLic(SQLLib sql, WindowsLic WinLic, NetworkConnectionInfo ni)
        {
            if (ni.HasAcl(ACLFlags.ComputerLogin) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;
                return(RESTStatus.Denied);
            }

            WinLic.MachineID = ni.Username;
            WinLic.Reported  = DateTime.Now;

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

            lock (ni.sqllock)
            {
                sql.ExecSQL("DELETE FROM WindowsLic WHERE MachineID=@m",
                            new SQLParam("@m", WinLic.MachineID));
            }

            if (NullTest.Test(WinLic) == false)
            {
                ni.Error   = "Invalid Data";
                ni.ErrorID = ErrorFlags.InvalidData;
                return(RESTStatus.Fail);
            }

            lock (ni.sqllock)
            {
                sql.InsertMultiData("WindowsLic",
                                    new SQLData("MachineID", WinLic.MachineID),
                                    new SQLData("Name", WinLic.Name),
                                    new SQLData("Description", WinLic.Description),
                                    new SQLData("GracePeriodRemaining", WinLic.GracePeriodRemaining),
                                    new SQLData("PartialProductKey", WinLic.PartialProductKey),
                                    new SQLData("ProductKeyID", WinLic.ProductKeyID),
                                    new SQLData("ProductKeyID2", WinLic.ProductKeyID2),
                                    new SQLData("LicenseFamily", WinLic.LicenseFamily),
                                    new SQLData("ProductKeyChannel", WinLic.ProductKeyChannel),
                                    new SQLData("LicenseStatus", WinLic.LicenseStatus),
                                    new SQLData("LicenseStatusText", WinLic.LicenseStatusText));
            }

            return(RESTStatus.Success);
        }
Example #15
0
        public RESTStatus ApproveComputer(SQLLib sql, ApproveComputer state, 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 (Convert.ToInt32(sql.ExecSQLScalar("SELECT COUNT(*) FROM ComputerAccounts WHERE MachineID=@m", new SQLParam("@m", id))) == 0)
                {
                    ni.Error   = "Invalid data";
                    ni.ErrorID = ErrorFlags.InvalidData;
                    return(RESTStatus.NotFound);
                }
            }

            lock (ni.sqllock)
            {
                if (Convert.ToInt32(sql.ExecSQLScalar("SELECT COUNT(*) FROM Grouping WHERE ID=@id", new SQLParam("@id", state.Group))) == 0)
                {
                    ni.Error   = "Invalid data";
                    ni.ErrorID = ErrorFlags.InvalidData;
                    return(RESTStatus.Fail);
                }
            }

            lock (ni.sqllock)
            {
                sql.ExecSQL("UPDATE ComputerAccounts SET Accepted=@a,Grouping=@g WHERE MachineID=@m",
                            new SQLParam("@m", id),
                            new SQLParam("@g", state.Group),
                            new SQLParam("@a", state.State == true ? 1 : 0));
            }
            return(RESTStatus.NoContent);
        }
Example #16
0
        static DateTime?GetDateTimex(SQLLib sql, string SettingsName)
        {
            string s = Convert.ToString(sql.ExecSQLScalar("SELECT Value FROM Config WHERE [Key]=@sn",
                                                          new SQLParam("@sn", SettingsName)));

            if (string.IsNullOrWhiteSpace(s) == true)
            {
                return(null);
            }
            Int64 i;

            if (Int64.TryParse(s, out i) == false)
            {
                return(null);
            }
            return(DateTime.FromFileTimeUtc(i));
        }
Example #17
0
        static Int64 GetInt64(SQLLib sql, string SettingsName, Int64 DefaultValue = 0)
        {
            string s = Convert.ToString(sql.ExecSQLScalar("SELECT Value FROM Config WHERE [Key]=@sn",
                                                          new SQLParam("@sn", SettingsName)));

            if (s == null)
            {
                return(DefaultValue);
            }
            Int64 o;

            if (Int64.TryParse(s, out o) == false)
            {
                return(DefaultValue);
            }
            return(o);
        }
Example #18
0
        public RESTStatus CompleteSTask(SQLLib sql, SimpleTaskResult STaskResult, NetworkConnectionInfo ni)
        {
            if (ni.HasAcl(ACLFlags.ComputerLogin) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;
                return(RESTStatus.Denied);
            }

            if (STaskResult == null)
            {
                ni.Error   = "Invalid ID";
                ni.ErrorID = ErrorFlags.InvalidData;
                return(RESTStatus.NotFound);
            }

            lock (ni.sqllock)
            {
                STaskResult.MachineID = ni.Username;
                if (STaskExsits(sql, STaskResult.ID, STaskResult.MachineID) == false)
                {
                    ni.Error   = "Invalid ID";
                    ni.ErrorID = ErrorFlags.InvalidData;
                    return(RESTStatus.NotFound);
                }
            }

            lock (ni.sqllock)
            {
                STaskResult.Name = Convert.ToString(sql.ExecSQLScalar("SELECT Name FROM SimpleTasks WHERE ID=@id",
                                                                      new SQLParam("@id", STaskResult.ID)));
            }

            lock (ni.sqllock)
            {
                sql.ExecSQL("DELETE FROM SimpleTasks WHERE ID=@id",
                            new SQLParam("@id", STaskResult.ID));
            }

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

            t.Start(STaskResult);

            return(RESTStatus.Success);
        }
Example #19
0
        public RESTStatus PutTaskAside(SQLLib sql, NetInt64 id, NetworkConnectionInfo ni)
        {
            if (ni.HasAcl(ACLFlags.ComputerLogin) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;
                return(RESTStatus.Denied);
            }

            if (STaskExsits(sql, id.Data, ni.Username) == false)
            {
                ni.Error   = "Invalid ID";
                ni.ErrorID = ErrorFlags.InvalidData;
                return(RESTStatus.NotFound);
            }

            object res = sql.ExecSQLScalar(@"DECLARE @tabl table(ID bigint); 
                insert into SimpleTasks (MachineID,Type,Name,Data) OUTPUT Inserted.ID INTO @tabl 
                Select MachineID,Type,Name,Data from SimpleTasks WHERE ID=@id
                DELETE FROM SimpleTasks where ID=@id
                SELECT * FROM @tabl",
                                           new SQLParam("@id", id.Data));

            if (res == null || res is DBNull)
            {
                ni.Error   = "SQL error";
                ni.ErrorID = ErrorFlags.SQLError;
                return(RESTStatus.NotFound);
            }

            NewTaskID = new NetInt64();
            try
            {
                NewTaskID.Data = Convert.ToInt64(res);
            }
            catch
            {
                ni.Error   = "other SQL error";
                ni.ErrorID = ErrorFlags.SQLError;
                return(RESTStatus.NotFound);
            }

            return(RESTStatus.Success);
        }
Example #20
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);
        }
Example #21
0
        static public bool InitNi(NetworkConnectionInfo ni)
        {
            if (ni == null)
            {
                return(false);
            }
            if (ni.Inited == true)
            {
                return(true);
            }
            ni.ServerInfo                 = new ServerInfo();
            ni.ServerInfo.Name            = Environment.MachineName;
            ni.ServerInfo.ProtocolVersion = 1;
            ni.ServerInfo.ServerVersion   = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
            if (ni.FromClone == false)
            {
                ni.LoggedIn         = false;
                ni.ComputerLoggedIn = false;
                ni.Username         = "";
                ni.Name             = "";
                ni.EMail            = "";
            }

            SQLLib sql = SQLTest.ConnectSQL("Fox SDC Server for " + ni.ID);

            if (sql == null)
            {
                return(false);
            }
            ni.sql          = sql;
            ni.sql.SEHError = true;

            ni.Inited = true;
            ni.ServerInfo.ServerGUID = Convert.ToString(sql.ExecSQLScalar("SELECT [Value] from Config WHERE [Key]='GUID'"));

            ni.ServerInfo.SQLServer         = "N/A";
            ni.ServerInfo.SQLService        = "N/A";
            ni.ServerInfo.SQLCollation      = "N/A";
            ni.ServerInfo.SQLEdition        = "N/A";
            ni.ServerInfo.SQLProductVersion = "N/A";
            ni.ServerInfo.SQLProductLevel   = "N/A";
            ni.ServerInfo.SQLProductName    = "N/A";

            ni.ServerInfo.LicFeatures       = "N/A";
            ni.ServerInfo.LicLicenseID      = "N/A";
            ni.ServerInfo.LicLicenseType    = "N/A";
            ni.ServerInfo.LicOwner          = "N/A";
            ni.ServerInfo.LicOwnerCustomID  = "N/A";
            ni.ServerInfo.LicSupportValidTo = null;
            ni.ServerInfo.LicUCID           = "N/A";
            ni.ServerInfo.LicVacant1        = "N/A";
            ni.ServerInfo.LicVacant2        = "N/A";
            ni.ServerInfo.LicVacant3        = "N/A";
            ni.ServerInfo.LicVacant4        = "N/A";
            ni.ServerInfo.LicVacant5        = "N/A";
            ni.ServerInfo.LicValidFrom      = new DateTime(2000, 1, 1, 0, 0, 0, 0);
            ni.ServerInfo.LicValidTo        = null;

            if (Settings.Default.CensorSQLInformations == false)
            {
                ni.ServerInfo.SQLServer         = Convert.ToString(sql.ExecSQLScalar("select @@SERVERNAME"));
                ni.ServerInfo.SQLService        = Convert.ToString(sql.ExecSQLScalar("select @@SERVICENAME"));
                ni.ServerInfo.SQLCollation      = Convert.ToString(sql.ExecSQLScalar("select SERVERPROPERTY ('Collation')"));
                ni.ServerInfo.SQLEdition        = Convert.ToString(sql.ExecSQLScalar("select SERVERPROPERTY ('edition')"));
                ni.ServerInfo.SQLProductVersion = Convert.ToString(sql.ExecSQLScalar("SELECT SERVERPROPERTY('productversion')"));
                ni.ServerInfo.SQLProductLevel   = Convert.ToString(sql.ExecSQLScalar("select SERVERPROPERTY ('productlevel')"));
                ni.ServerInfo.SQLProductName    = Convert.ToString(sql.ExecSQLScalar("SELECT LEFT(@@version, CHARINDEX(' - ', @@version))"));
            }

            if (Settings.Default.CensorLicInformations == false)
            {
                if (Fox_LicenseGenerator.SDCLicensing.Data != null)
                {
                    ni.ServerInfo.LicFeatures       = Fox_LicenseGenerator.SDCLicensing.Data.Features;
                    ni.ServerInfo.LicLicenseID      = Fox_LicenseGenerator.SDCLicensing.Data.LicenseID;
                    ni.ServerInfo.LicLicenseType    = Fox_LicenseGenerator.SDCLicensing.Data.LicenseType;
                    ni.ServerInfo.LicOwner          = Fox_LicenseGenerator.SDCLicensing.Data.Owner;
                    ni.ServerInfo.LicOwnerCustomID  = Fox_LicenseGenerator.SDCLicensing.Data.OwnerCustomID;
                    ni.ServerInfo.LicSupportValidTo = Fox_LicenseGenerator.SDCLicensing.Data.SupportValidTo;
                    ni.ServerInfo.LicUCID           = Fox_LicenseGenerator.SDCLicensing.Data.UCID;
                    ni.ServerInfo.LicVacant1        = Fox_LicenseGenerator.SDCLicensing.Data.Vacant1;
                    ni.ServerInfo.LicVacant2        = Fox_LicenseGenerator.SDCLicensing.Data.Vacant2;
                    ni.ServerInfo.LicVacant3        = Fox_LicenseGenerator.SDCLicensing.Data.Vacant3;
                    ni.ServerInfo.LicVacant4        = Fox_LicenseGenerator.SDCLicensing.Data.Vacant4;
                    ni.ServerInfo.LicVacant5        = Fox_LicenseGenerator.SDCLicensing.Data.Vacant5;
                    ni.ServerInfo.LicValidFrom      = Fox_LicenseGenerator.SDCLicensing.Data.ValidFrom;
                    ni.ServerInfo.LicValidTo        = Fox_LicenseGenerator.SDCLicensing.Data.ValidTo;
                }
                else
                {
                    ni.ServerInfo.LicOwner = "Error";
                }
            }

            return(true);
        }
Example #22
0
        public RESTStatus CreateGroup(SQLLib sql, CreateGroup GroupName, NetworkConnectionInfo ni)
        {
            if (ni.HasAcl(ACLFlags.ChangeServerSettings) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;
                return(RESTStatus.Denied);
            }

            if (GroupName.Name == null)
            {
                ni.Error   = "Invalid data";
                ni.ErrorID = ErrorFlags.InvalidData;
                return(RESTStatus.Fail);
            }

            if (GroupName.Name.Trim() == "")
            {
                ni.Error   = "Invalid data";
                ni.ErrorID = ErrorFlags.InvalidData;
                return(RESTStatus.Fail);
            }

            if (GroupName.ToParent != null)
            {
                lock (ni.sqllock)
                {
                    if (Convert.ToInt32(sql.ExecSQLScalar("SELECT COUNT(*) FROM Grouping WHERE ID=@id",
                                                          new SQLParam("@id", GroupName.ToParent))) == 0)
                    {
                        ni.Error   = "Group does not exist";
                        ni.ErrorID = ErrorFlags.InvalidData;
                        return(RESTStatus.Fail);
                    }
                }
            }

            lock (ni.sqllock)
            {
                if (Convert.ToInt32(sql.ExecSQLScalar("SELECT COUNT(*) FROM Grouping WHERE ParentID=@pid AND Name=@n",
                                                      new SQLParam("@pid", GroupName.ToParent),
                                                      new SQLParam("@n", GroupName.Name.Trim()))) > 0)
                {
                    ni.Error   = "Duplicate name";
                    ni.ErrorID = ErrorFlags.DuplicateElement;
                    return(RESTStatus.Fail);
                }
            }

            NewGroupID = new NetInt64();

            Int64?nid = null;

            lock (ni.sqllock)
            {
                nid = sql.InsertMultiDataID("Grouping",
                                            new SQLData("Name", GroupName.Name.Trim()),
                                            new SQLData("ParentID", GroupName.ToParent));
            }

            if (nid == null)
            {
                ni.Error   = "SQL Error";
                ni.ErrorID = ErrorFlags.SQLError;
                return(RESTStatus.ServerError);
            }
            NewGroupID.Data = nid.Value;

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

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

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

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

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

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

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

            Guid testguid;

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

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

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

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

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

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

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

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

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

            string newID = NetworkConnection.NewSession();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                object   dt;
                DateTime dtt;

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

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

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

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

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

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

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

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

            AddRemoveList.MachineID = ni.Username;

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

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

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

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

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

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

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

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

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

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

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

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

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

            AddRemoveProgramsLst l = new AddRemoveProgramsLst();

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

            t.Start(l);

            return(RESTStatus.Created);
        }
Example #25
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);
        }
Example #26
0
        public RESTStatus RemoveComputer(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 (Convert.ToInt32(sql.ExecSQLScalar("SELECT COUNT(*) FROM ComputerAccounts WHERE MachineID=@m", new SQLParam("@m", id))) == 0)
                {
                    ni.Error   = "Invalid data";
                    ni.ErrorID = ErrorFlags.InvalidData;
                    return(RESTStatus.NotFound);
                }
            }

            lock (ni.sqllock)
            {
                sql.ExecSQLScalar("UPDATE ComputerAccounts SET Accepted=0 WHERE MachineID=@m", new SQLParam("@m", id));
            }

            lock (ni.sqllock)
            {
                //delete other things
                sql.ExecSQLScalar(@"DECLARE @Deleted_Rows INT
                            DECLARE @Deleted_Rows_Total INT
                            SET @Deleted_Rows = 1
                            SET @Deleted_Rows_Total = 0

                            WHILE (@Deleted_Rows > 0)
                            BEGIN
                                delete top (10000) from EventLog where MachineID=@m
                                SET @Deleted_Rows = @@ROWCOUNT
                                SET @Deleted_Rows_Total = @Deleted_Rows_Total + @Deleted_Rows
                            END

                            Select @Deleted_Rows_Total",
                                  new SQLParam("@m", id));
            }
            lock (ni.sqllock)
                sql.ExecSQL("UPDATE Policies SET MachineID=null, Enabled=0 WHERE MachineID=@m", new SQLParam("@m", id));
            lock (ni.sqllock)
                sql.ExecSQL("DELETE FROM AddRemovePrograms WHERE MachineID=@m", new SQLParam("@m", id));
            lock (ni.sqllock)
                sql.ExecSQL("DELETE FROM BitlockerRK WHERE MachineID=@m", new SQLParam("@m", id));
            lock (ni.sqllock)
                sql.ExecSQL("DELETE FROM DevicesConfig WHERE MachineID=@m", new SQLParam("@m", id));
            lock (ni.sqllock)
                sql.ExecSQL("DELETE FROM DevicesFilter WHERE MachineID=@m", new SQLParam("@m", id));
            lock (ni.sqllock)
                sql.ExecSQL("DELETE FROM DiskData WHERE MachineID=@m", new SQLParam("@m", id));
            lock (ni.sqllock)
                sql.ExecSQL("DELETE FROM NetworkConfigSuppl WHERE MachineID=@m", new SQLParam("@m", id));
            lock (ni.sqllock)
                sql.ExecSQL("DELETE FROM NetworkConfig WHERE MachineID=@m", new SQLParam("@m", id));
            lock (ni.sqllock)
                sql.ExecSQL("DELETE FROM Reporting WHERE MachineID=@m", new SQLParam("@m", id));
            lock (ni.sqllock)
                sql.ExecSQL("DELETE FROM WindowsLic WHERE MachineID=@m", new SQLParam("@m", id));
            lock (ni.sqllock)
                sql.ExecSQL("DELETE FROM Chats WHERE MachineID=@m", new SQLParam("@m", id));
            lock (ni.sqllock)
                sql.ExecSQL("DELETE FROM UsersList WHERE MachineID=@m", new SQLParam("@m", id));
            lock (ni.sqllock)
                sql.ExecSQL("DELETE FROM SMARTDataAttributes WHERE MachineID=@m", new SQLParam("@m", id));
            lock (ni.sqllock)
                sql.ExecSQL("DELETE FROM SMARTData WHERE MachineID=@m", new SQLParam("@m", id));
            lock (ni.sqllock)
                sql.ExecSQL("DELETE FROM SimpleTasks WHERE MachineID=@m", new SQLParam("@m", id));
            lock (ni.sqllock)
                sql.ExecSQL("DELETE FROM Startups WHERE MachineID=@m", new SQLParam("@m", id));
            lock (ni.sqllock)
                Modules.FileTransfer.DeleteAllFiles(sql, id);
            //finally delete computer
            lock (ni.sqllock)
                sql.ExecSQL("DELETE FROM ComputerAccounts WHERE MachineID=@m", new SQLParam("@m", id));

            return(RESTStatus.NoContent);
        }
Example #27
0
        public static List <PolicyObject> GetPolicyForComputerInternal(SQLLib sql, string MachineID)
        {
            PolicyObjectList PolicyListSigned = new PolicyObjectList();

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

            SqlDataReader dr;

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

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

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

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

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

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

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

            #region Resolve Linked Policies for client

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

                    PolicyObject po = pol;

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

                        RunningIDs.Add(po.ID);

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

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

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

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

            #endregion

            return(PolicyListSigned.Items);
        }
Example #28
0
        public RESTStatus RenameGroup(SQLLib sql, NetString Rename, 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 (Convert.ToInt32(sql.ExecSQLScalar("SELECT COUNT(*) FROM Grouping WHERE ID=@id",
                                                      new SQLParam("@id", id))) == 0)
                {
                    ni.Error   = "Group does not exist";
                    ni.ErrorID = ErrorFlags.InvalidData;
                    return(RESTStatus.NotFound);
                }
            }

            if (Rename.Data == null)
            {
                ni.Error   = "Invalid data";
                ni.ErrorID = ErrorFlags.InvalidData;
                return(RESTStatus.Fail);
            }

            if (Rename.Data.Trim() == "")
            {
                ni.Error   = "Invalid data";
                ni.ErrorID = ErrorFlags.InvalidData;
                return(RESTStatus.Fail);
            }

            Int64?Parent = null;

            lock (ni.sqllock)
            {
                object P = sql.ExecSQLScalar("SELECT ParentID FROM Grouping WHERE ID=@id",
                                             new SQLParam("@id", id));
                Parent = P is DBNull ? (Int64?)null : Convert.ToInt64(P);
            }

            lock (ni.sqllock)
            {
                if (Convert.ToInt32(sql.ExecSQLScalar("SELECT COUNT(*) FROM Grouping WHERE ParentID" + (Parent == null ? " is null " : "=@pid") + " AND Name=@n AND ID!=@id",
                                                      new SQLParam("@pid", Parent),
                                                      new SQLParam("@id", id),
                                                      new SQLParam("@n", Rename.Data.Trim()))) > 0)
                {
                    ni.Error   = "Duplicate name";
                    ni.ErrorID = ErrorFlags.DuplicateElement;
                    return(RESTStatus.Fail);
                }
            }

            lock (ni.sqllock)
            {
                sql.ExecSQL("UPDATE Grouping SET Name=@n WHERE ID=@id",
                            new SQLParam("@n", Rename.Data.Trim()),
                            new SQLParam("@id", id));
            }

            return(RESTStatus.Success);
        }
Example #29
0
        public RESTStatus GetPolicyForComputer(SQLLib sql, object dummy, NetworkConnectionInfo ni)
        {
            if (ni.HasAcl(ACLFlags.ComputerLogin) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;
                return(RESTStatus.Denied);
            }

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

            string MachineID = ni.Username;

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

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

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

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

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

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

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

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

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

            #region Resolve Linked Policies for client

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

                    PolicyObject po = pol.Policy;

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

                        RunningIDs.Add(po.ID);

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

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

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

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

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

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

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

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

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

            #endregion

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

            return(RESTStatus.Success);
        }
Example #30
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);
        }