static string GetWMIProperty(string host, string username, string password) { string wmiNameSpace = "root\\cimv2"; ConnectionOptions options = new ConnectionOptions(); if (!String.IsNullOrEmpty(username)) { options.Username = username; options.Password = password; } ManagementScope scope = new ManagementScope(String.Format("\\\\{0}\\{1}", host, wmiNameSpace), options); string wmiQuery = @"SELECT DebugFilePath FROM Win32_OSRecoveryConfiguration"; try { scope.Connect(); ObjectQuery query = new ObjectQuery(wmiQuery); string WMIProperty = ""; ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query); ManagementObjectCollection data = searcher.Get(); foreach (ManagementObject result in data) { System.Management.PropertyDataCollection props = result.Properties; foreach (System.Management.PropertyData prop in props) { WMIProperty = prop.Value.ToString(); } } return(WMIProperty); } catch (Exception ex) { return(""); } }
internal ManagementBaseObject(IWbemClassObjectFreeThreaded wbemObject) { this.wbemObject = wbemObject; this.properties = null; this.systemProperties = null; this.qualifiers = null; }
public void Handle(string wmiMethod, List<PropertyDataObject> inParams, out PropertyDataCollection outParams) { outParams = null; ManagementBaseObject inParamsCollection = _managementClass.GetMethodParameters(wmiMethod); foreach (var inParam in inParams) { inParamsCollection[inParam.Name] = inParam.Value; } ManagementBaseObject outParamsCollection = _managementClass.InvokeMethod(wmiMethod, inParamsCollection, null); long returnValue; try { returnValue = long.Parse(outParamsCollection["returnValue"].ToString()); } catch (Exception ex) { throw new ProcessInstrumentationException(ExceptionMessages.ManagementObjectParseFail, ex); } outParams = outParamsCollection.Properties; }
private static List <string> GetPrinters() { List <string> printerNames = new List <string>(); // Use the ObjectQuery to get the list of configured printers System.Management.ObjectQuery oquery = new System.Management.ObjectQuery("SELECT * FROM Win32_Printer"); System.Management.ManagementObjectSearcher mosearcher = new System.Management.ManagementObjectSearcher(oquery); System.Management.ManagementObjectCollection moc = mosearcher.Get(); foreach (ManagementObject mo in moc) { System.Management.PropertyDataCollection pdc = mo.Properties; foreach (System.Management.PropertyData pd in pdc) { if (!(bool)mo["Network"]) { bool bExists = printerNames.Contains(mo["DeviceID"].ToString()); if (!bExists) { printerNames.Add(mo["DeviceID"].ToString()); } } } } return(printerNames); }
static void RemoteWMIProcessKill(string host, string processNameOrPid, string username, string password) { int pid = 0; bool parseResult = int.TryParse(processNameOrPid, out pid); string wmiNameSpace = "root\\cimv2"; ConnectionOptions options = new ConnectionOptions(); Console.WriteLine("\r\n Scope: \\\\{0}\\{1}", host, wmiNameSpace); if (!String.IsNullOrEmpty(username)) { Console.WriteLine(" User credentials: {0}", username); options.Username = username; options.Password = password; } Console.WriteLine(); ManagementScope scope = new ManagementScope(String.Format("\\\\{0}\\{1}", host, wmiNameSpace), options); try { scope.Connect(); string queryStr = ""; if (pid == 0) { queryStr = $"Select * from Win32_Process where Name='{processNameOrPid}'"; } else { queryStr = $"Select * from Win32_Process where ProcessId='{pid}'"; } ObjectQuery query = new ObjectQuery(queryStr); ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query); ManagementObjectCollection data = searcher.Get(); Console.WriteLine(); if (data.Count == 0) { Console.WriteLine($"[X] No process found with the name/PID '{processNameOrPid}'\r\n"); } else { foreach (ManagementObject result in data) { System.Management.PropertyDataCollection props = result.Properties; Console.WriteLine($"[+] Terminating {props["name"].Value} (PID {props["ProcessId"].Value})\r\n"); result.InvokeMethod("Terminate", new object[] { }); } } } catch (Exception ex) { Console.WriteLine(String.Format(" Exception : {0}", ex.Message)); } }
//General query. public WMI(String wmiClass, String[] arrayToGet) { this.className = wmiClass; this.arrayToGet = arrayToGet; this.arrayProp = CustomGetValues(); if (this.arrayProp != null) this.dictProp = CustomTransformProperties(this.arrayProp); }
public static bool LocalWMIQuery(string wmiQuery, out string[] results, string wmiNameSpace = "") { bool bRet = false; List <string> output = new List <string>(); ManagementObjectSearcher wmiData = null; try { if (String.IsNullOrEmpty(wmiNameSpace)) { wmiData = new ManagementObjectSearcher(wmiQuery); } else { wmiData = new ManagementObjectSearcher(wmiNameSpace, wmiQuery); } ManagementObjectCollection data = wmiData.Get(); foreach (ManagementObject result in data) { System.Management.PropertyDataCollection props = result.Properties; foreach (System.Management.PropertyData prop in props) { string propValue = String.Format("{0}", prop.Value); // wrap long output to 80 lines if (!String.IsNullOrEmpty(propValue) && (propValue.Length > 90)) { bool header = false; foreach (string line in Split(propValue, 80)) { if (!header) { output.Add(String.Format("{0,30} : {1}", prop.Name, line)); } else { output.Add(String.Format("{0,30} {1}", "", line)); } header = true; } } else { output.Add(String.Format("{0,30} : {1}", prop.Name, prop.Value)); } } } bRet = true; } catch (Exception ex) { output.Add(String.Format("Exception : {0}", ex.Message)); } results = output.ToArray(); return(bRet); }
static void LocalWMIQuery(string wmiQuery, string wmiNameSpace = "") { ManagementObjectSearcher wmiData = null; try { if (String.IsNullOrEmpty(wmiNameSpace)) { wmiData = new ManagementObjectSearcher(wmiQuery); } else { wmiData = new ManagementObjectSearcher(wmiNameSpace, wmiQuery); } ManagementObjectCollection data = wmiData.Get(); Console.WriteLine(); foreach (ManagementObject result in data) { System.Management.PropertyDataCollection props = result.Properties; foreach (System.Management.PropertyData prop in props) { string propValue = String.Format("{0}", prop.Value); // wrap long output to 80 lines if (!String.IsNullOrEmpty(propValue) && (propValue.Length > 90)) { bool header = false; foreach (string line in Split(propValue, 80)) { if (!header) { Console.WriteLine(String.Format("{0,30} : {1}", prop.Name, line)); } else { Console.WriteLine(String.Format("{0,30} {1}", "", line)); } header = true; } } else { Console.WriteLine(String.Format("{0,30} : {1}", prop.Name, prop.Value)); } } Console.WriteLine(); } } catch (Exception ex) { Console.WriteLine(String.Format(" Exception : {0}", ex.Message)); } }
//Single Query. public WMI(String wmiClass, String select, String[] arrayToGet) { this.className = wmiClass; this.select = select; if (this.className == AppConstants.DISK_CLASS) //Si és disk. this.select = "Win32_LogicalDisk.DeviceID=\"" + GetInstalledDrive() + "\""; this.arrayToGet = arrayToGet; this.arrayProp = CustomGetValues(true); if (this.arrayProp != null) this.dictProp = CustomTransformProperties(this.arrayProp); }
protected ManagementBaseObject(SerializationInfo info, StreamingContext context) { this._wbemObject = info.GetValue("wbemObject", typeof(IWbemClassObjectFreeThreaded)) as IWbemClassObjectFreeThreaded; if (this._wbemObject == null) { throw new SerializationException(); } this.properties = null; this.systemProperties = null; this.qualifiers = null; }
public static bool RemoteWMIQuery(string host, string wmiQuery, out string[] results, string wmiNameSpace = "", string username = "", string password = "") { bool bRet = false; List <string> output = new List <string>(); if (string.IsNullOrEmpty(wmiNameSpace)) { wmiNameSpace = "root\\cimv2"; } ConnectionOptions options = new ConnectionOptions(); output.Add(string.Format("Scope: \\\\{0}\\{1}", host, wmiNameSpace)); if (!String.IsNullOrEmpty(username)) { output.Add(string.Format("User credentials: {0}", username)); options.Username = username; options.Password = password; } output.Add(""); ManagementScope scope = new ManagementScope(String.Format("\\\\{0}\\{1}", host, wmiNameSpace), options); try { scope.Connect(); ObjectQuery query = new ObjectQuery(wmiQuery); ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query); ManagementObjectCollection data = searcher.Get(); output.Add(""); foreach (ManagementObject result in data) { System.Management.PropertyDataCollection props = result.Properties; foreach (System.Management.PropertyData prop in props) { output.Add(String.Format("{0,30} : {1}", prop.Name, prop.Value)); } output.Add(""); } bRet = true; } catch (Exception ex) { output.Add(String.Format("Exception : {0}", ex.Message)); } results = output.ToArray(); return(bRet); }
public static bool RemoteWMIExecute(string host, string command, out string[] results, string username = "", string password = "") { bool bRet = false; List <string> output = new List <string>(); string wmiNameSpace = "root\\cimv2"; ConnectionOptions options = new ConnectionOptions(); output.Add(string.Format("Host : {0}", host)); output.Add(string.Format("Command : {0}", command)); if (!String.IsNullOrEmpty(username)) { output.Add(string.Format("User credentials : {0}", username)); options.Username = username; options.Password = password; } else { options.Authority = "kerberos:LAB"; } output.Add(""); ManagementScope scope = new ManagementScope(String.Format("\\\\{0}\\{1}", host, wmiNameSpace), options); try { scope.Connect(); var wmiProcess = new ManagementClass(scope, new ManagementPath("Win32_Process"), new ObjectGetOptions()); ManagementBaseObject inParams = wmiProcess.GetMethodParameters("Create"); System.Management.PropertyDataCollection properties = inParams.Properties; inParams["CommandLine"] = command; ManagementBaseObject outParams = wmiProcess.InvokeMethod("Create", inParams, null); output.Add(string.Format("Creation of process returned : {0}", outParams["returnValue"])); output.Add(string.Format("Process ID : {0}", outParams["processId"])); bRet = true; } catch (Exception ex) { output.Add(String.Format("Exception : {0}", ex.Message)); } results = output.ToArray(); return(bRet); }
static void RemoteWMIQuery(string host, string wmiQuery, string wmiNameSpace, string username, string password) { if (wmiNameSpace == "") { wmiNameSpace = "root\\cimv2"; } ConnectionOptions options = new ConnectionOptions(); Console.WriteLine("\r\n Scope: \\\\{0}\\{1}", host, wmiNameSpace); if (!String.IsNullOrEmpty(username)) { Console.WriteLine(" User credentials: {0}", username); options.Username = username; options.Password = password; } Console.WriteLine(); ManagementScope scope = new ManagementScope(String.Format("\\\\{0}\\{1}", host, wmiNameSpace), options); try { scope.Connect(); ObjectQuery query = new ObjectQuery(wmiQuery); ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query); ManagementObjectCollection data = searcher.Get(); Console.WriteLine(); foreach (ManagementObject result in data) { System.Management.PropertyDataCollection props = result.Properties; foreach (System.Management.PropertyData prop in props) { Console.WriteLine(String.Format("{0,30} : {1}", prop.Name, prop.Value)); } Console.WriteLine(); } } catch (Exception ex) { Console.WriteLine(String.Format(" Exception : {0}", ex.Message)); } }
static void RemoteWMIExecute(string host, string command, string username, string password) { string wmiNameSpace = "root\\cimv2"; ConnectionOptions options = new ConnectionOptions(); Console.WriteLine("\r\n Host : {0}", host); Console.WriteLine(" Command : {0}", command); if (!String.IsNullOrEmpty(username)) { Console.WriteLine(" User credentials : {0}", username); options.Username = username; options.Password = password; } Console.WriteLine(); ManagementScope scope = new ManagementScope(String.Format("\\\\{0}\\{1}", host, wmiNameSpace), options); try { scope.Connect(); var wmiProcess = new ManagementClass(scope, new ManagementPath("Win32_Process"), new ObjectGetOptions()); ManagementBaseObject inParams = wmiProcess.GetMethodParameters("Create"); System.Management.PropertyDataCollection properties = inParams.Properties; inParams["CommandLine"] = command; ManagementBaseObject outParams = wmiProcess.InvokeMethod("Create", inParams, null); Console.WriteLine(" Creation of process returned : {0}", outParams["returnValue"]); Console.WriteLine(" Process ID : {0}\r\n", outParams["processId"]); } catch (Exception ex) { Console.WriteLine(String.Format(" Exception : {0}", ex.Message)); } }
public static DataTable dtlistaClasse(string cls, string cls_SEL, string srv, string usr, string pwd) { try { MPSfwk.Model.Server s = new MPSfwk.Model.Server(); s.IPHOST = srv; s.USUARIO = usr; s.SENHA = pwd; ManagementScope ms = scopeMgmt(true, s); //true = testa a conexao remota, senao // acaba retornando a local*** // extrai as classes localmente... //teste de conexao... if (ms == null) { return(null); } ManagementObjectSearcher srcd; // //testa se a Classe possui o Host ao inves do IP, se for muda o LocalAccount string aux_qry = ""; if ((srv.IndexOf(".") == -1) && (cls_SEL.ToUpper().IndexOf("LOCALACCOUNT = TRUE") > 0) && (srv.ToUpper() != "LOCALHOST") ) { aux_qry = cls_SEL.ToUpper().Replace("LOCALACCOUNT = TRUE", ("Domain = '" + srv.ToUpper() + "'")); } else { aux_qry = cls_SEL; } // //MPS teste - 10/out Console.WriteLine("DEBUG - aux_qry = " + aux_qry); // srcd = new ManagementObjectSearcher(ms, new ObjectQuery(aux_qry)); ManagementObjectCollection moc = srcd.Get(); //Cria tabela para preencher os campos DataTable dt1 = new DataTable(); dt1.TableName = cls; //teste... string aux_cls = ""; string[] aux = cls_SEL.Split(' '); if (aux.Length == 3) { aux_cls = aux[3]; } else { for (int i = 1; i < aux.Length; i++) { if (aux[i].ToUpper() == "FROM") { aux_cls = aux[i + 1]; break; } } } //Preenche o Grid com as colunas da classe WMI //(Caso haja campos determinados, seleciona somente os campos determinados...) // //ordena, conforme entrada.. string[] ordem = null; if (cls_SEL.IndexOf("*") > 0) { var wmiClasse = new ManagementClass(aux_cls); foreach (var prop in wmiClasse.Properties) { if ((cls_SEL.IndexOf(prop.Name) > 0) || (cls_SEL.IndexOf("*") > 0)) { dt1.Columns.Add(prop.Name); } } } else { int pos1 = cls_SEL.ToUpper().IndexOf("SELECT") + 6; int pos2 = cls_SEL.ToUpper().IndexOf("FROM"); if (pos1 < pos2) { if (cls_SEL.IndexOf(",") > 0) { ordem = cls_SEL.Substring(pos1, (pos2 - pos1)).Trim().Split(',', ' '); } else { ordem[0] = cls_SEL.Substring(pos1, (pos2 - pos1)); } // //Preenche as colunas com os campos determinados... for (int i = 0; i < ordem.Length; i++) { if (ordem[i] != "") { dt1.Columns.Add(ordem[i]); } } } } //Preenche o Grid com os valores da classe WMI foreach (ManagementObject mo in moc) { DataRow dr = dt1.NewRow(); System.Management.PropertyDataCollection pdc = mo.Properties; foreach (System.Management.PropertyData pd in pdc) { dr[pd.Name] = pd.Value; } dt1.Rows.Add(dr); } // // return(dt1); } catch (UnauthorizedAccessException) { return(null); } catch (ManagementException) { return(null); } }
private void getInstalledPrinters() { // Use the ObjectQuery to get the list of configured printers System.Management.ObjectQuery oquery = new System.Management.ObjectQuery("SELECT * FROM Win32_Printer"); System.Management.ManagementObjectSearcher mosearcher = new System.Management.ManagementObjectSearcher(oquery); System.Management.ManagementObjectCollection moc = mosearcher.Get(); Console.WriteLine(new String('*', 20)); listInstalledprinters.Clear(); foreach (ManagementObject mo in moc) { if ((bool)mo["Network"]) { System.Management.PropertyDataCollection pdc = mo.Properties; //Console.WriteLine(pdc["DeviceID"].Value); String printerName = (string)pdc["ShareName"].Value; String location = (string)pdc["Location"].Value; String driverName = (string)pdc["DriverName"].Value; String unc = (string)pdc["Name"].Value; listInstalledprinters.Add(unc); ListViewItem lvi = new ListViewItem(printerName); lvi.SubItems.Add(location); lvi.SubItems.Add(driverName); lvi.SubItems.Add(unc); lvi.Name = unc; // <-- key if (listViewInstalledPrinters.InvokeRequired) { listViewInstalledPrinters.Invoke(new AddListViewItemCallback(ListViewAdd), new object[] { listViewInstalledPrinters, lvi }); } else { ListViewAdd(listViewInstalledPrinters, lvi); } /* * foreach (System.Management.PropertyData pd in pdc) * { * Console.WriteLine("{0} = {1}", pd.Name, mo[pd.Name]); * } */ } } if (listViewInstalledPrinters.InvokeRequired) { listViewInstalledPrinters.Invoke(new CleanupInstalledPrintersCallback(CleanupInstalledPrinters)); } else { CleanupInstalledPrinters(); } }
static void Main() { bool exit = false; while (exit == false) { Console.Clear(); Console.WriteLine("\n===== y emu hard? =====\n"); Console.Write("\t[1] cmd.exe /c (T1059.003)\n\t[2] powershell - c (T1059.001)\n\t[3] Unmanaged PowerShell aka PS w/o PowerShell.exe (T1059.001)\n\t[4] CreateProcess() API (T1106)\n\t[5] WinExec() API (T1106)\n\t[6] ShellExecute (T1106)\n\t[7] Windows Management Instrumentation (T1047)\n\t[8] Windows Script Host (T1059.005)\n\t[9] Windows Fiber (research-based)\n\t[10] WMIC XSL Script/Squiblytwo (T1220)\n\nSelect an execution procedure (or exit): "); string exec = Console.ReadLine().ToLower(); switch (exec) { case "1": bool cmd = true; while (cmd) { Console.Clear(); Console.WriteLine("\n===== cmd.exe /c execution =====\n"); Console.Write("cmd.exe /c [magic]? <<< please provide magic (or back): "); string command = Console.ReadLine().ToLower(); if (command == "back") { Console.Clear(); Console.WriteLine("===== \"So the pie isn't perfect? Cut it into wedges. Stay in control, and never panic.\" --Martha Stewart ====="); Thread.Sleep(3000); cmd = false; }//end if else { Console.Write("\nAre you sure you want to execute:\n\tcmd.exe /c " + command + "\n\n[y/n/q]? "); string confirm = Console.ReadLine().ToLower(); switch (confirm) { case "y": Console.Clear(); Console.WriteLine("Executing cmd.exe /c " + command + "\n"); cliExec("cmd", command); Console.Write("\nPress enter to continue "); Console.ReadLine(); break; case "n": break; case "q": Console.Clear(); Console.WriteLine("===== No one likes a quiter... ====="); Thread.Sleep(3000); cmd = false; break; default: Console.WriteLine("\nMight want to rethink that last one..."); Thread.Sleep(3000); break; }//end swtich }//end else }//end while break; case "2": bool ps = true; while (ps) { Console.Clear(); Console.WriteLine("\n===== powershell.exe -c execution =====\n"); Console.Write("powershell.exe -c [sauce]? <<< please provide sauce (or back): "); string command = Console.ReadLine().ToLower(); if (command == "back") { Console.Clear(); Console.WriteLine("===== \"People say nothing is impossible, but I do nothing every day.\" --Winnie the Pooh ====="); Thread.Sleep(3000); ps = false; }//end if else { Console.Write("\nAre you sure you want to execute:\n\tpowershell.exe -c " + command + "\n\n[y/n/q]? "); string confirm = Console.ReadLine().ToLower(); switch (confirm) { case "y": Console.Clear(); Console.WriteLine("Executing powershell.exe -c " + command + "\n"); cliExec("powershell", command); Console.Write("\nPress enter to continue "); Console.ReadLine(); break; case "n": break; case "q": Console.Clear(); Console.WriteLine("===== There is no try, only quit... ====="); Thread.Sleep(3000); ps = false; break; default: Console.WriteLine("\nDon't be weird..."); Thread.Sleep(3000); break; }//end swtich }//end else }//end while break; case "3": bool noPs = true; while (noPs) { Console.Clear(); Console.WriteLine("\n===== Unmanaged PowerShell execution =====\n"); Console.Write("\"powershell.exe -c\" [oomph]? <<< but not really,\n\twarning: commands that include CLIs with no args such as just \"cmd\" or \"powershell\" may hang\n\tplease provice oomph (or back): "); string command = Console.ReadLine().ToLower(); if (command == "back") { Console.Clear(); Console.WriteLine("===== \"They say stay in the lines, but there's always something better on the other side.\" --John Mayer ====="); Thread.Sleep(3000); noPs = false; }//end if else { Console.Write("\nAre you sure you want to execute \"" + command + "\" using Unmanaged PowerShell\n\n[y/n/q]? "); string confirm = Console.ReadLine().ToLower(); switch (confirm) { case "y": Console.Clear(); Process currentProcess = Process.GetCurrentProcess(); Console.WriteLine("Executing \"" + command + "\" using Unmanaged PowerShell\n"); //thank you https://github.com/Ben0xA/AwesomerShell Runspace rs = RunspaceFactory.CreateRunspace(); rs.Open(); PowerShell power = PowerShell.Create(); power.Runspace = rs; power.AddScript(command); Collection<PSObject> output = power.Invoke(); Console.WriteLine("PS \"" + command + "\"" + " executed within " + currentProcess.Id + " at " + DateTime.Now.ToString("HH:mm:ss tt") + "\n"); Console.WriteLine("\n==== Output/Error(s) =====\n"); if (output != null) { foreach (PSObject rtnItem in output) { Console.WriteLine(rtnItem.ToString()); }//end foreach }//end if trackANDkill((int) currentProcess.Id); rs.Close(); Console.Write("\nPress enter to continue "); Console.ReadLine(); break; case "n": break; case "q": Console.Clear(); Console.WriteLine("===== Quiting is not giving up... ====="); Thread.Sleep(3000); noPs = false; break; default: Console.WriteLine("\nThat's a paddlin..."); Thread.Sleep(3000); break; }//end swtich }//end else }//end while break; case "4": bool cp = true; while (cp) { Console.Clear(); Console.WriteLine("\n===== CreateProcess() API execution =====\n"); Console.Write("API needs an application with full path and args (ex: C:\\Windows\\System32\\cmd.exe /c calc)\n\tplease oblige (or back): "); string command = Console.ReadLine().ToLower(); if (command == "back") { Console.Clear(); Console.WriteLine("===== \"There's no such thing as perfect...Even with your imperfections, you can do anything.\" --Bathtub Barracuda ====="); Thread.Sleep(3000); cp = false; }//end if else { string[] full = command.Split(' '); string app = ""; string param = ""; int count = 0; foreach (string i in full) { if (count == 0) app = i; else if (count == 1) param = i; else param += " " + i; count++; }//end foreach Console.Write("\nAre you sure you want to execute:\n\t" + app + " with parameters \"" + param + "\" using CreateProcess()\n\n[y/n/q]? "); string confirm = Console.ReadLine().ToLower(); switch (confirm) { case "y": Console.Clear(); STARTUPINFO si = new STARTUPINFO(); PROCESS_INFORMATION pi = new PROCESS_INFORMATION(); Console.WriteLine("Executing " + app + " with params \"" + param + "\" using CreateProcess()\n"); CreateProcess(app, param, IntPtr.Zero, IntPtr.Zero, false, 0, IntPtr.Zero, null, ref si, out pi); Console.WriteLine(app + " started as PID " + pi.dwProcessId + " at " + DateTime.Now.ToString("HH:mm:ss tt") + "\n"); Console.WriteLine("\n==== Output/Error(s) =====\n"); try { trackANDkill((int) pi.dwProcessId); }//end try catch { Console.WriteLine("\t Process died too fast to fully index"); }//end catch Console.Write("\nPress enter to continue "); Console.ReadLine(); break; case "n": break; case "q": Console.Clear(); Console.WriteLine("===== Jimmy Buffett would be so disappointed... ====="); Thread.Sleep(3000); cp = false; break; default: Console.WriteLine("\nY tho..."); Thread.Sleep(3000); break; }//end swtich }//end else }//end while break; case "5": bool winexec = true; while (winexec) { Console.Clear(); Console.WriteLine("\n===== WinExec() API execution =====\n"); Console.Write("API takes ANY command (exe + parameters), please give us direction/meaning/purpose (or back): "); string command = Console.ReadLine().ToLower(); if (command == "back") { Console.Clear(); Console.WriteLine("===== \"He who has a why to live can bear almost any how.\" --Friedrich Nietzsche ====="); Thread.Sleep(3000); winexec = false; }//end if else { Console.Write("\nAre you sure you want to execute " + command + " using WinExec()\n\n[y/n/q]? "); string confirm = Console.ReadLine().ToLower(); switch (confirm) { case "y": Console.Clear(); Process currentProcess = Process.GetCurrentProcess(); Console.WriteLine("Executing " + command + " using WinExec() at " + DateTime.Now.ToString("HH:mm:ss tt") + "\n"); Console.WriteLine("\n==== Output/Error(s) =====\n"); WinExec(command, 1); Thread.Sleep(2000); Console.WriteLine(); trackANDkill((int) currentProcess.Id); Console.Write("\nPress enter to continue "); Console.ReadLine(); break; case "n": break; case "q": Console.Clear(); Console.WriteLine("===== At least you're not too legit... ====="); Thread.Sleep(3000); winexec = false; break; default: Console.WriteLine("\nNow that's just rude..."); Thread.Sleep(3000); break; }//end swtich }//end else }//end while break; case "6": bool se = true; while (se) { Console.Clear(); Console.WriteLine("\n===== ShellExecute execution =====\n"); Console.Write("ShellExecute needs an application (an exe somewhere) and args\n\tplease oblige (or back): "); string command = Console.ReadLine().ToLower(); if (command == "back") { Console.Clear(); Console.WriteLine("===== \"They misunderestimated me.\" --George W. Bush ====="); Thread.Sleep(3000); se = false; }//end if else { string[] full = command.Split(' '); string app = ""; string param = ""; int count = 0; foreach (string i in full) { if (count == 0) app = i; else if (count == 1) param = i; else param += " " + i; count++; }//end foreach Console.Write("\nAre you sure you want to execute " + app + " with params \"" + param + "\" using ShellExecute\n\n[y/n/q]? "); string confirm = Console.ReadLine().ToLower(); switch (confirm) { case "y": Console.Clear(); Process process = new Process(); Console.WriteLine("Executing " + app + " with params \"" + param + "\" using ShellExecute\n"); process.StartInfo.FileName = app; process.StartInfo.Arguments = param; process.StartInfo.RedirectStandardOutput = false; process.StartInfo.RedirectStandardError = false; process.StartInfo.UseShellExecute = true; process.Start(); Console.WriteLine(process.ProcessName + " started at " + process.StartTime + " as PID " + process.Id); trackANDkill((int) process.Id); Console.Write("\nPress enter to continue "); Console.ReadLine(); break; case "n": break; case "q": Console.Clear(); Console.WriteLine("===== Boo... ====="); Thread.Sleep(3000); se = false; break; default: Console.WriteLine("\nI thought we were friends..."); Thread.Sleep(3000); break; }//end swtich }//end else }//end while break; case "7": bool wmi = true; while (wmi) { Console.Clear(); Console.WriteLine("\n===== WMI execution =====\n"); Console.Write("WMI needs an application (an exe somewhere) and args\n\tplease oblige (or back): "); string command = Console.ReadLine().ToLower(); if (command == "back") { Console.Clear(); Console.WriteLine("===== \"I'm not Mother Teresa, but I'm not Charles Manson, either.\" --Iron Mike Tyson ====="); Thread.Sleep(3000); wmi = false; }//end if else { Console.Write("\nAre you sure you want to execute " + command + " using WMI\n\n[y/n/q]? "); string confirm = Console.ReadLine().ToLower(); switch (confirm) { case "y": Console.Clear(); Console.WriteLine("Executing " + command + " using WMI\n"); //thank you https://github.com/GhostPack/SharpWMI ManagementScope scope = new ManagementScope("root\\cimv2"); var wmiProcess = new ManagementClass(scope, new ManagementPath("Win32_Process"), new ObjectGetOptions()); ManagementBaseObject inParams = wmiProcess.GetMethodParameters("Create"); System.Management.PropertyDataCollection properties = inParams.Properties; inParams["CommandLine"] = command; ManagementBaseObject outParams = wmiProcess.InvokeMethod("Create", inParams, null); Console.WriteLine(command + " executed at " + DateTime.Now.ToString("HH:mm:ss tt") + " as PID " + outParams["processId"]); Console.WriteLine("\n==== Output/Error(s) =====\n"); Console.WriteLine(outParams["returnValue"]); UInt32 pid = (UInt32) outParams["processId"]; trackANDkill((int) pid); Console.Write("\nPress enter to continue "); Console.ReadLine(); break; case "n": break; case "q": Console.Clear(); Console.WriteLine("===== Acronymns right... ====="); Thread.Sleep(3000); ps = false; break; default: Console.WriteLine("\nMaybe try that again, but better..."); Thread.Sleep(3000); break; }//end swtich }//end else }//end while break; case "8": bool wscript = true; while (wscript) { Console.Clear(); Console.WriteLine("\n===== Windows Script Engine execution =====\n"); Console.Write("I'll build a vbs file for you (you're welcome),\n\tbut I WILL NOT sanitize input (so play nice unless you know what you're doing)\n\tI need a full command and args (or back): "); string command = Console.ReadLine().ToLower(); if (command == "back") { Console.Clear(); Console.WriteLine("===== \"Automation may be a good thing, but don’t forget that it began with Frankenstein.\" --Anonymous ====="); Thread.Sleep(3000); wscript = false; }//end if else { Console.Write("\nAre you sure you want to execute:\n\t" + command + " with the wscript shell\n\n[y/n/q]? "); string confirm = Console.ReadLine().ToLower(); switch (confirm) { case "y": Console.Clear(); Console.WriteLine("Executing " + command + " using the wscript shell\n"); cliExec("wscript", command); Console.Write("\nPress enter to continue "); Console.ReadLine(); File.Delete(Directory.GetCurrentDirectory() + "\\parent.vbs"); break; case "n": break; case "q": Console.Clear(); Console.WriteLine("===== Like a bad habit... ====="); Thread.Sleep(3000); wscript = false; break; default: Console.WriteLine("\nEveryone likes a mystery..."); Thread.Sleep(3000); break; }//end swtich }//end else }//end while break; case "9": bool fiber = true; while (fiber) { Console.Clear(); Console.WriteLine("\n===== Windows Fiber execution =====\n"); Console.Write("Fibers are like threads but \"invisible\" in terms of scheduling to the kernel\n\tscheduling is implemented in userland, you're welcome\n\tI need a full command and args (or back): "); string command = Console.ReadLine().ToLower(); if (command == "back") { Console.Clear(); Console.WriteLine("===== \"Men don't pay attention to small things.\" --Katherine Johnson ====="); Thread.Sleep(3000); fiber = false; }//end if else { Console.Write("\nAre you sure you want to execute:\n\t" + command + " from a Windows fiber\n\n[y/n/q]? "); string confirm = Console.ReadLine().ToLower(); switch (confirm) { case "y": Console.Clear(); Console.WriteLine("Executing " + command + " from a Windows fiber\n"); Thread t = new Thread(ThreadProc); t.Start(command); Console.Write("\nPress enter to continue "); Console.ReadLine(); break; case "n": break; case "q": Console.Clear(); Console.WriteLine("===== Threads are easier anyways... ====="); Thread.Sleep(3000); fiber = false; break; default: Console.WriteLine("\nThis is already complex enough..."); Thread.Sleep(3000); break; }//end swtich }//end else }//end while break; case "10": bool wxsl = true; while (wxsl) { Console.Clear(); Console.WriteLine("\n===== WMIC XSL Script Processing (Squiblytwo) =====\n"); Console.Write("I'll build a xsl file for you (you're welcome),\n\tbut I WILL NOT sanitize input (so play nice unless you know what you're doing)\n\tI need a full command and args (or back): "); string command = Console.ReadLine().ToLower(); if (command == "back") { Console.Clear(); Console.WriteLine("===== \"...If it weren't for those meddling kids.\" --Too Many Scooby-Doo Villains ====="); Thread.Sleep(3000); wxsl = false; }//end if else { Console.Write("\nAre you sure you want to execute:\n\t" + command + " through a wmic xsl script\n\n[y/n/q]? "); string confirm = Console.ReadLine().ToLower(); switch (confirm) { case "y": Console.Clear(); Console.WriteLine("Executing " + command + " through a wmic xsl script\n"); cliExec("wxsl", command); Console.Write("\nPress enter to continue "); Console.ReadLine(); File.Delete(Directory.GetCurrentDirectory() + "\\parent.xsl"); break; case "n": break; case "q": Console.Clear(); Console.WriteLine("===== WMIC is weird... ====="); Thread.Sleep(3000); wxsl = false; break; default: Console.WriteLine("\nDon't try to wiggle out of this one..."); Thread.Sleep(3000); break; }//end swtich }//end else }//end while break; case "exit": Console.Clear(); Console.WriteLine("\n===== stay classy =====\n"); Thread.Sleep(3000); System.Environment.Exit(1); break; default: Console.Clear(); Console.WriteLine("\n===== try to play nice... =====\n"); break; }//end switch }//end while }//end Main
//S'encarrega d'obtenir el drive en el qual Windows està instal·lat (Ex: C:\). public String GetInstalledDrive() { String auxClassName = this.className; this.className = AppConstants.OPERATING_SYSTEM_CLASS; this.arrayProp = CustomGetValues(); this.className = auxClassName; return arrayProp["SystemDrive"].Value.ToString(); }
/// <summary> /// Recursively adds WMI event properties to a dictionary /// </summary> /// <param name="prefix"> /// The recursive event property name prefix /// </param> /// <param name="evtProps"> /// The event property collection to construct /// </param> /// <param name="wmiProps"> /// The WMI property collection source /// </param> private void AddProperties( String prefix, IDictionary<String, Object> evtProps, PropertyDataCollection wmiProps) { foreach (var prop in wmiProps) { var name = String.Format( (prefix != null) ? "{0}.{1}" : "{1}", prefix, prop.Name ); var wmiObject = prop.Value as ManagementBaseObject; if (wmiObject != null) AddProperties(name, evtProps, wmiObject.Properties); else evtProps.Add(name, prop.Value); } }
//Transforma l'array de propietats a un diccionari, degut a que aquest array no es pot modificar ni afegir valors, per tant amb un diccionari ens farem la vida més fàcil. private static Dictionary<String, Object> CustomTransformProperties(PropertyDataCollection prop) { Dictionary<String, Object> toReturn = new Dictionary<String, Object>(); foreach (PropertyData obj in prop) toReturn.Add(obj.Name, obj.Value); return toReturn; }
static void RemoteWMIExecute(string host, string command, string username, string password) { string wmiNameSpace = "root\\cimv2"; ConnectionOptions options = new ConnectionOptions(); Console.WriteLine("\r\n[*] Host : {0}", host); Console.WriteLine("[*] Command : {0}", command); if (!String.IsNullOrEmpty(username)) { Console.WriteLine("[*] User credentials : {0}", username); options.Username = username; options.Password = password; } ManagementScope scope = new ManagementScope(String.Format("\\\\{0}\\{1}", host, wmiNameSpace), options); // Store data in existing WMI property, but keep original value string Original_WMIProperty = GetWMIProperty(host, username, password); try { scope.Connect(); var wmiProcess = new ManagementClass(scope, new ManagementPath("Win32_Process"), new ObjectGetOptions()); ManagementBaseObject inParams = wmiProcess.GetMethodParameters("Create"); System.Management.PropertyDataCollection properties = inParams.Properties; string tmpcmd = String.Format("$output = ({0} | Out-String).Trim(); $EncodedText = [Int[]][Char[]]$output -Join ','; $a = Get-WmiObject -Class Win32_OSRecoveryConfiguration; $a.DebugFilePath = $EncodedText; $a.Put()", command); inParams["CommandLine"] = "powershell " + tmpcmd; ManagementBaseObject outParams = wmiProcess.InvokeMethod("Create", inParams, null); Console.WriteLine("[*] Creation of process returned : {0}", outParams["returnValue"]); Console.WriteLine("[*] Process ID : {0}", outParams["processId"]); int count = 0; while (true) { string New_WMIProperty = GetWMIProperty(host, username, password); if (New_WMIProperty == Original_WMIProperty) { if (count < 3) { count++; Console.WriteLine("[*] Tring get result..."); Thread.Sleep(3000); } else { Console.WriteLine("[-] Maybe no result. exit..."); System.Environment.Exit(0); } } else { string[] tmp = New_WMIProperty.Split(','); string result = ""; foreach (string i in tmp) { result += Convert.ToChar(Convert.ToInt32(i)); } Console.WriteLine("[+] Execute result:\r\n\r\n {0}\r\n", result); break; } } Console.WriteLine("[*] Recovery WMI Property.."); SetWMIProperty(host, username, password, Original_WMIProperty); } catch (Exception ex) { Console.WriteLine(String.Format("[X] Exception : {0}", ex.Message)); } }
static string Serialize (PropertyDataCollection properties, bool isLocal) { NativeCimProperties obj = new NativeCimProperties(); foreach (var p in properties) { obj.Add(p.Name, p.Origin, p.IsArray, p.IsLocal, Transform(p.Type), p.Value); } obj.Add("PSShowComputerName", "", false, true, Microsoft.Management.Infrastructure.CimType.Boolean, true); obj.Add("PSComputerName", "", false, true, Microsoft.Management.Infrastructure.CimType.String, isLocal ? "localhost" : properties["__SERVER"].Value); return NativeCimPropertiesHelper.Serialize (obj); }
private string FullMessage(PropertyDataCollection rawData) { var buffer = new StringBuilder(); foreach(var item in _interestingData) { buffer.AppendFormat(" {0} {1}", item, rawData[item].Value.ToString()); } return buffer.ToString(); }
static string SerializeSystem(PropertyDataCollection properties) { NativeCimProperties obj = new NativeCimProperties(); foreach (var p in properties) { obj.Add(p.Name, p.Origin, p.IsArray, p.IsLocal, Transform(p.Type), p.Value); } return NativeCimPropertiesHelper.Serialize (obj); }
static void RemoteWMIFirewall(string host, string username, string password) { string wmiNameSpace = "ROOT\\StandardCIMV2"; ConnectionOptions options = new ConnectionOptions(); Console.WriteLine("\r\n Scope: \\\\{0}\\{1}", host, wmiNameSpace); if (!String.IsNullOrEmpty(username)) { Console.WriteLine(" User credentials: {0}", username); options.Username = username; options.Password = password; } Console.WriteLine(); ManagementScope scope = new ManagementScope(String.Format("\\\\{0}\\{1}", host, wmiNameSpace), options); Dictionary <string, ArrayList> firewallRules = new Dictionary <string, ArrayList>(); try { scope.Connect(); ObjectQuery query = new ObjectQuery("SELECT Enabled,DisplayName,Action,Direction,InstanceID from MSFT_NetFirewallRule WHERE Enabled=1"); ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query); ManagementObjectCollection data = searcher.Get(); foreach (ManagementObject result in data) { System.Management.PropertyDataCollection props = result.Properties; string instanceID = props["InstanceID"].Value.ToString(); ArrayList ruleData = new ArrayList(); ruleData.Add(props["DisplayName"].Value.ToString()); ruleData.Add(props["Action"].Value.ToString()); ruleData.Add(props["Direction"].Value.ToString()); firewallRules[instanceID] = ruleData; } ObjectQuery query2 = new ObjectQuery("SELECT InstanceID,LocalPort from MSFT_NetProtocolPortFilter WHERE Protocol='TCP'"); ManagementObjectSearcher searcher2 = new ManagementObjectSearcher(scope, query2); ManagementObjectCollection data2 = searcher2.Get(); foreach (ManagementObject result in data2) { System.Management.PropertyDataCollection props = result.Properties; if ((props["LocalPort"].Value != null)) { string instanceID = props["InstanceID"].Value.ToString(); if (firewallRules.ContainsKey(instanceID)) { string[] localPorts = (string[])props["LocalPort"].Value; Console.WriteLine("Rulename : {0}", firewallRules[instanceID][0]); if (firewallRules[instanceID][1].ToString() == "2") { Console.WriteLine("Action : {0} (Allow)", firewallRules[instanceID][1]); } else if (firewallRules[instanceID][1].ToString() == "3") { Console.WriteLine("Action : {0} (AllowBypass)", firewallRules[instanceID][1]); } else if (firewallRules[instanceID][1].ToString() == "4") { Console.WriteLine("Action : {0} (Block)", firewallRules[instanceID][1]); } else { Console.WriteLine("Action : {0} (Unknown)", firewallRules[instanceID][1]); } if (firewallRules[instanceID][2].ToString() == "1") { Console.WriteLine("Direction : {0} (Inbound)", firewallRules[instanceID][2]); } else if (firewallRules[instanceID][2].ToString() == "2") { Console.WriteLine("Direction : {0} (Outbound)", firewallRules[instanceID][2]); } else { Console.WriteLine("Direction : {0} (Unknown)", firewallRules[instanceID][2]); } Console.WriteLine("LocalPorts : {0}\n", localPorts); } } } } catch (Exception ex) { Console.WriteLine(String.Format(" Exception : {0}", ex.Message)); } }
//================================================================================================= private PropertyData GetWmiColumnByName( PropertyDataCollection wmiColumns, string colName ) { foreach( PropertyData wmiCol in wmiColumns ) if( wmiCol.Name == colName ) return wmiCol; return null; }