public static void WriteEventLogList() { if (Directory.Exists(SystemInfos.ProgramData) == false) { Directory.CreateDirectory(SystemInfos.ProgramData); } #if DEBUG Formatting frm = Formatting.Indented; #else Formatting frm = Formatting.None; #endif byte[] data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(SyncedEventLog, frm)); File.WriteAllBytes(SystemInfos.ProgramData + "SyncedEventLog.json", data); byte[] sign = ApplicationCertificate.Sign(data); if (sign == null) { FoxEventLog.WriteEventLog("Cannot sign synced Event Log for saving", System.Diagnostics.EventLogEntryType.Error); return; } else { File.WriteAllBytes(SystemInfos.ProgramData + "SyncedEventLog.sign", sign); } }
static public void StopAllThreads() { FoxEventLog.VerboseWriteEventLog("StopAllThreads()", System.Diagnostics.EventLogEntryType.Information); StopThreads = true; Redirs.PortMappings_Kernel.StopAllConnections(); if (PolicyThreadHandle != null) { PolicyThreadHandle.Join(); } if (ReportingThreadHandle1 != null) { ReportingThreadHandle1.Join(); } if (ReportingThreadHandle2 != null) { ReportingThreadHandle2.Join(); } if (DownloadThreadHandle != null) { DownloadThreadHandle.Join(); } if (LocalPackagesHandle != null) { LocalPackagesHandle.Join(); } StopDownloads(); PushMain0.StopPushThread(); PushMain1.StopPushThread(); PushMain2.StopPushThread(); #if ENABLECHAT PushMain10.StopPushThread(); #endif UpdateCheck.StopUpdateThread(); DownloadSystemFSData.StopThread(); FoxEventLog.VerboseWriteEventLog("StopAllThreads() - Done", System.Diagnostics.EventLogEntryType.Information); }
static void PolicyThread() { Int64 NextRunTime = RegistryData.LastSyncPolicies; Int64 CurrentTime; while (StopThreads == false) { CurrentTime = CommonUtilities.DTtoINT(DateTime.Now); if (InvokePolicy == true) { InvokePolicy = false; NextRunTime = CommonUtilities.DTtoINT(DateTime.Now.AddMinutes(-1)); } if (CurrentTime < NextRunTime) { Thread.Sleep(1000); continue; } lock (LockLock3) { if (LockPolicyUpdate == true) { Thread.Sleep(1000); continue; } LockPolicyUpdate = true; } try { SyncPolicy.DoSyncPolicy(); #region Prevent criss cross with reportings wait until done! do { lock (LockLock1) { if (LockReportingUpdate1 == true) { if (StopThreads == true) { LockReportingUpdate1 = false; break; } Thread.Sleep(1000); continue; } LockReportingUpdate1 = true; break; } } while (true); #endregion if (StopThreads == false) { SyncPolicy.ApplyPolicy(SyncPolicy.ApplyPolicyFunction.ApplySystem); } #region Prevent criss cross with reportings wait until done! lock (LockLock1) { LockReportingUpdate1 = false; } #endregion } catch (Exception ee) { Debug.WriteLine(ee.ToString()); FoxEventLog.WriteEventLog("Servere error while syncing / applying policies: " + ee.ToString(), EventLogEntryType.Error); } Int64 Tim = RegistryData.LastSyncPoliciesWaitTime; if (Tim < 1) { Tim = 5; } NextRunTime = CommonUtilities.DTtoINT(DateTime.Now.AddMinutes(Tim)); RegistryData.LastSyncPolicies = NextRunTime; lock (LockLock3) { LockPolicyUpdate = false; } } }
static bool CollectEVT2(string Book) { try { EventLogSession session = new EventLogSession(); bool Found = false; foreach (string logName in session.GetLogNames()) { if (Book == logName) { Found = true; break; } } if (Found == false) { return(true); } EventLogReader evt = new EventLogReader(Book); EventRecord log; while ((log = evt.ReadEvent()) != null) { EventLogReport ev = new EventLogReport(); ev.Category = "(" + log.Id + ")"; ev.CategoryNumber = log.Id; ev.Data = new byte[0]; ev.EventLog = Book; switch (log.LevelDisplayName.ToLower()) { case "information": ev.EventLogType = (int)EventLogEntryType.Information; break; case "warning": ev.EventLogType = (int)EventLogEntryType.Warning; break; case "error": ev.EventLogType = (int)EventLogEntryType.Error; break; default: ev.EventLogType = (int)EventLogEntryType.Information; break; } ev.InstanceID = log.Id; ev.LogID = ""; ev.MachineID = SystemInfos.SysInfo.MachineID; ev.Message = MakeNiceXML(log.ToXml()); ev.Source = log.ProviderName; ev.TimeGenerated = log.TimeCreated == null?DateTime.Now: log.TimeCreated.Value; ev.TimeWritten = log.TimeCreated == null ? DateTime.Now : log.TimeCreated.Value; ev.JSONReplacementStrings = "[]"; CommonUtilities.CalcEventLogID(ev); HasEVTLogs.Add(ev.LogID); lst.Add(ev); } } catch { FoxEventLog.WriteEventLog("Cannot collect EventLog " + Book, EventLogEntryType.Error); } return(true); }
static void DownloadThreadRunner() { try { int Direction = -1; lock (FileLock) { if (FilesystemData.FileTransferStatus.ServerID == null) { return; } Direction = FilesystemData.FileTransferStatus.Direction; } #region Client to Server if (Direction == 1) { string LocalFilename = ""; string MD5; Int64 ServerID = 0; Int64 CurrentSZ; Int64 TotalSZ; bool OverrideMetered; bool ReqOnly; DateTime LastModified; try { lock (FileLock) { LocalFilename = FilesystemData.FileTransferStatus.RemoteFileLocation; ServerID = FilesystemData.FileTransferStatus.ServerID.Value; CurrentSZ = FilesystemData.FileTransferStatus.ProgressSize; TotalSZ = FilesystemData.FileTransferStatus.Size; MD5 = FilesystemData.FileTransferStatus.MD5CheckSum; OverrideMetered = FilesystemData.FileTransferStatus.OverrideMeteredConnection; ReqOnly = FilesystemData.FileTransferStatus.RequestOnly; LastModified = FilesystemData.FileTransferStatus.LastModfied; } //won't start when in metered connection! if (OverrideMetered == false) { try { if (MeteredConnection.IsMeteredConnection() == true) { FoxEventLog.VerboseWriteEventLog("Upload paused = metered connection detected", System.Diagnostics.EventLogEntryType.Information); return; } } catch { } } Int64 ReallyCurrentSZ = 0; try { if (File.Exists(LocalFilename) == true) { FileInfo fi = new FileInfo(LocalFilename); ReallyCurrentSZ = fi.Length; } else { FoxEventLog.WriteEventLog("File " + LocalFilename + " does not exist for upload.", System.Diagnostics.EventLogEntryType.Error); return; } } catch (Exception ee) { FoxEventLog.WriteEventLog("Checking upload file " + LocalFilename + " ID: " + ServerID.ToString() + " failed:\n" + ee.ToString(), System.Diagnostics.EventLogEntryType.Error); return; } downloadnet = Utilities.ConnectNetwork(7); if (downloadnet == null) { return; } if (ReqOnly == true) { Status.UpdateMessage(7, "Checking " + LocalFilename); MD5 = MD5Utilities.CalcMD5File(LocalFilename); FileInfo fi = new FileInfo(LocalFilename); lock (FileLock) { FilesystemData.FileTransferStatus.MD5CheckSum = MD5; FilesystemData.FileTransferStatus.LastModfied = fi.LastWriteTimeUtc; FilesystemData.WriteFileTransferStatus(); } Int64?NewID = downloadnet.File_Agent_NewUploadReq(LocalFilename, OverrideMetered, MD5); if (NewID == null) { FoxEventLog.VerboseWriteEventLog("Cannot create a new upload req for " + LocalFilename, System.Diagnostics.EventLogEntryType.Warning); return; } if (downloadnet.File_Agent_CancelUpload(ServerID) == false) { FoxEventLog.VerboseWriteEventLog("Cannot delete temp upload req for " + LocalFilename + " ID: " + ServerID.ToString(), System.Diagnostics.EventLogEntryType.Warning); return; } lock (FileLock) { //wait for the new upload req ClearDataFSD(); FilesystemData.WriteFileTransferStatus(); UnlockTimer = true; return; } } else { FileStream fs = null; do { try { if (CancelAndDeleteDL == true) { return; } FileInfo fi = new FileInfo(LocalFilename); if (roughDT(fi.LastWriteTimeUtc, LastModified) == false || fi.Length != TotalSZ) { if (downloadnet.File_Agent_CancelUpload(ServerID) == false) { FoxEventLog.VerboseWriteEventLog("Cannot cancel upload req for " + LocalFilename + " ID: " + ServerID.ToString() + ", due file changes", System.Diagnostics.EventLogEntryType.Warning); lock (FileLock) { ClearDataFSD(); FilesystemData.WriteFileTransferStatus(); } return; } else { FoxEventLog.VerboseWriteEventLog("Cannot upload req for " + LocalFilename + " ID: " + ServerID.ToString() + ": File has been changed!", System.Diagnostics.EventLogEntryType.Warning); } return; } try { if (fs == null) { fs = File.Open(LocalFilename, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); } } catch (Exception ee) { FoxEventLog.WriteEventLog("Cannot upload file " + LocalFilename + " ID: " + ServerID.ToString() + " failed:\n" + ee.ToString(), System.Diagnostics.EventLogEntryType.Warning); return; } try { fs.Seek(CurrentSZ, SeekOrigin.Begin); } catch { FoxEventLog.WriteEventLog("Cannot properly seek in file " + LocalFilename + " ID: " + ServerID.ToString() + " Pos: 0x" + CurrentSZ.ToString("X"), System.Diagnostics.EventLogEntryType.Warning); return; } byte[] data = null; try { int read = 1024 * 1024; data = new byte[read]; read = fs.Read(data, 0, read); if (data.Length != read) { byte[] ddd = new byte[read]; Array.Copy(data, ddd, read); data = ddd; } } catch { FoxEventLog.WriteEventLog("Cannot read file " + LocalFilename + " ID: " + ServerID.ToString() + " Pos: 0x" + CurrentSZ.ToString("X"), System.Diagnostics.EventLogEntryType.Warning); return; } Status.UpdateMessage(7, "Uploading " + LocalFilename + "\r\n" + CommonUtilities.NiceSize(CurrentSZ) + " of " + CommonUtilities.NiceSize(TotalSZ)); bool res = downloadnet.File_Agent_AppendUpload(ServerID, data); if (res == false) { FoxEventLog.VerboseWriteEventLog("Cannot upload append req for " + LocalFilename + " ID: " + ServerID.ToString(), System.Diagnostics.EventLogEntryType.Warning); return; } CurrentSZ += data.Length; lock (FileLock) { FilesystemData.FileTransferStatus.ProgressSize = CurrentSZ; FilesystemData.WriteFileTransferStatus(); } if (CurrentSZ == TotalSZ) { FoxEventLog.WriteEventLog("Upload file success " + LocalFilename + " ID: " + ServerID.ToString(), System.Diagnostics.EventLogEntryType.Information); lock (FileLock) { ClearDataFSD(); FilesystemData.WriteFileTransferStatus(); } UnlockTimer = true; return; } } finally { if (fs != null) { fs.Close(); fs = null; } } } while (true); } } catch (Exception ee) { FoxEventLog.WriteEventLog("Downloading file " + LocalFilename + " ID: " + ServerID.ToString() + " crashed:\n" + ee.ToString(), System.Diagnostics.EventLogEntryType.Error); } finally { Status.UpdateMessage(7); } } #endregion #region Server to Client if (Direction == 0) { string LocalFilename; string MD5; Int64 ServerID; Int64 CurrentSZ; Int64 TotalSZ; bool OverrideMetered; lock (FileLock) { LocalFilename = FilesystemData.FileTransferStatus.RemoteFileLocation; ServerID = FilesystemData.FileTransferStatus.ServerID.Value; CurrentSZ = FilesystemData.FileTransferStatus.ProgressSize; TotalSZ = FilesystemData.FileTransferStatus.Size; MD5 = FilesystemData.FileTransferStatus.MD5CheckSum; OverrideMetered = FilesystemData.FileTransferStatus.OverrideMeteredConnection; } //won't start when in metered connection! if (OverrideMetered == false) { try { if (MeteredConnection.IsMeteredConnection() == true) { FoxEventLog.VerboseWriteEventLog("Download paused = metered connection detected", System.Diagnostics.EventLogEntryType.Information); return; } } catch { } } Int64 ReallyCurrentSZ = 0; try { string Dir = Path.GetDirectoryName(LocalFilename); if (Directory.Exists(Dir) == false) { Directory.CreateDirectory(Dir); } if (File.Exists(LocalFilename) == true) { FileInfo fi = new FileInfo(LocalFilename); ReallyCurrentSZ = fi.Length; } else { ReallyCurrentSZ = 0; } } catch (Exception ee) { FoxEventLog.WriteEventLog("Checking download file " + LocalFilename + " ID: " + ServerID.ToString() + " failed:\n" + ee.ToString(), System.Diagnostics.EventLogEntryType.Error); } if (ReallyCurrentSZ != CurrentSZ) { FoxEventLog.WriteEventLog("File Size does not match: deleting the file " + LocalFilename, System.Diagnostics.EventLogEntryType.Warning); try { File.Delete(LocalFilename); } catch (Exception ee) { FoxEventLog.WriteEventLog("Cannot delete " + LocalFilename + "\n" + ee.ToString(), System.Diagnostics.EventLogEntryType.Error); } lock (FileLock) { ClearDataFSD(); FilesystemData.WriteFileTransferStatus(); return; } } downloadnet = Utilities.ConnectNetwork(7); if (downloadnet == null) { return; } try { downloadnet.DownloadNotify += Downloadnet_DownloadNotify; if (downloadnet.DownloadFile("api/agent/filefiledownload/" + ServerID.ToString(), LocalFilename, TotalSZ) == false) { FileInfo fi = new FileInfo(LocalFilename); lock (FileLock) { FilesystemData.FileTransferStatus.ProgressSize = fi.Length; FilesystemData.WriteFileTransferStatus(); } } else { if (downloadnet.StopDownload == false) { Status.UpdateMessage(7, "Checking " + FilesystemData.FileTransferStatus.RemoteFileLocation + "..."); string CalcMD5 = MD5Utilities.CalcMD5File(LocalFilename); if (MD5.ToLower() != CalcMD5.ToLower()) { FoxEventLog.WriteEventLog("File MD5 does not match: deleting the file " + LocalFilename, System.Diagnostics.EventLogEntryType.Warning); try { File.Delete(LocalFilename); } catch (Exception ee) { FoxEventLog.WriteEventLog("Cannot delete " + LocalFilename + "\n" + ee.ToString(), System.Diagnostics.EventLogEntryType.Error); } lock (FileLock) { ClearDataFSD(); FilesystemData.WriteFileTransferStatus(); return; } } else { //success! FoxEventLog.WriteEventLog("File download success: " + LocalFilename, System.Diagnostics.EventLogEntryType.Information); downloadnet.File_Agent_CancelUpload(ServerID); lock (FileLock) { ClearDataFSD(); FilesystemData.WriteFileTransferStatus(); } UnlockTimer = true; return; } } else { if (CancelAndDeleteDL == true) { FoxEventLog.VerboseWriteEventLog("File " + LocalFilename + " canceled by server req.", System.Diagnostics.EventLogEntryType.Information); try { File.Delete(LocalFilename); } catch (Exception ee) { FoxEventLog.WriteEventLog("Cannot delete " + LocalFilename + "\n" + ee.ToString(), System.Diagnostics.EventLogEntryType.Error); } lock (FileLock) { ClearDataFSD(); FilesystemData.WriteFileTransferStatus(); return; } } } } } catch (Exception ee) { FoxEventLog.WriteEventLog("Downloading file " + LocalFilename + " ID: " + ServerID.ToString() + " crashed:\n" + ee.ToString(), System.Diagnostics.EventLogEntryType.Error); } finally { downloadnet.DownloadNotify -= Downloadnet_DownloadNotify; Status.UpdateMessage(7); } } #endregion } finally { try { if (downloadnet != null) { downloadnet.CloseConnection(); } } catch { } downloadnet = null; } }
public static int CollectSystemInfo() { if (IsRunningOnMono() == true) { FoxEventLog.WriteEventLog("Running on Mono is not supported!", EventLogEntryType.Error); Console.WriteLine("Running on Mono is not supported!"); return(1); } if (GetWineVersion() != "") { FoxEventLog.WriteEventLog("Running on Wine/CrossOver is not supported!", EventLogEntryType.Error); Console.WriteLine("Running on Wine/CrossOver is not supported!"); return(1); } SysInfo = new BaseSystemInfo(); SysInfo.RunningInWindowsPE = WindowsPE.IsRunningInWindowsPE; SysInfo.ComputerModel = GetComputerModel(); SysInfo.ComputerName = SystemInformation.ComputerName; SysInfo.CPU = GetCPU().ToString(); SysInfo.MachineID = RegistryData.MachineID; SysInfo.IsTSE = IsSystemTSE(); SysInfo.OSName = SysInfo.RunningInWindowsPE == true ? "Windows PE / MiniNT" : GetWindowsProduct(); SysInfo.OSSuite = GetOSSuite().ToString(); SysInfo.OSVerBuild = Environment.OSVersion.Version.Build; SysInfo.OSVerMaj = Environment.OSVersion.Version.Major; SysInfo.OSVerMin = Environment.OSVersion.Version.Minor; SysInfo.Language = CultureInfo.InstalledUICulture.Name; SysInfo.DisplayLanguage = CultureInfo.InstalledUICulture.EnglishName; SysInfo.RunningInHypervisor = ProgramAgent.CPP.IsInHypervisor(); SysInfo.BIOS = GetBIOSData(); SysInfo.BIOSType = ProgramAgent.CPP.FoxGetFirmwareType(); GetProcessorInfos(out SysInfo.NumberOfProcessors, out SysInfo.NumberOfLogicalProcessors, out SysInfo.TotalPhysicalMemory); SysInfo.CPUName = GetProcessorName(); SysInfo.SecureBootState = GetSecureBootState(); SysInfo.SystemRoot = Environment.GetFolderPath(Environment.SpecialFolder.Windows); SysInfo.SUSID = GetSUSID(); try { SysInfo.IsMeteredConnection = MeteredConnection.IsMeteredConnection(); } catch (Exception ee) { Debug.WriteLine(ee.ToString()); SysInfo.IsMeteredConnection = null; } OSVERSIONINFOEX os = new OSVERSIONINFOEX(); os.dwOSVersionInfoSize = Marshal.SizeOf(os); GetVersionEx(ref os); SysInfo.OSVerType = os.wSuiteMask; #if DEBUG SysInfo.AgentVersion = VulpesBranding.AgentIdentifier + " [DEBUG] " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(); #else SysInfo.AgentVersion = VulpesBranding.AgentIdentifier + " " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(); #endif SysInfo.AgentVersionID = FoxVersion.Version; CPUType CPU = GetCPU(); if (CPU != CPUType.Intel32 && CPU != CPUType.EM64T && CPU != CPUType.ARM64) { FoxEventLog.WriteEventLog("Only i386, AMD64 (EM64T) or ARM64 CPU are supported!", EventLogEntryType.Error); return(1); } if (CPU == CPUType.EM64T) { if (Is64Bit() == null) { FoxEventLog.WriteEventLog("Cannot determine WOW state.", EventLogEntryType.Error); return(1); } if (Is64Bit() == false && CPU == CPUType.EM64T) { FoxEventLog.WriteEventLog("If you've a 64 bit CPU, then run this process as 64 bit!!!!", EventLogEntryType.Error); return(1); } SysInfo.Is64Bit = Is64Bit().Value; } else { SysInfo.Is64Bit = false; } if (SysInfo.MachineID == "") { FoxEventLog.WriteEventLog("Cannot get machine ID.", EventLogEntryType.Error); return(1); } if (SysInfo.ComputerModel == null) { FoxEventLog.WriteEventLog("Cannot get Computer Model.", EventLogEntryType.Error); return(1); } PasswordID = RegistryData.MachinePassword; if (PasswordID == "") { FoxEventLog.WriteEventLog("Cannot get PassID.", EventLogEntryType.Error); return(1); } if (SysInfo.OSSuite == "Unknown") { FoxEventLog.WriteEventLog("Unknown OS Suite.", EventLogEntryType.Error); return(1); } if (RegistryData.UseOnPrem == true) { ServerURL = RegistryData.ServerURL; } else { ServerURL = ProgramAgent.VulpesURL; } if (ServerURL == "") { FoxEventLog.WriteEventLog("Cannot get Server URL.", EventLogEntryType.Error); return(1); } ProgramData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); if (ProgramData.EndsWith("\\") == false) { ProgramData += "\\"; } ProgramData += "Fox\\SDC Agent\\"; try { if (Directory.Exists(ProgramData) == false) { Directory.CreateDirectory(ProgramData); } } catch { FoxEventLog.WriteEventLog("Error accessing " + ProgramData, EventLogEntryType.Error); return(1); } SysInfo.UCID = UCID.GetUCID(); SysInfo.LegacyUCID = UCID.GetUCIDLegacy(); if (RegistryData.UCIDOverride != "") { string UUU = RegistryData.UCIDOverride.Trim().ToUpper(); if (UUU.Length == 32) { FoxEventLog.WriteEventLog("UCID Overriden from " + SysInfo.UCID + " to " + UUU, EventLogEntryType.Warning); SysInfo.UCID = UUU; } } string SysInfoResumee = ""; ContractID = RegistryData.ContractID.Trim(); ContractPassword = RegistryData.ContractPassword; SysInfoResumee += "System Info:\r\n"; SysInfoResumee += "Agent: " + SysInfo.AgentVersion + "\r\n"; SysInfoResumee += SysInfo.OSName + "\r\n"; SysInfoResumee += "aka Windows NT " + SysInfo.OSVerMaj.ToString() + "." + SysInfo.OSVerMin.ToString() + "." + SysInfo.OSVerBuild.ToString() + "\r\n"; SysInfoResumee += "Suite: " + SysInfo.OSSuite + "\r\n"; SysInfoResumee += "Language: " + SysInfo.Language + " (" + SysInfo.DisplayLanguage + ")\r\n"; SysInfoResumee += "Bits: " + (SysInfo.Is64Bit == true ? "64 bit" : "32 bit") + "\r\n"; SysInfoResumee += "TSE: " + (SysInfo.IsTSE == false ? "no" : "yes") + "\r\n"; SysInfoResumee += "OS Suite: " + SysInfo.OSVerType + "\r\n"; SysInfoResumee += "CPU: " + CPU.ToString() + "\r\n"; SysInfoResumee += "Model: " + SysInfo.ComputerModel + "\r\n"; SysInfoResumee += "BIOS: " + SysInfo.BIOS + "\r\n"; SysInfoResumee += "Computername: " + SysInfo.ComputerName + "\r\n"; SysInfoResumee += "Machine ID: " + SysInfo.MachineID + "\r\n"; SysInfoResumee += "Server URL: " + ServerURL + "\r\n"; SysInfoResumee += "UCID: " + SysInfo.UCID + "\r\n"; SysInfoResumee += "Program Data: " + ProgramData + "\r\n"; SysInfoResumee += "Running in Hypervisor: " + (SysInfo.RunningInHypervisor == false ? "no" : "yes") + "\r\n"; FoxEventLog.WriteEventLog("Fox SDC Agent starting: " + SysInfoResumee, EventLogEntryType.Information); return(0); }
public static void RunPipeClient() { Process2ProcessComm p2p = new Process2ProcessComm(); if (p2p.ConnectPipe(ProgramAgent.PipeGUID) == false) { FoxEventLog.VerboseWriteEventLog("Cannot connect to pipe " + ProgramAgent.PipeGUID, EventLogEntryType.Error); return; } string Action = p2p.GetAction(); if (Action == null) { FoxEventLog.VerboseWriteEventLog("Got no action data from pipe " + ProgramAgent.PipeGUID, EventLogEntryType.Error); return; } switch (Action.ToLower()) { case "install": { PackageInstaller inst = new PackageInstaller(); DataHInstallPackageTODO todo = p2p.GetTODO <DataHInstallPackageTODO>(); if (todo == null) { FoxEventLog.VerboseWriteEventLog("Got no todo data from pipe " + ProgramAgent.PipeGUID, EventLogEntryType.Error); return; } DataHInstallPackageResult result = new DataHInstallPackageResult(); result.Return = inst.InstallPackage(todo.Filename, todo.CerCertificates, todo.Mode, todo.ZipIsMetaOnly, out result.ErrorText, out result.res, out result.Reciept, todo.OtherDLL); if (inst.ScriptTempDLLFilename != null) { FoxEventLog.VerboseWriteEventLog("Script DLL file = " + inst.ScriptTempDLLFilename, EventLogEntryType.Information); } result.TempDLLFilename = inst.ScriptTempDLLFilename; p2p.SetResult(result); break; } case "runuser": { DataHRunasUserTODO todo = p2p.GetTODO <DataHRunasUserTODO>(); DataHRunasUserResult res = new DataHRunasUserResult(); try { Process p = new Process(); p.StartInfo.FileName = todo.Filename; p.StartInfo.Arguments = todo.Args; p.StartInfo.UserName = todo.Username; p.StartInfo.Password = Utilities.MakeSecString(todo.Password); p.StartInfo.UseShellExecute = false; p.Start(); } catch (Win32Exception ee) { FoxEventLog.VerboseWriteEventLog("RUNUSER: Cannot run " + todo.Filename + " as user " + todo.Username + ": " + ee.ToString(), EventLogEntryType.Warning); res.Result = 0x00000000FFFFFFFF & ee.NativeErrorCode; Debug.WriteLine(ee.ToString()); } catch (Exception ee) { FoxEventLog.VerboseWriteEventLog("RUNUSER: Cannot run " + todo.Filename + " as user " + todo.Username + ": " + ee.ToString(), EventLogEntryType.Warning); res.Result = 0x8000ffff; Debug.WriteLine(ee.ToString()); } p2p.SetResult(res); break; } case "conredir": { DataHRunConredir R = p2p.GetTODO <DataHRunConredir>(); MainSTDIORedir.RunPipeConsoleEnd(p2p, R); break; } default: FoxEventLog.VerboseWriteEventLog("Action " + Action + " from pipe " + ProgramAgent.PipeGUID + "?? häh???", EventLogEntryType.Warning); return; } }
public static bool InvokeRunAsUser(string Filename, string Args, string Username, string Password, int SessionID, out DataHRunasUserResult ores, out Int64 W32Res) { ores = null; W32Res = 0xe9; DataHRunasUserTODO d = new DataHRunasUserTODO(); d.Filename = Filename; d.Args = Args; d.Username = Username; d.Password = Password; Process2ProcessComm p2p = new Process2ProcessComm(); p2p.SetTODO("RUNUSER", d); if (p2p.StartPipe() == false) { FoxEventLog.WriteEventLog("Cannot start P2PC for RUNUSER " + p2p.GetGUID(), EventLogEntryType.Error); return(false); } if (SessionID == 0) { try { Process proc = new Process(); proc.StartInfo.FileName = Assembly.GetExecutingAssembly().Location; proc.StartInfo.Arguments = "-pipeaction " + p2p.GetGUID(); proc.StartInfo.UseShellExecute = false; proc.Start(); proc.WaitForExit(); } catch (Win32Exception ee) { W32Res = 0x00000000FFFFFFFF & ee.NativeErrorCode; Debug.WriteLine(ee.ToString()); FoxEventLog.WriteEventLog("Cannot start P2PC for SYS RUNUSER " + p2p.GetGUID(), EventLogEntryType.Error); return(false); } catch (Exception ee) { W32Res = 0x8000ffff; Debug.WriteLine(ee.ToString()); FoxEventLog.WriteEventLog("Cannot start P2PC for SYS RUNUSER " + p2p.GetGUID(), EventLogEntryType.Error); return(false); } } else { if (ProgramAgent.CPP.StartAppAsUserWait(Assembly.GetExecutingAssembly().Location, "-pipeaction " + p2p.GetGUID(), SessionID) == false) { W32Res = ProgramAgent.CPP.WGetLastError(); FoxEventLog.WriteEventLog("Cannot start P2PC Process for RUNUSER " + p2p.GetGUID() + " Error: 0x" + ProgramAgent.CPP.WGetLastError().ToString("X"), EventLogEntryType.Error); p2p.ClosePipe(); return(false); } } ores = p2p.GetResult <DataHRunasUserResult>(); p2p.ClosePipe(); if (ores == null) { FoxEventLog.WriteEventLog("P2PC didn't return any data for RUNUSER " + p2p.GetGUID(), EventLogEntryType.Error); return(false); } return(true); }
public static void SMain() { #if !DEBUG AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; #endif FoxEventLog.RegisterEventLog(); if (UsePipeAction == false && UseScreenAction == false && UseDNSAutoConfig == false && UseLoginRecovery == false) //Pipe Actions can also be run in user-space ... { if (IsSystemUser() != true) { #if !DEBUG || DEBUGSERVICE service.Stop(); #endif return; } } if (LoadDLL() == false) { #if !DEBUG || DEBUGSERVICE service.Stop(); #endif return; } #if !DEBUG if (TestIntegrity(null) == false) { FoxEventLog.WriteEventLog("Integrity check failed!", EventLogEntryType.Error); service.Stop(); return; } #endif if (UseDNSAutoConfig == true) { try { List <List <string> > Query = CPP.DNSQueryTXT("sdc-contract.my-vulpes-config.lu"); if (Query == null) { return; } string ContractID = null; string ContractPassword = null; string UseOnPrem = null; string OnPremURL = null; foreach (List <string> Q in Query) { if (Q == null) { continue; } foreach (string QR in Q) { if (string.IsNullOrWhiteSpace(QR) == true) { continue; } if (QR.ToLower().StartsWith("contractid=") == true) { ContractID = QR.Substring(11).Trim(); } if (QR.ToLower().StartsWith("contractpassword="******"useonprem=") == true) { UseOnPrem = QR.Substring(10).Trim(); } if (QR.ToLower().StartsWith("onpremurl=") == true) { OnPremURL = QR.Substring(10).Trim(); } } } using (RegistryKey k = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Fox\\SDC")) { if (string.IsNullOrWhiteSpace(ContractID) == false && string.IsNullOrWhiteSpace(ContractPassword) == false) { k.SetValue("ContractID", ContractID, RegistryValueKind.String); k.SetValue("ContractPassword", ContractPassword, RegistryValueKind.String); } int UseOnPremInt; if (int.TryParse(UseOnPrem, out UseOnPremInt) == true) { if (UseOnPremInt == 1 && string.IsNullOrWhiteSpace(OnPremURL) == false) { k.SetValue("UseOnPremServer", 1, RegistryValueKind.DWord); k.SetValue("Server", OnPremURL, RegistryValueKind.String); } else { k.SetValue("UseOnPremServer", 0, RegistryValueKind.DWord); } } else { k.SetValue("UseOnPremServer", 0, RegistryValueKind.DWord); } } } catch (Exception ee) { Debug.WriteLine(ee.ToString()); } return; } if (UseLoginRecovery == true) { if (SystemInfos.CollectSystemInfo() != 0) { return; } #if !DEBUG if (SystemInfos.SysInfo.RunningInWindowsPE == false || SystemInfos.SysInfo.RunningInWindowsPE == null) { return; } #endif RecoveryLogon reclogon = new RecoveryLogon(); reclogon.UCID = SystemInfos.SysInfo.UCID; reclogon.ContractID = SystemInfos.ContractID; reclogon.ContractPassword = SystemInfos.ContractPassword; string Check = SystemInfos.SysInfo.CPUName.Trim(); Check += SystemInfos.SysInfo.ComputerModel == "" ? "N/A" : SystemInfos.SysInfo.ComputerModel.Trim(); Check += SystemInfos.SysInfo.BIOS == "" ? "N/A" : SystemInfos.SysInfo.BIOS.Trim(); reclogon.MoreMachineHash = MD5Utilities.CalcMD5(Check); Network net = Utilities.NoConnectNetwork(); RecoveryData rd = net.GetRecoveryLogon(reclogon); if (rd == null) { return; } if (rd.Worked == false) { return; } string Registry = "Windows Registry Editor Version 5.00\r\n\r\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\Fox\\SDC]\r\n\"ID\"=\"" + rd.MachineID + "\"\r\n\"PassID\"=\"" + rd.MachinePassword + "\""; try { File.WriteAllText(Environment.ExpandEnvironmentVariables("%SYSTEMROOT%\\Fox SDC MachinePW.reg"), Registry, Encoding.Unicode); } catch { } return; } if (UsePipeAction == false && UseScreenAction == false) { using (RegistryKey installer = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\" + VulpesBranding.MSIGUID, false)) { if (installer == null) { FoxEventLog.WriteEventLog("Missing installer key in HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\" + VulpesBranding.MSIGUID + ". This can lead to erratic behavoir of the program!", EventLogEntryType.Warning); } } if (CPP.SetToken() == false) { FoxEventLog.WriteEventLog("Cannot setup token - 0x" + Marshal.GetLastWin32Error().ToString("X") + " - " + new Win32Exception(Marshal.GetLastWin32Error()).Message, System.Diagnostics.EventLogEntryType.Error); return; } } if (UsePipeAction == true) { try { Process2ProcessCommClient.RunPipeClient(); } catch (Exception ee) { FoxEventLog.WriteEventLog("Pipe SEH " + ee.ToString(), System.Diagnostics.EventLogEntryType.Error); } return; } if (UseScreenAction == true) { try { if (SystemInfos.CollectSystemInfo() != 0) { return; } MainScreenSystemClient.RunPipeClient(); } catch (Exception ee) { FoxEventLog.WriteEventLog("Screen Pipe SEH " + ee.ToString(), System.Diagnostics.EventLogEntryType.Error); } return; } if (SystemInfos.CollectSystemInfo() != 0) { #if !DEBUG || DEBUGSERVICE service.Stop(); #endif return; } RegistryData.InstallPath = AppPath; if (ApplicationCertificate.LoadCertificate() == false) { FoxEventLog.WriteEventLog("Cannot load certificate", System.Diagnostics.EventLogEntryType.Error); #if !DEBUG || DEBUGSERVICE service.Stop(); #endif return; } if (FilesystemData.LoadCertificates() == false) { #if !DEBUG || DEBUGSERVICE service.Stop(); #endif return; } if (FilesystemData.LoadPolicies() == false) { #if !DEBUG || DEBUGSERVICE service.Stop(); #endif return; } FilesystemData.LoadLocalPackageData(); FilesystemData.LoadLocalPackages(); FilesystemData.LoadUserPackageData(); FilesystemData.LoadEventLogList(); SyncPolicy.ApplyPolicy(SyncPolicy.ApplyPolicyFunction.ApplySystem); PipeCommunicationSRV.StartPipeSrv(); try { string p = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); if (p.EndsWith("\\") == false) { p += "\\"; } using (RegistryKey reg = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true)) { reg.SetValue("FoxSDCAgent", p + "FoxSDC_Agent_UI.exe", RegistryValueKind.String); reg.SetValue("FoxSDCAgentApply", p + "FoxSDC_ApplyUserSettings.exe", RegistryValueKind.String); reg.Close(); } } catch { } try { using (RegistryKey reg = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", true)) { object o = reg.GetValue("SoftwareSASGeneration", null); int rvalue = 0; if (o != null) { rvalue = Convert.ToInt32(o); } if (rvalue != 1 && rvalue != 3) { reg.SetValue("SoftwareSASGeneration", 1); } reg.Close(); } } catch { } Threads.StartAllThreads(); }
static public void RemovePackage(PackagesToInstall Package, bool ForceRemove = false) { if (LocalPackages == null) { return; } string PackagesFolder = SystemInfos.ProgramData + "Packages\\"; if (Directory.Exists(PackagesFolder) == false) { Directory.CreateDirectory(PackagesFolder); } PackagesToInstall pkg = null; foreach (PackagesToInstall pp in LocalPackages) { if (Package == pp) { pkg = pp; break; } } if (pkg == null) { return; } LocalPackageData rmlpkg = null; foreach (LocalPackageData lpkg in LocalPackageDataList) { if (lpkg.PackageID == pkg.PackageID && lpkg.Version == pkg.Version) { rmlpkg = lpkg; break; } } if (ForceRemove == false) { if (rmlpkg != null) { if (rmlpkg.PKGRecieptFilename != null) { FoxEventLog.VerboseWriteEventLog("Not removing Package: " + pkg.PackageID + " V" + pkg.Version.ToString() + ". Reciept file is registred.", EventLogEntryType.Warning); if (pkg.Filename != null) { if (File.Exists(PackagesFolder + pkg.Filename) == true) { CommonUtilities.SpecialDeleteFile(PackagesFolder + pkg.Filename); } pkg.Filename = null; } rmlpkg.ServerHasPackage = false; return; } } } if (pkg.MetaFilename != null) { if (File.Exists(PackagesFolder + pkg.MetaFilename) == true) { CommonUtilities.SpecialDeleteFile(PackagesFolder + pkg.MetaFilename); } } if (pkg.Filename != null) { if (File.Exists(PackagesFolder + pkg.Filename) == true) { CommonUtilities.SpecialDeleteFile(PackagesFolder + pkg.Filename); } } LocalPackages.Remove(pkg); WritePackageList(); if (rmlpkg != null) { if (rmlpkg.PKGRecieptFilename != null) { CommonUtilities.SpecialDeleteFile(PackagesFolder + rmlpkg.PKGRecieptFilename); CommonUtilities.SpecialDeleteFile(PackagesFolder + rmlpkg.PKGRecieptFilename + ".sign"); } LocalPackageDataList.Remove(rmlpkg); WritePackageDataList(); } }
static public bool LoadCertificates(bool Shutup = false) { LoadedCertificates = new List <FilesystemCertificateData>(); string CertFolder = SystemInfos.ProgramData + "Certificates\\"; if (Directory.Exists(CertFolder) == false) { Directory.CreateDirectory(CertFolder); } for (int i = 1; i < 100; i++) { if (File.Exists(CertFolder + "Certificate" + i.ToString("00") + ".cer") == false) { if (File.Exists(CertFolder + "Certificate" + i.ToString("00") + ".sign") == true) { FoxEventLog.WriteEventLog("Found lonely file \"Certificate" + i.ToString("00") + ".sign\" - deleting the file", System.Diagnostics.EventLogEntryType.Warning); File.Delete(CertFolder + "Certificate" + i.ToString("00") + ".sign"); } } else { if (File.Exists(CertFolder + "Certificate" + i.ToString("00") + ".sign") == false) { FoxEventLog.WriteEventLog("Found \"Certificate" + i.ToString("00") + ".cer\" but no signature - deleting the file", System.Diagnostics.EventLogEntryType.Warning); File.Delete(CertFolder + "Certificate" + i.ToString("00") + ".cer"); } else { FileInfo file; file = new FileInfo(CertFolder + "Certificate" + i.ToString("00") + ".cer"); if (file.Length > 5242880) { FoxEventLog.WriteEventLog("File \"Certificate" + i.ToString("00") + ".cer\" too large (>5MB) - deleting the files", System.Diagnostics.EventLogEntryType.Warning); File.Delete(CertFolder + "Certificate" + i.ToString("00") + ".cer"); File.Delete(CertFolder + "Certificate" + i.ToString("00") + ".sign"); continue; } file = new FileInfo(CertFolder + "Certificate" + i.ToString("00") + ".sign"); if (file.Length > 5242880) { FoxEventLog.WriteEventLog("File \"Certificate" + i.ToString("00") + ".sign\" too large (>5MB) - deleting the files", System.Diagnostics.EventLogEntryType.Warning); File.Delete(CertFolder + "Certificate" + i.ToString("00") + ".cer"); File.Delete(CertFolder + "Certificate" + i.ToString("00") + ".sign"); continue; } byte[] cert = File.ReadAllBytes(CertFolder + "Certificate" + i.ToString("00") + ".cer"); byte[] sign = File.ReadAllBytes(CertFolder + "Certificate" + i.ToString("00") + ".sign"); if (ApplicationCertificate.Verify(cert, sign) == false) { FoxEventLog.WriteEventLog("File \"Certificate" + i.ToString("00") + ".cer\" and \"Certificate" + i.ToString("00") + ".sign\" do not match - deleting the files", System.Diagnostics.EventLogEntryType.Warning); File.Delete(CertFolder + "Certificate" + i.ToString("00") + ".cer"); File.Delete(CertFolder + "Certificate" + i.ToString("00") + ".sign"); continue; } if (ContainsLoadedCert(cert) == true) { FoxEventLog.WriteEventLog("File \"Certificate" + i.ToString("00") + ".cer\" this certificate is already loaded from a different file - deleting the files", System.Diagnostics.EventLogEntryType.Warning); File.Delete(CertFolder + "Certificate" + i.ToString("00") + ".cer"); File.Delete(CertFolder + "Certificate" + i.ToString("00") + ".sign"); continue; } Debug.WriteLine(CertFolder + "Certificate" + i.ToString("00") + ".cer loaded"); FilesystemCertificateData fscer = new FilesystemCertificateData(); fscer.FSFilename = "Certificate" + i.ToString("00") + ".cer"; fscer.Certificate = cert; LoadedCertificates.Add(fscer); if (Shutup == false) { FoxEventLog.WriteEventLog("Certificate " + Certificates.GetCN(cert) + " loaded", System.Diagnostics.EventLogEntryType.Information); } } } } return(true); }
static public bool LoadPolicies() { LoadedPolicyObjects = new List <LoadedPolicyObject>(); string PoliciesFolder = SystemInfos.ProgramData + "Policies\\"; if (Directory.Exists(PoliciesFolder) == false) { Directory.CreateDirectory(PoliciesFolder); } foreach (string file in Directory.EnumerateFiles(PoliciesFolder, "*.pol", SearchOption.TopDirectoryOnly)) { string signfile = file.Substring(0, file.Length - 4) + ".sign"; if (File.Exists(file) == false) { if (File.Exists(signfile) == true) { FoxEventLog.WriteEventLog("Found lonely file \"" + file + "\" - deleting the file", System.Diagnostics.EventLogEntryType.Warning); File.Delete(signfile); } } else { if (File.Exists(signfile) == false) { FoxEventLog.WriteEventLog("Found \"" + file + "\" but no signature - deleting the file", System.Diagnostics.EventLogEntryType.Warning); File.Delete(file); } else { FileInfo fileinfo; fileinfo = new FileInfo(file); if (fileinfo.Length > 33554432) { FoxEventLog.WriteEventLog("File \"" + file + "\" too large (>32MB) - deleting the files", System.Diagnostics.EventLogEntryType.Warning); File.Delete(file); File.Delete(signfile); continue; } fileinfo = new FileInfo(signfile); if (fileinfo.Length > 33554432) { FoxEventLog.WriteEventLog("File \"" + signfile + "\" too large (>32MB) - deleting the files", System.Diagnostics.EventLogEntryType.Warning); File.Delete(file); File.Delete(signfile); continue; } byte[] pol = File.ReadAllBytes(file); byte[] sign = File.ReadAllBytes(signfile); if (ApplicationCertificate.Verify(pol, sign) == false) { FoxEventLog.WriteEventLog("File \"" + file + "\" is not proper signed - deleting the files", System.Diagnostics.EventLogEntryType.Warning); File.Delete(file); File.Delete(signfile); continue; } try { PolicyObject obj = JsonConvert.DeserializeObject <PolicyObject>(Encoding.UTF8.GetString(pol)); if (ContainsPolicy(obj, true, true) == true) { FoxEventLog.WriteEventLog("File \"" + file + "\" is already loaded from a different file - deleting the files", System.Diagnostics.EventLogEntryType.Warning); File.Delete(file); File.Delete(signfile); continue; } LoadedPolicyObject lobj = new LoadedPolicyObject(); lobj.PolicyObject = obj; lobj.Filename = file; lobj.SignFilename = signfile; LoadedPolicyObjects.Add(lobj); Debug.WriteLine(file + " loaded"); } catch { FoxEventLog.WriteEventLog("File \"" + file + "\" cannot be loaded properly - deleting the files", System.Diagnostics.EventLogEntryType.Warning); File.Delete(file); File.Delete(signfile); continue; } } } } return(true); }
public static void AppendIntoHOSTSFile(string Entry, string IPAddress) { try { if (string.IsNullOrWhiteSpace(Entry) == true || string.IsNullOrWhiteSpace(IPAddress) == true) { return; } string HostsLine = IPAddress + " " + Entry + " # from Fox SDC Agent"; string HostsFile = Environment.ExpandEnvironmentVariables("%SYSTEMROOT%\\System32\\Drivers\\Etc\\Hosts"); if (File.Exists(HostsFile) == false) { File.AppendAllText(HostsFile, "\r\n" + HostsLine + "\r\n", Encoding.ASCII); return; } List <string> Data = new List <string>(); bool AppendLine = true; using (TextReader txtr = new StreamReader(File.Open(HostsFile, FileMode.Open, FileAccess.Read, FileShare.Read))) { string Line = ""; while ((Line = txtr.ReadLine()) != null) { Data.Add(Line); if (Line.Contains("#") == true) { Line = Line.Substring(0, Line.IndexOf('#')).Trim(); } if (Line.Trim() == "") { continue; } string[] splitty = Line.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); if (splitty.Length < 2) { continue; } if (splitty[0].ToLower().Trim() == IPAddress.ToLower().Trim() && //exact match - out, no changes splitty[1].ToLower().Trim() == Entry.ToLower().Trim()) { return; } if (splitty[1].ToLower().Trim() == Entry.ToLower().Trim()) //Name match, but not it's IP Address { Data.RemoveAt(Data.Count - 1); Data.Add(HostsLine); AppendLine = false; } } } if (AppendLine == false) { File.WriteAllLines(HostsFile, Data.ToArray(), Encoding.ASCII); } else { File.AppendAllText(HostsFile, "\r\n" + HostsLine + "\r\n", Encoding.ASCII); } } catch (Exception ee) { FoxEventLog.WriteEventLog("Cannot edit HOSTS file: " + ee.ToString(), System.Diagnostics.EventLogEntryType.Error); } }
public static bool DoSyncSMART() { try { Status.UpdateMessage(1, "Collecting SMART Informations"); Network net; net = Utilities.ConnectNetwork(1); if (net == null) { return(false); } Status.UpdateMessage(1, "Collecting SMART Informations"); List <VulpesSMARTInfo> SMART; try { SMART = GetSMARTInfo(); } catch (ManagementException ee) { if (ee.ErrorCode == ManagementStatus.NotSupported) { SMART = new List <VulpesSMARTInfo>(); SMART.Add(new VulpesSMARTInfo() { Attributes = null, Caption = "Unsupported", FirmwareRevision = "AAAA", InterfaceType = "IDE", Model = "Unsupported", Name = "Unsupported", PNPDeviceID = "LEGACY\\UNSUPPORTED", PredictFailure = false, SerialNumber = "00000000000000", Size = 1024 * 1024, Status = "OK", VendorSpecific = null, VendorSpecificThreshold = null }); } else { throw; } } catch { throw; } if (SMART == null) { Status.UpdateMessage(1); net.CloseConnection(); return(false); } Status.UpdateMessage(1, "Collecting SMART Informations (Sending data ...)"); net.ReportSMARTInfos(SystemInfos.SysInfo.MachineID, SMART); net.CloseConnection(); } catch (Exception ee) { Debug.WriteLine(ee.ToString()); FoxEventLog.WriteEventLog("Servere error while syncing SMART Informations: " + ee.ToString(), EventLogEntryType.Error); } Status.UpdateMessage(1); return(true); }
static bool RunUpdate() { string pkgfile = ProgramAgent.AppPath + "agentupdate.foxpkg"; const string PackageID = "Vulpes-SDCA1-Update"; net = Utilities.ConnectNetwork(-1); if (net == null) { return(false); } bool EarlyChannel = RegistryData.EarlyUpdates == 1 ? true : false; Int64?Version = net.GetAvailableAgentVersion(EarlyChannel); if (Version == null) { net.CloseConnection(); return(false); } if (Version.Value <= FoxVersion.Version) { net.CloseConnection(); return(false); } if (net.DownloadFile("api/" + (EarlyChannel == true ? "early" : "") + "update/package/1", pkgfile) == false) { net.CloseConnection(); return(false); } net.CloseConnection(); PackageInstaller pkgi = new PackageInstaller(); string Error; if (pkgi.PackageInfo(pkgfile, null, out Error) == false) { CommonUtilities.SpecialDeleteFile(pkgfile); FoxEventLog.WriteEventLog("Self-Update: Error reading package file " + pkgfile + ": " + Error, System.Diagnostics.EventLogEntryType.Error); return(false); } if (pkgi.PackageInfoData.PackageID != PackageID) { CommonUtilities.SpecialDeleteFile(pkgfile); FoxEventLog.WriteEventLog("Self-Update: PackageID mismatch on file " + pkgfile, System.Diagnostics.EventLogEntryType.Error); return(false); } if (pkgi.PackageInfoData.VersionID <= FoxSDC_Agent.FoxVersion.Version) { CommonUtilities.SpecialDeleteFile(pkgfile); FoxEventLog.WriteEventLog("Self-Update: Version on package is same or older than installed for file " + pkgfile, System.Diagnostics.EventLogEntryType.Error); return(false); } string UpdateApp = ProgramAgent.AppPath + "FoxSDC_Selfupdate.exe"; FoxEventLog.WriteEventLog("Self-Update: Starting " + UpdateApp + " to update from " + FoxSDC_Agent.FoxVersion.Version.ToString() + " to " + pkgi.PackageInfoData.VersionID.ToString(), System.Diagnostics.EventLogEntryType.Information); #if !DEBUG if (ProgramAgent.CPP.VerifyEXESignature(UpdateApp) == false) { FoxEventLog.WriteEventLog("The file " + UpdateApp + " cannot be verified. Update will not work.", EventLogEntryType.Error); } else #endif { try { Process.Start(UpdateApp); } catch { } } return(true); }
static public void LoadLocalPackages() { string PackagesFolder = SystemInfos.ProgramData + "Packages\\"; if (Directory.Exists(PackagesFolder) == false) { Directory.CreateDirectory(PackagesFolder); } if (LocalPackages == null) { LocalPackages = new List <PackagesToInstall>(); } try { if (File.Exists(PackagesFolder + "List.json") == true && File.Exists(PackagesFolder + "List.sign") == true) { byte[] list = File.ReadAllBytes(PackagesFolder + "List.json"); byte[] sign = File.ReadAllBytes(PackagesFolder + "List.sign"); if (ApplicationCertificate.Verify(list, sign) == false) { File.Delete(PackagesFolder + "List.json"); File.Delete(PackagesFolder + "List.sign"); FoxEventLog.WriteEventLog("Package list signature is invalid: deleting the files!", EventLogEntryType.Warning); LocalPackages = new List <PackagesToInstall>(); } else { LocalPackages = JsonConvert.DeserializeObject <List <PackagesToInstall> >(Encoding.UTF8.GetString(list)); } } } catch (Exception ee) { Debug.WriteLine(ee.ToString()); FoxEventLog.WriteEventLog("Error decoding package list data", EventLogEntryType.Warning); LocalPackages = new List <PackagesToInstall>(); } try { foreach (PackagesToInstall pkg in LocalPackages) { if (pkg.Filename != null) { if (File.Exists(PackagesFolder + pkg.Filename) == false) { FoxEventLog.WriteEventLog("Referenced package " + pkg.Filename + " does not exist", EventLogEntryType.Warning); pkg.Filename = null; } } if (pkg.MetaFilename != null) { if (File.Exists(PackagesFolder + pkg.MetaFilename) == false) { FoxEventLog.WriteEventLog("Referenced meta package " + pkg.Filename + " does not exist", EventLogEntryType.Warning); pkg.MetaFilename = null; } } } List <PackagesToInstall> RemovePackages = new List <PackagesToInstall>(); foreach (PackagesToInstall pkg in LocalPackages) { if (pkg.MetaFilename == null) { RemovePackages.Add(pkg); } } foreach (PackagesToInstall pkg in RemovePackages) { LocalPackages.Remove(pkg); if (pkg.MetaFilename != null) { File.Delete(PackagesFolder + pkg.MetaFilename); } if (pkg.Filename != null) { File.Delete(PackagesFolder + pkg.Filename); } } } catch (Exception ee) { Debug.WriteLine(ee.ToString()); FoxEventLog.WriteEventLog("Error processing package list data", EventLogEntryType.Error); LocalPackages = new List <PackagesToInstall>(); } }
static WindowsLic GetWindowsLicense() { WindowsLic lic = new WindowsLic(); try { ManagementScope Scope; Scope = new ManagementScope("\\\\.\\root\\CIMV2", null); Scope.Connect(); ObjectQuery Query = new ObjectQuery("SELECT * FROM SoftwareLicensingProduct Where PartialProductKey<>null AND ApplicationId='55c92734-d682-4d71-983e-d6ec3f16059f' AND LicenseIsAddon=False"); EnumerationOptions eo = new EnumerationOptions(); eo.Timeout = new TimeSpan(0, 0, 3, 0); ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query, eo); foreach (ManagementObject WmiObject in Searcher.Get()) { lic.Name = (String)WmiObject["Name"]; lic.Description = (String)WmiObject["Description"]; lic.GracePeriodRemaining = (UInt32)WmiObject["GracePeriodRemaining"]; lic.PartialProductKey = (String)WmiObject["PartialProductKey"]; lic.ProductKeyID = (String)WmiObject["ProductKeyID"]; try { lic.ProductKeyID2 = (String)WmiObject["ProductKeyID2"]; } catch { lic.ProductKeyID2 = ""; } lic.LicenseFamily = (String)WmiObject["LicenseFamily"]; try { lic.ProductKeyChannel = (String)WmiObject["ProductKeyChannel"]; } catch { lic.ProductKeyChannel = ""; } lic.LicenseStatus = (UInt32)WmiObject["LicenseStatus"]; switch ((UInt32)WmiObject["LicenseStatus"]) { case 0: lic.LicenseStatusText = "Unlicensed"; break; case 1: lic.LicenseStatusText = "Licensed"; break; case 2: lic.LicenseStatusText = "Out-Of-Box Grace Period"; break; case 3: lic.LicenseStatusText = "Out-Of-Tolerance Grace Period"; break; case 4: lic.LicenseStatusText = "On-Genuine Grace Period"; break; case 5: lic.LicenseStatusText = "Notification"; break; default: lic.LicenseStatusText = lic.LicenseStatus.ToString(); break; } } } catch (ManagementException ee) { if (ee.ErrorCode == ManagementStatus.CallCanceled || ee.ErrorCode == ManagementStatus.Timedout) { //drop message silently Debug.WriteLine(ee.ToString()); return(null); } else { Debug.WriteLine(ee.ToString()); FoxEventLog.WriteEventLog("Cannot get Windows License Info " + ee.ToString(), System.Diagnostics.EventLogEntryType.Error); return(null); } } catch (Exception ee) { Debug.WriteLine(ee.ToString()); FoxEventLog.WriteEventLog("Cannot get Windows License Info " + ee.ToString(), System.Diagnostics.EventLogEntryType.Error); return(null); } return(lic); }
static public void LoadUserPackageData() { string PackagesFolder = SystemInfos.ProgramData + "Packages\\"; if (Directory.Exists(PackagesFolder) == false) { Directory.CreateDirectory(PackagesFolder); } if (AvailableUserPackages == null) { AvailableUserPackages = new List <PackageIDData>(); } if (UserPackagesToInstall == null) { UserPackagesToInstall = new List <PackageIDData>(); } try { if (File.Exists(PackagesFolder + "AvailableUserPackages.json") == true && File.Exists(PackagesFolder + "AvailableUserPackages.sign") == true) { byte[] list = File.ReadAllBytes(PackagesFolder + "AvailableUserPackages.json"); byte[] sign = File.ReadAllBytes(PackagesFolder + "AvailableUserPackages.sign"); if (ApplicationCertificate.Verify(list, sign) == false) { File.Delete(PackagesFolder + "AvailableUserPackages.json"); File.Delete(PackagesFolder + "AvailableUserPackages.sign"); FoxEventLog.WriteEventLog("AvailableUserPackages list signature is invalid: deleting the files!", EventLogEntryType.Warning); AvailableUserPackages = new List <PackageIDData>(); } else { AvailableUserPackages = JsonConvert.DeserializeObject <List <PackageIDData> >(Encoding.UTF8.GetString(list)); } } } catch (Exception ee) { Debug.WriteLine(ee.ToString()); FoxEventLog.WriteEventLog("Error decoding AvailableUserPackages", EventLogEntryType.Warning); AvailableUserPackages = new List <PackageIDData>(); } try { if (File.Exists(PackagesFolder + "UserPackagesToInstall.json") == true && File.Exists(PackagesFolder + "UserPackagesToInstall.sign") == true) { byte[] list = File.ReadAllBytes(PackagesFolder + "UserPackagesToInstall.json"); byte[] sign = File.ReadAllBytes(PackagesFolder + "UserPackagesToInstall.sign"); if (ApplicationCertificate.Verify(list, sign) == false) { File.Delete(PackagesFolder + "UserPackagesToInstall.json"); File.Delete(PackagesFolder + "UserPackagesToInstall.sign"); FoxEventLog.WriteEventLog("UserPackagesToInstall list signature is invalid: deleting the files!", EventLogEntryType.Warning); UserPackagesToInstall = new List <PackageIDData>(); } else { UserPackagesToInstall = JsonConvert.DeserializeObject <List <PackageIDData> >(Encoding.UTF8.GetString(list)); } } } catch (Exception ee) { Debug.WriteLine(ee.ToString()); FoxEventLog.WriteEventLog("Error decoding UserPackagesToInstall", EventLogEntryType.Warning); UserPackagesToInstall = new List <PackageIDData>(); } }
static int Main(string[] args) { Init(); for (int i = 0; i < args.Length; i++) { if (args[i].ToLower() == "-reset") { Console.WriteLine("Resetting"); FoxEventLog.WriteEventLog("RESET: Recovering from a crash", EventLogEntryType.Warning); try { ServiceController ctrl = new ServiceController("FoxSDCA"); ctrl.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 5, 0)); ctrl.Start(); } catch (Exception ee) { Console.WriteLine(ee.ToString()); return(-1); } return(0); } if (args[i].ToLower() == "-install") { try { ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location }); } catch (Exception ee) { Console.WriteLine(ee.ToString()); return(-1); } return(0); } if (args[i].ToLower() == "-pipeaction") { if (args.Length <= i) { return(-1); } PipeGUID = args[i + 1]; UsePipeAction = true; i++; SMain(); return(0); } if (args[i].ToLower() == "-screen") { if (args.Length <= i) { return(-1); } PipeGUID = args[i + 1]; UseScreenAction = true; i++; SMain(); return(0); } if (args[i].ToLower() == "-autodnsconfig") { UseDNSAutoConfig = true; i++; SMain(); return(0); } if (args[i].ToLower() == "-recovercreds") { UseLoginRecovery = true; i++; SMain(); return(0); } } #if DEBUG && !DEBUGSERVICE SMain(); Console.WriteLine("DEBUG: Running - Press any key . . . "); Console.ReadKey(true); Console.WriteLine("DEBUG: Stopping . . . "); Threads.StopAllThreads(); #else ServicesToRun = new ServiceBase[] { service }; ServiceBase.Run(ServicesToRun); #endif return(0); }
static public bool UpdatePolicyOrder(PolicyObject obj, Int64 Order) { if (LoadedPolicyObjects == null) { LoadedPolicyObjects = new List <LoadedPolicyObject>(); } foreach (LoadedPolicyObject pol in LoadedPolicyObjects) { if (pol.PolicyObject.ID != obj.ID) { continue; } if (pol.PolicyObject.Name != obj.Name) { continue; } if (pol.PolicyObject.Type != obj.Type) { continue; } if (pol.PolicyObject.Version != obj.Version) { continue; } if (pol.PolicyObject.DT != obj.DT) { continue; } pol.PolicyObject.Order = Order; byte[] ppol = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(pol.PolicyObject)); byte[] sign = ApplicationCertificate.Sign(ppol); if (sign == null) { FoxEventLog.WriteEventLog("Cannot sign policy for saving", System.Diagnostics.EventLogEntryType.Error); return(false); } try { File.WriteAllBytes(pol.Filename, ppol); } catch { FoxEventLog.WriteEventLog("Cannot save policy", System.Diagnostics.EventLogEntryType.Error); return(false); } try { File.WriteAllBytes(pol.SignFilename, sign); } catch { try { File.Delete(pol.Filename); } catch { } FoxEventLog.WriteEventLog("Cannot save policy signature", System.Diagnostics.EventLogEntryType.Error); return(false); } break; } return(true); }
public static bool InvokeInstallPackage(string Filename, List <byte[]> CerCertificates, InstallMode Mode, bool ZipIsMetaOnly, out string ErrorText, out PKGStatus res, out PKGRecieptData Reciept, string OtherDLL = "") { ErrorText = "Internal issues"; res = PKGStatus.Failed; Reciept = null; DataHInstallPackageTODO inst = new DataHInstallPackageTODO(); inst.Filename = Filename; inst.CerCertificates = CerCertificates; inst.Mode = Mode; inst.ZipIsMetaOnly = ZipIsMetaOnly; inst.OtherDLL = OtherDLL; Process2ProcessComm p2p = new Process2ProcessComm(); p2p.SetTODO("INSTALL", inst); if (p2p.StartPipe() == false) { FoxEventLog.WriteEventLog("Cannot start P2PC for INSTALL " + p2p.GetGUID(), EventLogEntryType.Error); return(false); } Process p = new Process(); p.StartInfo.Arguments = "-pipeaction " + p2p.GetGUID(); p.StartInfo.FileName = Assembly.GetExecutingAssembly().Location; p.StartInfo.UseShellExecute = false; if (p.Start() == false) { FoxEventLog.WriteEventLog("Cannot start P2PC Process for INSTALL " + p2p.GetGUID(), EventLogEntryType.Error); p2p.ClosePipe(); return(false); } p.WaitForExit(); DataHInstallPackageResult ores = p2p.GetResult <DataHInstallPackageResult>(); p2p.ClosePipe(); if (ores == null) { FoxEventLog.WriteEventLog("P2PC didn't return any data for INSTALL " + p2p.GetGUID(), EventLogEntryType.Error); return(false); } ErrorText = ores.ErrorText; res = ores.res; Reciept = ores.Reciept; if (ores.TempDLLFilename != null) { try { File.Delete(ores.TempDLLFilename); } catch { } } return(ores.Return); }
static public bool InstallPolicy(PolicyObject data, Int64 Order) { if (data == null) { return(false); } data.Order = Order; string PoliciesFolder = SystemInfos.ProgramData + "Policies\\"; string Filename = data.ID.ToString("X8") + "-" + Guid.NewGuid().ToString(); byte[] pol = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data)); byte[] sign = ApplicationCertificate.Sign(pol); if (sign == null) { FoxEventLog.WriteEventLog("Cannot sign policy for saving", System.Diagnostics.EventLogEntryType.Error); return(false); } //do we have that policy loaded?... - overwrite that (and store it to an Update Dict) if (LoadedPolicyObjects == null) { LoadedPolicyObjects = new List <LoadedPolicyObject>(); } foreach (LoadedPolicyObject loadedpol in LoadedPolicyObjects) { if (loadedpol.PolicyObject.ID != data.ID) { continue; } if (UpdatePolicies == null) { UpdatePolicies = new Dictionary <LoadedPolicyObject, LoadedPolicyObject>(); } UpdatePolicies.Add( new LoadedPolicyObject() { Filename = loadedpol.Filename, SignFilename = loadedpol.SignFilename, PolicyObject = new PolicyObject() { Condition = loadedpol.PolicyObject.Condition, DataAddtions1 = loadedpol.PolicyObject.DataAddtions1, DataAddtions2 = loadedpol.PolicyObject.DataAddtions2, DataAddtions3 = loadedpol.PolicyObject.DataAddtions3, DataAddtions4 = loadedpol.PolicyObject.DataAddtions4, DataAddtions5 = loadedpol.PolicyObject.DataAddtions5, Data = loadedpol.PolicyObject.Data, DT = loadedpol.PolicyObject.DT, Enabled = loadedpol.PolicyObject.Enabled, Grouping = loadedpol.PolicyObject.Grouping, ID = loadedpol.PolicyObject.ID, MachineID = loadedpol.PolicyObject.MachineID, Name = loadedpol.PolicyObject.Name, Order = loadedpol.PolicyObject.Order, TimeStampCheck = loadedpol.PolicyObject.TimeStampCheck, Type = loadedpol.PolicyObject.Type, Version = loadedpol.PolicyObject.Version } } , new LoadedPolicyObject() { PolicyObject = data, Filename = loadedpol.Filename, SignFilename = loadedpol.SignFilename }); loadedpol.PolicyObject = data; try { File.WriteAllBytes(loadedpol.Filename, pol); } catch { FoxEventLog.WriteEventLog("Cannot save policy", System.Diagnostics.EventLogEntryType.Error); return(false); } try { File.WriteAllBytes(loadedpol.SignFilename, sign); } catch { try { File.Delete(loadedpol.Filename); } catch { } FoxEventLog.WriteEventLog("Cannot save policy signature", System.Diagnostics.EventLogEntryType.Error); return(false); } return(true); } //no? create the file LoadedPolicyObject lobj = new LoadedPolicyObject(); lobj.PolicyObject = data; lobj.Filename = PoliciesFolder + Filename + ".pol"; lobj.SignFilename = PoliciesFolder + Filename + ".sign"; try { File.WriteAllBytes(lobj.Filename, pol); } catch { FoxEventLog.WriteEventLog("Cannot save policy", System.Diagnostics.EventLogEntryType.Error); return(false); } try { File.WriteAllBytes(lobj.SignFilename, sign); } catch { try { File.Delete(lobj.Filename); } catch { } FoxEventLog.WriteEventLog("Cannot save policy signature", System.Diagnostics.EventLogEntryType.Error); return(false); } LoadedPolicyObjects.Add(lobj); return(true); }
public static Network ConnectNetwork(int MessageChannel) { if (SystemInfos.ServerURL == ProgramAgent.VulpesURL) { if (SystemInfos.ContractID == "" || SystemInfos.ContractPassword == "") { FoxEventLog.VerboseWriteEventLog("Missing contract data for Vulpes Server (" + ProgramAgent.VulpesURL + ")", System.Diagnostics.EventLogEntryType.Error); return(null); } } Network net = new Network(); if (MessageChannel > -1) { Status.UpdateMessage(MessageChannel, "Connecting to server " + SystemInfos.ServerURL); } FoxEventLog.VerboseWriteEventLog("Connecting to server " + SystemInfos.ServerURL, System.Diagnostics.EventLogEntryType.Information); try { ServerInfo = null; URL = SystemInfos.ServerURL; if (net.Connect(SystemInfos.ServerURL) == false) { if (MessageChannel > -1) { Status.UpdateMessage(MessageChannel, "Connecting to server " + SystemInfos.ServerURL + " failed"); } FoxEventLog.VerboseWriteEventLog("Connecting to server " + SystemInfos.ServerURL + " failed", System.Diagnostics.EventLogEntryType.Information); return(null); } try { SystemInfos.SysInfo.IsMeteredConnection = MeteredConnection.IsMeteredConnection(); //always update this } catch (Exception ee) { Debug.WriteLine(ee.ToString()); SystemInfos.SysInfo.IsMeteredConnection = null; } if (net.ComputerLogin(SystemInfos.SysInfo.MachineID, SystemInfos.PasswordID, SystemInfos.ContractID, SystemInfos.ContractPassword, SystemInfos.SysInfo) == false) { if (net.LoginError == null) { if (MessageChannel > -1) { Status.UpdateMessage(MessageChannel, "Login failed: <no data> ( on server " + SystemInfos.ServerURL + ")"); } FoxEventLog.VerboseWriteEventLog("Login failed: <no data> ( on server " + SystemInfos.ServerURL + ")", System.Diagnostics.EventLogEntryType.Information); } else { if (MessageChannel > -1) { Status.UpdateMessage(MessageChannel, "Login failed: " + net.LoginError.Error + " - " + net.LoginError.ErrorID.ToString() + " ( on server " + SystemInfos.ServerURL + ")"); } FoxEventLog.VerboseWriteEventLog("Login failed: " + net.LoginError.Error + " - " + net.LoginError.ErrorID.ToString() + " ( on server " + SystemInfos.ServerURL + ")", System.Diagnostics.EventLogEntryType.Information); } net.CloseConnection(); return(null); } if (net.GetInfo() == true) { ServerInfo = net.serverinfo; URL = SystemInfos.ServerURL; } if (MessageChannel > -1) { Status.UpdateMessage(MessageChannel); } } catch { FoxEventLog.VerboseWriteEventLog("Login failed - something really has gone wrong: (" + SystemInfos.ServerURL + ")", System.Diagnostics.EventLogEntryType.Information); if (MessageChannel > -1) { Status.UpdateMessage(MessageChannel); } return(null); } return(net); }
public static bool DoSyncPolicy() { RequestCertPolicyID = 0; RequestCertPolicyMessageID = 0; RequestCertPolicyCERData = null; List <Int64> ProcessedPolicies = new List <long>(); Network net; net = Utilities.ConnectNetwork(9); if (net == null) { return(false); } Status.UpdateMessage(9, "Downloading client settings"); FoxEventLog.VerboseWriteEventLog("Downloading client settings", System.Diagnostics.EventLogEntryType.Information); ClientSettings settings = net.GetClientSettings(); if (settings != null) { RegistryData.AdministratorName = settings.AdministratorName; RegistryData.MessageDisclaimer = settings.MessageDisclaimer; } Status.UpdateMessage(9, "Downloading policies"); FoxEventLog.VerboseWriteEventLog("Downloading policies", System.Diagnostics.EventLogEntryType.Information); PolicyObjectListSigned policieslistsigned = net.GetPoliciesForComputer(); List <PolicyObjectSigned> policies = policieslistsigned == null ? null : policieslistsigned.Items; if (policies == null) { FoxEventLog.VerboseWriteEventLog("Downloading policies - nix", System.Diagnostics.EventLogEntryType.Information); Status.UpdateMessage(9); net.CloseConnection(); return(true); } if (FilesystemData.LoadedCertificates.Count > 0) { bool SignatureOK = false; foreach (FilesystemCertificateData cer in FilesystemData.LoadedCertificates) { if (Certificates.Verify(policieslistsigned, cer.Certificate) == true) { SignatureOK = true; break; } } if (SignatureOK == false) { FoxEventLog.WriteEventLog("Invalid signature for PolicyList - no policies will be processed.", System.Diagnostics.EventLogEntryType.Error); net.CloseConnection(); return(true); } } if (RegistryData.Verbose == 1) { string data = "Got policy:\r\n"; foreach (PolicyObjectSigned obj in policies) { data += obj.Policy.Name + " [ID: " + obj.Policy.ID + " VER: " + obj.Policy.Version + "]\r\n"; } FoxEventLog.VerboseWriteEventLog("Downloading policies " + data, System.Diagnostics.EventLogEntryType.Information); } if (FilesystemData.LoadedCertificates.Count > 0) { foreach (PolicyObjectSigned obj in policies) { if (ApplicationCertificate.Verify(obj) == false) { FoxEventLog.WriteEventLog("One or more policies were tampered - no policies will be processed.", System.Diagnostics.EventLogEntryType.Error); net.CloseConnection(); return(true); } } } #region Certificate Checks foreach (PolicyObjectSigned obj in policies) { if (obj.Policy.Type == PolicyIDs.SignCertificate) { if (FilesystemData.ContainsPolicy(obj.Policy, false, false) == true) { continue; } PolicyObjectSigned objj = net.GetPolicyObjectSigned(obj.Policy.ID); //do not verify signing here - that won't work! - Fox PolicySigningCertificates Cert = JsonConvert.DeserializeObject <PolicySigningCertificates>(objj.Policy.Data); if (FilesystemData.ContainsLoadedCert(Convert.FromBase64String(Cert.UUCerFile)) == true) { continue; } bool sig = Certificates.Verify(Convert.FromBase64String(Cert.UUCerFile), Convert.FromBase64String(Cert.UUSignFile), InternalCertificate.Main); if (sig == false) { RequestCertPolicyID = objj.Policy.ID; RequestCertPolicyCERData = Convert.FromBase64String(Cert.UUCerFile); string CN = Certificates.GetCN(Convert.FromBase64String(Cert.UUCerFile)); if (CN == null) { FoxEventLog.WriteEventLog("Invalid certificate from server (Policy ID=" + objj.Policy.ID.ToString() + " Name=" + objj.Policy.Name + ")", System.Diagnostics.EventLogEntryType.Error); continue; } Status.RequestCertificateConfirm("The certificate with " + CN + " is not signed by Vulpes. This may that someone tampered the connection, or a false certificate is installed on the server.\nDo you want to continue, and trust this certificate?", RequestCertPolicyID); RequestCertPolicyMessageID = Status.MessageID; FoxEventLog.WriteEventLog("Got unsinged certificate (Policy ID=" + objj.Policy.ID.ToString() + " Name=" + objj.Policy.Name + " " + CN + ")", System.Diagnostics.EventLogEntryType.Warning); } else { string CN = Certificates.GetCN(Convert.FromBase64String(Cert.UUCerFile)); if (CN == null) { FoxEventLog.WriteEventLog("Invalid (Vulpes signed) certificate from server (Policy ID=" + objj.Policy.ID.ToString() + " Name=" + objj.Policy.Name + ")", System.Diagnostics.EventLogEntryType.Error); continue; } FilesystemData.InstallCertificate(Convert.FromBase64String(Cert.UUCerFile)); } } } #endregion if (FilesystemData.LoadedCertificates.Count > 0) { foreach (PolicyObjectSigned obj in policies) { if (FilesystemData.ContainsPolicy(obj.Policy, false, false) == true) { if (ProcessedPolicies.Contains(obj.Policy.ID) == false) { ProcessedPolicies.Add(obj.Policy.ID); } FilesystemData.UpdatePolicyOrder(obj.Policy, obj.Policy.Order); continue; } PolicyObjectSigned objj = net.GetPolicyObjectSigned(obj.Policy.ID); if (objj == null) { FoxEventLog.WriteEventLog("No data for policy - not applying (Policy ID=" + obj.Policy.ID.ToString() + " Name=" + obj.Policy.Name + ")", System.Diagnostics.EventLogEntryType.Error); continue; } if (ApplicationCertificate.Verify(objj) == false) { FoxEventLog.WriteEventLog("Policy was tampered - not applying (Policy ID=" + objj.Policy.ID.ToString() + " Name=" + objj.Policy.Name + ")", System.Diagnostics.EventLogEntryType.Error); continue; } if (FilesystemData.InstallPolicy(objj.Policy, obj.Policy.Order) == false) { continue; } if (ProcessedPolicies.Contains(obj.Policy.ID) == false) { ProcessedPolicies.Add(obj.Policy.ID); } } List <LoadedPolicyObject> RemovePol = new List <LoadedPolicyObject>(); foreach (LoadedPolicyObject lobj in FilesystemData.LoadedPolicyObjects) { if (ProcessedPolicies.Contains(lobj.PolicyObject.ID) == false) { RemovePol.Add(lobj); } } foreach (LoadedPolicyObject lobj in RemovePol) { FilesystemData.DeletePolicy(lobj); } } net.CloseConnection(); if (RequestCertPolicyID == 0) { Status.UpdateMessage(9); } FoxEventLog.VerboseWriteEventLog("Downloading policies - DONE", System.Diagnostics.EventLogEntryType.Information); return(true); }
static void ThreadRunner() { lock (FileLock) { FilesystemData.LoadFileTransferStatus(); } while (StopService == false) { try { Network net = Utilities.ConnectNetwork(7); if (net == null) { Wait(60); continue; } NetInt64ListSigned lst = net.File_Agent_GetFileList(); if (lst == null) { net.CloseConnection(); Wait(2 * 60); continue; } if (ApplicationCertificate.Verify(lst) == false) { FoxEventLog.WriteEventLog("One or more DownloadFS Lists are tampered - no download / uploads will be processed.", System.Diagnostics.EventLogEntryType.Error); net.CloseConnection(); Wait(2 * 60); continue; } if (lst.data.data.Count == 0) { net.CloseConnection(); Wait(2 * 60); continue; } Int64 RunningID = 0; lock (FileLock) { if (FilesystemData.FileTransferStatus.ServerID != null) { bool Found = false; foreach (Int64 l in lst.data.data) { if (l == FilesystemData.FileTransferStatus.ServerID.Value) { Found = true; RunningID = l; break; } } if (Found == false) { RunningID = lst.data.data[0]; } } else { RunningID = lst.data.data[0]; } } Debug.Assert(RunningID != 0); FileUploadDataSigned fud = net.File_Agent_GetFileAnyData(RunningID); if (ApplicationCertificate.Verify(fud) == false) { FoxEventLog.WriteEventLog("One or more DownloadFS Elements are tampered - no download / uploads will be processed.", System.Diagnostics.EventLogEntryType.Error); net.CloseConnection(); Wait(2 * 60); continue; } net.CloseConnection(); string LocalFilename = ""; bool WaitandContinue = false; lock (FileLock) { //may be needed for deleting the file (if canceled by the server) LocalFilename = FilesystemData.FileTransferStatus.RemoteFileLocation; if (FilesystemData.FileTransferStatus.ServerID != null) { if (RunningID != FilesystemData.FileTransferStatus.ServerID) { CancelAndDeleteDL = true; } else { if (FilesystemData.FileTransferStatus.Size != fud.Data.Size || FilesystemData.FileTransferStatus.RemoteFileLocation != fud.Data.RemoteFileLocation || FilesystemData.FileTransferStatus.MD5CheckSum.ToLower() != fud.Data.MD5CheckSum.ToLower() || FilesystemData.FileTransferStatus.RequestOnly != fud.Data.RequestOnly) { CancelAndDeleteDL = true; } else { if (RunningDLThread == null) { RunningDLThread = new Thread(new ThreadStart(DownloadThreadRunner)); RunningDLThread.Start(); } else { if (RunningDLThread.IsAlive == false) { RunningDLThread = new Thread(new ThreadStart(DownloadThreadRunner)); RunningDLThread.Start(); } } } WaitandContinue = true; } } } if (WaitandContinue == true) { Wait(2 * 60); continue; } if (CancelAndDeleteDL == true) { if (RunningDLThread != null) { RunningDLThread.Join(); } if (string.IsNullOrWhiteSpace(LocalFilename) == false) { try { if (FilesystemData.FileTransferStatus.Direction == 0) { if (File.Exists(LocalFilename) == true) { File.Delete(LocalFilename); } } } catch (Exception ee) { FoxEventLog.WriteEventLog("Cannot check / delete " + LocalFilename + "\n" + ee.ToString(), System.Diagnostics.EventLogEntryType.Error); } } } CancelAndDeleteDL = false; lock (FileLock) { FilesystemData.FileTransferStatus.Size = fud.Data.Size; FilesystemData.FileTransferStatus.RemoteFileLocation = fud.Data.RemoteFileLocation; FilesystemData.FileTransferStatus.MD5CheckSum = fud.Data.MD5CheckSum.ToLower(); FilesystemData.FileTransferStatus.OverrideMeteredConnection = fud.Data.OverrideMeteredConnection; FilesystemData.FileTransferStatus.Direction = fud.Data.Direction; FilesystemData.FileTransferStatus.ProgressSize = 0; FilesystemData.FileTransferStatus.ServerID = RunningID; FilesystemData.FileTransferStatus.RequestOnly = fud.Data.RequestOnly; FilesystemData.FileTransferStatus.LastModfied = fud.Data.FileLastModified; FilesystemData.WriteFileTransferStatus(); } RunningDLThread = new Thread(new ThreadStart(DownloadThreadRunner)); RunningDLThread.Start(); Wait(2 * 60); continue; } catch (Exception ee) { FoxEventLog.WriteEventLog("Internal crash in DownloadFS System: " + ee.Message, System.Diagnostics.EventLogEntryType.Error); Wait(10); } Wait(2 * 60); } ; }
public static bool ApplyPolicy(ApplyPolicyFunction applymethod) { if (ActivePolicy == null) { ActivePolicy = new List <LoadedPolicyObject>(); } FilesystemData.ReOrderPolicies(); foreach (Type type in GetTypesWithHelpAttribute(Assembly.GetExecutingAssembly())) { PolicyObjectAttr po = type.GetCustomAttribute <PolicyObjectAttr>(); IPolicyClass instance = (IPolicyClass)Activator.CreateInstance(type); try { instance.PreApplyPolicy(); } catch (Exception ee) { Debug.WriteLine(ee.ToString()); FoxEventLog.WriteEventLog("SEH Error while finalising policy - Type 0x" + po.PolicyType.ToString("X"), System.Diagnostics.EventLogEntryType.Error); } } if (FilesystemData.UpdatePolicies != null) { foreach (KeyValuePair <LoadedPolicyObject, LoadedPolicyObject> kvp in FilesystemData.UpdatePolicies) { foreach (Type type in GetTypesWithHelpAttribute(Assembly.GetExecutingAssembly())) { PolicyObjectAttr po = type.GetCustomAttribute <PolicyObjectAttr>(); if (po.PolicyType == kvp.Key.PolicyObject.Type) { IPolicyClass instance = (IPolicyClass)Activator.CreateInstance(type); try { instance.UpdatePolicy(kvp.Key, kvp.Value); } catch (Exception ee) { Debug.WriteLine(ee.ToString()); FoxEventLog.WriteEventLog("SEH Error while updating policy - (Policy ID=" + kvp.Value.PolicyObject.ID.ToString() + " Name=" + kvp.Value.PolicyObject.Name + ")", System.Diagnostics.EventLogEntryType.Error); } break; } } } } List <LoadedPolicyObject> RemovePol = new List <LoadedPolicyObject>(); foreach (LoadedPolicyObject a in ActivePolicy) { bool PolicyFound = false; foreach (LoadedPolicyObject b in FilesystemData.LoadedPolicyObjects) { if (a.PolicyObject.ID == b.PolicyObject.ID && a.PolicyObject.Type == b.PolicyObject.Type) { PolicyFound = true; break; } } if (PolicyFound == false) { RemovePol.Add(a); } } foreach (LoadedPolicyObject a in RemovePol) { foreach (Type type in GetTypesWithHelpAttribute(Assembly.GetExecutingAssembly())) { PolicyObjectAttr po = type.GetCustomAttribute <PolicyObjectAttr>(); if (po.PolicyType == a.PolicyObject.Type) { IPolicyClass instance = (IPolicyClass)Activator.CreateInstance(type); try { instance.RemovePolicy(a); } catch (Exception ee) { Debug.WriteLine(ee.ToString()); FoxEventLog.WriteEventLog("SEH Error while removing policy - (Policy ID=" + a.PolicyObject.ID.ToString() + " Name=" + a.PolicyObject.Name + ")", System.Diagnostics.EventLogEntryType.Error); } ActivePolicy.Remove(a); break; } } } RemovePol = new List <LoadedPolicyObject>(); //empty out foreach (LoadedPolicyObject a in FilesystemData.LoadedPolicyObjects) { bool PolicyFound = false; foreach (LoadedPolicyObject b in ActivePolicy) { if (a.PolicyObject.ID == b.PolicyObject.ID && a.PolicyObject.Version == b.PolicyObject.Version && a.PolicyObject.Type == b.PolicyObject.Type) { PolicyFound = true; break; } } if (PolicyFound == false) { bool CanProcessPolicy = false; bool FoundPolicyProcessor = false; foreach (Type type in GetTypesWithHelpAttribute(Assembly.GetExecutingAssembly())) { PolicyObjectAttr po = type.GetCustomAttribute <PolicyObjectAttr>(); if (po.PolicyType == a.PolicyObject.Type) { IPolicyClass instance = (IPolicyClass)Activator.CreateInstance(type); try { instance.ApplyPolicy(a); } catch (Exception ee) { Debug.WriteLine(ee.ToString()); FoxEventLog.WriteEventLog("SEH Error while applying policy - (Policy ID=" + a.PolicyObject.ID.ToString() + " Name=" + a.PolicyObject.Name + ")", System.Diagnostics.EventLogEntryType.Error); } CanProcessPolicy = true; FoundPolicyProcessor = true; break; } } if (CanProcessPolicy == true || FoundPolicyProcessor == true) { ActivePolicy.Add(a); } if (FoundPolicyProcessor == false) { FoxEventLog.WriteEventLog("Don't know how to process policy type 0x" + a.PolicyObject.Type.ToString("X") + " - (Policy ID=" + a.PolicyObject.ID.ToString() + " Name=" + a.PolicyObject.Name + ")", System.Diagnostics.EventLogEntryType.Warning); } } } foreach (LoadedPolicyObject a in ActivePolicy) { foreach (Type type in GetTypesWithHelpAttribute(Assembly.GetExecutingAssembly())) { PolicyObjectAttr po = type.GetCustomAttribute <PolicyObjectAttr>(); if (po.PolicyType == a.PolicyObject.Type) { IPolicyClass instance = (IPolicyClass)Activator.CreateInstance(type); try { instance.ApplyOrdering(a, a.PolicyObject.Order); } catch (Exception ee) { Debug.WriteLine(ee.ToString()); FoxEventLog.WriteEventLog("SEH Error while reordering polcy - Type 0x" + po.PolicyType.ToString("X"), System.Diagnostics.EventLogEntryType.Error); } } } } foreach (Type type in GetTypesWithHelpAttribute(Assembly.GetExecutingAssembly())) { PolicyObjectAttr po = type.GetCustomAttribute <PolicyObjectAttr>(); IPolicyClass instance = (IPolicyClass)Activator.CreateInstance(type); try { switch (applymethod) { case ApplyPolicyFunction.ApplySystem: instance.FinaliseApplyPolicy(); break; case ApplyPolicyFunction.ApplyUser: instance.FinaliseApplyPolicyUserPart(); break; case ApplyPolicyFunction.Uninstall: instance.FinaliseUninstallProgramm(); break; } } catch (Exception ee) { Debug.WriteLine(ee.ToString()); FoxEventLog.WriteEventLog("SEH Error while finalising policy (applymethod=" + applymethod.ToString() + ") - Type 0x" + po.PolicyType.ToString("X"), System.Diagnostics.EventLogEntryType.Error); } } FilesystemData.UpdatePolicies = null; if (applymethod == ApplyPolicyFunction.ApplySystem) { string ApplyUserSettingsApp = ProgramAgent.AppPath + "FoxSDC_ApplyUserSettings.exe"; if (File.Exists(ApplyUserSettingsApp) == false) { FoxEventLog.WriteEventLog("The file " + ApplyUserSettingsApp + " does not exist. User settings are not applied properly.", EventLogEntryType.Error); } else { #if !DEBUG if (ProgramAgent.CPP.VerifyEXESignature(ApplyUserSettingsApp) == false) { FoxEventLog.WriteEventLog("The file " + ApplyUserSettingsApp + " cannot be verified. User settings are not applied properly.", EventLogEntryType.Error); } else #endif { try { Process.Start(ApplyUserSettingsApp, ""); //NT_AUTHORITY\SYSTEM } catch { } try { ProgramAgent.CPP.StartAppAsUser(ApplyUserSettingsApp, ""); //all other logged in users } catch { } } } } return(true); }
public static bool DoSyncAddRemovePrograms() { try { Network net; net = Utilities.ConnectNetwork(0); if (net == null) { return(false); } Status.UpdateMessage(0, "Collecting installed programs (HKLM)"); ListAddRemoveApps Finaldata = new ListAddRemoveApps(); Finaldata.Items = new List <AddRemoveApp>(); Finaldata.MachineID = SystemInfos.SysInfo.MachineID; Finaldata.SIDUsers = new List <string>(); ListAddRemoveApps data = CollectInfos(Registry.LocalMachine, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall", "SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall", ""); if (data == null) { return(false); } if (data.Items != null) { Finaldata.Items.AddRange(data.Items); } foreach (string kvp in Userregistries.GetLoadedUserRegistries()) { Status.UpdateMessage(0, "Collecting installed programs (" + kvp + ")"); Finaldata.SIDUsers.Add(kvp); data = CollectInfos(Registry.Users, kvp + "\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall", kvp + "\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall", kvp); if (data == null) { continue; } if (data.Items == null) { continue; } Finaldata.Items.AddRange(data.Items); } Status.UpdateMessage(0, "Reporting installed programs"); net.ReportAddRemovePrograms(Finaldata); net.CloseConnection(); } catch (Exception ee) { Debug.WriteLine(ee.ToString()); FoxEventLog.WriteEventLog("Servere error while syncing AddRemovePrograms: " + ee.ToString(), EventLogEntryType.Error); } Status.UpdateMessage(0); return(true); }
public static bool DoSyncEventLog() { try { Network net; net = Utilities.ConnectNetwork(0); if (net == null) { return(false); } net.CloseConnection(); Status.UpdateMessage(0, "Collecting EventLog data"); lst = new List <EventLogReport>(); HasEVTLogs = new HashSet <string>(); Status.UpdateMessage(0, "Collecting EventLog data (Application)"); if (CollectEVT("Application") == false) { return(false); } Status.UpdateMessage(0, "Collecting EventLog data (Security)"); if (CollectEVT("Security") == false) { return(false); } Status.UpdateMessage(0, "Collecting EventLog data (System)"); if (CollectEVT("System") == false) { return(false); } if (RegistryData.EnableAdditionalEventLogs == true) { string AdditionalBooks = RegistryData.AdditionalEventLogs; if (string.IsNullOrWhiteSpace(AdditionalBooks) == false) { foreach (string AdditionalBook in AdditionalBooks.Split('|')) { if (string.IsNullOrWhiteSpace(AdditionalBook) == true) { continue; } Status.UpdateMessage(0, "Collecting EventLog data (" + AdditionalBook + ")"); if (CollectEVT2(AdditionalBook) == false) { return(false); } } } } Status.UpdateMessage(0, "Collecting EventLog data (Processing ...)"); HashSet <string> RM = new HashSet <string>(); foreach (string evt in FilesystemData.SyncedEventLog) { if (HasEVTLogs.Contains(evt) == false) { RM.Add(evt); } } foreach (string evt in RM) { FilesystemData.SyncedEventLog.Remove(evt); } RM.Clear(); List <EventLogReport> REP = new List <EventLogReport>(); net = Utilities.ConnectNetwork(0); if (net == null) { return(false); } Status.UpdateMessage(0, "Collecting EventLog data (Sending data ...)"); Int64 UploadCounter = 0; foreach (EventLogReport evt in lst) { UploadCounter++; if (FilesystemData.SyncedEventLog.Contains(evt.LogID) == true) { continue; } REP.Add(evt); if (REP.Count > 99) { Status.UpdateMessage(0, "Collecting EventLog data (Sending data ... " + UploadCounter.ToString() + " of " + lst.Count.ToString() + ")"); if (net.ReportEventLogs(REP) == false) { net.CloseConnection(); Status.UpdateMessage(0); return(false); } foreach (EventLogReport rep in REP) { FilesystemData.SyncedEventLog.Add(rep.LogID); } FilesystemData.WriteEventLogList(); REP.Clear(); } } if (REP.Count > 0) { Status.UpdateMessage(0, "Collecting EventLog data (Sending data ...)"); if (net.ReportEventLogs(REP) == false) { net.CloseConnection(); Status.UpdateMessage(0); return(false); } foreach (EventLogReport rep in REP) { FilesystemData.SyncedEventLog.Add(rep.LogID); } FilesystemData.WriteEventLogList(); REP.Clear(); } lst.Clear(); HasEVTLogs.Clear(); net.CloseConnection(); } catch (Exception ee) { Debug.WriteLine(ee.ToString()); FoxEventLog.WriteEventLog("Servere error while syncing Event Log Data: " + ee.ToString(), EventLogEntryType.Error); } Status.UpdateMessage(0); return(true); }