コード例 #1
0
        public ActionResult StartMonitoring(string RunId, string Directory)
        {
            if (RunId != null)
            {
                if (DatabaseManager.GetRun(RunId) != null)
                {
                    return(Json(GUI_ERROR.UNIQUE_ID));
                }

                DatabaseManager.InsertRun(RunId, new Dictionary <RESULT_TYPE, bool>()
                {
                    { RESULT_TYPE.FILEMONITOR, true }
                });

                MonitorCommandOptions opts = new MonitorCommandOptions
                {
                    RunId = RunId,
                    EnableFileSystemMonitor = true,
                    MonitoredDirectories    = Directory,
                    FilterLocation          = "filters.json"
                };
                AttackSurfaceAnalyzerClient.ClearMonitors();
                return(Json((int)AttackSurfaceAnalyzerClient.RunGuiMonitorCommand(opts)));
            }
            return(Json(-1));
        }
コード例 #2
0
        public FileSystemMonitor(MonitorCommandOptions opts, Action <FileMonitorObject> changeHandler)
        {
            options            = opts ?? new MonitorCommandOptions();
            this.changeHandler = changeHandler ?? throw new NullReferenceException(nameof(changeHandler));

            fsc = new FileSystemCollector(new CollectorOptions()
            {
                DownloadCloud = false,
                GatherHashes  = options.GatherHashes,
            });

            foreach (var dir in options?.MonitoredDirectories.Any() is true ? options.MonitoredDirectories : fsc.Roots.ToList())
            {
                foreach (var filter in defaultFiltersList)
                {
                    var watcher = new FileSystemWatcher();

                    watcher.Path = dir;

                    watcher.NotifyFilter = filter;

                    watcher.IncludeSubdirectories = true;

                    // Changed, Created and Deleted can share a handler, because they throw the same type of event
                    watcher.Changed += GetFunctionForFilterType(filter);
                    watcher.Created += GetFunctionForFilterType(filter);
                    watcher.Deleted += GetFunctionForFilterType(filter);

                    // Renamed needs a different handler because it throws a different kind of event
                    watcher.Renamed += GetRenamedFunctionForFilterType(filter);

                    watchers.Add(watcher);
                }
            }
        }
コード例 #3
0
        public ActionResult StartMonitoring(string RunId, string Directory)
        {
            if (RunId != null)
            {
                if (DatabaseManager.GetRun(RunId) != null)
                {
                    return(Json(ASA_ERROR.UNIQUE_ID));
                }

                var run = new AsaRun(RunId: RunId, Timestamp: DateTime.Now, Version: AsaHelpers.GetVersionString(), Platform: AsaHelpers.GetPlatform(), new List <RESULT_TYPE>()
                {
                    RESULT_TYPE.FILEMONITOR
                }, RUN_TYPE.MONITOR);
                DatabaseManager.InsertRun(run);

                MonitorCommandOptions opts = new MonitorCommandOptions
                {
                    RunId = RunId,
                    EnableFileSystemMonitor = true,
                    MonitoredDirectories    = Directory,
                    Verbose = Logger.Verbose,
                    Debug   = Logger.Debug,
                    Quiet   = Logger.Quiet
                };
                AttackSurfaceAnalyzerClient.ClearMonitors();
                return(Json((int)AttackSurfaceAnalyzerClient.RunGuiMonitorCommand(opts)));
            }
            return(Json(-1));
        }
コード例 #4
0
        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);
        }
コード例 #5
0
        public ActionResult StartMonitoring(string RunId, string Directory, string Extension)
        {
            if (RunId != null)
            {
                using (var cmd = new SqliteCommand(INSERT_RUN, DatabaseManager.Connection, DatabaseManager.Transaction))
                {
                    cmd.Parameters.AddWithValue("@run_id", RunId.Trim());
                    cmd.Parameters.AddWithValue("@file_system", true);
                    cmd.Parameters.AddWithValue("@ports", false);
                    cmd.Parameters.AddWithValue("@users", false);
                    cmd.Parameters.AddWithValue("@services", false);
                    cmd.Parameters.AddWithValue("@registry", false);
                    cmd.Parameters.AddWithValue("@certificates", false);
                    cmd.Parameters.AddWithValue("@firewall", false);
                    cmd.Parameters.AddWithValue("@comobjects", false);
                    cmd.Parameters.AddWithValue("@type", "monitor");
                    cmd.Parameters.AddWithValue("@timestamp", DateTime.Now.ToString("o", CultureInfo.InvariantCulture));
                    cmd.Parameters.AddWithValue("@version", AsaHelpers.GetVersionString());
                    cmd.Parameters.AddWithValue("@platform", AsaHelpers.GetPlatformString());
                    try
                    {
                        cmd.ExecuteNonQuery();
                        DatabaseManager.Commit();
                    }
                    catch (SqliteException e)
                    {
                        Log.Warning(e.StackTrace);
                        Log.Warning(e.Message);
                        return(Json((int)GUI_ERROR.UNIQUE_ID));
                    }
                }

                MonitorCommandOptions opts = new MonitorCommandOptions
                {
                    RunId = RunId,
                    EnableFileSystemMonitor = true,
                    MonitoredDirectories    = Directory,
                    FilterLocation          = "filters.json"
                };
                AttackSurfaceAnalyzerClient.ClearMonitors();
                return(Json((int)AttackSurfaceAnalyzerClient.RunGuiMonitorCommand(opts)));
            }
            return(Json(-1));
        }
