Skip to content

Commit 5aa4453

Browse files
committedFeb 13, 2021
Fixed some logic with PS runspaces and tested all commands
1 parent 47ec66c commit 5aa4453

File tree

5 files changed

+329
-151
lines changed

5 files changed

+329
-151
lines changed
 

‎CIMplant/CIMplant.csproj

+1
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@
6767
<ItemGroup>
6868
<Compile Include="Commander.cs" />
6969
<Compile Include="Connector.cs" />
70+
<Compile Include="ExceptionLogging.cs" />
7071
<Compile Include="ExecuteWMIwithProvider.cs" />
7172
<Compile Include="ExecuteCIM.cs" />
7273
<Compile Include="ExecuteWMI.cs" />

‎CIMplant/ExceptionLogging.cs

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
using System;
2+
using System.Globalization;
3+
using System.IO;
4+
5+
namespace CIMplant
6+
{
7+
/// <summary>
8+
/// Summary description for ExceptionLogging
9+
/// Borrowed from https://www.c-sharpcorner.com/UploadFile/0c1bb2/logging-excetion-to-text-file/
10+
/// </summary>
11+
public static class ExceptionLogging
12+
{
13+
14+
private static string ErrorlineNo, Errormsg, extype, exurl, hostIp, ErrorLocation, HostAdd;
15+
16+
public static void SendErrorToText(Exception ex)
17+
{
18+
var line = Environment.NewLine + Environment.NewLine;
19+
20+
ErrorlineNo = ex.StackTrace.Substring(ex.StackTrace.Length - 7, 7);
21+
Errormsg = ex.GetType().Name;
22+
extype = ex.GetType().ToString();
23+
ErrorLocation = ex.Message;
24+
25+
try
26+
{
27+
string filepath = Directory.GetCurrentDirectory(); //Text File Path
28+
29+
if (!Directory.Exists(filepath))
30+
Directory.CreateDirectory(filepath);
31+
32+
filepath = filepath + DateTime.Today.ToString("dd-MM-yy") + ".txt"; //Text File Name
33+
34+
if (!File.Exists(filepath))
35+
File.Create(filepath).Dispose();
36+
37+
using (StreamWriter sw = File.AppendText(filepath))
38+
{
39+
string error = "Log Written Date:" + " " + DateTime.Now.ToString(CultureInfo.InvariantCulture) + line + "Error Line No :" + " " + ErrorlineNo + line + "Error Message:" + " " + Errormsg + line + "Exception Type:" + " " + extype + line + "Error Location :" + " " + ErrorLocation + line + " Error Page Url:" + " " + exurl + line + "User Host IP:" + " " + hostIp + line;
40+
sw.WriteLine("-----------Exception Details on " + " " + DateTime.Now.ToString(CultureInfo.InvariantCulture) + "-----------------");
41+
sw.WriteLine("-------------------------------------------------------------------------------------");
42+
sw.WriteLine(line);
43+
sw.WriteLine(error);
44+
sw.WriteLine("--------------------------------*End*------------------------------------------");
45+
sw.WriteLine(line);
46+
sw.Flush();
47+
sw.Close();
48+
}
49+
}
50+
catch (Exception e)
51+
{
52+
e.ToString();
53+
}
54+
}
55+
}
56+
}

‎CIMplant/ExecuteCIM.cs

+96-67
Original file line numberDiff line numberDiff line change
@@ -329,15 +329,20 @@ public object cat(Planter planter)
329329
return null;
330330
}
331331

332-
string command1 = "$data = (Get-Content " + path + " | Out-String).Trim()";
333-
const string command2 = @"$encdata = [Int[]][Char[]]$data -Join ','";
334-
const string command3 =
335-
@"$a = Get-WmiObject -Class Win32_OSRecoveryConfiguration; $a.DebugFilePath = $encdata; $a.Put()";
336-
337-
powershell.Commands.AddScript(command1, false);
338-
powershell.Commands.AddScript(command2, false);
339-
powershell.Commands.AddScript(command3, false);
340-
Collection<PSObject> result = powershell.Invoke();
332+
if (powershell.Runspace.ConnectionInfo != null)
333+
{
334+
string command1 = "$data = (Get-Content " + path + " | Out-String).Trim()";
335+
const string command2 = @"$encdata = [Int[]][Char[]]$data -Join ','";
336+
const string command3 =
337+
@"$a = Get-WmiObject -Class Win32_OSRecoveryConfiguration; $a.DebugFilePath = $encdata; $a.Put()";
338+
339+
powershell.Commands.AddScript(command1, false);
340+
powershell.Commands.AddScript(command2, false);
341+
powershell.Commands.AddScript(command3, false);
342+
Collection<PSObject> result = powershell.Invoke();
343+
}
344+
else
345+
wsman = false;
341346
}
342347
}
343348

