Yet another UnauthorizedAccessException with WMI - c#

I am trying to run application remotely on WinXP. Here is the code.
void RemoteExecute(string userName,
string password,
string path,
object[] commandLine)
{
ConnectionOptions options = new ConnectionOptions();
options.Impersonation = ImpersonationLevel.Impersonate;
options.Authentication = AuthenticationLevel.Default;
options.Username = userName;
options.Password = password;
options.Authority = null;
options.EnablePrivileges = true;
ManagementScope scope = new ManagementScope(path, options);
scope.Connect();
using (ManagementClass process = new ManagementClass("Win32_Process"))
{
process.Scope = scope;
process.InvokeMethod("Create", commandLine);
}
}
...
object[] commandLine = { "cmd.exe", null, null, 0 };
RemoteExecute("acid",
"123",
#"\\192.168.142.128\Root\CIMV2",
commandLine);
Then I got exception on scope.Connect(): Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)). Googling about this lead me to tweak Security settings on target machine. Here is what I have done.
Disabled firewalls on both source and target boxes
DCOMCNFG => Component Services => My Computer => Properties => COM Security => Access Permissions/Lunch and Activation Permissions => Edit Limits/Edit Default => add account/put all possible allow checkmarks.
WMI Control => Properties => Security ROOT and CIMV2 => Security => Added new account/put checkmark on Allow everywhere.
Tried with account administrator. No empty passwords.
What else should I do to avoid exception?

Related

Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))' firewall INetFwPolicy2

Access is denied.
private void MakeRule(string IP, int Protocole, NET_FW_RULE_DIRECTION_ ruleDirection, string ruleName)
{
Type tNetFwPolicy2 = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
INetFwPolicy2 fwPolicy2 = (INetFwPolicy2)Activator.CreateInstance(tNetFwPolicy2);
var currentProfiles = fwPolicy2.CurrentProfileTypes;
// Let's create a new rule
INetFwRule2 Rule = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
Rule.Enabled = true;
NET_FW_RULE_DIRECTION_ direction = ruleDirection;
Rule.Direction = direction; //Inbound
Rule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
Rule.Profiles = currentProfiles;
Rule.Protocol = protNumber; // ANY/TCP/UDP
try
{
Rule.RemoteAddresses = str;
}
catch (Exception)
{
MessageBox.Show("Can't add Rules. Maybe a Format failure?");
}
//Rule.LocalPorts = "81"; //Port 81
//Name of rule
Rule.Name = ruleName;
// ...//
//Rule.Profiles = (int)NET_FW_PROFILE_TYPE_.NET_FW_PROFILE_TYPE_MAX;
// Now add the rule
INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
try
{
firewallPolicy.Rules.Add(Rule);
}
catch (Exception ex)
{
throw ex;
}
}
If you want to make your app run as administrator, you can create a manifest file to make it work.
First, please right click your project and add a new item called Application Manifest File.
Second, please find requestedExecutionLevel tag and change into the following tag:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
Third, you will get a UAC prompt when they start the program. Choose Restart under different credentials.
Finally, you can run the program with the amdin power.
Also, you can read the following link to use c# code to run the app as admin.
Run as administrator C#
Testabc user have the administrator right.
//Run EXTERNAL APP AS AN ADMIN
var pass = new SecureString();
pass.AppendChar('t');
pass.AppendChar('e');
pass.AppendChar('s');
pass.AppendChar('t');
var ps1File = #"C:\Users\testabc\Desktop\LT_Admin.ps1";
ProcessStartInfo processAdmin;
processAdmin = new ProcessStartInfo();
processAdmin.UseShellExecute = false;
processAdmin.CreateNoWindow = true;
processAdmin.WindowStyle=System.Diagnostics.ProcessWindowStyle.Hidden;
processAdmin.Password = pass;
processAdmin.UserName = "testabc";
processAdmin.Domain = "soft";
processAdmin.FileName = #"C:\windows\system32\windowspowershell\v1.0\powershell.exe";
processAdmin.Arguments = $"-NoProfile -ExecutionPolicy unrestricted -file \"{ps1File}\"";
processAdmin.RedirectStandardOutput = true;
Process.Start(processAdmin);
In ps1File I have this code
Start-Process -FilePath "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" -Verb RunAs
Working perfectly...

Problem starting an exe file on remote machine using wmi