コード例 #6
0
        public ActionResult StartMonitoring(string RunId, string Directory, string Extension)
        {
            using (var cmd = new SqliteCommand(INSERT_RUN, DatabaseManager.Connection, DatabaseManager.Transaction))
            {
                cmd.Parameters.AddWithValue("@run_id", RunId.Trim());
                cmd.Parameters.AddWithValue("@file_system", true);
                cmd.Parameters.AddWithValue("@ports", false);
                cmd.Parameters.AddWithValue("@users", false);
                cmd.Parameters.AddWithValue("@services", false);
                cmd.Parameters.AddWithValue("@registry", false);
                cmd.Parameters.AddWithValue("@certificates", false);
                cmd.Parameters.AddWithValue("@type", "monitor");
                cmd.Parameters.AddWithValue("@timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                cmd.Parameters.AddWithValue("@version", Helpers.GetVersionString());
                try
                {
                    cmd.ExecuteNonQuery();
                    DatabaseManager.Commit();
                }
                catch (Exception e)
                {
                    Log.Warning(e.StackTrace);
                    Log.Warning(e.Message);
                    return(Json((int)ERRORS.UNIQUE_ID));
                }
            }

            MonitorCommandOptions opts = new MonitorCommandOptions
            {
                RunId = RunId,
                EnableFileSystemMonitor = true,
                MonitoredDirectories    = Directory,
                FilterLocation          = "filters.json"
            };

            AttackSurfaceAnalyzerCLI.ClearMonitors();
            return(Json((int)AttackSurfaceAnalyzerCLI.RunGuiMonitorCommand(opts)));
        }
コード例 #7
0
        public FileSystemMonitor(MonitorCommandOptions opts, Action <FileMonitorObject> changeHandler)
        {
            options = opts ?? new MonitorCommandOptions();
#pragma warning disable CA1303 // Do not pass literals as localized parameters
            this.changeHandler = changeHandler ?? throw new NullReferenceException(nameof(changeHandler));
#pragma warning restore CA1303 // This string doesn't need to be localized, it is the name of the variable

            fsc = new FileSystemCollector(new CollectorOptions()
            {
                DownloadCloud = false,
                GatherHashes  = options.GatherHashes,
            });

            foreach (var dir in options?.MonitoredDirectories?.Any() is true ? options.MonitoredDirectories : fsc.Roots.ToArray())
            {
                foreach (var filter in defaultFiltersList)
                {
                    var watcher = new FileSystemWatcher();

                    watcher.Path = dir;

                    watcher.NotifyFilter = filter;

                    watcher.IncludeSubdirectories = true;

                    // Changed, Created and Deleted can share a handler, because they throw the same
                    // type of event
                    watcher.Changed += GetFunctionForFilterType(filter);
                    watcher.Created += GetFunctionForFilterType(filter);
                    watcher.Deleted += GetFunctionForFilterType(filter);

                    // Renamed needs a different handler because it throws a different kind of event
                    watcher.Renamed += GetRenamedFunctionForFilterType(filter);

                    watchers.Add(watcher);
                }
            }
        }
コード例 #8
0
        public static ASA_ERROR RunGuiMonitorCommand(MonitorCommandOptions opts)
        {
            if (opts is null)
            {
                return(ASA_ERROR.NO_COLLECTORS);
            }
            if (opts.EnableFileSystemMonitor)
            {
                monitors.Add(new FileSystemMonitor(opts, x => DatabaseManager.Write(x, opts.RunId)));
            }

            if (monitors.Count == 0)
            {
                Log.Warning(Strings.Get("Err_NoMonitors"));
            }

            foreach (var c in monitors)
            {
                c.StartRun();
            }

            return(ASA_ERROR.NONE);
        }
コード例 #9
0
        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);
        }