@@ -481,11 +486,15 @@ public object download(Planter planter)
481486
powershell.Commands.AddScript(setEnv, false);
482487
}
483488

484-
powershell.Commands.AddScript(command1, false);
485-
powershell.Commands.AddScript(command2, false);
486-
powershell.Commands.AddScript(command3, false);
487-
powershell.Invoke();
488-
489+
if (powershell.Runspace.ConnectionInfo != null)
490+
{
491+
powershell.Commands.AddScript(command1, false);
492+
powershell.Commands.AddScript(command2, false);
493+
powershell.Commands.AddScript(command3, false);
494+
powershell.Invoke();
495+
}
496+
else
497+
wsman = false;
489498
}
490499
catch (PSRemotingTransportException)
491500
{
@@ -754,11 +763,15 @@ public object upload(Planter planter)
754763
@"[byte[]] $decoded = $decode -split ' '; Set-Content -Encoding byte -Force -Path '" +
755764
writePath + "' -Value $decoded";
756765

757-
powershell.Commands.AddScript(command1, false);
758-
powershell.Commands.AddScript(command2, false);
759-
powershell.Commands.AddScript(command3, false);
760-
powershell.Invoke();
761-
766+
if (powershell.Runspace.ConnectionInfo != null)
767+
{
768+
powershell.Commands.AddScript(command1, false);
769+
powershell.Commands.AddScript(command2, false);
770+
powershell.Commands.AddScript(command3, false);
771+
powershell.Invoke();
772+
}
773+
else
774+
wsman = false;
762775
}
763776
catch (PSRemotingTransportException)
764777
{
@@ -832,7 +845,7 @@ public object command_exec(Planter planter)
832845
{
833846
try
834847
{
835-
if (!string.IsNullOrEmpty(planter.Password?.ToString()))
848+
if (!string.IsNullOrEmpty(planter.System?.ToString()))
836849
powershell.Runspace = RunspaceCreate(planter);
837850
else
838851
{
@@ -857,46 +870,51 @@ public object command_exec(Planter planter)
857870
Console.WriteLine(e);
858871
}
859872

860-
string command1 = "$data = (" + command + " | Out-String).Trim()";
861-
const string command2 = @"$encdata = [Int[]][Char[]]$data -Join ','";
862-
const string command3 =
863-
@"$a = Get-WmiObject -Class Win32_OSRecoveryConfiguration; $a.DebugFilePath = $encdata; $a.Put()";
864-
865-
powershell.Commands.AddScript(command1, false);
866-
powershell.Commands.AddScript(command2, false);
867-
powershell.Commands.AddScript(command3, false);
868-
869-
// If running powershell.exe let's run it and not worry about the output otherwise it will hang for very long time
870-
if (noDebugCheck)
873+
if (powershell.Runspace.ConnectionInfo != null)
871874
{
872-
// start the timer and get a timeout
873-
DateTime startTime = DateTime.Now;
874-
IAsyncResult asyncPs = powershell.BeginInvoke();
875+
string command1 = "$data = (" + command + " | Out-String).Trim()";
876+
const string command2 = @"$encdata = [Int[]][Char[]]$data -Join ','";
877+
const string command3 =
878+
@"$a = Get-WmiObject -Class Win32_OSRecoveryConfiguration; $a.DebugFilePath = $encdata; $a.Put()";
879+
880+
powershell.Commands.AddScript(command1, false);
881+
powershell.Commands.AddScript(command2, false);
882+
powershell.Commands.AddScript(command3, false);
875883

876-
while (asyncPs.IsCompleted == false)
884+
// If running powershell.exe let's run it and not worry about the output otherwise it will hang for very long time
885+
if (noDebugCheck)
877886
{
878-
//Console.WriteLine("Waiting for pipeline to finish...");
879-
Thread.Sleep(5000);
887+
// start the timer and get a timeout
888+
DateTime startTime = DateTime.Now;
889+
IAsyncResult asyncPs = powershell.BeginInvoke();
880890

881-
// Check on our timeout here
882-
TimeSpan elasped = DateTime.Now.Subtract(startTime);
883-
if (elasped > timeout)
884-
break;
885-
}
891+
while (asyncPs.IsCompleted == false)
892+
{
893+
//Console.WriteLine("Waiting for pipeline to finish...");
894+
Thread.Sleep(5000);
886895

887-
//powershell.EndInvoke(asyncPs);
896+
// Check on our timeout here
897+
TimeSpan elasped = DateTime.Now.Subtract(startTime);
898+
if (elasped > timeout)
899+
break;
900+
}
901+
902+
//powershell.EndInvoke(asyncPs);
903+
}
904+
else
905+
{
906+
powershell.Invoke();
907+
}
888908
}
889909
else
890-
{
891-
powershell.Invoke();
892-
}
910+
wsman = false;
893911
}
894912
}
895913

