private void SessionConnect() { try { SecureString securepassword = new SecureString(); foreach (char c in PasswordTextBox.Password) { securepassword.AppendChar(c); } // create Credentials CimCredential Credentials = new CimCredential(PasswordAuthenticationMechanism.Default, Domain, Username, securepassword); // create SessionOptions using Credentials WSManSessionOptions SessionOptions = new WSManSessionOptions(); SessionOptions.AddDestinationCredentials(Credentials); // create Session using computer, SessionOptions Session = CimSession.Create(Server, SessionOptions); } catch (Exception ex) { snackMessageQueue.Enqueue(ex); SnackbarNotify.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#D63031")); log.Error(ex.Message); } }
static CimSession CreateSession(string target, string user, string pass, string domain, string proto, bool ssl) { if (target == "." || target == "127.0.0.1" || target == "localhost") { Console.WriteLine("Querying localhost"); return(CimSession.Create(target)); } else { Console.WriteLine("Querying " + target); SecureString secpass = new SecureString(); foreach (char c in pass) { secpass.AppendChar(c); } CimCredential Credentials = new CimCredential(PasswordAuthenticationMechanism.Default, domain, user, secpass); if (proto == "dcom") { var dcomOptions = new DComSessionOptions(); dcomOptions.AddDestinationCredentials(Credentials); return(CimSession.Create(target, dcomOptions)); } else { var wsmanOptions = new WSManSessionOptions(); wsmanOptions.AddDestinationCredentials(Credentials); wsmanOptions.UseSsl = ssl; return(CimSession.Create(target, wsmanOptions)); } } }
internal static CimSession CreateCimSession( string computerName, PSCredential credential, string authentication, bool isLocalHost, PSCmdlet cmdlet, CancellationToken cancellationToken) { if (isLocalHost) { return(CimSession.Create(null)); } var sessionOptions = new CimSessionOptions(); CimCredential cimCredentials = GetCimCredentials(authentication, credential); if (cimCredentials != null) { sessionOptions.AddDestinationCredentials(cimCredentials); } CimSession cimSession = CimSession.Create(computerName, sessionOptions); return(cimSession); }
/// <summary> /// Create a new <see cref="CimSession"/> base on given cmdlet /// and its parameter. /// </summary> /// <param name="cmdlet"></param> /// <param name="sessionOptions"></param> /// <param name="credential"></param> internal void NewCimSession(NewCimSessionCommand cmdlet, CimSessionOptions sessionOptions, CimCredential credential) { DebugHelper.WriteLogEx(); IEnumerable <string> computerNames = ConstValue.GetComputerNames(cmdlet.ComputerName); foreach (string computerName in computerNames) { CimSessionProxy proxy; if (sessionOptions == null) { DebugHelper.WriteLog("Create CimSessionOption due to NewCimSessionCommand has null sessionoption", 1); sessionOptions = CimSessionProxy.CreateCimSessionOption(computerName, cmdlet.OperationTimeoutSec, credential); } proxy = new CimSessionProxyTestConnection(computerName, sessionOptions); string computerNameValue = (computerName == ConstValue.NullComputerName) ? ConstValue.LocalhostComputerName : computerName; CimSessionWrapper wrapper = new CimSessionWrapper(0, Guid.Empty, cmdlet.Name, computerNameValue, proxy.CimSession, proxy.Protocol); CimTestCimSessionContext context = new CimTestCimSessionContext(proxy, wrapper); proxy.ContextObject = context; // Skip test the connection if user intend to if (cmdlet.SkipTestConnection.IsPresent) { AddSessionToCache(proxy.CimSession, context, new CmdletOperationBase(cmdlet)); } else { // CimSession will be returned as part of TestConnection this.cimTestSession.TestCimSession(computerName, proxy); } } }
/// <summary> /// Add Connection driver to use Windows Remote management /// </summary> /// <param name="optionsBuilder">WmiContextOptionsBuilder to extend</param> /// <param name="computerName">Computer name or IP address to connect</param> /// <param name="nameSpace">WMI Namespace to work with</param> /// <param name="credential">Preconfigured <c>CimCredential</c> object</param> /// <returns>WmiContextOptionsBuilder (itself)</returns> public static WmiContextOptionsBuilder UseCim( this WmiContextOptionsBuilder optionsBuilder, string computerName, string nameSpace, CimCredential credential) { optionsBuilder.Options.Connection = new CimConnection(computerName, nameSpace, credential); return(optionsBuilder); }
private void ClassSetup(string ComputerName, string Domain, string UserName, SecureString Password, DComSessionOptions Options) { if (AuthType == PasswordAuthenticationMechanism.Default) { AuthType = PasswordAuthenticationMechanism.Kerberos; } Credentials = new CimCredential(AuthType, Domain, UserName, Password); Options.AddDestinationCredentials(Credentials); SystemSession = CimSession.Create(ComputerName, SessionOptions); if (PortTest(ComputerName)) { Connected = SystemSession.TestConnection(out CimInstance TmpInstance, out CimException TmpExeption); if (!Connected) { Err = TmpExeption; ConnectionStatuMessage = Err.Message; } else { ConnectionStatuMessage = "Connected"; } } else { Connected = false; ConnectionStatuMessage = "Port not open on host"; } RegSoftwareUninstall = new List <string>(); }
/// <summary> /// Constructor that configures connection to host using specified credential object and takes WMI namespace /// </summary> /// <param name="computerName">Computer name or IP address to connect</param> /// <param name="nameSpace">Namespace to configure</param> /// <param name="credential">Preconfigured credential object to be used in connection</param> public CimConnection(string computerName, string nameSpace, CimCredential credential) { var sessionOptions = new WSManSessionOptions(); sessionOptions.AddDestinationCredentials(credential); _connection = CimSession.Create(computerName, sessionOptions); _nameSpace = nameSpace; }
protected override void ProcessRecord() { CimSessionOptions cimSessionOption = null; CimCredential cimCredential = null; this.BuildSessionOptions(out cimSessionOption, out cimCredential); this.cimNewSession.NewCimSession(this, cimSessionOption, cimCredential); this.cimNewSession.ProcessActions(this.CmdletOperation); }
private CimSession DoCimConnection(Planter planter) { //Block for connecting to the remote system and returning a CimSession object SystemToConn = planter.System; Domain = planter.Domain; Username = planter.User; Password = planter.Password; WSManSessionOptions sessionOptions = new WSManSessionOptions(); CimSession connectedCimSession; if (SystemToConn == null) { SystemToConn = "localhost"; } if (Username == null) { Username = Environment.UserName; } switch (SystemToConn) { case "127.0.0.1": case "localhost": Messenger.GoodMessage("[+] Connecting to local CIM instance using " + Username + "..."); break; default: Messenger.GoodMessage("[+] Connecting to remote CIM instance using " + Username + "..."); break; } if (!string.IsNullOrEmpty(Password?.ToString())) { // create Credentials CimCredential credentials = new CimCredential(PasswordAuthenticationMechanism.Default, Domain, Username, Password); sessionOptions.AddDestinationCredentials(credentials); sessionOptions.MaxEnvelopeSize = 256000; // Not sure how else to get around this connectedCimSession = CimSession.Create(SystemToConn, sessionOptions); } else { DComSessionOptions options = new DComSessionOptions { Impersonation = ImpersonationType.Impersonate }; connectedCimSession = CimSession.Create(SystemToConn, options); } // Test connection to make sure we're connected if (!connectedCimSession.TestConnection()) { return(null); } Messenger.GoodMessage("[+] Connected\n"); return(connectedCimSession); }
internal static CimSession CreateCimSession(string computerName, PSCredential credential, string authentication, CancellationToken cancellationToken, PSCmdlet cmdlet) { CimSessionOptions sessionOptions = new CimSessionOptions(); CimCredential cimCredentials = GetCimCredentials(authentication, credential); if (cimCredentials != null) { sessionOptions.AddDestinationCredentials(cimCredentials); } return(CimSession.Create(computerName, sessionOptions)); }
static void Main(string[] args) { string computer = "Computer_B"; string domain = "DOMAIN"; string username = "******"; string plaintextpassword; Console.WriteLine("Enter password:"******"root\cimv2", "WQL", "SELECT * FROM Win32_Volume"); var allPDisks = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_DiskDrive"); // Loop through all volumes foreach (CimInstance oneVolume in allVolumes) { // Show volume information if (oneVolume.CimInstanceProperties["DriveLetter"].ToString()[0] > ' ') { Console.WriteLine("Volume ‘{0}’ has {1} bytes total, {2} bytes available", oneVolume.CimInstanceProperties["DriveLetter"], oneVolume.CimInstanceProperties["Size"], oneVolume.CimInstanceProperties["SizeRemaining"]); } } // Loop through all physical disks foreach (CimInstance onePDisk in allPDisks) { // Show physical disk information Console.WriteLine("Disk {0} is model {1}, serial number {2}", onePDisk.CimInstanceProperties["DeviceId"], onePDisk.CimInstanceProperties["Model"].ToString().TrimEnd(), onePDisk.CimInstanceProperties["SerialNumber"]); } Console.ReadLine(); }
public string GetHostname() { string hostname = string.Empty; if (string.IsNullOrEmpty(wincred.Domain)) { wincred.Domain = ip.ToString(); } CimCredential Credentials = new CimCredential(PasswordAuthenticationMechanism.Default, wincred.Domain, wincred.Username, wincred.Password); WSManSessionOptions SessionOptions = new WSManSessionOptions(); SessionOptions.AddDestinationCredentials(Credentials); if (ssl) { SessionOptions.UseSsl = true; } else { SessionOptions.UseSsl = false; } SessionOptions.DestinationPort = port; if (checkcert) { SessionOptions.CertCACheck = true; SessionOptions.CertCNCheck = true; SessionOptions.CertRevocationCheck = true; } else { SessionOptions.CertCACheck = false; SessionOptions.CertCNCheck = false; SessionOptions.CertRevocationCheck = false; } try { Session = CimSession.Create(ip.ToString(), SessionOptions); CimInstance searchInstance = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT CSNAME from win32_operatingsystem").FirstOrDefault(); if (searchInstance != null) { hostname = searchInstance.CimInstanceProperties["CSName"].Value.ToString(); } } catch (Exception ex) { log.Error("IPADDRESS: " + ip + " ;MESSAGE: " + ex.Message); } return(hostname); }
private void ClassSetup(string ComputerName, PasswordAuthenticationMechanism AuthType, string Domain, string UserName, SecureString Password, uint Port) { if (AuthType == PasswordAuthenticationMechanism.Default) { AuthType = PasswordAuthenticationMechanism.Kerberos; } Credentials = new CimCredential(AuthType, Domain, UserName, Password); SessionOptions = new WSManSessionOptions() { DestinationPort = Port }; SessionOptions.AddDestinationCredentials(Credentials); SystemSession = CimSession.Create(ComputerName, SessionOptions); Connected = SystemSession.TestConnection(out CimInstance TmpInstance, out CimException TmpExeption); }
/// <summary> /// Create credentials based on given authentication type and PSCredential. /// </summary> /// <param name="psCredentials"></param> /// <param name="passwordAuthentication"></param> /// <returns></returns> internal CimCredential CreateCimCredentials(PSCredential psCredentials, PasswordAuthenticationMechanism passwordAuthentication, string operationName, string parameterName) { DebugHelper.WriteLogEx("PSCredential:{0}; PasswordAuthenticationMechanism:{1}; operationName:{2}; parameterName:{3}.", 0, psCredentials, passwordAuthentication, operationName, parameterName); CimCredential credentials = null; if (psCredentials != null) { NetworkCredential networkCredential = psCredentials.GetNetworkCredential(); DebugHelper.WriteLog("Domain:{0}; UserName:{1}; Password:{2}.", 1, networkCredential.Domain, networkCredential.UserName, psCredentials.Password); credentials = new CimCredential(passwordAuthentication, networkCredential.Domain, networkCredential.UserName, psCredentials.Password); } else { ImpersonatedAuthenticationMechanism impersonatedAuthentication; switch (passwordAuthentication) { case PasswordAuthenticationMechanism.Default: impersonatedAuthentication = ImpersonatedAuthenticationMechanism.None; break; case PasswordAuthenticationMechanism.Negotiate: impersonatedAuthentication = ImpersonatedAuthenticationMechanism.Negotiate; break; case PasswordAuthenticationMechanism.Kerberos: impersonatedAuthentication = ImpersonatedAuthenticationMechanism.Kerberos; break; case PasswordAuthenticationMechanism.NtlmDomain: impersonatedAuthentication = ImpersonatedAuthenticationMechanism.NtlmDomain; break; default: ThrowInvalidAuthenticationTypeError(operationName, parameterName, passwordAuthentication); return(null); } credentials = new CimCredential(impersonatedAuthentication); } DebugHelper.WriteLogEx("return credential {0}", 1, credentials); return(credentials); }
private void KickOffCimAsync(Computer computer, Credential credential, string commandline, CimSessionOptions options) { var optionsBuilder = new DbContextOptionsBuilder <ACEWebServiceDbContext>(); optionsBuilder.UseSqlServer("Server=(localdb)\\MSSQLLocalDB;Database=ACEWebService;Trusted_Connection=True;MultipleActiveResultSets=true"); using (ACEWebServiceDbContext context = new ACEWebServiceDbContext(optionsBuilder.Options)) { // Convert stored password to a secure string SecureString securePwd = new SecureString(); foreach (char c in _cryptoService.Decrypt(credential.Password)) { securePwd.AppendChar(c); } CimCredential cimCreds = null; if (credential.UserName.Contains('\\')) { // Create a CimCredential object cimCreds = new CimCredential(PasswordAuthenticationMechanism.Kerberos, credential.UserName.Split('\\')[0], credential.UserName.Split('\\')[1], securePwd); } else { // Create a CimCredential object cimCreds = new CimCredential(PasswordAuthenticationMechanism.Default, null, credential.UserName, securePwd); } // Create a CimSession with the remote system options.AddDestinationCredentials(cimCreds); CimSession session = CimSession.Create(computer.ComputerName, options); // Create a CimMethodParametersCollection to pass to method invocation CimMethodParametersCollection collection = new CimMethodParametersCollection(); collection.Add(CimMethodParameter.Create("CommandLine", commandline, CimFlags.None)); CimMethodResult result = session.InvokeMethod("root/cimv2", "Win32_Process", "Create", collection); if (result.ReturnValue.ToString() == "0") { } else { } session.Dispose(); } }
/// <summary> /// Constructor that configures connection to host using specified credentials and takes WMI namespace /// </summary> /// <param name="computerName">Computer name or IP address to connect</param> /// <param name="nameSpace">Namespace to configure</param> /// <param name="authenticationMechanism">Authentication mechanism to be used</param> /// <param name="domain">User domain</param> /// <param name="userName">User name</param> /// <param name="password">User password</param> public CimConnection(string computerName, string nameSpace, PasswordAuthenticationMechanism authenticationMechanism, string domain, string userName, string password) { var securePassword = new SecureString(); foreach (var c in password) { securePassword.AppendChar(c); } var credential = new CimCredential(authenticationMechanism, domain, userName, securePassword); var sessionOptions = new WSManSessionOptions(); sessionOptions.AddDestinationCredentials(credential); _connection = CimSession.Create(computerName, sessionOptions); _nameSpace = nameSpace; }
private void KickOffCim(Computer computer, Credential credential, string commandline, CimSessionOptions options) { // Convert stored password to a secure string SecureString securePwd = new SecureString(); foreach (char c in _cryptoService.Decrypt(credential.Password)) { Console.WriteLine("[char]: {0}", c); securePwd.AppendChar(c); } CimCredential cimCreds = null; if (credential.UserName.Contains('\\')) { // Create a CimCredential object cimCreds = new CimCredential(PasswordAuthenticationMechanism.Kerberos, credential.UserName.Split('\\')[0], credential.UserName.Split('\\')[1], securePwd); } else { // Create a CimCredential object cimCreds = new CimCredential(PasswordAuthenticationMechanism.Default, null, credential.UserName, securePwd); } // Create a CimSession with the remote system options.AddDestinationCredentials(cimCreds); CimSession session = CimSession.Create(computer.ComputerName, options); // Create a CimMethodParametersCollection to pass to method invocation CimMethodParametersCollection collection = new CimMethodParametersCollection { CimMethodParameter.Create("CommandLine", commandline, CimFlags.None) }; CimMethodResult result = session.InvokeMethod("root/cimv2", "Win32_Process", "Create", collection); if (result.ReturnValue.ToString() == "0") { } else { } session.Dispose(); }
public static MSMQConnectSession connect(String host, String domain, String username, String password) { SecureString securepassword = new SecureString(); foreach (Char p in password.ToCharArray()) { securepassword.AppendChar(p); } CimCredential Credentials = new CimCredential(PasswordAuthenticationMechanism.Kerberos + "", domain, username, securepassword); WSManSessionOptions SessionOptions = new WSManSessionOptions(); SessionOptions.AddDestinationCredentials(Credentials); return(new MSMQConnectSession(CimSession.Create(host, SessionOptions))); }
public static CimSession newSession(string computername, string domain, string username, string password, bool impersonate = false) { CimSession cimSession; if (impersonate) { DComSessionOptions options = new DComSessionOptions { Impersonation = ImpersonationType.Impersonate }; cimSession = CimSession.Create(computername, options); } else { CimCredential credentials = new CimCredential(PasswordAuthenticationMechanism.Negotiate, domain, username, Misc.CreateSecuredString(password)); WSManSessionOptions sessionOptions = new WSManSessionOptions(); sessionOptions.AddDestinationCredentials(credentials); sessionOptions.MaxEnvelopeSize = 256000; cimSession = CimSession.Create(computername, sessionOptions); } return(cimSession); }
public RDPOperations(string machineName = lh, PSCredential psCreds = null) { var dComOpts = new DComSessionOptions() { Culture = CultureInfo.CurrentCulture, UICulture = CultureInfo.CurrentUICulture, PacketIntegrity = true, PacketPrivacy = true, Timeout = new TimeSpan(0) }; if (psCreds != null) { UsingCredentials = true; var user = RDPCredential.ParseUser(psCreds); var dom = RDPCredential.ParseDomain(psCreds); var cimCred = new CimCredential(PasswordAuthenticationMechanism.Default, dom, user, psCreds.Password); dComOpts.AddDestinationCredentials(cimCred); } _cim = CimSession.Create(machineName, dComOpts); }
public static List <MachineHardwareInfo> GetHardwareInfo(string computer, string domain, string username, string plaintextpassword) { MachineName = computer; List <MachineHardwareInfo> info = new List <MachineHardwareInfo>(); SecureString securepassword = new SecureString(); foreach (char c in plaintextpassword) { securepassword.AppendChar(c); } // create Credentials CimCredential Credentials = new CimCredential(PasswordAuthenticationMechanism.Default, domain, username, securepassword); // create SessionOptions using Credentials WSManSessionOptions SessionOptions = new WSManSessionOptions(); SessionOptions.AddDestinationCredentials(Credentials); // create Session using computer, SessionOptions using (CimSession Session = CimSession.Create(computer, SessionOptions)) { var usb = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_USBControllerDevice"); var disks = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_LogicalDisk"); var ram = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_PhysicalMemory"); var processor = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_Processor"); var sound = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_SoundDevice"); info.AddRange(RamInfo(ram)); info.AddRange(ProcessorInfo(processor)); info.AddRange(USBInfo(usb)); info.AddRange(DiskInfo(disks)); } return(info); }
private void RamScan(bool PC1, bool PC2, bool PC3) { var password = new SecureString(); foreach (char c in Data.rudepassword) { password.AppendChar(c); } CimCredential Credentials = new CimCredential(PasswordAuthenticationMechanism.Default, Data.domain, Data.username, password); WSManSessionOptions SessionOptions = new WSManSessionOptions(); SessionOptions.AddDestinationCredentials(Credentials); if (PC1) { try { CimSession Session1 = CimSession.Create(Data.computer1, SessionOptions); var allMemory1 = Session1.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_PhysicalMemory"); Data.memory1size = 0; foreach (CimInstance oneMemory1 in allMemory1) { Data.ram1size = String.Format("{0}", oneMemory1.CimInstanceProperties["Capacity"].Value); Data.memory1size += Math.Round(Convert.ToDouble(Data.ram1size) / 1073741824, 2); Data.ram1size = Data.memory1size.ToString() + " GB"; labelRam1Size.Text = Data.ram1size; } var allUsedMemory1 = Session1.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_PerfFormattedData_PerfOS_Memory"); foreach (CimInstance oneUsedMemory1 in allUsedMemory1) { Int32.TryParse(String.Format("{0}", oneUsedMemory1.CimInstanceProperties["PercentCommittedBytesInUse"].Value), out Data.ram1percent); } labelRam1Used.Text = Data.ram1percent + "%"; BarRAM1.Value = Data.ram1percent; } catch { Data.LoadPC1 = false; } } if (PC2) { try { CimSession Session2 = CimSession.Create(Data.computer2, SessionOptions); var allMemory2 = Session2.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_PhysicalMemory"); Data.memory2size = 0; foreach (CimInstance oneMemory2 in allMemory2) { Data.ram2size = String.Format("{0}", oneMemory2.CimInstanceProperties["Capacity"].Value); Data.memory2size += Math.Round(Convert.ToDouble(Data.ram2size) / 1073741824, 2); Data.ram2size = Data.memory2size.ToString() + " GB"; labelRam2Size.Text = Data.ram2size; } var allUsedMemory2 = Session2.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_PerfFormattedData_PerfOS_Memory"); foreach (CimInstance oneUsedMemory2 in allUsedMemory2) { Int32.TryParse(String.Format("{0}", oneUsedMemory2.CimInstanceProperties["PercentCommittedBytesInUse"].Value), out Data.ram2percent); } labelRam2Used.Text = Data.ram2percent + "%"; BarRAM2.Value = Data.ram2percent; } catch { Data.LoadPC2 = false; } } if (PC3) { try { CimSession Session3 = CimSession.Create(Data.computer3, SessionOptions); var allMemory3 = Session3.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_PhysicalMemory"); Data.memory3size = 0; foreach (CimInstance oneMemory3 in allMemory3) { Data.ram3size = String.Format("{0}", oneMemory3.CimInstanceProperties["Capacity"].Value); Data.memory3size += Math.Round(Convert.ToDouble(Data.ram3size) / 1073741824, 2); Data.ram3size = Data.memory3size.ToString() + " GB"; labelRam3Size.Text = Data.ram3size; } var allUsedMemory3 = Session3.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_PerfFormattedData_PerfOS_Memory"); foreach (CimInstance oneUsedMemory3 in allUsedMemory3) { Int32.TryParse(String.Format("{0}", oneUsedMemory3.CimInstanceProperties["PercentCommittedBytesInUse"].Value), out Data.ram3percent); } labelRam3Used.Text = Data.ram3percent + "%"; BarRAM3.Value = Data.ram3percent; } catch { Data.LoadPC3 = false; } } }
private void CpuScan(bool PC1, bool PC2, bool PC3) { var password = new SecureString(); foreach (char c in Data.rudepassword) { password.AppendChar(c); } CimCredential Credentials = new CimCredential(PasswordAuthenticationMechanism.Default, Data.domain, Data.username, password); WSManSessionOptions SessionOptions = new WSManSessionOptions(); SessionOptions.AddDestinationCredentials(Credentials); if (PC1) { try { CimSession Session1 = CimSession.Create(Data.computer1, SessionOptions); var allUsedCore1 = Session1.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor"); foreach (CimInstance oneUsedCore1 in allUsedCore1) { Int32.TryParse(String.Format("{0}", oneUsedCore1.CimInstanceProperties["PercentProcessorTime"].Value), out Data.cpu1percent); } labelCpu1Used.Text = Data.cpu1percent + "%"; BarCPU1.Value = Data.cpu1percent; } catch { Data.LoadPC1 = false; } } if (PC2) { try { CimSession Session2 = CimSession.Create(Data.computer2, SessionOptions); var allUsedCore2 = Session2.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor"); foreach (CimInstance oneUsedCore2 in allUsedCore2) { Int32.TryParse(String.Format("{0}", oneUsedCore2.CimInstanceProperties["PercentProcessorTime"].Value), out Data.cpu2percent); } labelCpu2Used.Text = Data.cpu2percent + "%"; BarCPU2.Value = Data.cpu2percent; } catch { Data.LoadPC2 = false; } } if (PC3) { try { CimSession Session3 = CimSession.Create(Data.computer3, SessionOptions); var allUsedCore3 = Session3.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor"); foreach (CimInstance oneUsedCore3 in allUsedCore3) { Int32.TryParse(String.Format("{0}", oneUsedCore3.CimInstanceProperties["PercentProcessorTime"].Value), out Data.cpu3percent); } labelCpu3Used.Text = Data.cpu3percent + "%"; BarCPU3.Value = Data.cpu3percent; } catch { Data.LoadPC3 = false; } } }
private void AppScan(bool PC1, bool PC2, bool PC3) { Boolean isOn = false; var password = new SecureString(); foreach (char c in Data.rudepassword) { password.AppendChar(c); } CimCredential Credentials = new CimCredential(PasswordAuthenticationMechanism.Default, Data.domain, Data.username, password); WSManSessionOptions SessionOptions = new WSManSessionOptions(); SessionOptions.AddDestinationCredentials(Credentials); if (PC1) { try { CimSession Session1 = CimSession.Create(Data.computer1, SessionOptions); var allApp1 = Session1.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_Process"); isOn = false; foreach (CimInstance oneApp1 in allApp1) { if (oneApp1.CimInstanceProperties["Name"].ToString() == "Name = \"VerificationSupervision.exe\"") { labelApp1.Text = "Online"; buttonShowStatut1.BackColor = System.Drawing.Color.Lime; isOn = true; } } if (!isOn) { labelApp1.Text = "Offline"; buttonShowStatut1.BackColor = System.Drawing.Color.DarkRed; } } catch { Data.LoadPC1 = false; } } if (PC2) { try { CimSession Session2 = CimSession.Create(Data.computer2, SessionOptions); var allApp2 = Session2.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_Process"); isOn = false; foreach (CimInstance oneApp2 in allApp2) { if (oneApp2.CimInstanceProperties["Name"].ToString() == "Name = \"VerificationSupervision.exe\"") { labelApp2.Text = "Online"; buttonShowStatut2.BackColor = System.Drawing.Color.Lime; isOn = true; } } if (!isOn) { labelApp2.Text = "Offline"; buttonShowStatut2.BackColor = System.Drawing.Color.DarkRed; } } catch { Data.LoadPC2 = false; } } if (PC3) { try { CimSession Session3 = CimSession.Create(Data.computer3, SessionOptions); var allApp3 = Session3.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_Process"); isOn = false; foreach (CimInstance oneApp3 in allApp3) { if (oneApp3.CimInstanceProperties["Name"].ToString() == "Name = \"VerificationSupervision.exe\"") { labelApp3.Text = "Online"; buttonShowStatut3.BackColor = System.Drawing.Color.Lime; isOn = true; } } if (!isOn) { labelApp3.Text = "Offline"; buttonShowStatut3.BackColor = System.Drawing.Color.DarkRed; } } catch { Data.LoadPC3 = false; } } }
internal WSManSessionOptions CreateWSMANSessionOptions() { WSManSessionOptions wSManSessionOption = new WSManSessionOptions(); if (!this.noEncryptionSet) { wSManSessionOption.NoEncryption = false; } else { wSManSessionOption.NoEncryption = true; this.noEncryptionSet = false; } if (!this.skipCACheckSet) { wSManSessionOption.CertCACheck = true; } else { wSManSessionOption.CertCACheck = false; this.skipCACheckSet = false; } if (!this.skipCNCheckSet) { wSManSessionOption.CertCNCheck = true; } else { wSManSessionOption.CertCNCheck = false; this.skipCNCheckSet = false; } if (!this.skipRevocationCheckSet) { wSManSessionOption.CertRevocationCheck = true; } else { wSManSessionOption.CertRevocationCheck = false; this.skipRevocationCheckSet = false; } if (!this.encodeportinserviceprincipalnameSet) { wSManSessionOption.EncodePortInServicePrincipalName = false; } else { wSManSessionOption.EncodePortInServicePrincipalName = this.EncodePortInServicePrincipalName; this.encodeportinserviceprincipalnameSet = false; } if (!this.encodingSet) { wSManSessionOption.PacketEncoding = PacketEncoding.Utf8; } else { wSManSessionOption.PacketEncoding = this.Encoding; } if (this.HttpPrefix != null) { wSManSessionOption.HttpUrlPrefix = this.HttpPrefix; } if (!this.maxenvelopesizekbSet) { wSManSessionOption.MaxEnvelopeSize = 0; } else { wSManSessionOption.MaxEnvelopeSize = this.MaxEnvelopeSizeKB; } if (!string.IsNullOrWhiteSpace(this.ProxyCertificateThumbprint)) { CimCredential cimCredential = new CimCredential(CertificateAuthenticationMechanism.Default, this.ProxyCertificateThumbprint); wSManSessionOption.AddProxyCredentials(cimCredential); } if (this.proxyauthenticationSet) { this.proxyauthenticationSet = false; DebugHelper.WriteLogEx("create credential", 1); CimCredential cimCredential1 = base.CreateCimCredentials(this.ProxyCredential, this.ProxyAuthentication, "New-CimSessionOption", "ProxyAuthentication"); if (cimCredential1 != null) { try { DebugHelper.WriteLogEx("Add proxy credential", 1); wSManSessionOption.AddProxyCredentials(cimCredential1); } catch (Exception exception1) { Exception exception = exception1; DebugHelper.WriteLogEx(exception.ToString(), 1); throw exception; } } } if (!this.proxytypeSet) { wSManSessionOption.ProxyType = ProxyType.WinHttp; } else { wSManSessionOption.ProxyType = this.ProxyType; this.proxytypeSet = false; } if (!this.usesslSet) { wSManSessionOption.UseSsl = false; } else { wSManSessionOption.UseSsl = this.UseSsl; this.usesslSet = false; } wSManSessionOption.DestinationPort = 0; return(wSManSessionOption); }
internal void BuildSessionOptions(out CimSessionOptions outputOptions, out CimCredential outputCredential) { WSManSessionOptions wSManSessionOption; PasswordAuthenticationMechanism authentication; DebugHelper.WriteLogEx(); CimSessionOptions dComSessionOption = null; /* Requires Authentication for Remote Host */ if (this.credential == null && ComputerName != null) { bool requiredAuth = false; foreach (var c in ComputerName) { if (c != null && !c.Equals("localhost", StringComparison.OrdinalIgnoreCase)) { requiredAuth = true; break; } } if (requiredAuth) { TrySetCredentials(); } } if (this.SessionOption != null) { if (this.SessionOption as WSManSessionOptions == null) { dComSessionOption = new DComSessionOptions(this.sessionOption as DComSessionOptions); } else { dComSessionOption = new WSManSessionOptions(this.sessionOption as WSManSessionOptions); } } outputOptions = null; outputCredential = null; if (dComSessionOption != null) { DComSessionOptions dComSessionOption1 = dComSessionOption as DComSessionOptions; if (dComSessionOption1 != null) { bool flag = false; string empty = string.Empty; if (this.CertificateThumbprint != null) { flag = true; empty = "CertificateThumbprint"; } if (this.portSet) { flag = true; empty = "Port"; } if (flag) { base.ThrowConflictParameterWasSet("New-CimSession", empty, "DComSessionOptions"); return; } } } if (this.portSet || this.CertificateThumbprint != null) { if (dComSessionOption == null) { wSManSessionOption = new WSManSessionOptions(); } else { wSManSessionOption = dComSessionOption as WSManSessionOptions; } WSManSessionOptions port = wSManSessionOption; if (this.portSet) { port.DestinationPort = this.Port; this.portSet = false; } if (this.CertificateThumbprint != null) { CimCredential cimCredential = new CimCredential(CertificateAuthenticationMechanism.Default, this.CertificateThumbprint); port.AddDestinationCredentials(cimCredential); } dComSessionOption = port; } if (this.operationTimeoutSet && dComSessionOption != null) { dComSessionOption.Timeout = TimeSpan.FromSeconds((double)((float)this.OperationTimeoutSec)); } if (this.authenticationSet || this.credential != null) { if (this.authenticationSet) { authentication = this.Authentication; } else { authentication = PasswordAuthenticationMechanism.Default; } PasswordAuthenticationMechanism passwordAuthenticationMechanism = authentication; if (this.authenticationSet) { this.authenticationSet = false; } CimCredential cimCredential1 = base.CreateCimCredentials(this.Credential, passwordAuthenticationMechanism, "New-CimSession", "Authentication"); if (cimCredential1 != null) { object[] objArray = new object[1]; objArray [0] = cimCredential1; DebugHelper.WriteLog("Credentials: {0}", 1, objArray); outputCredential = cimCredential1; if (dComSessionOption != null) { object[] objArray1 = new object[1]; objArray1 [0] = dComSessionOption; DebugHelper.WriteLog("Add credentials to option: {0}", 1, objArray1); dComSessionOption.AddDestinationCredentials(cimCredential1); } } else { return; } } object[] objArray2 = new object[1]; objArray2[0] = outputOptions; DebugHelper.WriteLogEx("Set outputOptions: {0}", 1, objArray2); outputOptions = dComSessionOption; }
internal void NewCimSession(NewCimSessionCommand cmdlet, CimSessionOptions sessionOptions, CimCredential credential) { string localhostComputerName; DebugHelper.WriteLogEx(); IEnumerable <string> computerNames = ConstValue.GetComputerNames(cmdlet.ComputerName); foreach (string computerName in computerNames) { if (sessionOptions == null) { DebugHelper.WriteLog("Create CimSessionOption due to NewCimSessionCommand has null sessionoption", 1); sessionOptions = CimSessionProxy.CreateCimSessionOption(computerName, cmdlet.OperationTimeoutSec, credential); } CimSessionProxy cimSessionProxyTestConnection = new CimSessionProxyTestConnection(computerName, sessionOptions); if (computerName == ConstValue.NullComputerName) { localhostComputerName = ConstValue.LocalhostComputerName; } else { localhostComputerName = computerName; } string str = localhostComputerName; CimSessionWrapper cimSessionWrapper = new CimSessionWrapper(0, Guid.Empty, cmdlet.Name, str, cimSessionProxyTestConnection.CimSession, cimSessionProxyTestConnection.Protocol); CimNewSession.CimTestCimSessionContext cimTestCimSessionContext = new CimNewSession.CimTestCimSessionContext(cimSessionProxyTestConnection, cimSessionWrapper); cimSessionProxyTestConnection.ContextObject = cimTestCimSessionContext; SwitchParameter skipTestConnection = cmdlet.SkipTestConnection; if (!skipTestConnection.IsPresent) { this.cimTestSession.TestCimSession(computerName, cimSessionProxyTestConnection); } else { this.AddSessionToCache(cimSessionProxyTestConnection.CimSession, cimTestCimSessionContext, new CmdletOperationBase(cmdlet)); } } }
internal CimCredential CreateCimCredentials(PSCredential psCredentials, PasswordAuthenticationMechanism passwordAuthentication, string operationName, string parameterName) { CimCredential cimCredential; ImpersonatedAuthenticationMechanism impersonatedAuthenticationMechanism; object[] objArray = new object[4]; objArray[0] = psCredentials; objArray[1] = passwordAuthentication; objArray[2] = operationName; objArray[3] = parameterName; DebugHelper.WriteLogEx("PSCredential:{0}; PasswordAuthenticationMechanism:{1}; operationName:{2}; parameterName:{3}.", 0, objArray); if (psCredentials == null) { PasswordAuthenticationMechanism passwordAuthenticationMechanism = passwordAuthentication; if (passwordAuthenticationMechanism == PasswordAuthenticationMechanism.Default) { impersonatedAuthenticationMechanism = ImpersonatedAuthenticationMechanism.None; } else if (passwordAuthenticationMechanism == PasswordAuthenticationMechanism.Digest || passwordAuthenticationMechanism == PasswordAuthenticationMechanism.Basic) { this.ThrowInvalidAuthenticationTypeError(operationName, parameterName, passwordAuthentication); return(null); } else if (passwordAuthenticationMechanism == PasswordAuthenticationMechanism.Negotiate) { impersonatedAuthenticationMechanism = ImpersonatedAuthenticationMechanism.Negotiate; } else if (passwordAuthenticationMechanism == PasswordAuthenticationMechanism.Kerberos) { impersonatedAuthenticationMechanism = ImpersonatedAuthenticationMechanism.Kerberos; } else if (passwordAuthenticationMechanism == PasswordAuthenticationMechanism.NtlmDomain) { impersonatedAuthenticationMechanism = ImpersonatedAuthenticationMechanism.NtlmDomain; } else { this.ThrowInvalidAuthenticationTypeError(operationName, parameterName, passwordAuthentication); return(null); } cimCredential = new CimCredential(impersonatedAuthenticationMechanism); } else { NetworkCredential networkCredential = psCredentials.GetNetworkCredential(); /* Send directly PSCredentials SecurePassword if NetworkCredentials password is only encrypted */ object[] domain = new object[3]; domain[0] = networkCredential.Domain; domain[1] = networkCredential.UserName; domain[2] = networkCredential.SecurePassword ?? psCredentials.Password; DebugHelper.WriteLog("Domain:{0}; UserName:{1}; Password:{2}.", 1, domain); cimCredential = new CimCredential(passwordAuthentication, networkCredential.Domain, networkCredential.UserName, networkCredential.SecurePassword ?? psCredentials.Password); } object[] objArray1 = new object[1]; objArray1[0] = cimCredential; DebugHelper.WriteLogEx("return credential {0}", 1, objArray1); return(cimCredential); this.ThrowInvalidAuthenticationTypeError(operationName, parameterName, passwordAuthentication); return(null); }
/// <summary> /// Build a CimSessionOptions, used to create CimSession. /// </summary> /// <returns>Null means no prefer CimSessionOptions.</returns> internal void BuildSessionOptions(out CimSessionOptions outputOptions, out CimCredential outputCredential) { DebugHelper.WriteLogEx(); CimSessionOptions options = null; if (this.SessionOption != null) { // clone the sessionOption object if (this.SessionOption is WSManSessionOptions) { options = new WSManSessionOptions(this.SessionOption as WSManSessionOptions); } else { options = new DComSessionOptions(this.SessionOption as DComSessionOptions); } } outputOptions = null; outputCredential = null; if (options != null) { DComSessionOptions dcomOptions = (options as DComSessionOptions); if (dcomOptions != null) { bool conflict = false; string parameterName = string.Empty; if (this.CertificateThumbprint != null) { conflict = true; parameterName = @"CertificateThumbprint"; } if (portSet) { conflict = true; parameterName = @"Port"; } if (conflict) { ThrowConflictParameterWasSet(@"New-CimSession", parameterName, @"DComSessionOptions"); return; } } } if (portSet || (this.CertificateThumbprint != null)) { WSManSessionOptions wsmanOptions = (options == null) ? new WSManSessionOptions() : options as WSManSessionOptions; if (portSet) { wsmanOptions.DestinationPort = this.Port; portSet = false; } if (this.CertificateThumbprint != null) { CimCredential credentials = new(CertificateAuthenticationMechanism.Default, this.CertificateThumbprint); wsmanOptions.AddDestinationCredentials(credentials); } options = wsmanOptions; } if (this.operationTimeoutSet) { if (options != null) { options.Timeout = TimeSpan.FromSeconds((double)this.OperationTimeoutSec); } } if (this.authenticationSet || (this.Credential != null)) { PasswordAuthenticationMechanism authentication = this.authenticationSet ? this.Authentication : PasswordAuthenticationMechanism.Default; if (this.authenticationSet) { this.authenticationSet = false; } CimCredential credentials = CreateCimCredentials(this.Credential, authentication, @"New-CimSession", @"Authentication"); if (credentials == null) { return; } DebugHelper.WriteLog("Credentials: {0}", 1, credentials); outputCredential = credentials; if (options != null) { DebugHelper.WriteLog("Add credentials to option: {0}", 1, options); options.AddDestinationCredentials(credentials); } } DebugHelper.WriteLogEx("Set outputOptions: {0}", 1, outputOptions); outputOptions = options; }
static void Main(string[] args) { Thread th = Thread.CurrentThread; th.Name = "MainThread"; var comparer = StringComparer.OrdinalIgnoreCase; var arguments = new Dictionary <string, string>(comparer); CimCredential Credentials = null; int maxThreads = 10; int timeout = 10; int workers, async; String mode = "all"; //we create a DComSessionOptions object to force our remote connections to use DCom instead of WinRM DComSessionOptions SessionOptions = new DComSessionOptions(); foreach (string argument in args) { int idx = argument.IndexOf('='); if (idx > 0) { arguments[argument.Substring(0, idx)] = argument.Substring(idx + 1); } if (argument.ToLower() == "help" || argument.ToLower() == "-h") { help(); System.Environment.Exit(0); } } List <String> targetHosts = new List <string>(); Console.WriteLine(""); //gather targets, either from file or directly from commandline if (arguments.ContainsKey("-l")) { targetHosts = arguments["-l"].Split(',').ToList(); if (arguments.ContainsKey("-f")) { Console.WriteLine("Error -- please only use one targeting flag at a time (-l or -f)"); System.Environment.Exit(1); } } else if (arguments.ContainsKey("-f")) { try { targetHosts = File.ReadAllLines(arguments["-f"]).ToList(); } catch { Console.WriteLine($"Error - the input file at {arguments["-f"]} could not be read"); System.Environment.Exit(2); } } else { Console.WriteLine("Error -- please to enter systems to target\n"); help(); Environment.Exit(1); } if (arguments.ContainsKey("-m")) { try { mode = System.Enum.Parse(typeof(Modules), arguments["-m"], true).ToString(); } catch { Console.WriteLine("Error -- invalid collection mode selected"); System.Environment.Exit(1); } } if ((arguments.ContainsKey("-d")) || (arguments.ContainsKey("-u")) || (arguments.ContainsKey("-p"))) { try { SecureString securepassword = new SecureString(); foreach (char c in arguments["-p"]) { securepassword.AppendChar(c); } Credentials = new CimCredential(PasswordAuthenticationMechanism.Default, arguments["-d"], arguments["-u"], securepassword); } catch { Console.WriteLine("Error -- if using alternative credentials, please ensure to include domain, username, and password (use a domain of . for a local account)"); System.Environment.Exit(1); } } //get available worker threads, we dont care about async. ThreadPool.GetAvailableThreads(out workers, out async); if (arguments.ContainsKey("-t")) { if (System.Convert.ToInt32(arguments["-t"]) <= workers) { maxThreads = System.Convert.ToInt32(arguments["-t"]); } else { Console.WriteLine("Error - not enough available worker threads in the .net thread pool (max available = " + workers + ")"); System.Environment.Exit(1); } } Console.WriteLine(workers + " worker threads available, will use up to " + maxThreads + " threads"); ThreadPool.SetMaxThreads(maxThreads, 1); //wait / timeout value for wmi connects if (arguments.ContainsKey("-w")) { timeout = System.Convert.ToInt32(arguments["-w"]); } TimeSpan interval = new TimeSpan(0, 0, timeout); SessionOptions.Timeout = interval; // if using CimCredential with creds not inherited from current session, we'll add to our session options if (Credentials != null) { SessionOptions.AddDestinationCredentials(Credentials); } Console.WriteLine("Starting collection on " + targetHosts.Count + " host(s)"); var count = new CountdownEvent(targetHosts.Count); foreach (string s in targetHosts) { ThreadPool.QueueUserWorkItem(status => { wmiConnect(s, SessionOptions, mode); count.Signal(); }); } count.Wait(); Console.WriteLine("----------Collection completed, results should be displayed above----------"); }