public static void Stop() { try { if (SettingsManager.Firewall) { Firewall.Stop(); } if (SettingsManager.NIDS) { NetworkMonitor.Stop(); } if (SettingsManager.SystemMonitor) { FileSystemMonitor.Stop(); } if (SettingsManager.WebAgent) { WebMonitor.Stop(); } Protected = false; AntivirusState.SetProtection(false); } catch (Exception ex) { AntiCrash.LogException(ex); } finally { } }
public void TestFileMonitor() { var stack = new ConcurrentStack <FileMonitorObject>(); var monitor = new FileSystemMonitor(new MonitorCommandOptions() { MonitoredDirectories = Path.GetTempPath() }, x => stack.Push(x)); monitor.StartRun(); var created = Path.GetTempFileName(); // Create a file var renamed = $"{created}-renamed"; File.WriteAllText(created, "Test"); // Change the size File.Move(created, renamed); // Rename it File.Delete(renamed); //Delete it Thread.Sleep(100); monitor.StopRun(); Assert.IsTrue(stack.Any(x => x.NotifyFilters == NotifyFilters.FileName && x.Path == created)); Assert.IsTrue(stack.Any(x => x.NotifyFilters == NotifyFilters.Size && x.Path == created)); Assert.IsTrue(stack.Any(x => x.ChangeType == CHANGE_TYPE.RENAMED && x.NotifyFilters == NotifyFilters.FileName && x.Path == renamed)); Assert.IsTrue(stack.Any(x => x.ChangeType == CHANGE_TYPE.DELETED && x.Path == renamed)); }
public void CanBeStoppedEvenIfNotStarted() { monitor.Stop(); monitor = new FileSystemMonitor(_path); monitor.Stop(); Assert.IsTrue(true); }
public async Task StartWatcher(int watcherID) { bool isTripped = false; Watcher watcher = await this.watcherRepo.FirstOrDefaultAsync(a => a.ID == watcherID); SymbolicLink symbolicLink = await this.symbolicLinkRepo.FirstOrDefaultAsync(a => a.ID == watcher.SymbolicLinkID); System.Tuple <int, int> monitorKey = new System.Tuple <int, int>(watcher.SymbolicLinkID, watcher.ID); if (DirWatcherTransferApp.Monitors.ContainsKey(monitorKey)) { throw new System.Exception("Watcher already has monitor running. Please end the existing monitor before starting a new one."); } FileSystemMonitor fileSystemMonitor = new FileSystemMonitor(); // This actions gets fired when a file changes. fileSystemMonitor.CopyCompletedAction = async(notifyFilter, fileSystemEventArgs) => { // TODO: Implement a better way to check for visual studio temp files. This will fail if the actual file have a "~" in the name. if (!isTripped && fileSystemEventArgs.Name.Contains("~") && !fileSystemEventArgs.Name.EndsWith("~")) { isTripped = true; string fileName = fileSystemEventArgs.Name; string filePath = fileSystemEventArgs.FullPath; if (fileSystemEventArgs.Name.Contains("~") && !fileSystemEventArgs.Name.EndsWith("~")) { // Remove the vs caching name format. fileName = fileSystemEventArgs.Name.Remove(fileSystemEventArgs.Name.LastIndexOf("~")); filePath = fileSystemEventArgs.FullPath.Replace(fileSystemEventArgs.Name, fileName); } // Sync the changed file with the target file and update the SignalR clients of the copied file. CopyDiagnostics copyDiagnostics = await this.SyncLinkedFile(fileName, filePath); await this.fileSystemHubContext.Clients.All.SendAsync("onFileCopied", copyDiagnostics); await LogUtility.WriteToLog(notifyFilter, copyDiagnostics); // Update counts. if (notifyFilter != null) { await this.symbolicLinkRepo.IncrementCount(fileSystemEventArgs.FullPath.Replace(@"\" + fileSystemEventArgs.Name, string.Empty), (NotifyFilters)notifyFilter); await this.watcherRepo.IncrementCount(watcher, (NotifyFilters)notifyFilter); } isTripped = false; } }; fileSystemMonitor.StartWatcher(symbolicLink.Source, DirWatcherTransferApp.ProcessWatcherFiltersAsList(watcher)); DirWatcherTransferApp.Monitors.Add(monitorKey, fileSystemMonitor); }
public void SetUp() { _path = Path.GetFullPath(Guid.NewGuid().ToString()); Directory.CreateDirectory(_path); monitor = new FileSystemMonitor(_path); monitor.Start(); tester = new FileSystemMonitorTester(_path); sync = new Semaphore(0); msecs = 1000; aFile = "foo.txt"; }
public void SetUp () { _path = Path.GetFullPath(Guid.NewGuid().ToString()); Directory.CreateDirectory(_path); monitor = new FileSystemMonitor(_path); monitor.Start(); tester = new FileSystemMonitorTester(_path); sync = new Semaphore(0); msecs = 1000; aFile = "foo.txt"; }
/// <summary> /// Executes when a Start command is sent to this service. /// </summary> /// <param name="args">Data passed by the start command.</param> protected override void OnStart(string[] args) { // Initialize the event viewer stuff // Log = new EventLog(); if (!EventLog.SourceExists(QueryableStorageEventSource)) { EventLog.CreateEventSource( QueryableStorageEventSource, QueryableStorageEventLog ); } Log.Source = QueryableStorageEventSource; Log.Log = QueryableStorageEventLog; // Load configurations // WriteLogEntry( "Reading configuration file.", EventLogEntryType.Information ); Configuration = new ServiceConfiguration(); // Link up database // WriteLogEntry( "Trying connection to database.", EventLogEntryType.Information ); DatabaseConnection = DatabaseConnectionFactory.GetConnection( Configuration[ConfigurationKey.DatabaseConnectorName], Configuration[ConfigurationKey.DatabaseHostName], Convert.ToUInt16(Configuration[ConfigurationKey.DatabasePort]), Configuration[ConfigurationKey.DatabaseUsername], Configuration[ConfigurationKey.DatabasePassword] ); DatabaseConnection.OwnerService = this; // Set up the file system monitor // WriteLogEntry( "Spawning file system monitor.", EventLogEntryType.Information ); FileSystemMonitor = new FileSystemMonitor(DatabaseConnection); }
public void Test_FileSystem_1() { var t1path = Path.Combine(folder, "test.txt"); var t2path = Path.Combine(folder, "test2.txt"); File.Delete(t1path); File.Delete(t2path); var locker = new object(); var evs = new List <FileSystemEvent>(); Audit.Core.Configuration.Setup() .UseDynamicProvider(_ => _.OnInsert(ev => { lock (locker) { evs.Add((ev as FileSystem.AuditEventFileSystem).FileSystemEvent); } })); var fsMon = new FileSystemMonitor(folder); fsMon.Options.IncludeSubdirectories = true; fsMon.Options.IncludeContentPredicate = _ => ContentType.Text; fsMon.Start(); Thread.Sleep(500); File.WriteAllText(t1path, "this is a test"); Thread.Sleep(500); File.Move(t1path, t2path); Thread.Sleep(500); File.Delete(t2path); Thread.Sleep(500); var create = evs.Single(x => x.Event == FileSystemEventType.Create); Assert.IsTrue(evs.Count >= 3); Assert.AreEqual(FileSystemEventType.Create, create.Event); Assert.AreEqual("test.txt", create.Name); Assert.AreEqual(14, create.Length); Assert.AreEqual(ContentType.Text, create.FileContent.Type); Assert.AreEqual("this is a test", (create.FileContent as FileTextualContent).Value); Assert.IsNotNull(create.MD5); var rename = evs.Single(x => x.Event == FileSystemEventType.Rename); Assert.AreEqual("test.txt", rename.OldName); Assert.AreEqual("test2.txt", rename.Name); Assert.IsNotNull(rename.MD5); var delete = evs.Single(x => x.Event == FileSystemEventType.Delete); Assert.AreEqual("test2.txt", delete.Name); }
public void FileSystemWatcherConstructorInvalidPathTest() { ArgumentException expected = null; try { FileSystemMonitor target = new FileSystemMonitor("\\Path\\That\\Does\\Not\\Exist", "*.*"); } catch (ArgumentException ex) { expected = ex; } Assert.IsTrue(expected != null); }
public void EventsRelatedToFilesInDeployPathAreIgnored() { FieldInfo f = location.GetType().GetField("_fileSystemWatcher", BindingFlags.GetField | BindingFlags.Instance | BindingFlags.NonPublic); Assert.IsNotNull(f); //FileSystemWatcher watcher = (FileSystemWatcher) f.GetValue(location); FileSystemMonitor watcher = (FileSystemMonitor)f.GetValue(location); Assert.IsNotNull(watcher); Assert.AreEqual(NotifyFilters.DirectoryName | NotifyFilters.Attributes, watcher.NotifyFilter); Assert.AreEqual( Enum.Parse(typeof(NotifyFilters), 0.ToString()), watcher.NotifyFilter & NotifyFilters.FileName); }
public void FileSystemWatcherConstructorNullPath2() { ArgumentNullException expected = null; try { FileSystemMonitor target = new FileSystemMonitor(null, "*.*"); } catch (ArgumentNullException ex) { expected = ex; } Assert.IsTrue(expected != null); }
public void PathNullTest() { ArgumentNullException expected = null; FileSystemMonitor target = new FileSystemMonitor(); try { target.Path = null; } catch (ArgumentNullException ex) { expected = ex; } target.Dispose(); Assert.IsTrue(expected != null); }
public static ASA_ERROR RunGuiMonitorCommand(MonitorCommandOptions opts) { if (opts is null) { return(ASA_ERROR.NO_COLLECTORS); } if (opts.EnableFileSystemMonitor) { List <string> directories = new List <string>(); var parts = opts.MonitoredDirectories?.Split(',') ?? Array.Empty <string>(); foreach (string part in parts) { directories.Add(part); } foreach (string dir in directories) { try { FileSystemMonitor newMon = new FileSystemMonitor(opts.RunId ?? DateTime.Now.ToString("o", CultureInfo.InvariantCulture), dir, opts.InterrogateChanges); monitors.Add(newMon); } catch (ArgumentException) { Log.Warning("{1}: {0}", dir, Strings.Get("InvalidPath")); return(ASA_ERROR.INVALID_PATH); } } } if (monitors.Count == 0) { Log.Warning(Strings.Get("Err_NoMonitors")); } foreach (var c in monitors) { c.StartRun(); } return(ASA_ERROR.NONE); }
public static void InitMonitors() { try { if (SettingsManager.WebAgent) { WebMonitor.Initialize(); WebMonitor.Start(); } if (SettingsManager.Firewall) { Firewall.Init(); Firewall.AccessDenied += new DenyRule(Firewall_AccessDenied); Firewall.Start(); } if (SettingsManager.NIDS) { NetworkMonitor.Initialize(SettingsManager.BrekleyFilter); NetworkMonitor.Start(); } if (SettingsManager.SystemMonitor) { FileSystemMonitor.Initialize(SettingsManager.HighSense); FileSystemMonitor.Start(); } DriveDetector detect = new DriveDetector(); detect.DeviceArrived += new DriveDetectorEventHandler(detect_DeviceArrived); Protected = true; } catch (Exception ex) { AntiCrash.LogException(ex); } finally { } }
public void CanBeStoppedEvenIfNotStarted () { monitor.Stop(); monitor = new FileSystemMonitor(_path); monitor.Stop(); Assert.IsTrue(true); }
/// <summary> /// Internally creates and starts the monitor thread. /// </summary> /// <returns> /// True if the thread was successfully created. /// To ensure the monitor was successfully activated, handle the MonitorOpened event. /// </returns> /// <remarks></remarks> protected bool internalWatch() { int blen = 0; int bufflen = (int)_Buff.Size; var tbuff = _Buff.Handle; if (_thread is object) { return(false); } if (!internalOpenFile()) { return(false); } FILE_NOTIFY_INFORMATION fn; fn.ptr = _Buff; _thread = new System.Threading.Thread(() => { var notice = IntPtr.Zero; User32.PostMessage(Handle, FileSystemMonitor.WM_SIGNAL_OPEN, IntPtr.Zero, IntPtr.Zero); do { try { // let's clean up the memory before the next execute. if (blen > 0) { _Buff.ZeroMemory(0L, blen); blen = 0; } if (!FileSystemMonitor.ReadDirectoryChangesW(_hFile, tbuff, bufflen, true, _Filter, ref blen, IntPtr.Zero, IntPtr.Zero)) { notice = (IntPtr)User32.GetLastError(); break; } } catch (System.Threading.ThreadAbortException) { break; } catch (Exception) { notice = (IntPtr)1; break; } // block until the lock is acquired. Hopefully the // UI thread will not take that long to clean the list. System.Threading.Monitor.Enter(_WaitList); _WaitList.Add(FSMonitorEventArgs.FromPtr(fn, this)); // and we're done ... System.Threading.Monitor.Exit(_WaitList); // post to the UI thread that there are items to dequeue and continue! User32.PostMessage(Handle, FileSystemMonitor.WM_SIGNAL, IntPtr.Zero, IntPtr.Zero); }while (true); _thread = null; User32.PostMessage(Handle, FileSystemMonitor.WM_SIGNAL_CLOSE, IntPtr.Zero, IntPtr.Zero); }); _thread.SetApartmentState(System.Threading.ApartmentState.STA); _thread.IsBackground = true; _thread.Start(); return(true); }
private static int RunMonitorCommand(MonitorCommandOptions opts) { #if DEBUG Logger.Setup(true, opts.Verbose); #else Logger.Setup(opts.Debug, opts.Verbose); #endif AdminOrQuit(); SetupOrDie(opts.DatabaseFilename); AsaTelemetry.Setup(); Dictionary <string, string> StartEvent = new Dictionary <string, string>(); StartEvent.Add("Files", opts.EnableFileSystemMonitor.ToString(CultureInfo.InvariantCulture)); StartEvent.Add("Admin", AsaHelpers.IsAdmin().ToString(CultureInfo.InvariantCulture)); AsaTelemetry.TrackEvent("Begin monitoring", StartEvent); CheckFirstRun(); if (opts.RunId is string) { opts.RunId = opts.RunId.Trim(); } else { opts.RunId = DateTime.Now.ToString("o", CultureInfo.InvariantCulture); } if (opts.Overwrite) { DatabaseManager.DeleteRun(opts.RunId); } else { if (DatabaseManager.GetRun(opts.RunId) != null) { Log.Error(Strings.Get("Err_RunIdAlreadyUsed")); return((int)ASA_ERROR.UNIQUE_ID); } } var run = new AsaRun(RunId: opts.RunId, Timestamp: DateTime.Now, Version: AsaHelpers.GetVersionString(), Platform: AsaHelpers.GetPlatform(), new List <RESULT_TYPE>() { RESULT_TYPE.FILEMONITOR }, RUN_TYPE.MONITOR); DatabaseManager.InsertRun(run); int returnValue = 0; if (opts.EnableFileSystemMonitor) { List <String> directories = new List <string>(); if (opts.MonitoredDirectories != null) { var parts = opts.MonitoredDirectories.Split(','); foreach (String part in parts) { directories.Add(part); } } else { if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { directories.Add("/"); } if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { directories.Add("C:\\"); } if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { directories.Add("/"); } } List <NotifyFilters> filterOptions = new List <NotifyFilters> { NotifyFilters.Attributes, NotifyFilters.CreationTime, NotifyFilters.DirectoryName, NotifyFilters.FileName, NotifyFilters.LastAccess, NotifyFilters.LastWrite, NotifyFilters.Security, NotifyFilters.Size }; foreach (String dir in directories) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { var newMon = new FileSystemMonitor(opts.RunId, dir, false); monitors.Add(newMon); } else { foreach (NotifyFilters filter in filterOptions) { Log.Information("Adding Path {0} Filter Type {1}", dir, filter.ToString()); var newMon = new FileSystemMonitor(opts.RunId, dir, false, filter); monitors.Add(newMon); } } } } //if (opts.EnableRegistryMonitor) //{ //var monitor = new RegistryMonitor(); //monitors.Add(monitor); //} if (monitors.Count == 0) { Log.Warning(Strings.Get("Err_NoMonitors")); returnValue = (int)ASA_ERROR.NO_COLLECTORS; } using var exitEvent = new ManualResetEvent(false); // If duration is set, we use the secondary timer. if (opts.Duration > 0) { Log.Information("{0} {1} {2}.", Strings.Get("MonitorStartedFor"), opts.Duration, Strings.Get("Minutes")); using var aTimer = new System.Timers.Timer { Interval = opts.Duration * 60 * 1000, //lgtm [cs/loss-of-precision] AutoReset = false, }; aTimer.Elapsed += (source, e) => { exitEvent.Set(); }; // Start the timer aTimer.Enabled = true; } foreach (FileSystemMonitor c in monitors) { Log.Information(Strings.Get("Begin"), c.GetType().Name); try { c.StartRun(); } catch (Exception ex) { Log.Error(Strings.Get("Err_CollectingFrom"), c.GetType().Name, ex.Message, ex.StackTrace); returnValue = 1; } } // Set up the event to capture CTRL+C Console.CancelKeyPress += (sender, eventArgs) => { eventArgs.Cancel = true; exitEvent.Set(); }; Console.Write(Strings.Get("MonitoringPressC")); // Write a spinner and wait until CTRL+C WriteSpinner(exitEvent); Log.Information(""); foreach (var c in monitors) { Log.Information(Strings.Get("End"), c.GetType().Name); try { c.StopRun(); if (c is FileSystemMonitor) { ((FileSystemMonitor)c).Dispose(); } } catch (Exception ex) { Log.Error(ex, " {0}: {1}", c.GetType().Name, ex.Message, Strings.Get("Err_Stopping")); } } DatabaseManager.Commit(); return(returnValue); }