Skip to content

Commit 0f97498

Browse files
authored
TryExecute (#457)
* Better Exception Handling in Collectors (#455) Fix #454 Fix #453 * Catch all collector Exceptions * Replace Execute with TryExecute (#456)
1 parent fee5e76 commit 0f97498

File tree

5 files changed

+102
-80
lines changed

5 files changed

+102
-80
lines changed

Cli/Program.cs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1056,7 +1056,10 @@ public static int RunCollectCommand(CollectCommandOptions opts)
10561056
{
10571057
DatabaseManager.BeginTransaction();
10581058

1059-
Task.Run(() => c.Execute());
1059+
Task.Run(() =>
1060+
{
1061+
c.TryExecute();
1062+
});
10601063

10611064
Thread.Sleep(1);
10621065

Lib/Collectors/BaseCollector.cs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ public abstract class BaseCollector : IPlatformRunnable
2020
{
2121
public ConcurrentStack<CollectObject> Results { get; } = new ConcurrentStack<CollectObject>();
2222
internal CollectCommandOptions opts = new CollectCommandOptions();
23-
public void Execute()
23+
public void TryExecute()
2424
{
2525
if (!CanRunOnPlatform())
2626
{
@@ -29,7 +29,14 @@ public void Execute()
2929
else
3030
{
3131
Start();
32-
ExecuteInternal();
32+
try
33+
{
34+
ExecuteInternal();
35+
}
36+
catch(Exception e)
37+
{
38+
Log.Debug("Failed to run {0} ({1}:{2})", GetType(), e.GetType(), e.Message);
39+
}
3340
Stop();
3441
}
3542
}

Lib/Collectors/ServiceCollector.cs

Lines changed: 77 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -36,96 +36,108 @@ public override bool CanRunOnPlatform()
3636
/// </summary>
3737
public void ExecuteWindows()
3838
{
39-
var fsc = new FileSystemCollector(new CollectCommandOptions() { SingleThread = opts.SingleThread });
40-
System.Management.SelectQuery sQuery = new System.Management.SelectQuery("select * from Win32_Service"); // where name = '{0}'", "MCShield.exe"));
41-
using System.Management.ManagementObjectSearcher mgmtSearcher = new System.Management.ManagementObjectSearcher(sQuery);
42-
foreach (System.Management.ManagementObject service in mgmtSearcher.Get())
39+
try
4340
{
44-
try
41+
System.Management.SelectQuery sQuery = new System.Management.SelectQuery("select * from Win32_Service"); // where name = '{0}'", "MCShield.exe"));
42+
using System.Management.ManagementObjectSearcher mgmtSearcher = new System.Management.ManagementObjectSearcher(sQuery);
43+
foreach (System.Management.ManagementObject service in mgmtSearcher.Get())
4544
{
46-
var val = service.GetPropertyValue("Name").ToString();
47-
if (val != null)
45+
try
4846
{
49-
var obj = new ServiceObject(val);
47+
var val = service.GetPropertyValue("Name").ToString();
48+
if (val != null)
49+
{
50+
var obj = new ServiceObject(val);
5051

51-
val = service.GetPropertyValue("AcceptPause")?.ToString();
52-
if (!string.IsNullOrEmpty(val))
53-
obj.AcceptPause = bool.Parse(val);
52+
val = service.GetPropertyValue("AcceptPause")?.ToString();
53+
if (!string.IsNullOrEmpty(val))
54+
obj.AcceptPause = bool.Parse(val);
5455

55-
val = service.GetPropertyValue("AcceptStop")?.ToString();
56-
if (!string.IsNullOrEmpty(val))
57-
obj.AcceptStop = bool.Parse(val);
56+
val = service.GetPropertyValue("AcceptStop")?.ToString();
57+
if (!string.IsNullOrEmpty(val))
58+
obj.AcceptStop = bool.Parse(val);
5859

59-
obj.Caption = service.GetPropertyValue("Caption")?.ToString();
60+
obj.Caption = service.GetPropertyValue("Caption")?.ToString();
6061

61-
val = service.GetPropertyValue("CheckPoint")?.ToString();
62-
if (!string.IsNullOrEmpty(val))
63-
obj.CheckPoint = uint.Parse(val, CultureInfo.InvariantCulture);
62+
val = service.GetPropertyValue("CheckPoint")?.ToString();
63+
if (!string.IsNullOrEmpty(val))
64+
obj.CheckPoint = uint.Parse(val, CultureInfo.InvariantCulture);
6465

65-
obj.CreationClassName = service.GetPropertyValue("CreationClassName")?.ToString();
66+
obj.CreationClassName = service.GetPropertyValue("CreationClassName")?.ToString();
6667

67-
val = service.GetPropertyValue("DelayedAutoStart")?.ToString();
68-
if (!string.IsNullOrEmpty(val))
69-
obj.DelayedAutoStart = bool.Parse(val);
68+
val = service.GetPropertyValue("DelayedAutoStart")?.ToString();
69+
if (!string.IsNullOrEmpty(val))
70+
obj.DelayedAutoStart = bool.Parse(val);
7071

71-
obj.Description = service.GetPropertyValue("Description")?.ToString();
72+
obj.Description = service.GetPropertyValue("Description")?.ToString();
7273

73-
val = service.GetPropertyValue("DesktopInteract")?.ToString();
74-
if (!string.IsNullOrEmpty(val))
75-
obj.DesktopInteract = bool.Parse(val);
74+
val = service.GetPropertyValue("DesktopInteract")?.ToString();
75+
if (!string.IsNullOrEmpty(val))
76+
obj.DesktopInteract = bool.Parse(val);
7677

77-
obj.DisplayName = service.GetPropertyValue("DisplayName")?.ToString();
78-
obj.ErrorControl = service.GetPropertyValue("ErrorControl")?.ToString();
78+
obj.DisplayName = service.GetPropertyValue("DisplayName")?.ToString();
79+
obj.ErrorControl = service.GetPropertyValue("ErrorControl")?.ToString();
7980

80-
val = service.GetPropertyValue("ExitCode")?.ToString();
81-
if (!string.IsNullOrEmpty(val))
82-
obj.ExitCode = uint.Parse(val, CultureInfo.InvariantCulture);
81+
val = service.GetPropertyValue("ExitCode")?.ToString();
82+
if (!string.IsNullOrEmpty(val))
83+
obj.ExitCode = uint.Parse(val, CultureInfo.InvariantCulture);
8384

84-
if (DateTime.TryParse(service.GetPropertyValue("InstallDate")?.ToString(), out DateTime dateTime))
85-
{
86-
obj.InstallDate = dateTime;
87-
}
88-
obj.PathName = service.GetPropertyValue("PathName")?.ToString();
85+
if (DateTime.TryParse(service.GetPropertyValue("InstallDate")?.ToString(), out DateTime dateTime))
86+
{
87+
obj.InstallDate = dateTime;
88+
}
89+
obj.PathName = service.GetPropertyValue("PathName")?.ToString();
8990

90-
val = service.GetPropertyValue("ProcessId")?.ToString();
91-
if (!string.IsNullOrEmpty(val))
92-
obj.ProcessId = uint.Parse(val, CultureInfo.InvariantCulture);
91+
val = service.GetPropertyValue("ProcessId")?.ToString();
92+
if (!string.IsNullOrEmpty(val))
93+
obj.ProcessId = uint.Parse(val, CultureInfo.InvariantCulture);
9394

94-
val = service.GetPropertyValue("ServiceSpecificExitCode")?.ToString();
95-
if (!string.IsNullOrEmpty(val))
96-
obj.ServiceSpecificExitCode = uint.Parse(val, CultureInfo.InvariantCulture);
95+
val = service.GetPropertyValue("ServiceSpecificExitCode")?.ToString();
96+
if (!string.IsNullOrEmpty(val))
97+
obj.ServiceSpecificExitCode = uint.Parse(val, CultureInfo.InvariantCulture);
9798

98-
obj.ServiceType = service.GetPropertyValue("ServiceType")?.ToString();
99+
obj.ServiceType = service.GetPropertyValue("ServiceType")?.ToString();
99100

100-
val = service.GetPropertyValue("Started").ToString();
101-
if (!string.IsNullOrEmpty(val))
102-
obj.Started = bool.Parse(val);
101+
val = service.GetPropertyValue("Started").ToString();
102+
if (!string.IsNullOrEmpty(val))
103+
obj.Started = bool.Parse(val);
103104

104-
obj.StartMode = service.GetPropertyValue("StartMode")?.ToString();
105-
obj.StartName = service.GetPropertyValue("StartName")?.ToString();
106-
obj.State = service.GetPropertyValue("State")?.ToString();
107-
obj.Status = service.GetPropertyValue("Status")?.ToString();
108-
obj.SystemCreationClassName = service.GetPropertyValue("SystemCreationClassName")?.ToString();
109-
obj.SystemName = service.GetPropertyValue("SystemName")?.ToString();
105+
obj.StartMode = service.GetPropertyValue("StartMode")?.ToString();
106+
obj.StartName = service.GetPropertyValue("StartName")?.ToString();
107+
obj.State = service.GetPropertyValue("State")?.ToString();
108+
obj.Status = service.GetPropertyValue("Status")?.ToString();
109+
obj.SystemCreationClassName = service.GetPropertyValue("SystemCreationClassName")?.ToString();
110+
obj.SystemName = service.GetPropertyValue("SystemName")?.ToString();
110111

111-
val = service.GetPropertyValue("TagId")?.ToString();
112-
if (!string.IsNullOrEmpty(val))
113-
obj.TagId = uint.Parse(val, CultureInfo.InvariantCulture);
112+
val = service.GetPropertyValue("TagId")?.ToString();
113+
if (!string.IsNullOrEmpty(val))
114+
obj.TagId = uint.Parse(val, CultureInfo.InvariantCulture);
114115

115-
val = service.GetPropertyValue("WaitHint")?.ToString();
116-
if (!string.IsNullOrEmpty(val))
117-
obj.WaitHint = uint.Parse(val, CultureInfo.InvariantCulture);
116+
val = service.GetPropertyValue("WaitHint")?.ToString();
117+
if (!string.IsNullOrEmpty(val))
118+
obj.WaitHint = uint.Parse(val, CultureInfo.InvariantCulture);
118119

119-
Results.Push(obj);
120+
Results.Push(obj);
121+
}
122+
}
123+
catch (Exception e) when (
124+
e is TypeInitializationException ||
125+
e is PlatformNotSupportedException)
126+
{
127+
Log.Warning(Strings.Get("CollectorNotSupportedOnPlatform"), GetType().ToString());
128+
}
129+
catch (Exception e)
130+
{
131+
Log.Warning(e, "Failed to grok Service Collector object at {0}.",service.Path);
120132
}
121-
}
122-
catch (Exception e) when (
123-
e is TypeInitializationException ||
124-
e is PlatformNotSupportedException)
125-
{
126-
Log.Warning(Strings.Get("CollectorNotSupportedOnPlatform"), GetType().ToString());
127133
}
128134
}
135+
catch (Exception e)
136+
{
137+
Log.Warning(e, "Failed to run Service Collector.");
138+
}
139+
140+
var fsc = new FileSystemCollector(new CollectCommandOptions() { SingleThread = opts.SingleThread });
129141

130142
foreach (var file in Directory.EnumerateFiles("C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Startup"))
131143
{

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ All data collected is stored in a set of local SQLite databases.
5656
Run the following commands in an Administrator Shell (or as root). Replace ```asa``` with ```asa.exe``` as appropriate for your platform.
5757

5858
### CLI Mode
59-
To start a default all collectors run: ```asa collect```
59+
To start a default all collectors run: ```asa collect -a```
6060

6161
To compare the last two collection runs: ```asa export-collect```
6262

Tests/CollectorTests.cs

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ public void TestFileCollector()
6363
}
6464

6565
var fsc = new FileSystemCollector(opts);
66-
fsc.Execute();
66+
fsc.TryExecute();
6767

6868
Assert.IsTrue(fsc.Results.Any(x => x is FileSystemObject FSO && FSO.Path.EndsWith("AsaLibTesterJavaClass") && FSO.IsExecutable == true));
6969
Assert.IsTrue(fsc.Results.Any(x => x is FileSystemObject FSO && FSO.Path.EndsWith("AsaLibTesterMZ") && FSO.IsExecutable == true));
@@ -93,7 +93,7 @@ public void TestEventCollectorWindows()
9393
eventLog.WriteEntry("This Log Entry was created for testing the Attack Surface Analyzer library.", EventLogEntryType.Warning, 101, 1);
9494

9595
var fsc = new EventLogCollector(new CollectCommandOptions());
96-
fsc.Execute();
96+
fsc.TryExecute();
9797

9898
EventLog.DeleteEventSource(source);
9999
EventLog.Delete(logname);
@@ -108,7 +108,7 @@ public void TestEventCollectorWindows()
108108
public void TestCertificateCollectorWindows()
109109
{
110110
var fsc = new CertificateCollector();
111-
fsc.Execute();
111+
fsc.TryExecute();
112112

113113
Assert.IsTrue(fsc.Results.Where(x => x.ResultType == RESULT_TYPE.CERTIFICATE).Count() > 0);
114114
}
@@ -137,7 +137,7 @@ public void TestPortCollectorWindows()
137137
Console.WriteLine("Failed to open port.");
138138
}
139139
var fsc = new OpenPortCollector();
140-
fsc.Execute();
140+
fsc.TryExecute();
141141
server.Stop();
142142

143143
Assert.IsTrue(fsc.Results.Any(x => x is OpenPortObject OPO && OPO.Port == 13000));
@@ -154,7 +154,7 @@ public void TestFirewallCollectorOSX()
154154
_ = ExternalCommandRunner.RunExternalCommand("/usr/libexec/ApplicationFirewall/socketfilterfw", "--add /bin/bash");
155155

156156
var fwc = new FirewallCollector();
157-
fwc.Execute();
157+
fwc.TryExecute();
158158
_ = ExternalCommandRunner.RunExternalCommand("/usr/libexec/ApplicationFirewall/socketfilterfw", "--remove /bin/bash");
159159
Assert.IsTrue(fwc.Results.Any(x => x is FirewallObject FWO && FWO.ApplicationName == "/bin/bash"));
160160
}
@@ -171,7 +171,7 @@ public void TestFirewallCollectorLinux()
171171
var result = ExternalCommandRunner.RunExternalCommand("iptables", "-A INPUT -p tcp --dport 19999 -j DROP");
172172

173173
var fwc = new FirewallCollector();
174-
fwc.Execute();
174+
fwc.TryExecute();
175175

176176
Assert.IsTrue(fwc.Results.Any(x => x is FirewallObject FWO && FWO.LocalPorts.Contains("19999")));
177177

@@ -204,7 +204,7 @@ public void TestFirewallCollectorWindows()
204204
FirewallManager.Instance.Rules.Add(rule);
205205

206206
var fwc = new FirewallCollector();
207-
fwc.Execute();
207+
fwc.TryExecute();
208208

209209
Assert.IsTrue(fwc.Results.Any(x => x is FirewallObject FWO && FWO.LocalPorts.Contains("9999")));
210210
Assert.IsTrue(fwc.Results.Any(x => x is FirewallObject FWO && FWO.ApplicationName is string && FWO.ApplicationName.Equals(@"C:\MyApp.exe")));
@@ -243,7 +243,7 @@ public void TestRegistryCollectorWindows()
243243
key.Close();
244244

245245
var rc = new RegistryCollector(new List<(RegistryHive, string)>() { (RegistryHive.CurrentUser, name) }, new CollectCommandOptions() { SingleThread = true });
246-
rc.Execute();
246+
rc.TryExecute();
247247

248248
Registry.CurrentUser.DeleteSubKey(name);
249249

@@ -267,7 +267,7 @@ public void TestServiceCollectorWindows()
267267
ExternalCommandRunner.RunExternalCommand("sc.exe", cmd);
268268

269269
var sc = new ServiceCollector();
270-
sc.Execute();
270+
sc.TryExecute();
271271

272272
Assert.IsTrue(sc.Results.Any(x => x is ServiceObject RO && RO.Name.Equals(serviceName)));
273273

@@ -286,7 +286,7 @@ public void TestComObjectCollector()
286286
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
287287
{
288288
var coc = new ComObjectCollector(new CollectCommandOptions());
289-
coc.Execute();
289+
coc.TryExecute();
290290

291291
Assert.IsTrue(coc.Results.Any(x => x is ComObject y && y.x86_Binary != null));
292292
}
@@ -308,7 +308,7 @@ public void TestUserCollectorWindows()
308308
ExternalCommandRunner.RunExternalCommand("net", cmd);
309309

310310
var uac = new UserAccountCollector();
311-
uac.Execute();
311+
uac.TryExecute();
312312

313313
Assert.IsTrue(uac.Results.Any(x => x is UserAccountObject y && y.Name.Equals(user)));
314314

0 commit comments

Comments
 (0)