I followed some articles here and managed to start notepad.exe on a remote machine.
I am trying to start a third-party software we bought and installed on the remote machine once it restarts, but it's not running the exe..
object[] theProcessToRun = { #"C:\Program Files (x86)\xyz\xyz.exe" };
var connection = new ConnectionOptions
{
Username = "username",
Password = "password",
Authority = ""ntlmdomain:.local"",
};
var scope = new ManagementScope("\\\\IP\\root\\CIMV2", connection);
scope.Connect();
using (var managementClass = new ManagementClass(scope, new ManagementPath("Win32_Process"), new ObjectGetOptions()))
{
managementClass.InvokeMethod("Create", theProcessToRun);
}

Error Connecting to a VM on a different domain

This code works fine when opening two other VMs but gives me an RPC error on
opening a computer on a different domain. At the moment I am using the ConnectionOptions class to connect to the remote computer
`options.Username = dif_users[i]; // Assume correct user name
options.Password = dif_passwords[i]; // Assume correct password
if (i == 2) // To execute for the third VM. (i = 0 in the beginning)
{
//
options.Authentication = AuthenticationLevel.Packet;
options.Impersonation = ImpersonationLevel.Impersonate;
options.EnablePrivileges = true;
options.Authority = "ntlmdomain:DIFFERENT_DOMAIN";
}
ManagementScope scope = new ManagementScope("\\\\" + comps + "\\root\\cimv2", options);
scope.Connect(); // RPC server is unavaialaible
`

WMI connection error C#

using System;
using System.Management;
public class Class1
{
public static void Main()
{
string strComputer = string.Format(#"machineName.domainname\root\cimv2");
ConnectionOptions options = new ConnectionOptions();
options.EnablePrivileges = true;
options.Impersonation = ImpersonationLevel.Impersonate;
options.Authentication = AuthenticationLevel.Packet;
options.Authority = "ntlmdomain:InsTIL.com:InsTIL.com";
options.Username = "usr";
options.Password = "pwd";
ManagementScope oMs = new ManagementScope(strComputer, options);
SelectQuery query =new SelectQuery("Select * From Win32_Directory Where Name ='"+string.Format(#"C:\Scripts")+"'");
ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oMs,query);
ManagementObjectCollection oReturnCollection = oSearcher.Get();
if (oReturnCollection.Count < 1)
{
Console.WriteLine("Folder does not exist");
}
else
{
Console.WriteLine("Folder does exist");
}
}
}
I'm trying to connect to remote machine and checking existence of folder.But I'm getting below mentioned error.
I tried and incorporated changes discussed in remote wmi connection c# - invalid parameter error
Program abruptly stops working and throws below error:
Unhandled Exception: System.Management.ManagementException: Invalid parameter
at System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStat
us errorCode)
at System.Management.ManagementPath.CreateWbemPath(String path)
at System.Management.ManagementPath..ctor(String path)
at Class1.Main()
You need backslashes before your machine name. Change this:
string strComputer = string.Format(#"machineName.domainname\root\cimv2");
to this:
string strComputer = string.Format(#"\\machineName.domainname\root\cimv2");

C# WMI Win32_ScheduledJob properties

ConnectionOptions connOptions = new ConnectionOptions();
connOptions.Username = _username;
connOptions.Password = _password;
connOptions.Impersonation = ImpersonationLevel.Impersonate;
connOptions.Authentication = AuthenticationLevel.PacketPrivacy;
connOptions.EnablePrivileges = true;
ManagementScope manScope = new ManagementScope(_server, connOptions);
manScope.Connect();
ObjectGetOptions objectGetOptions = new ObjectGetOptions();
ManagementPath managementPath = new ManagementPath("Win32_ScheduledJob");
ManagementClass processClass = new ManagementClass(manScope, managementPath, objectGetOptions);
ManagementBaseObject inParams = processClass.GetMethodParameters("Create");
inParams["Name"] = "TESTER";
inParams["Owner"] = "Tester";
inParams["Command"] = command;
inParams["StartTime"] = "********171000.000000-300";
I'm tyring to connect to a remote system to create a scheduled task. I can create the scheduled tasks, but its being created with user - SYSTEM. I want it to be created under my user. I tried using the properties like 'Owner' and 'Name' eg:
inParams["Owner"] = ;
inParams["Name"] = ;
But they throw a ManagementException, "Not Found". Does anyone know how I can do this, or what might be wrong that I'm doing here...
Thanks
Creating a scheduled job with the Win32_ScheduledJob WMI class is equivalent to create job using the AT command. The AT service normally run under the Local\System account or the NetworkService Account. so when you uses this class your jobs are created using one of these accounts for more info about this topic you can check the remarks part of the MSDN documentation.

Categories