/// <summary> /// Gets the environment variables for the user. /// </summary> /// <param name="name"></param> /// <param name="value"></param> public IDictionary <string, string> GetUsersEnvironmentVariables() { if (!this.Created) { throw new InvalidOperationException("ProcessPrison has to be created first."); } var ret = new Dictionary <string, string>(); using (var impersonator = new UserImpersonator(this.WindowsUsername, this.WindowsDomain, this.WindowsPassword, true)) { using (var registryHandle = impersonator.GetRegistryHandle()) { using (var registry = RegistryKey.FromHandle(registryHandle)) { using (var envRegKey = registry.OpenSubKey("Environment", true)) { foreach (var key in envRegKey.GetValueNames()) { ret[key] = (string)envRegKey.GetValue(key); } } } } } return(ret); }
/// <summary> /// Sets an environment variable for the user. /// </summary> /// <param name="name"></param> /// <param name="value"></param> public void SetUsersEnvironmentVariable(string name, string value) { if (!this.Created) { throw new InvalidOperationException("ProcessPrison has to be created first."); } if (string.IsNullOrEmpty(name) || name.Contains('=')) { throw new ArgumentException("Invalid name", "name"); } if (value == null) { throw new ArgumentException("Value is null", "value"); } this.myenvvars[name] = value; using (var impersonator = new UserImpersonator(this.WindowsUsername, this.WindowsDomain, this.WindowsPassword, true)) { using (var registryHandle = impersonator.GetRegistryHandle()) { using (var registry = RegistryKey.FromHandle(registryHandle)) { using (var envRegKey = registry.OpenSubKey("Environment", true)) { envRegKey.SetValue(name, value, RegistryValueKind.String); } } } } }
private void UploadWorkFlow() { string taskListFile = string.Empty; string workFlowfile = string.Empty; //copy the workflow file to the remote location UpdateStatus("Uploading Workflow to device."); var creds = new NetworkCredential(_credential.UserName, _credential.Password, _credential.Domain); string scheduledTaskFolder = $@"\\{_serverInfo.Address}\c$\Program Files (x86)\HP\Embedded Capture Installer\scheduledTaskFiles"; scheduledTaskFolder = Path.Combine(scheduledTaskFolder, _sessionId); var workFlowStream = File.OpenRead(_data.WorkflowFile); UserImpersonator.Execute(() => workFlowfile = CreateRemoteFile(scheduledTaskFolder, Path.GetFileName(_data.WorkflowFile), workFlowStream), creds); UpdateStatus($"Created Workflow File on remote server at {workFlowfile}"); var workFlowDoc = XDocument.Parse(string.Format(Properties.Resources.UploadWorkFlow, workFlowfile, _data.ServerVersion)); UserImpersonator.Execute(() => taskListFile = CreateRemoteXmlFile(scheduledTaskFolder, "tasklist.xml", workFlowDoc), creds); UpdateStatus($"Created Task File on remote server at {taskListFile}"); UpdateStatus("Remote Task for Uploading workflow scheduled, and will run in 10 seconds."); var configureTask = InsertRemoteTask("Configure_HPEC", FdtFileName, $"\"{_deviceListFile}\" \"{taskListFile}\""); workFlowStream.Dispose(); if (!Retry.UntilTrue(() => IsTaskComplete(configureTask), 10, _retryTimeSpan)) { UpdateStatus("Upload Workflow Task did not complete successfully. Please check server for further information."); throw new Exception("Uninstallation Failed"); } UpdateStatus("Workflow uploaded successfully."); RemoveRemoteTask(configureTask); UpdateStatus("Scheduled Task removed successfully."); }
public void Destroy() { this.TerminateProcesses(); if (this.createInfo.NetworkOutboundRateLimitBitsPerSecond > 0) { NetworkQos.RemoveOutboundThrottlePolicy(this.WindowsUsername); if (this.createInfo.UrlPortAccess > 0) { NetworkQos.RemoveOutboundThrottlePolicy(this.createInfo.UrlPortAccess.ToString()); } } if (this.createInfo.UrlPortAccess > 0) { UrlsAcl.RemovePortAccess(this.createInfo.UrlPortAccess); } UserImpersonator.DeleteUserProfile(this.WindowsUsername, ""); WindowsUsersAndGroups.DeleteUser(this.WindowsUsername); if (this.jobObject != null) { jobObject.Dispose(); jobObject = null; } this.Created = false; }
private string CreateDeviceList(PrintDeviceInfo deviceInfo) { string activityUrn = "urn:hp:imaging:con:service:systemconfiguration:SystemConfigurationService"; string endpoint = "systemconfiguration"; string deviceListFileName = string.Empty; var jediDevice = new JediDevice(deviceInfo.Address, deviceInfo.AdminPassword); var systemConfigurationTicket = jediDevice.WebServices.GetDeviceTicket(endpoint, activityUrn); var deviceListDoc = XDocument.Parse(Properties.Resources.DeviceList); deviceListDoc.Element("DeviceList")?.Element("Name")?.SetValue($"DL#{DateTime.Now:HHmmdd}"); var deviceGuid = Guid.NewGuid(); var deviceElement = deviceListDoc.Element("DeviceList")?.Element("Devices")?.Elements("Device") .FirstOrDefault(); if (deviceElement != null) { deviceElement.Attribute("guid")?.SetValue(deviceGuid); deviceElement.Attribute("deviceId")? .SetValue( $"{systemConfigurationTicket.FindElement("MakeAndModel").Value}#{systemConfigurationTicket.FindElement("SerialNumber").Value}"); deviceElement.Attribute("ipAddress")?.SetValue(deviceInfo.Address); //we need to enter hashed password here, so let's do that later string hashedPassword = EncryptStringByAes(deviceInfo.AdminPassword, SaltString, BoundaryAeshk); deviceElement.Element("Password")?.SetValue($"{hashedPassword}"); deviceElement.Element("Model")?.SetValue(systemConfigurationTicket.FindElement("MakeAndModel").Value); deviceElement.Element("Hostname")?.SetValue(HostName(jediDevice)); deviceElement.Element("FactoryDefaultHostname")?.SetValue(HostName(jediDevice)); deviceElement.Element("MacAddress")?.SetValue(MacId(jediDevice)); deviceElement.Element("FwVersion")?.SetValue(jediDevice.GetDeviceInfo().FirmwareRevision); var fwDateTimeString = jediDevice.GetDeviceInfo().FirmwareDateCode; string format = "yyyyMMdd"; DateTime fwDateTime = DateTime.ParseExact(fwDateTimeString, format, CultureInfo.InvariantCulture); deviceElement.Element("FwDate")?.SetValue(fwDateTime.ToString("s")); deviceElement.Element("Ram")?.SetValue(systemConfigurationTicket.FindElement("MemoryInstalled").Value); deviceElement.Element("SerialNumber")?.SetValue(systemConfigurationTicket.FindElement("SerialNumber").Value); } string scheduledTaskFolder = $@"\\{_serverInfo.Address}\c$\Program Files (x86)\HP\Embedded Capture Installer\scheduledTaskFiles"; scheduledTaskFolder = Path.Combine(scheduledTaskFolder, _sessionId); UserImpersonator.Execute(() => deviceListFileName = CreateRemoteXmlFile(scheduledTaskFolder, "deviceList.xml", deviceListDoc), new NetworkCredential(_credential.UserName, _credential.Password, _credential.Domain)); return(deviceListFileName); }
public void BasicTest() { string rnd = (DateTime.Now.Ticks % 100).ToString(); string userbase = "UhuruTestUser" + rnd; string user1 = userbase + "1"; string user2 = userbase + "2"; string groupbase = "UhuruTestGroup" + rnd; string group1 = groupbase + "1"; string group2 = groupbase + "2"; // test users WindowsUsersAndGroups.CreateUser(user1, "test1234#"); WindowsUsersAndGroups.CreateUser(user2, "test1234#", "Delete me pls..."); using (new UserImpersonator(user2, "", "test1234#", true)) { } UserImpersonator.DeleteUserProfile(user2, ""); Assert.IsTrue(WindowsUsersAndGroups.ExistsUser(user2)); Assert.IsTrue(WindowsUsersAndGroups.GetUsers().Contains(user2)); WindowsUsersAndGroups.DeleteUser(user2); Assert.IsFalse(WindowsUsersAndGroups.GetUsers().Contains(user2)); Assert.IsFalse(WindowsUsersAndGroups.ExistsUser(user2)); // test groups WindowsUsersAndGroups.CreateGroup(group1); WindowsUsersAndGroups.CreateGroup(group2, "delete me too..."); Assert.IsTrue(WindowsUsersAndGroups.ExistsGroup(group2)); Assert.IsTrue(WindowsUsersAndGroups.GetGroups().Contains(group2)); WindowsUsersAndGroups.DeleteGroup(group2); Assert.IsFalse(WindowsUsersAndGroups.GetGroups().Contains(group2)); Assert.IsFalse(WindowsUsersAndGroups.ExistsGroup(group2)); // test users and groups Assert.IsFalse(WindowsUsersAndGroups.IsUserMemberOfGroup(user1, group1)); WindowsUsersAndGroups.AddUserToGroup(user1, group1); Assert.IsTrue(WindowsUsersAndGroups.IsUserMemberOfGroup(user1, group1)); WindowsUsersAndGroups.RemoveUserFromGroup(user1, group1); Assert.IsFalse(WindowsUsersAndGroups.IsUserMemberOfGroup(user1, group1)); WindowsUsersAndGroups.DeleteGroup(group1); WindowsUsersAndGroups.DeleteUser(user1); }
/// <summary> /// Sets an environment variable for the user. /// </summary> /// <param name="name"></param> /// <param name="value"></param> public void SetUsersEnvironmentVariables(Dictionary <string, string> envVariables) { if (!this.Created) { throw new InvalidOperationException("ProcessPrison has to be created first."); } if (envVariables.Keys.Any(x => x.Contains('='))) { throw new ArgumentException("A name of an environment variable contains the invalid '=' characther", "envVariables"); } if (envVariables.Keys.Any(x => string.IsNullOrEmpty(x))) { throw new ArgumentException("A name of an environment variable is null or empty", "envVariables"); } //if (envVariables.Values.Any(x => x == null)) //{ // throw new ArgumentException("A value of an environment variable is null", "envVariables"); //} foreach (string key in envVariables.Keys) { this.myenvvars[key] = envVariables[key]; } using (var impersonator = new UserImpersonator(this.WindowsUsername, this.WindowsDomain, this.WindowsPassword, true)) { using (var registryHandle = impersonator.GetRegistryHandle()) { using (var registry = RegistryKey.FromHandle(registryHandle)) { using (var envRegKey = registry.OpenSubKey("Environment", true)) { foreach (var env in envVariables) { var value = env.Value == null ? string.Empty : env.Value; envRegKey.SetValue(env.Key, value, RegistryValueKind.String); } } } } } }
/// <summary> /// get the counter sample for the machine /// </summary> public void Collect() { // if no user name then it means no need to impersonate if (!string.IsNullOrEmpty(_credentials.UserName)) { try { NetworkCredential networkCredential = new NetworkCredential(_credentials.UserName, _credentials.Password, _credentials.Domain); UserImpersonator.Execute(CollectCounters, networkCredential); } catch (Win32Exception w32Exception) { // we have an error with authorization, we will stop this counter from being collected again to prevent system overheads TraceFactory.Logger.Error("Halting collection on Host: {0}".FormatWith(this.TargetHost), w32Exception); _isError = true; } } else { CollectCounters(); } }
private void InstallHpec() { string taskListFileName = string.Empty; var installDoc = XDocument.Parse(string.Format(Properties.Resources.InstallHpec, _data.ServerVersion)); UpdateStatus("Installing HPEC from device."); string scheduledTaskFolder = $@"\\{_serverInfo.Address}\c$\Program Files (x86)\HP\Embedded Capture Installer\scheduledTaskFiles"; scheduledTaskFolder = Path.Combine(scheduledTaskFolder, _sessionId); UserImpersonator.Execute(() => taskListFileName = CreateRemoteXmlFile(scheduledTaskFolder, "taskList.xml", installDoc), new NetworkCredential(_credential.UserName, _credential.Password, _credential.Domain)); UpdateStatus($"Created Task File on remote server at {taskListFileName}"); UpdateStatus("Remote Task for Installing HPEC, and will run in 10 seconds."); var installTask = InsertRemoteTask("Install_HPEC", FdtFileName, $"\"{_deviceListFile}\" \"{taskListFileName}\""); if (!Retry.UntilTrue(() => IsTaskComplete(installTask), 30, _retryTimeSpan)) { UpdateStatus("Install Task did not complete successfully. Please check server for further information."); throw new Exception("Installation Failed"); } UpdateStatus("HPEC Installed successfully."); RemoveRemoteTask(installTask); UpdateStatus("Scheduled Task removed successfully."); }
private void LoadCategories(string machineName) { if (_loadFromMachine) { try { if (!string.IsNullOrEmpty(userName_textBox.Text)) { NetworkCredential networkCredential = new NetworkCredential(userName_textBox.Text, password_textBox.Text, string.IsNullOrEmpty(domain_textBox.Text) ? "." : domain_textBox.Text); UserImpersonator.Execute(() => LoadCategoriesImpl(machineName), networkCredential); } else { LoadCategoriesImpl(machineName); } } catch (Win32Exception w32Exception) { TraceFactory.Logger.Error(w32Exception); MessageBox.Show("Could not access counters. Please ensure the following services are running on remote machine: " + Environment.NewLine + "1. Performance Logs & Alerts" + Environment.NewLine + "2. Remote Registry. " + w32Exception.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly); server_ListBox.SelectedIndex = -1; return; } catch (UnauthorizedAccessException unauthException) { TraceFactory.Logger.Error(unauthException); MessageBox.Show("Unable to access host, please check the user credentials provided."); server_ListBox.SelectedIndex = -1; return; } catch (ArgumentException argException) { TraceFactory.Logger.Error(argException); MessageBox.Show("Could not access counters. Please ensure the following services are running on remote machine: " + Environment.NewLine + "1. Performance Logs & Alerts" + Environment.NewLine + "2. Remote Registry. ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly); server_ListBox.SelectedIndex = -1; return; } } else { //Load categories from the database. using (EnterpriseTestContext context = new EnterpriseTestContext()) { category_ListBox.Items.Clear(); var categoryTop = ResourceWindowsCategory.Select(context, "PerfMon").FirstOrDefault(c => string.IsNullOrEmpty(c.Name)); foreach (var counter in categoryTop.Children) { category_ListBox.Items.Add(counter.Name); } category_ListBox.SelectedIndex = -1; category_ListBox.SelectedIndexChanged += category_ListBox_SelectedIndexChanged; } } }