896914
GetOut:
897915
if (wsman == false)
898916
{
899-
if (string.IsNullOrEmpty(planter.Password?.ToString()))
917+
if (string.IsNullOrEmpty(planter.System?.ToString()))
900918
{
901919
try
902920
{
@@ -1335,29 +1353,33 @@ public object remote_posh(Planter planter)
13351353
script = Regex.Replace(script, @"\bcalldllmainsc2\b", RandomString(10), RegexOptions.IgnoreCase);
13361354
script = Regex.Replace(script, @"\bcalldllmainsc3\b", RandomString(10), RegexOptions.IgnoreCase);
13371355

1338-
1339-
// This all works right now but if we see issues down the line with output we may need to throw the output in DebugFilePath property
1340-
// Will want to add in some obfuscation
1341-
powerShell.AddScript(script).AddScript("Invoke-Expression ; " + functionToRun);
1342-
Collection<PSObject> results;
1343-
try
1344-
{
1345-
results = powerShell?.Invoke();
1346-
}
1347-
catch (RemoteException e)
1356+
if (powerShell.Runspace.ConnectionInfo != null)
13481357
{
1349-
Messenger.ErrorMessage("[-] Error: Issues with PowerShell script, it may have been flagged by AV");
1350-
Console.WriteLine(e);
1351-
throw new CaughtByAvException(e.Message);
1352-
}
1353-
1354-
if (results != null)
1355-
foreach (PSObject result in results)
1358+
// This all works right now but if we see issues down the line with output we may need to throw the output in DebugFilePath property
1359+
// Will want to add in some obfuscation
1360+
powerShell.AddScript(script).AddScript("Invoke-Expression ; " + functionToRun);
1361+
Collection<PSObject> results;
1362+
try
13561363
{
1357-
Console.WriteLine(result);
1364+
results = powerShell?.Invoke();
1365+
}
1366+
catch (RemoteException e)
1367+
{
1368+
Messenger.ErrorMessage("[-] Error: Issues with PowerShell script, it may have been flagged by AV");
1369+
Console.WriteLine(e);
1370+
throw new CaughtByAvException(e.Message);
13581371
}
13591372

1360-
return true;
1373+
if (results != null)
1374+
foreach (PSObject result in results)
1375+
{
1376+
Console.WriteLine(result);
1377+
}
1378+
1379+
return true;
1380+
}
1381+
else
1382+
wsman = false;
13611383
}
13621384
}
13631385

@@ -2293,15 +2315,22 @@ public string CheckForFinishedDebugFilePath(string originalWmiProperty, CimSessi
22932315
bool warn = false;
22942316
string returnRecovery = null;
22952317
bool breakLoop = false;
2318+
int counter = 0;
22962319

22972320
do
22982321
{
22992322
string modifiedRecovery = GetOsRecovery(cimSession);
23002323
if (modifiedRecovery == originalWmiProperty)
23012324
{
23022325
Messenger.WarningMessage("DebugFilePath write not completed, sleeping for 10s...");
2303-
System.Threading.Thread.Sleep(10000);
2326+
Thread.Sleep(10000);
23042327
warn = true;
2328+
counter++;
2329+
if (counter > 12)
2330+
{
2331+
// We only want to run for 2 mins max
2332+
breakLoop = true;
2333+
}
23052334
}
23062335
else
23072336
{

0 commit comments

Comments
 (0)