From 1efd3ab0e03d5017596c10a1ab29b82514cba7d3 Mon Sep 17 00:00:00 2001 From: Gabe Stocco Date: Thu, 4 Apr 2019 13:43:29 -0700 Subject: [PATCH] Switched logging to serilog. Now actually works. (#63) --- AttackSurfaceAnalyzer.sln | 6 +- Cli/AttackSurfaceAnalyzerCli.csproj | 8 +- Cli/Program.cs | 114 +++++++++--------- Gui/AttackSurfaceAnalyzerGui.csproj | 1 + Gui/Controllers/HomeController.cs | 5 +- Lib/AttackSurfaceAnalyzerLib.csproj | 5 +- Lib/Collectors/BaseCollector.cs | 1 + Lib/Collectors/BaseCompare.cs | 5 +- Lib/Collectors/BaseMonitor.cs | 1 + .../Certificates/CertificateCollector.cs | 11 +- .../Certificates/CertificateCompare.cs | 5 +- .../FileSystem/FileSystemCollector.cs | 33 ++--- .../FileSystem/FileSystemCompare.cs | 3 +- .../FileSystem/FileSystemMonitor.cs | 1 + Lib/Collectors/FileSystem/FileSystemUtils.cs | 7 +- .../FileSystem/LinuxFileSystemUtils.cs | 5 +- .../FileSystem/WindowsFileSystemUtils.cs | 9 +- Lib/Collectors/OpenPorts/OpenPortCollector.cs | 21 ++-- Lib/Collectors/OpenPorts/OpenPortCompare.cs | 2 +- Lib/Collectors/Registry/RegistryCollector.cs | 23 ++-- Lib/Collectors/Registry/RegistryCompare.cs | 9 +- Lib/Collectors/Registry/RegistryMonitor.cs | 3 +- Lib/Collectors/Service/ServiceCollector.cs | 5 +- Lib/Collectors/Service/ServiceCompare.cs | 1 + .../UserAccount/UserAccountCollector.cs | 17 +-- .../UserAccount/UserAccountCompare.cs | 7 +- Lib/Objects/CertificateObject.cs | 1 + Lib/Objects/FileSystemObject.cs | 5 +- Lib/Objects/OpenPortObject.cs | 3 +- Lib/Objects/RegistryObject.cs | 5 +- Lib/Objects/ResultObjects.cs | 1 + Lib/Objects/ServiceObject.cs | 1 + Lib/Objects/UserAccountObject.cs | 1 + Lib/Utils/DataWriter.cs | 3 +- Lib/Utils/DatabaseManager.cs | 11 +- Lib/Utils/DirectoryWalker.cs | 17 +-- Lib/Utils/Elevation.cs | 3 +- Lib/Utils/FileWatcher.cs | 6 +- Lib/Utils/Filter.cs | 21 ++-- Lib/Utils/Logger.cs | 62 +++------- Lib/Utils/RegistryWalker.cs | 9 +- Lib/Utils/Win32OpenPortListenerHelper.cs | 13 +- 42 files changed, 243 insertions(+), 227 deletions(-) diff --git a/AttackSurfaceAnalyzer.sln b/AttackSurfaceAnalyzer.sln index aae8278e2..f082ae241 100644 --- a/AttackSurfaceAnalyzer.sln +++ b/AttackSurfaceAnalyzer.sln @@ -12,14 +12,12 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution ProjectSection(SolutionItems) = preProject BUILD.md = BUILD.md CONTRIBUTING.md = CONTRIBUTING.md + filters.json = filters.json global.json = global.json + LICENSE = LICENSE PRIVACY.md = PRIVACY.md README.md = README.md version.json = version.json - filters.json = filters.json - LICENSE.txt = LICENSE.txt - nlog.config = nlog.config - NOTICE.txt = NOTICE.txt EndProjectSection EndProject Global diff --git a/Cli/AttackSurfaceAnalyzerCli.csproj b/Cli/AttackSurfaceAnalyzerCli.csproj index bb97e5b76..2abb2650d 100644 --- a/Cli/AttackSurfaceAnalyzerCli.csproj +++ b/Cli/AttackSurfaceAnalyzerCli.csproj @@ -17,16 +17,20 @@ + + - + - + + PreserveNewest + LICENSE.txt PreserveNewest diff --git a/Cli/Program.cs b/Cli/Program.cs index 7777a98bb..794ffa3ad 100644 --- a/Cli/Program.cs +++ b/Cli/Program.cs @@ -20,6 +20,9 @@ using System.Reflection; using System.Diagnostics; using Microsoft.ApplicationInsights.Extensibility; +using System.Threading.Tasks; +using Serilog; + namespace AttackSurfaceAnalyzer.Cli { @@ -197,8 +200,8 @@ static void Main(string[] args) .GetEntryAssembly() .GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false) as AssemblyInformationalVersionAttribute[])[0].InformationalVersion; - Logger.Instance.Info("AttackSurfaceAnalyzerCli v." + version); - Logger.Instance.Debug(version); + Log.Information("AttackSurfaceAnalyzerCli v." + version); + Log.Debug(version); var argsResult = Parser.Default.ParseArguments(args) .MapResult( @@ -211,7 +214,7 @@ static void Main(string[] args) errs => 1 ); - Logger.Instance.Info("Attack Surface Analyzer Complete."); + Log.Information("Attack Surface Analyzer Complete."); } private static int SetupConfig(ConfigCommandOptions opts) @@ -222,14 +225,14 @@ private static int SetupConfig(ConfigCommandOptions opts) { DatabaseManager.CloseDatabase(); File.Delete(opts.DatabaseFilename); - Logger.Instance.Info("Deleted Database"); + Log.Information("Deleted Database"); } else { if (opts.ListRuns) { - Logger.Instance.Info("Begin Collect Run Ids"); + Log.Information("Begin Collect Run Ids"); List CollectRuns = GetRuns("collect"); foreach (string run in CollectRuns) { @@ -245,7 +248,7 @@ private static int SetupConfig(ConfigCommandOptions opts) reader["version"].ToString(), reader["type"].ToString(), reader["run_id"].ToString()); - Logger.Instance.Info(output); + Log.Information(output); output = String.Format("{0} {1} {2} {3} {4} {5}", (int.Parse(reader["file_system"].ToString()) != 0) ? "FILES" : "", (int.Parse(reader["ports"].ToString()) != 0) ? "PORTS" : "", @@ -253,13 +256,13 @@ private static int SetupConfig(ConfigCommandOptions opts) (int.Parse(reader["services"].ToString()) != 0) ? "SERVICES" : "", (int.Parse(reader["certificates"].ToString()) != 0) ? "CERTIFICATES" : "", (int.Parse(reader["registry"].ToString()) != 0) ? "REGISTRY" : ""); - Logger.Instance.Info(output); + Log.Information(output); } } } } - Logger.Instance.Info("Begin monitor Run Ids"); + Log.Information("Begin monitor Run Ids"); List MonitorRuns = GetRuns("monitor"); foreach (string monitorRun in MonitorRuns) { @@ -275,7 +278,7 @@ private static int SetupConfig(ConfigCommandOptions opts) reader["version"].ToString(), reader["type"].ToString(), reader["run_id"].ToString()); - Logger.Instance.Info(output); + Log.Information(output); output = String.Format("{0} {1} {2} {3} {4} {5}", (int.Parse(reader["file_system"].ToString()) != 0) ? "FILES" : "", (int.Parse(reader["ports"].ToString()) != 0) ? "PORTS" : "", @@ -283,7 +286,7 @@ private static int SetupConfig(ConfigCommandOptions opts) (int.Parse(reader["services"].ToString()) != 0) ? "SERVICES" : "", (int.Parse(reader["certificates"].ToString()) != 0) ? "CERTIFICATES" : "", (int.Parse(reader["registry"].ToString()) != 0) ? "REGISTRY" : ""); - Logger.Instance.Info(output); + Log.Information(output); } } @@ -294,7 +297,7 @@ private static int SetupConfig(ConfigCommandOptions opts) if (opts.TelemetryOptOut != null) { Telemetry.SetOptOut(bool.Parse(opts.TelemetryOptOut)); - Logger.Instance.Info("Your current telemetry opt out setting is {0}.", (bool.Parse(opts.TelemetryOptOut)) ? "Opted out" : "Opted in"); + Log.Information("Your current telemetry opt out setting is {0}.", (bool.Parse(opts.TelemetryOptOut)) ? "Opted out" : "Opted in"); } if (opts.DeleteRunId != null) { @@ -314,7 +317,7 @@ private static int RunExportCollectCommand(ExportCollectCommandOptions opts) #else Logger.Setup(false, opts.Verbose); #endif - Logger.Instance.Debug("Entering RunExportCollectCommand"); + Log.Debug("Entering RunExportCollectCommand"); DatabaseManager.SqliteFilename = opts.DatabaseFilename; Telemetry.Setup(); @@ -323,7 +326,7 @@ private static int RunExportCollectCommand(ExportCollectCommandOptions opts) StartEvent.Add("OutputPathSet", (opts.OutputPath != null).ToString()); Telemetry.Client.TrackEvent("Begin Export Compare", StartEvent); - Logger.Instance.Debug("Halfway RunExportCollectCommand"); + Log.Debug("Halfway RunExportCollectCommand"); CompareCommandOptions options = new CompareCommandOptions(); options.DatabaseFilename = opts.DatabaseFilename; @@ -337,7 +340,7 @@ private static int RunExportCollectCommand(ExportCollectCommandOptions opts) NullValueHandling = NullValueHandling.Ignore }; serializer.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter()); - Logger.Instance.Debug("Done comparing RunExportCollectCommand"); + Log.Debug("Done comparing RunExportCollectCommand"); using (StreamWriter sw = new StreamWriter(Path.Combine(opts.OutputPath, Helpers.MakeValidFileName(opts.FirstRunId + "_vs_" + opts.SecondRunId + "_summary.json.txt")))) //lgtm[cs/path-injection] { @@ -346,7 +349,7 @@ private static int RunExportCollectCommand(ExportCollectCommandOptions opts) serializer.Serialize(writer, results); } } - Logger.Instance.Info("Done writing"); + Log.Information("Done writing"); return 0; } @@ -356,7 +359,7 @@ public static void WriteScanJson(int ResultType, string BaseId, string CompareId string GET_COMPARISON_RESULTS = "select * from compared where base_run_id=@base_run_id and compare_run_id=@compare_run_id and data_type=@data_type order by base_row_key;"; string GET_SERIALIZED_RESULTS = "select serialized from @table_name where row_key = @row_key and run_id = @run_id"; - Logger.Instance.Debug("Starting WriteScanJson"); + Log.Debug("Starting WriteScanJson"); List ToExport = new List { (RESULT_TYPE)ResultType }; Dictionary actualExported = new Dictionary(); @@ -586,7 +589,7 @@ private static int RunMonitorCommand(MonitorCommandOptions opts) { while (reader.Read()) { - Logger.Instance.Error("That runid was already used. Must use a unique runid for each run. Use --overwrite to discard previous run information."); + Log.Error("That runid was already used. Must use a unique runid for each run. Use --overwrite to discard previous run information."); return (int)ERRORS.UNIQUE_ID; } } @@ -613,8 +616,8 @@ private static int RunMonitorCommand(MonitorCommandOptions opts) } catch (Exception e) { - Logger.Instance.Warn(e.StackTrace); - Logger.Instance.Warn(e.Message); + Log.Warning(e.StackTrace); + Log.Warning(e.Message); } int returnValue = 0; @@ -669,7 +672,7 @@ private static int RunMonitorCommand(MonitorCommandOptions opts) if (monitors.Count == 0) { - Logger.Instance.Warn("No monitors have been defined."); + Log.Warning("No monitors have been defined."); returnValue = 1; } @@ -678,7 +681,7 @@ private static int RunMonitorCommand(MonitorCommandOptions opts) // If duration is set, we use the secondary timer. if (opts.Duration > 0) { - Logger.Instance.Info("Monitor started for " + opts.Duration + " minute(s)."); + Log.Information("Monitor started for " + opts.Duration + " minute(s)."); var aTimer = new System.Timers.Timer { Interval = opts.Duration * 60 * 1000, @@ -692,7 +695,7 @@ private static int RunMonitorCommand(MonitorCommandOptions opts) foreach (var c in monitors) { - Logger.Instance.Info("Executing: {0}", c.GetType().Name); + Log.Information("Executing: {0}", c.GetType().Name); try { @@ -700,7 +703,7 @@ private static int RunMonitorCommand(MonitorCommandOptions opts) } catch (Exception ex) { - Logger.Instance.Error(ex, "Error collecting from {0}: {1} {2}", c.GetType().Name, ex.Message, ex.StackTrace); + Log.Error(ex, "Error collecting from {0}: {1} {2}", c.GetType().Name, ex.Message, ex.StackTrace); returnValue = 1; } } @@ -715,11 +718,11 @@ private static int RunMonitorCommand(MonitorCommandOptions opts) // Write a spinner and wait until CTRL+C WriteSpinner(exitEvent); - Logger.Instance.Info(""); + Log.Information(""); foreach (var c in monitors) { - Logger.Instance.Info("Stopping: {0}", c.GetType().Name); + Log.Information("Stopping: {0}", c.GetType().Name); try { @@ -727,7 +730,7 @@ private static int RunMonitorCommand(MonitorCommandOptions opts) } catch (Exception ex) { - Logger.Instance.Error(ex, "Error stopping {0}: {1}", c.GetType().Name, ex.Message); + Log.Error(ex, "Error stopping {0}: {1}", c.GetType().Name, ex.Message); returnValue = 1; } } @@ -804,7 +807,7 @@ public static Dictionary CompareRuns(CompareCommandOptions opts) comparators = new List(); var cmd = new SqliteCommand(SQL_GET_RESULT_TYPES, DatabaseManager.Connection, DatabaseManager.Transaction); - Logger.Instance.Debug("Getting result types"); + Log.Debug("Getting result types"); cmd.Parameters.AddWithValue("@base_run_id", opts.FirstRunId); cmd.Parameters.AddWithValue("@compare_run_id", opts.SecondRunId); @@ -879,23 +882,18 @@ public static Dictionary CompareRuns(CompareCommandOptions opts) } } } - Logger.Instance.Debug("Inserting run into results table as running"); - - cmd = new SqliteCommand(INSERT_RUN_INTO_RESULT_TABLE_SQL, DatabaseManager.Connection, DatabaseManager.Transaction); - cmd.Parameters.AddWithValue("@base_run_id", opts.FirstRunId); - cmd.Parameters.AddWithValue("@compare_run_id", opts.SecondRunId); - cmd.Parameters.AddWithValue("@status", RUN_STATUS.RUNNING); - cmd.ExecuteNonQuery(); - foreach (var c in comparators) + // Logging stops at this loop + Parallel.ForEach(comparators, + (c => { - Logger.Instance.Info("Starting {0}", c.GetType()); + Log.Information("Starting {0}", c.GetType()); if (!c.TryCompare(opts.FirstRunId, opts.SecondRunId)) { - Logger.Instance.Warn("Error when comparing {0}", c.GetType().FullName); + Log.Warning("Error when comparing {0}", c.GetType().FullName); } c.Results.ToList().ForEach(x => results.Add(x.Key, x.Value)); - } + })); cmd = new SqliteCommand(UPDATE_RUN_IN_RESULT_TABLE, DatabaseManager.Connection, DatabaseManager.Transaction); cmd.Parameters.AddWithValue("@base_run_id", opts.FirstRunId); cmd.Parameters.AddWithValue("@compare_run_id", opts.SecondRunId); @@ -927,7 +925,7 @@ public static int RunGuiMonitorCommand(MonitorCommandOptions opts) if (monitors.Count == 0) { - Logger.Instance.Warn("No monitors have been defined."); + Log.Warning("No monitors have been defined."); } foreach (var c in monitors) @@ -938,7 +936,7 @@ public static int RunGuiMonitorCommand(MonitorCommandOptions opts) } catch (Exception ex) { - Logger.Instance.Error(ex, "Error collecting from {0}: {1} {2}", c.GetType().Name, ex.Message, ex.StackTrace); + Log.Error(ex, "Error collecting from {0}: {1} {2}", c.GetType().Name, ex.Message, ex.StackTrace); } } @@ -949,7 +947,7 @@ public static int StopMonitors() { foreach (var c in monitors) { - Logger.Instance.Info("Stopping: {0}", c.GetType().Name); + Log.Information("Stopping: {0}", c.GetType().Name); try { @@ -957,7 +955,7 @@ public static int StopMonitors() } catch (Exception ex) { - Logger.Instance.Error(ex, "Error stopping {0}: {1}", c.GetType().Name, ex.Message); + Log.Error(ex, "Error stopping {0}: {1}", c.GetType().Name, ex.Message); } } @@ -971,7 +969,7 @@ public static void AdminOrQuit() { if (!Elevation.IsAdministrator()) { - Logger.Instance.Warn("Attack Surface Enumerator must be run as Administrator."); + Log.Warning("Attack Surface Enumerator must be run as Administrator."); Environment.Exit(1); } } @@ -979,7 +977,7 @@ public static void AdminOrQuit() { if (!Elevation.IsRunningAsRoot()) { - Logger.Instance.Fatal("Attack Surface Enumerator must be run as root."); + Log.Fatal("Attack Surface Enumerator must be run as root."); Environment.Exit(1); } } @@ -987,7 +985,7 @@ public static void AdminOrQuit() { if (!Elevation.IsRunningAsRoot()) { - Logger.Instance.Fatal("Attack Surface Enumerator must be run as root."); + Log.Fatal("Attack Surface Enumerator must be run as root."); Environment.Exit(1); } } @@ -995,7 +993,7 @@ public static void AdminOrQuit() public static int SetupTelemetryAndRunCollectCommand(CollectCommandOptions opts) { - Logger.Instance.Debug("Before telemetry"); + Log.Debug("Before telemetry"); try { Telemetry.Setup(); @@ -1013,10 +1011,10 @@ public static int SetupTelemetryAndRunCollectCommand(CollectCommandOptions opts) } catch (Exception e) { - Logger.Instance.Debug(e.GetType()); - Logger.Instance.Debug(e.Message); + Log.Debug(e.GetType().ToString()); + Log.Debug(e.Message); } - Logger.Instance.Debug("After telemetry"); + Log.Debug("After telemetry"); return RunCollectCommand(opts); } @@ -1057,7 +1055,7 @@ public static int RunCollectCommand(CollectCommandOptions opts) if (collectors.Count == 0) { - Logger.Instance.Warn("No collectors have been defined."); + Log.Warning("No collectors have been defined."); return -1; } @@ -1078,7 +1076,7 @@ public static int RunCollectCommand(CollectCommandOptions opts) { while (reader.Read()) { - Logger.Instance.Error("That runid was already used. Must use a unique runid for each run. Use --overwrite to discard previous run information."); + Log.Error("That runid was already used. Must use a unique runid for each run. Use --overwrite to discard previous run information."); return (int)ERRORS.UNIQUE_ID; } } @@ -1139,8 +1137,8 @@ public static int RunCollectCommand(CollectCommandOptions opts) } catch (Exception e) { - Logger.Instance.Warn(e.StackTrace); - Logger.Instance.Warn(e.Message); + Log.Warning(e.StackTrace); + Log.Warning(e.Message); returnValue = (int)ERRORS.UNIQUE_ID; } } @@ -1148,19 +1146,19 @@ public static int RunCollectCommand(CollectCommandOptions opts) foreach (BaseCollector c in collectors) { // c.Filters = read filters in here - Logger.Instance.Info("Executing: {0}", c.GetType().Name); + Log.Information("Executing: {0}", c.GetType().Name); try { c.Execute(); } catch (Exception ex) { - Logger.Instance.Error(ex, "Error collecting from {0}: {1} {2}", c.GetType().Name, ex.Message, ex.StackTrace); + Log.Error(ex, "Error collecting from {0}: {1} {2}", c.GetType().Name, ex.Message, ex.StackTrace); returnValue = 1; } - Logger.Instance.Info("Completed: {0}", c.GetType().Name); + Log.Information("Completed: {0}", c.GetType().Name); } - Logger.Instance.Info("Started {0} collectors", collectors.Count.ToString()); + Log.Information("Started {0} collectors", collectors.Count.ToString()); DatabaseManager.Commit(); return returnValue; @@ -1213,7 +1211,7 @@ private static int RunCompareCommand(CompareCommandOptions opts) #endif DatabaseManager.SqliteFilename = opts.DatabaseFilename; - Logger.Instance.Debug("Starting CompareRuns"); + Log.Debug("Starting CompareRuns"); var results = CompareRuns(opts); var engine = new RazorLightEngineBuilder() diff --git a/Gui/AttackSurfaceAnalyzerGui.csproj b/Gui/AttackSurfaceAnalyzerGui.csproj index 1c3fc03d0..2bde0684b 100644 --- a/Gui/AttackSurfaceAnalyzerGui.csproj +++ b/Gui/AttackSurfaceAnalyzerGui.csproj @@ -22,6 +22,7 @@ + diff --git a/Gui/Controllers/HomeController.cs b/Gui/Controllers/HomeController.cs index 4bd6ca629..2b1bd5d4c 100644 --- a/Gui/Controllers/HomeController.cs +++ b/Gui/Controllers/HomeController.cs @@ -17,6 +17,7 @@ using Microsoft.ApplicationInsights.Extensibility; using System.Runtime.InteropServices; using Microsoft.ApplicationInsights; +using Serilog; namespace AttackSurfaceAnalyzer.Gui.Controllers { @@ -421,8 +422,8 @@ public ActionResult StartMonitoring(string RunId, string Directory, string Exten } catch (Exception e) { - Logger.Instance.Warn(e.StackTrace); - Logger.Instance.Warn(e.Message); + Log.Warning(e.StackTrace); + Log.Warning(e.Message); return Json((int)ERRORS.UNIQUE_ID); } } diff --git a/Lib/AttackSurfaceAnalyzerLib.csproj b/Lib/AttackSurfaceAnalyzerLib.csproj index 8531ade97..e7225caca 100644 --- a/Lib/AttackSurfaceAnalyzerLib.csproj +++ b/Lib/AttackSurfaceAnalyzerLib.csproj @@ -41,7 +41,9 @@ This NuGet contains the AttackSurfaceAnalyzer Library, which is used by the CLI - + + + @@ -52,7 +54,6 @@ This NuGet contains the AttackSurfaceAnalyzer Library, which is used by the CLI - all diff --git a/Lib/Collectors/BaseCollector.cs b/Lib/Collectors/BaseCollector.cs index 8dd6ba5aa..84dca2c74 100644 --- a/Lib/Collectors/BaseCollector.cs +++ b/Lib/Collectors/BaseCollector.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using AttackSurfaceAnalyzer.ObjectTypes; +using Serilog; namespace AttackSurfaceAnalyzer.Collectors { diff --git a/Lib/Collectors/BaseCompare.cs b/Lib/Collectors/BaseCompare.cs index 7f43f97c1..42cf07d16 100644 --- a/Lib/Collectors/BaseCompare.cs +++ b/Lib/Collectors/BaseCompare.cs @@ -5,6 +5,7 @@ using AttackSurfaceAnalyzer.ObjectTypes; using AttackSurfaceAnalyzer.Utils; using Microsoft.Data.Sqlite; +using Serilog; namespace AttackSurfaceAnalyzer.Collectors { @@ -37,8 +38,8 @@ public bool TryCompare(string firstRunId, string secondRunId) } catch(Exception ex) { - Logger.Instance.Warn(ex, "Exception from Compare(): {0}", ex.StackTrace); - Logger.Instance.Warn(ex.Message); + Log.Warning(ex, "Exception from Compare(): {0}", ex.StackTrace); + Log.Warning(ex.Message); Stop(); return false; } diff --git a/Lib/Collectors/BaseMonitor.cs b/Lib/Collectors/BaseMonitor.cs index dc81e9ee7..96cf1be28 100644 --- a/Lib/Collectors/BaseMonitor.cs +++ b/Lib/Collectors/BaseMonitor.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using AttackSurfaceAnalyzer.ObjectTypes; +using Serilog; namespace AttackSurfaceAnalyzer.Collectors { diff --git a/Lib/Collectors/Certificates/CertificateCollector.cs b/Lib/Collectors/Certificates/CertificateCollector.cs index 14985c42f..fe2debee8 100644 --- a/Lib/Collectors/Certificates/CertificateCollector.cs +++ b/Lib/Collectors/Certificates/CertificateCollector.cs @@ -11,6 +11,7 @@ using System.Security.Cryptography.X509Certificates; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; +using Serilog; namespace AttackSurfaceAnalyzer.Collectors.Certificates { @@ -70,11 +71,11 @@ public void Write(StoreLocation storeLocation, StoreName storeName, X509Certific } catch (NullReferenceException e) { - Logger.Instance.Warn(e.StackTrace); + Log.Warning(e.StackTrace); } catch (Microsoft.Data.Sqlite.SqliteException e) { - Logger.Instance.Warn(e.Message); + Log.Warning(e.Message); //This catches duplicate certificates } } @@ -106,9 +107,9 @@ public override void Execute() } catch (Exception e) { - Logger.Instance.Debug(e.StackTrace); - Logger.Instance.Debug(e.GetType()); - Logger.Instance.Debug(e.Message); + Log.Debug(e.StackTrace); + Log.Debug(e.GetType().ToString()); + Log.Debug(e.Message); } } } diff --git a/Lib/Collectors/Certificates/CertificateCompare.cs b/Lib/Collectors/Certificates/CertificateCompare.cs index fa0624708..6f7a6af94 100644 --- a/Lib/Collectors/Certificates/CertificateCompare.cs +++ b/Lib/Collectors/Certificates/CertificateCompare.cs @@ -5,6 +5,7 @@ using AttackSurfaceAnalyzer.Utils; using Microsoft.Data.Sqlite; using AttackSurfaceAnalyzer.ObjectTypes; +using Serilog; namespace AttackSurfaceAnalyzer.Collectors.Certificates { @@ -98,8 +99,8 @@ public override void Compare(string firstRunId, string secondRunId) } catch (Exception e) { - Logger.Instance.Debug(e.StackTrace); - Logger.Instance.Debug(e.Message); + Log.Debug(e.StackTrace); + Log.Debug(e.Message); } } } diff --git a/Lib/Collectors/FileSystem/FileSystemCollector.cs b/Lib/Collectors/FileSystem/FileSystemCollector.cs index dd86afb7b..24acb2c02 100644 --- a/Lib/Collectors/FileSystem/FileSystemCollector.cs +++ b/Lib/Collectors/FileSystem/FileSystemCollector.cs @@ -12,6 +12,7 @@ using AttackSurfaceAnalyzer.Utils; using Microsoft.Data.Sqlite; using Newtonsoft.Json; +using Serilog; namespace AttackSurfaceAnalyzer.Collectors.FileSystem { @@ -51,7 +52,7 @@ public void WriteUntilEmpty() CommitTimer.Enabled = false; while (_queue.Count > 0) { - Logger.Instance.Warn(_queue.Count); + Log.Warning(_queue.Count.ToString()); FileSystemObject fso = _queue.Dequeue(); Write(cmd, fso); } @@ -75,9 +76,9 @@ public void Write(SqliteCommand cmd, FileSystemObject obj) } catch (Exception e) { - Logger.Instance.Info(e.StackTrace); - Logger.Instance.Info(e.Message); - Logger.Instance.Info(e.GetType()); + Log.Information(e.StackTrace); + Log.Information(e.Message); + Log.Information(e.GetType().ToString()); } } @@ -120,9 +121,9 @@ public void Write(FileSystemObject obj) } catch (Exception e) { - Logger.Instance.Info(e.StackTrace); - Logger.Instance.Info(e.Message); - Logger.Instance.Info(e.GetType()); + Log.Information(e.StackTrace); + Log.Information(e.Message); + Log.Information(e.GetType().ToString()); } } @@ -172,9 +173,9 @@ public override bool CanRunOnPlatform() // } // catch (Exception e) // { - // Logger.Instance.Info(e.StackTrace); - // Logger.Instance.Info(e.Message); - // Logger.Instance.Info(e.GetType()); + // Log.Information(e.StackTrace); + // Log.Information(e.Message); + // Log.Information(e.GetType()); // } //} @@ -216,7 +217,7 @@ public override void Execute() foreach (var root in this.roots) { - Logger.Instance.Warn("Scanning root " + root.ToString()); + Log.Warning("Scanning root " + root.ToString()); try { var fileInfoEnumerable = DirectoryWalker.WalkDirectory(root); @@ -251,13 +252,13 @@ public override void Execute() } catch (Exception ex) { - Logger.Instance.Debug(ex, "Error processing {0}", fileInfo?.FullName); + Log.Debug(ex, "Error processing {0}", fileInfo?.FullName); } })); } catch (Exception ex) { - Logger.Instance.Debug(ex, "Error collecting file system information: {0}", ex.Message); + Log.Debug(ex, "Error collecting file system information: {0}", ex.Message); } } @@ -270,8 +271,8 @@ public override void Execute() t.Minutes, t.Seconds, t.Milliseconds); - Logger.Instance.Info("Completed FileSystemCollector in " + answer); - Logger.Instance.Info("Flushing data"); + Log.Information("Completed FileSystemCollector in " + answer); + Log.Information("Flushing data"); watch = System.Diagnostics.Stopwatch.StartNew(); DatabaseManager.Commit(); @@ -283,7 +284,7 @@ public override void Execute() t.Minutes, t.Seconds, t.Milliseconds); - Logger.Instance.Info("Flush completed in " + answer); + Log.Information("Flush completed in " + answer); } } } \ No newline at end of file diff --git a/Lib/Collectors/FileSystem/FileSystemCompare.cs b/Lib/Collectors/FileSystem/FileSystemCompare.cs index e285caee1..6cf5797ac 100644 --- a/Lib/Collectors/FileSystem/FileSystemCompare.cs +++ b/Lib/Collectors/FileSystem/FileSystemCompare.cs @@ -6,6 +6,7 @@ using AttackSurfaceAnalyzer.Utils; using Microsoft.Data.Sqlite; using Newtonsoft.Json; +using Serilog; namespace AttackSurfaceAnalyzer.Collectors.FileSystem { @@ -123,7 +124,7 @@ public override void Compare(string firstRunId, string secondRunId) catch (Exception e) { // Debugging - Logger.Instance.Info(e.Message); + Log.Information(e.Message); } } } diff --git a/Lib/Collectors/FileSystem/FileSystemMonitor.cs b/Lib/Collectors/FileSystem/FileSystemMonitor.cs index be88be5bd..0db35d1dc 100644 --- a/Lib/Collectors/FileSystem/FileSystemMonitor.cs +++ b/Lib/Collectors/FileSystem/FileSystemMonitor.cs @@ -9,6 +9,7 @@ using AttackSurfaceAnalyzer.Utils; using Microsoft.Data.Sqlite; using Newtonsoft.Json; +using Serilog; namespace AttackSurfaceAnalyzer.Collectors.FileSystem { diff --git a/Lib/Collectors/FileSystem/FileSystemUtils.cs b/Lib/Collectors/FileSystem/FileSystemUtils.cs index 1cca8c557..d20581e7a 100644 --- a/Lib/Collectors/FileSystem/FileSystemUtils.cs +++ b/Lib/Collectors/FileSystem/FileSystemUtils.cs @@ -8,6 +8,7 @@ using System.Security.Cryptography.X509Certificates; using AttackSurfaceAnalyzer.Utils; using Murmur; +using Serilog; namespace AttackSurfaceAnalyzer.Collectors.FileSystem { @@ -31,7 +32,7 @@ protected internal static string GetFilePermissions(FileSystemInfo fileInfo) protected internal static string GetFileHash(FileSystemInfo fileInfo) { - Logger.Instance.Debug("Generating file hash for {0}", fileInfo.FullName); + Log.Debug("Generating file hash for {0}", fileInfo.FullName); string hashValue = null; try @@ -43,7 +44,7 @@ protected internal static string GetFileHash(FileSystemInfo fileInfo) } catch (Exception ex) { - Logger.Instance.Warn("Unable to take hash of file: {0}: {1}", fileInfo.FullName, ex.Message); + Log.Warning("Unable to take hash of file: {0}: {1}", fileInfo.FullName, ex.Message); } return hashValue; } @@ -75,7 +76,7 @@ public static KeyValuePair GetSignatureDetails(string pa } catch(Exception ex) { - Logger.Instance.Debug(ex, "Exception checking for file signature for {0}: {1}", path, ex.Message); + Log.Debug(ex, "Exception checking for file signature for {0}: {1}", path, ex.Message); return new KeyValuePair(false, certificate); } diff --git a/Lib/Collectors/FileSystem/LinuxFileSystemUtils.cs b/Lib/Collectors/FileSystem/LinuxFileSystemUtils.cs index 22ec1a841..65c1f51f6 100644 --- a/Lib/Collectors/FileSystem/LinuxFileSystemUtils.cs +++ b/Lib/Collectors/FileSystem/LinuxFileSystemUtils.cs @@ -4,6 +4,7 @@ using System.IO; using AttackSurfaceAnalyzer.Utils; using Mono.Unix; +using Serilog; namespace AttackSurfaceAnalyzer.Collectors.FileSystem { @@ -24,7 +25,7 @@ protected internal static string GetFilePermissions(FileSystemInfo fileInfo) } catch (Exception ex) { - Logger.Instance.Warn("Unable to get access control for {0}: {1}", fileInfo.FullName, ex.Message); + Log.Warning("Unable to get access control for {0}: {1}", fileInfo.FullName, ex.Message); } } else if (fileInfo is DirectoryInfo) @@ -35,7 +36,7 @@ protected internal static string GetFilePermissions(FileSystemInfo fileInfo) } catch (Exception ex) { - Logger.Instance.Warn("Unable to get access control for {0}: {1}", fileInfo.FullName, ex.Message); + Log.Warning("Unable to get access control for {0}: {1}", fileInfo.FullName, ex.Message); } } else diff --git a/Lib/Collectors/FileSystem/WindowsFileSystemUtils.cs b/Lib/Collectors/FileSystem/WindowsFileSystemUtils.cs index 0cb4da28c..df927031b 100644 --- a/Lib/Collectors/FileSystem/WindowsFileSystemUtils.cs +++ b/Lib/Collectors/FileSystem/WindowsFileSystemUtils.cs @@ -4,6 +4,7 @@ using System.IO; using System.Security.AccessControl; using AttackSurfaceAnalyzer.Utils; +using Serilog; namespace AttackSurfaceAnalyzer.Collectors.FileSystem { @@ -26,8 +27,8 @@ protected internal static string GetFilePermissions(FileSystemInfo fileInfo) } catch (Exception ex) { - Logger.Instance.Debug("Unable to get access control for {0}: {1}", fileInfo.FullName, ex.Message); - //Logger.Instance.Debug(ex.StackTrace); + Log.Debug("Unable to get access control for {0}: {1}", fileInfo.FullName, ex.Message); + //Log.Debug(ex.StackTrace); } } else if (fileInfo is DirectoryInfo) @@ -38,8 +39,8 @@ protected internal static string GetFilePermissions(FileSystemInfo fileInfo) } catch (Exception ex) { - Logger.Instance.Debug("Unable to get access control for {0}: {1}", fileInfo.FullName, ex.Message); - //Logger.Instance.Debug(ex.StackTrace); + Log.Debug("Unable to get access control for {0}: {1}", fileInfo.FullName, ex.Message); + //Log.Debug(ex.StackTrace); } } diff --git a/Lib/Collectors/OpenPorts/OpenPortCollector.cs b/Lib/Collectors/OpenPorts/OpenPortCollector.cs index 624fe2cfa..be4dc86d6 100644 --- a/Lib/Collectors/OpenPorts/OpenPortCollector.cs +++ b/Lib/Collectors/OpenPorts/OpenPortCollector.cs @@ -10,6 +10,7 @@ using Microsoft.Data.Sqlite; using AttackSurfaceAnalyzer.ObjectTypes; using Newtonsoft.Json; +using Serilog; namespace AttackSurfaceAnalyzer.Collectors.OpenPorts { @@ -23,7 +24,7 @@ public class OpenPortCollector : BaseCollector public OpenPortCollector(string runId) { - Logger.Instance.Debug("Initializing a new OpenPortCollector object."); + Log.Debug("Initializing a new OpenPortCollector object."); if (runId == null) { throw new ArgumentException("runIdentifier may not be null."); @@ -50,7 +51,7 @@ public override bool CanRunOnPlatform() osRelease = osRelease.ToLower(); if (osRelease.Contains("microsoft") || osRelease.Contains("wsl")) { - Logger.Instance.Debug("OpenPortCollector cannot run on WSL until https://github.com/Microsoft/WSL/issues/2249 is fixed."); + Log.Debug("OpenPortCollector cannot run on WSL until https://github.com/Microsoft/WSL/issues/2249 is fixed."); return false; } } @@ -69,7 +70,7 @@ public void Write(OpenPortObject obj) var objStr = obj.ToString(); if (this.processedObjects.Contains(objStr)) { - Logger.Instance.Debug("Object already exists, ignoring: {0}", objStr); + Log.Debug("Object already exists, ignoring: {0}", objStr); return; } @@ -90,7 +91,7 @@ public void Write(OpenPortObject obj) public override void Execute() { Start(); - Logger.Instance.Debug("Collecting open port information..."); + Log.Debug("Collecting open port information..."); Truncate(runId); if (!this.CanRunOnPlatform()) @@ -112,7 +113,7 @@ public override void Execute() } else { - Logger.Instance.Warn("OpenPortCollector is not available on {0}", RuntimeInformation.OSDescription); + Log.Warning("OpenPortCollector is not available on {0}", RuntimeInformation.OSDescription); } Stop(); } @@ -124,7 +125,7 @@ public override void Execute() /// public void ExecuteWindows() { - Logger.Instance.Debug("Collecting open port information (Windows implementation)"); + Log.Debug("Collecting open port information (Windows implementation)"); var properties = IPGlobalProperties.GetIPGlobalProperties(); foreach (var endpoint in properties.GetActiveTcpListeners()) @@ -168,7 +169,7 @@ public void ExecuteWindows() /// private void ExecuteLinux() { - Logger.Instance.Debug("ExecuteLinux()"); + Log.Debug("ExecuteLinux()"); var runner = new ExternalCommandRunner(); var result = runner.RunExternalCommand("ss", "-ln"); @@ -213,7 +214,7 @@ private void ExecuteLinux() /// private void ExecuteOsX() { - Logger.Instance.Debug("ExecuteOsX()"); + Log.Debug("ExecuteOsX()"); var runner = new ExternalCommandRunner(); var result = runner.RunExternalCommand("sudo", "lsof -Pn -i4 -i6"); @@ -298,7 +299,7 @@ public void Compare(string beforeKey, string afterKey) } if (!afterSet.Contains(b)) { - Logger.Instance.Info("Open port no longer open: {0}", b.ToString()); + Log.Information("Open port no longer open: {0}", b.ToString()); } } @@ -306,7 +307,7 @@ public void Compare(string beforeKey, string afterKey) { if (!beforeSet.Contains(b)) { - Logger.Instance.Info("New open port: {0}", b.ToString()); + Log.Information("New open port: {0}", b.ToString()); } } } diff --git a/Lib/Collectors/OpenPorts/OpenPortCompare.cs b/Lib/Collectors/OpenPorts/OpenPortCompare.cs index 0f81a5785..abbfe9608 100644 --- a/Lib/Collectors/OpenPorts/OpenPortCompare.cs +++ b/Lib/Collectors/OpenPorts/OpenPortCompare.cs @@ -122,7 +122,7 @@ public override void Compare(string firstRunId, string secondRunId) //{ // while (reader.Read()) // { - // Logger.Instance.Warn("Modified row: {0}", reader["row_key"]?.ToString()); + // Log.Warning("Modified row: {0}", reader["row_key"]?.ToString()); // var obj = new OpenPortObject() // { // address = reader["address"].ToString(), diff --git a/Lib/Collectors/Registry/RegistryCollector.cs b/Lib/Collectors/Registry/RegistryCollector.cs index 16a81d653..463183095 100644 --- a/Lib/Collectors/Registry/RegistryCollector.cs +++ b/Lib/Collectors/Registry/RegistryCollector.cs @@ -11,6 +11,7 @@ using Microsoft.Data.Sqlite; using Microsoft.Win32; using Newtonsoft.Json; +using Serilog; namespace AttackSurfaceAnalyzer.Collectors.Registry { @@ -91,18 +92,18 @@ public void Write(RegistryObject obj) } catch (Exception e) { - Logger.Instance.Debug(e.GetType() + "thrown in registry collector"); + Log.Debug(e.GetType() + "thrown in registry collector"); } if (_numCollected++ % 100000 == 0) { - Logger.Instance.Info(_numCollected + (" of 6-800k")); + Log.Information(_numCollected + (" of 6-800k")); } } } catch(Exception) { - Logger.Instance.Trace("Had trouble writing {0}",obj.Key); + Log.Debug("Had trouble writing {0}",obj.Key); } customCrawlHandler?.Invoke(obj); @@ -115,8 +116,8 @@ public override void Execute() Start(); Console.WriteLine("Starting"); - Logger.Instance.Info("Starting"); - Logger.Instance.Info(JsonConvert.SerializeObject(DefaultHives)); + Log.Information("Starting"); + Log.Information(JsonConvert.SerializeObject(DefaultHives)); if (!this.CanRunOnPlatform()) { @@ -127,13 +128,13 @@ public override void Execute() Parallel.ForEach(Hives, (hive => { - Logger.Instance.Debug("Starting " + hive.ToString()); + Log.Debug("Starting " + hive.ToString()); if (Filter.IsFiltered(Filter.RuntimeString(), "Scan", "Registry", "Hive", "Include", hive.ToString())) { } else if (Filter.IsFiltered(Filter.RuntimeString(), "Scan", "Registry", "Hive", "Exclude", hive.ToString(), out Regex Capturer)) { - Logger.Instance.Info("Excluding hive '{0}' due to filter '{1}'.", hive.ToString(), Capturer.ToString()); + Log.Information("Excluding hive '{0}' due to filter '{1}'.", hive.ToString(), Capturer.ToString()); return; } @@ -151,15 +152,15 @@ public override void Execute() // Some registry keys don't get along catch (InvalidOperationException e) { - Logger.Instance.Debug(registryObject.Key + " " + e.GetType()); + Log.Debug(registryObject.Key + " " + e.GetType()); } })); } catch (Exception e) { - Logger.Instance.Debug(e.GetType()); - Logger.Instance.Debug(e.Message); - Logger.Instance.Debug(e.StackTrace); + Log.Debug(e.GetType().ToString()); + Log.Debug(e.Message); + Log.Debug(e.StackTrace); } })); diff --git a/Lib/Collectors/Registry/RegistryCompare.cs b/Lib/Collectors/Registry/RegistryCompare.cs index d9a0286af..03bbd36d1 100644 --- a/Lib/Collectors/Registry/RegistryCompare.cs +++ b/Lib/Collectors/Registry/RegistryCompare.cs @@ -6,6 +6,7 @@ using AttackSurfaceAnalyzer.Utils; using Microsoft.Data.Sqlite; using Newtonsoft.Json; +using Serilog; namespace AttackSurfaceAnalyzer.Collectors.Registry { @@ -42,7 +43,7 @@ public override void Compare(string firstRunId, string secondRunId) // TODO: Check if this comparison has already been completed // Skip the rest if it has - Logger.Instance.Info("Starting RegistryCompare Created"); + Log.Information("Starting RegistryCompare Created"); var addObjects = new List(); var cmd = new SqliteCommand(SELECT_INSERTED_SQL, DatabaseManager.Connection, DatabaseManager.Transaction); cmd.Parameters.AddWithValue("@first_run_id", firstRunId); @@ -66,7 +67,7 @@ public override void Compare(string firstRunId, string secondRunId) } Results["registry_add"] = addObjects; - Logger.Instance.Info("Starting RegistryCompare Deleted"); + Log.Information("Starting RegistryCompare Deleted"); // Which files are gone? var removeObjects = new List(); cmd = new SqliteCommand(SELECT_DELETED_SQL, DatabaseManager.Connection, DatabaseManager.Transaction); @@ -91,7 +92,7 @@ public override void Compare(string firstRunId, string secondRunId) } Results["registry_remove"] = removeObjects; - Logger.Instance.Info("Starting RegistryCompare Modified"); + Log.Information("Starting RegistryCompare Modified"); // Which files had some other property modified? var modifyObjects = new List(); cmd = new SqliteCommand(SELECT_MODIFIED_SQL, DatabaseManager.Connection, DatabaseManager.Transaction); @@ -123,7 +124,7 @@ public override void Compare(string firstRunId, string secondRunId) } catch (Exception e) { - Logger.Instance.Info(e.Message); + Log.Information(e.Message); } } } diff --git a/Lib/Collectors/Registry/RegistryMonitor.cs b/Lib/Collectors/Registry/RegistryMonitor.cs index 148bd5c29..799c3a056 100644 --- a/Lib/Collectors/Registry/RegistryMonitor.cs +++ b/Lib/Collectors/Registry/RegistryMonitor.cs @@ -5,6 +5,7 @@ using System.IO; using System.Runtime.InteropServices; using AttackSurfaceAnalyzer.Utils; +using Serilog; namespace AttackSurfaceAnalyzer.Collectors.Registry { @@ -20,7 +21,7 @@ public RegistryMonitor() public void MyOnEntryWritten(object source, EntryWrittenEventArgs e) { - Logger.Instance.Info(e.Entry.Source); + Log.Information(e.Entry.Source); } public override void Start() diff --git a/Lib/Collectors/Service/ServiceCollector.cs b/Lib/Collectors/Service/ServiceCollector.cs index acf826917..94e2a2198 100644 --- a/Lib/Collectors/Service/ServiceCollector.cs +++ b/Lib/Collectors/Service/ServiceCollector.cs @@ -10,6 +10,7 @@ using AttackSurfaceAnalyzer.Utils; using Microsoft.Data.Sqlite; using Newtonsoft.Json; +using Serilog; namespace AttackSurfaceAnalyzer.Collectors.Service { @@ -76,7 +77,7 @@ public override void Execute() if (!this.CanRunOnPlatform()) { - Logger.Instance.Info("ServiceCollector cannot run on this platform."); + Log.Information("ServiceCollector cannot run on this platform."); return; } @@ -89,7 +90,7 @@ public override void Execute() { if (this.filter != null && !this.filter(service)) { - Logger.Instance.Info("Service [{0}] did not pass filter, ignoring.", service.ToString()); + Log.Information("Service [{0}] did not pass filter, ignoring.", service.ToString()); continue; } diff --git a/Lib/Collectors/Service/ServiceCompare.cs b/Lib/Collectors/Service/ServiceCompare.cs index 8c9569fe4..8824fd4c1 100644 --- a/Lib/Collectors/Service/ServiceCompare.cs +++ b/Lib/Collectors/Service/ServiceCompare.cs @@ -6,6 +6,7 @@ using AttackSurfaceAnalyzer.Utils; using Microsoft.Data.Sqlite; using Newtonsoft.Json; +using Serilog; namespace AttackSurfaceAnalyzer.Collectors.Service { diff --git a/Lib/Collectors/UserAccount/UserAccountCollector.cs b/Lib/Collectors/UserAccount/UserAccountCollector.cs index 54eee6df9..56f41e0af 100644 --- a/Lib/Collectors/UserAccount/UserAccountCollector.cs +++ b/Lib/Collectors/UserAccount/UserAccountCollector.cs @@ -10,6 +10,7 @@ using AttackSurfaceAnalyzer.Utils; using Microsoft.Data.Sqlite; using Newtonsoft.Json; +using Serilog; namespace AttackSurfaceAnalyzer.Collectors.UserAccount { @@ -26,7 +27,7 @@ public class UserAccountCollector : BaseCollector public UserAccountCollector(string runId, Func filter = null) { - Logger.Instance.Debug("Initializing a new UserAccountCollector object."); + Log.Debug("Initializing a new UserAccountCollector object."); this.runId = runId; this.filter = filter; } @@ -88,7 +89,7 @@ public void Write(UserAccountObject obj) { - Logger.Instance.Info(result["Name"]); + Log.Information(result["Name"]); }; @@ -112,7 +113,7 @@ Code Block ManagementObject account = new ManagementObject(user["PartComponent"].ToString()); - Logger.Instance.Info(" " + account["Name"]); + Log.Information(" " + account["Name"]); }; @@ -124,7 +125,7 @@ public override void Execute() if (!this.CanRunOnPlatform()) { - Logger.Instance.Warn("UserAccountCollector is not available on {0}", RuntimeInformation.OSDescription); + Log.Warning("UserAccountCollector is not available on {0}", RuntimeInformation.OSDescription); return; } @@ -144,7 +145,7 @@ public override void Execute() } else { - Logger.Instance.Warn("UserAccountCollector is not available on {0}", RuntimeInformation.OSDescription); + Log.Warning("UserAccountCollector is not available on {0}", RuntimeInformation.OSDescription); } Stop(); @@ -155,7 +156,7 @@ public override void Execute() /// public void ExecuteWindows() { - Logger.Instance.Debug("ExecuteWindows()"); + Log.Debug("ExecuteWindows()"); SelectQuery query = new SelectQuery("Win32_UserAccount", "LocalAccount = 'True'"); ManagementObjectSearcher searcher = new ManagementObjectSearcher(query); @@ -191,7 +192,7 @@ public void ExecuteWindows() /// private void ExecuteLinux() { - Logger.Instance.Debug("ExecuteLinux()"); + Log.Debug("ExecuteLinux()"); var runner = new ExternalCommandRunner(); var etc_passwd_lines = File.ReadAllLines("/etc/passwd"); @@ -255,7 +256,7 @@ private void ExecuteLinux() private void ExecuteOsX() { - Logger.Instance.Debug("ExecuteOsX()"); + Log.Debug("ExecuteOsX()"); var runner = new ExternalCommandRunner(); diff --git a/Lib/Collectors/UserAccount/UserAccountCompare.cs b/Lib/Collectors/UserAccount/UserAccountCompare.cs index 119ea7c43..28195f1a2 100644 --- a/Lib/Collectors/UserAccount/UserAccountCompare.cs +++ b/Lib/Collectors/UserAccount/UserAccountCompare.cs @@ -6,6 +6,7 @@ using AttackSurfaceAnalyzer.Utils; using Microsoft.Data.Sqlite; using Newtonsoft.Json; +using Serilog; namespace AttackSurfaceAnalyzer.Collectors.UserAccount { @@ -96,7 +97,7 @@ public override void Compare(string firstRunId, string secondRunId) { while (reader.Read()) { - Logger.Instance.Warn("Modified row: {0}", reader["row_key"]?.ToString()); + Log.Warning("Modified row: {0}", reader["row_key"]?.ToString()); var obj = new UserAccountResult() { Base = JsonConvert.DeserializeObject(reader["a_serialized"].ToString()), @@ -117,8 +118,8 @@ public override void Compare(string firstRunId, string secondRunId) } catch(Exception e) { - Logger.Instance.Warn(e.StackTrace); - Logger.Instance.Warn(e.GetType()); + Log.Warning(e.StackTrace); + Log.Warning(e.GetType().ToString()); } } } diff --git a/Lib/Objects/CertificateObject.cs b/Lib/Objects/CertificateObject.cs index bc89ab93d..d5969d965 100644 --- a/Lib/Objects/CertificateObject.cs +++ b/Lib/Objects/CertificateObject.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; using System.Text; +using Serilog; namespace AttackSurfaceAnalyzer.ObjectTypes { diff --git a/Lib/Objects/FileSystemObject.cs b/Lib/Objects/FileSystemObject.cs index 89998cd54..eb40aae9a 100644 --- a/Lib/Objects/FileSystemObject.cs +++ b/Lib/Objects/FileSystemObject.cs @@ -9,6 +9,7 @@ using System.Text; using AttackSurfaceAnalyzer.Utils; using Newtonsoft.Json; +using Serilog; namespace AttackSurfaceAnalyzer.ObjectTypes @@ -52,7 +53,7 @@ public string SignatureStatus } catch(Exception ex) { - Logger.Instance.Debug(ex.StackTrace); + Log.Debug(ex.StackTrace); // Fall back to a call out to powershell.exe try { @@ -87,7 +88,7 @@ public string SignatureStatus } catch(Exception ex2) { - Logger.Instance.Debug(ex2.StackTrace); + Log.Debug(ex2.StackTrace); } return null; } diff --git a/Lib/Objects/OpenPortObject.cs b/Lib/Objects/OpenPortObject.cs index 0a279760d..e2e2921d1 100644 --- a/Lib/Objects/OpenPortObject.cs +++ b/Lib/Objects/OpenPortObject.cs @@ -4,6 +4,7 @@ using System.Text; using AttackSurfaceAnalyzer.Utils; using Newtonsoft.Json; +using Serilog; namespace AttackSurfaceAnalyzer.ObjectTypes { @@ -50,7 +51,7 @@ public int CompareTo(object obj) { if (this.port == "135" && other.port == "135") { - Logger.Instance.Info("Comparing {0} to {1}, result={2}", this.ToString(), obj.ToString(), result); + Log.Information("Comparing {0} to {1}, result={2}", this.ToString(), obj.ToString(), result); } return result.Value; } diff --git a/Lib/Objects/RegistryObject.cs b/Lib/Objects/RegistryObject.cs index 8d8e8514a..dedb10193 100644 --- a/Lib/Objects/RegistryObject.cs +++ b/Lib/Objects/RegistryObject.cs @@ -5,6 +5,7 @@ using System.Security.AccessControl; using AttackSurfaceAnalyzer.Utils; using Microsoft.Win32; +using Serilog; namespace AttackSurfaceAnalyzer.ObjectTypes { @@ -62,7 +63,7 @@ private static Dictionary GetValues(RegistryKey key) { if (Value.ToString() == Value.GetType().ToString()) { - Logger.Instance.Warn("Uh oh, this type isn't handled. " + Value.ToString()); + Log.Warning("Uh oh, this type isn't handled. " + Value.ToString()); } str = Value.ToString(); } @@ -83,7 +84,7 @@ public RegistryObject(RegistryKey Key) } catch(Exception e) { - Logger.Instance.Trace(e.GetType() + " failed to get security descriptor for " + Key.Name); + Log.Debug(e.GetType() + " failed to get security descriptor for " + Key.Name); } } diff --git a/Lib/Objects/ResultObjects.cs b/Lib/Objects/ResultObjects.cs index ddea46948..6a42be591 100644 --- a/Lib/Objects/ResultObjects.cs +++ b/Lib/Objects/ResultObjects.cs @@ -2,6 +2,7 @@ // Licensed under the MIT License. using AttackSurfaceAnalyzer.Collectors.FileSystem; using AttackSurfaceAnalyzer.ObjectTypes; +using Serilog; namespace AttackSurfaceAnalyzer.ObjectTypes { diff --git a/Lib/Objects/ServiceObject.cs b/Lib/Objects/ServiceObject.cs index cd2c6a0a4..0da526bad 100644 --- a/Lib/Objects/ServiceObject.cs +++ b/Lib/Objects/ServiceObject.cs @@ -3,6 +3,7 @@ using System.Text; using AttackSurfaceAnalyzer.Utils; using Newtonsoft.Json; +using Serilog; namespace AttackSurfaceAnalyzer.ObjectTypes { diff --git a/Lib/Objects/UserAccountObject.cs b/Lib/Objects/UserAccountObject.cs index 60989b53e..d8a0d5af2 100644 --- a/Lib/Objects/UserAccountObject.cs +++ b/Lib/Objects/UserAccountObject.cs @@ -5,6 +5,7 @@ using System.Text; using AttackSurfaceAnalyzer.Utils; using Newtonsoft.Json; +using Serilog; namespace AttackSurfaceAnalyzer.ObjectTypes { diff --git a/Lib/Utils/DataWriter.cs b/Lib/Utils/DataWriter.cs index 74ebe9c6a..93132cb35 100644 --- a/Lib/Utils/DataWriter.cs +++ b/Lib/Utils/DataWriter.cs @@ -1,12 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. + namespace AttackSurfaceAnalyzer.Utils { class DataWriter { public static void Write(object o) { - Logger.Instance.Error("Received Object {0}", o); + //Log.Error("Received Object {0}", o); } } } \ No newline at end of file diff --git a/Lib/Utils/DatabaseManager.cs b/Lib/Utils/DatabaseManager.cs index 4c333efe0..c48a8e97d 100644 --- a/Lib/Utils/DatabaseManager.cs +++ b/Lib/Utils/DatabaseManager.cs @@ -2,6 +2,7 @@ // Licensed under the MIT License. using System; using Microsoft.Data.Sqlite; +using Serilog; namespace AttackSurfaceAnalyzer.Utils { @@ -62,7 +63,7 @@ public static void Setup() { if (Connection == null) { - Logger.Instance.Debug("Starting database setup"); + Log.Debug("Starting database setup"); Connection = new SqliteConnection($"Filename=" + _SqliteFilename); Connection.Open(); @@ -114,7 +115,7 @@ public static void Setup() cmd = new SqliteCommand(SQL_CREATE_REGISTRY_RUN_ID_INDEX, DatabaseManager.Connection, DatabaseManager.Transaction); cmd.ExecuteNonQuery(); - Logger.Instance.Debug("Halfway"); + Log.Debug("Halfway"); cmd = new SqliteCommand(SQL_CREATE_RESULT_CHANGE_TYPE_INDEX, DatabaseManager.Connection, DatabaseManager.Transaction); cmd.ExecuteNonQuery(); @@ -133,7 +134,7 @@ public static void Setup() DatabaseManager.Transaction.Commit(); _transaction = null; - Logger.Instance.Debug("Done with database setup"); + Log.Debug("Done with database setup"); } } @@ -161,7 +162,7 @@ public static void Commit() } catch (Exception) { - Logger.Instance.Debug("Commit collision"); + Log.Debug("Commit collision"); } _transaction = null; @@ -220,7 +221,7 @@ public static string SqliteFilename } catch (Exception ex) { - Logger.Instance.Warn(ex, "Unable to open SQLite connection to {0}: {1}", value, ex.Message); + Log.Warning(ex, "Unable to open SQLite connection to {0}: {1}", value, ex.Message); } } } diff --git a/Lib/Utils/DirectoryWalker.cs b/Lib/Utils/DirectoryWalker.cs index 9e8dcdafb..eb303ca27 100644 --- a/Lib/Utils/DirectoryWalker.cs +++ b/Lib/Utils/DirectoryWalker.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; using System.IO; +using Serilog; namespace AttackSurfaceAnalyzer.Utils { @@ -45,12 +46,12 @@ public static IEnumerable WalkDirectory(string root) // about the systems on which this code will run. catch (UnauthorizedAccessException e) { - Logger.Instance.Debug(e.Message); + Log.Debug(e.Message); continue; } catch (System.IO.DirectoryNotFoundException e) { - Logger.Instance.Debug(e.Message); + Log.Debug(e.Message); continue; } // @TODO: Improve this catch. @@ -60,7 +61,7 @@ public static IEnumerable WalkDirectory(string root) // directories. catch (Exception) { - //Logger.Instance.Debug(ex.StackTrace); + //Log.Debug(ex.StackTrace); continue; } @@ -73,13 +74,13 @@ public static IEnumerable WalkDirectory(string root) catch (UnauthorizedAccessException e) { - Logger.Instance.Debug(e.Message); + Log.Debug(e.Message); continue; } catch (System.IO.DirectoryNotFoundException e) { - Logger.Instance.Debug(e.Message); + Log.Debug(e.Message); continue; } // Perform the required action on each file here. @@ -96,7 +97,7 @@ public static IEnumerable WalkDirectory(string root) // If file was deleted by a separate application // or thread since the call to TraverseTree() // then just continue. - Logger.Instance.Debug(e.Message); + Log.Debug(e.Message); continue; } string FullPath = String.Format("{0}{1}{2}", currentDir, Path.PathSeparator, file); @@ -128,12 +129,12 @@ public static IEnumerable WalkDirectory(string root) // If file was deleted by a separate application // or thread since the call to TraverseTree() // then just continue. - Logger.Instance.Debug(e.Message); + Log.Debug(e.Message); continue; } catch (Exception e) { - Logger.Instance.Debug(e.Message); + Log.Debug(e.Message); continue; } dirs.Push(str); diff --git a/Lib/Utils/Elevation.cs b/Lib/Utils/Elevation.cs index 61a530be2..27212402f 100644 --- a/Lib/Utils/Elevation.cs +++ b/Lib/Utils/Elevation.cs @@ -5,6 +5,7 @@ using System.Diagnostics; using System.Runtime.InteropServices; using System.Security.Principal; +using Serilog; /*********************************** Module Header ***********************************\ Module Name: MainForm.cs @@ -423,7 +424,7 @@ public void CheckElevation() } else { - Logger.Instance.Debug("Running as admin."); + Log.Debug("Running as admin."); } } diff --git a/Lib/Utils/FileWatcher.cs b/Lib/Utils/FileWatcher.cs index 8203bfc0c..d430cca3f 100644 --- a/Lib/Utils/FileWatcher.cs +++ b/Lib/Utils/FileWatcher.cs @@ -3,6 +3,8 @@ using System; using System.Collections.Generic; using System.IO; +using Serilog; + namespace AttackSurfaceAnalyzer.Utils { @@ -12,8 +14,8 @@ public class FileWatcher public readonly List EventList = new List(); - private static readonly Action DefaultChangedDelegate = (e) => { FileSystemEventArgs i_e = (FileSystemEventArgs)e; Logger.Instance.Info(i_e.ChangeType.ToString() + " " + i_e.FullPath.ToString()); }; - private static readonly Action DefaultRenamedDelegate = (e) => { RenamedEventArgs i_e = (RenamedEventArgs)e; Logger.Instance.Info(i_e.ChangeType.ToString() + " " + i_e.OldFullPath.ToString() + " " + i_e.FullPath.ToString()); }; + private static readonly Action DefaultChangedDelegate = (e) => { FileSystemEventArgs i_e = (FileSystemEventArgs)e; Log.Information(i_e.ChangeType.ToString() + " " + i_e.FullPath.ToString()); }; + private static readonly Action DefaultRenamedDelegate = (e) => { RenamedEventArgs i_e = (RenamedEventArgs)e; Log.Information(i_e.ChangeType.ToString() + " " + i_e.OldFullPath.ToString() + " " + i_e.FullPath.ToString()); }; private static readonly NotifyFilters DefaultFilters = NotifyFilters.Attributes | NotifyFilters.CreationTime diff --git a/Lib/Utils/Filter.cs b/Lib/Utils/Filter.cs index 53efd2391..271cc5b03 100644 --- a/Lib/Utils/Filter.cs +++ b/Lib/Utils/Filter.cs @@ -6,6 +6,7 @@ using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; +using Serilog; namespace AttackSurfaceAnalyzer.Utils { @@ -65,15 +66,15 @@ public static bool IsFiltered(string Platform, string ScanType, string ItemType, if (rgx.IsMatch(Target)) { regex = rgx; - Logger.Instance.Debug("{0} caught {1}", rgx, Target); + Log.Debug("{0} caught {1}", rgx, Target); return true; } } catch (Exception e) { - Logger.Instance.Trace("Probably this is omse of those garbled keys or a bad regex"); - Logger.Instance.Trace(e.GetType()); - Logger.Instance.Trace(filter.ToString()); + Log.Debug("Probably this is omse of those garbled keys or a bad regex"); + Log.Debug(e.GetType().ToString()); + Log.Debug(filter.ToString()); } @@ -81,9 +82,9 @@ public static bool IsFiltered(string Platform, string ScanType, string ItemType, } catch (NullReferenceException) { - Logger.Instance.Debug(JsonConvert.SerializeObject(config)); + Log.Debug(JsonConvert.SerializeObject(config)); // No filter entry for that Platform, Scantype, Itemtype, Property - Logger.Instance.Debug("No Filter Entry {0}, {1}, {2}, {3}, {4}", Platform, ScanType, ItemType, Property, FilterType); + Log.Debug("No Filter Entry {0}, {1}, {2}, {3}, {4}", Platform, ScanType, ItemType, Property, FilterType); } return false; @@ -91,7 +92,7 @@ public static bool IsFiltered(string Platform, string ScanType, string ItemType, public static void LoadFilters(string filterLoc = "filters.json") { - Logger.Instance.Debug("Loading filters"); + Log.Debug("Loading filters"); try { using (StreamReader file = File.OpenText(filterLoc)) @@ -101,19 +102,19 @@ public static void LoadFilters(string filterLoc = "filters.json") } if (config == null) { - Logger.Instance.Debug("Out of entries"); + Log.Debug("Out of entries"); } } catch (System.IO.FileNotFoundException) { //That's fine, we just don't have any filters to load - Logger.Instance.Debug("{0} is missing (filter configuration file)", filterLoc); + Log.Debug("{0} is missing (filter configuration file)", filterLoc); return; } catch (NullReferenceException) { - Logger.Instance.Debug("{0} is missing (filter configuration file)", filterLoc); + Log.Debug("{0} is missing (filter configuration file)", filterLoc); return; } diff --git a/Lib/Utils/Logger.cs b/Lib/Utils/Logger.cs index 6f02d4a40..fe92e851f 100644 --- a/Lib/Utils/Logger.cs +++ b/Lib/Utils/Logger.cs @@ -1,21 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -using NLog; -using NLog.Config; -using NLog.Targets; +using Serilog; +using Serilog.Events; namespace AttackSurfaceAnalyzer.Utils { public class Logger { - public static ILogger Instance { get; private set; } - - static Logger() - { - Instance = LogManager.GetCurrentClassLogger(); - } - public static void Setup() { Setup(false, false); @@ -23,46 +15,32 @@ public static void Setup() public static void Setup(bool debug, bool verbose) { - var config = new LoggingConfiguration(); - - var consoleTarget = new ColoredConsoleTarget("console") + if (verbose) { - Layout = @"${date:format=HH\:mm\:ss} ${level} ${message} ${exception}" - }; - config.AddTarget(consoleTarget); - - var fileTarget = new FileTarget("debug") - { - FileName = "asa.debug.log", - Layout = "${longdate} ${level} ${message} ${exception}" - }; - config.AddTarget(fileTarget); - - if (debug || verbose) - { - config.AddRuleForOneLevel(LogLevel.Debug, consoleTarget); - config.AddRuleForOneLevel(LogLevel.Warn, consoleTarget); - config.AddRuleForOneLevel(LogLevel.Error, consoleTarget); - config.AddRuleForOneLevel(LogLevel.Fatal, consoleTarget); + Log.Logger = new LoggerConfiguration() + .MinimumLevel.Verbose() + .WriteTo.File("asa.log.txt") + .WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Verbose) + .CreateLogger(); } - if (debug || verbose) + else if (debug) { - config.AddRuleForAllLevels(fileTarget); + Log.Logger = new LoggerConfiguration() + .MinimumLevel.Debug() + .WriteTo.File("asa.log.txt") + .WriteTo.Console() + .CreateLogger(); } - //if (trace) - //{ - // config.AddRuleForAllLevels(fileTarget); - // config.AddRuleForAllLevels(consoleTarget); - //} else { - config.AddRuleForOneLevel(LogLevel.Info, consoleTarget); - config.AddRuleForOneLevel(LogLevel.Warn, consoleTarget); - config.AddRuleForOneLevel(LogLevel.Error, consoleTarget); - config.AddRuleForOneLevel(LogLevel.Fatal, consoleTarget); + Log.Logger = new LoggerConfiguration() + .MinimumLevel.Debug() + .WriteTo.File("asa.log.txt") + .WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Information) + .CreateLogger(); + } - LogManager.Configuration = config; } } } \ No newline at end of file diff --git a/Lib/Utils/RegistryWalker.cs b/Lib/Utils/RegistryWalker.cs index 050196354..84c603a6a 100644 --- a/Lib/Utils/RegistryWalker.cs +++ b/Lib/Utils/RegistryWalker.cs @@ -5,6 +5,7 @@ using System.IO; using AttackSurfaceAnalyzer.ObjectTypes; using Microsoft.Win32; +using Serilog; namespace AttackSurfaceAnalyzer.Utils { @@ -49,7 +50,7 @@ public static IEnumerable WalkHive(RegistryHive Hive) // These are expected as we are running as administrator, not System. catch (System.Security.SecurityException e) { - Logger.Instance.Trace(e.GetType() + " " + e.Message + " " + currentKey.Name); + Log.Debug(e.GetType() + " " + e.Message + " " + currentKey.Name); } // There seem to be some keys which are listed as existing by the APIs but don't actually exist. @@ -57,11 +58,11 @@ public static IEnumerable WalkHive(RegistryHive Hive) // Since this isn't use actionable, also just supress these to the debug stream. catch (System.IO.IOException e) { - Logger.Instance.Debug(e.GetType() + " " + e.Message + " " + currentKey.Name); + Log.Debug(e.GetType() + " " + e.Message + " " + currentKey.Name); } catch (Exception e) { - Logger.Instance.Info(e.GetType() + " " + e.Message + " " + currentKey.Name); + Log.Information(e.GetType() + " " + e.Message + " " + currentKey.Name); } } RegistryObject regObj = null; @@ -70,7 +71,7 @@ public static IEnumerable WalkHive(RegistryHive Hive) regObj = new RegistryObject(currentKey); } - catch (Exception) { Logger.Instance.Debug("I'm blue"); } + catch (Exception) { Log.Debug("I'm blue"); } if (regObj != null) { yield return regObj; diff --git a/Lib/Utils/Win32OpenPortListenerHelper.cs b/Lib/Utils/Win32OpenPortListenerHelper.cs index ff950648c..87514380e 100644 --- a/Lib/Utils/Win32OpenPortListenerHelper.cs +++ b/Lib/Utils/Win32OpenPortListenerHelper.cs @@ -5,6 +5,7 @@ using System.Diagnostics; using System.IO; using System.Text.RegularExpressions; +using Serilog; namespace AttackSurfaceAnalyzer.Utils { @@ -66,7 +67,7 @@ private static List GetNetStatPorts() if (Proc.ExitCode != 0) { - Logger.Instance.Error("Unable to run netstat.exe. Open ports will not be available."); + Log.Error("Unable to run netstat.exe. Open ports will not be available."); return ProcessPorts; } @@ -114,22 +115,22 @@ private static List GetNetStatPorts() { if (!outputLine.StartsWith("Proto") && !outputLine.StartsWith("Active") && !String.IsNullOrWhiteSpace(outputLine)) { - Logger.Instance.Warn("Primary Parsing error when processing netstat.exe output: {0}", outputLine); + Log.Warning("Primary Parsing error when processing netstat.exe output: {0}", outputLine); } } } catch (Exception e) { - Logger.Instance.Warn("Secondary Parsing error when processing netstat.exe output: {0}", outputLine); - Logger.Instance.Warn(e.Message); - Logger.Instance.Warn(e.GetType().ToString()); + Log.Warning("Secondary Parsing error when processing netstat.exe output: {0}", outputLine); + Log.Warning(e.Message); + Log.Warning(e.GetType().ToString()); } } } } catch (Exception ex) { - Logger.Instance.Warn("Error processing open ports: {0}", ex.Message); + Log.Warning("Error processing open ports: {0}", ex.Message); } return ProcessPorts; }