Trying to remotely access through wmi using C# - c#

I have this piece of code:
private ManagementScope CreateNewManagementScope(string server)
{
string serverString = "\\\\" + server + "\\root\\cimv2";
ConnectionOptions options = new ConnectionOptions();
options.Username = "name";
options.Password = "password";
ManagementScope scope = new ManagementScope(serverString, options);
scope.Connect();
return scope;
}
With that code I am trying to remotely access another PC though WMI. The password and the username are 100% correct (I tested them with wmic /node:pc /username:name /password:pwd and this worked) but I am getting access denied
(Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
Any Ideas what I am doing wrong? I am working with Win 7/C#/.NET 4.0
Thanks for any Help!

you can try with admin credential :
string serverString = #"\\" + strIPAddress + #"\root\cimv2"

Check what is logged on the other machines Security eventlog since it will provide you with a clue on what's wrong with access permissions.
I'm quite sure that you can solve the issue after checking the TechNet article "Connecting to WMI Remotely Starting with Windows Vista" and the related one. Specifically this part:
"Setting DCOM Security to Allow a User to Access a Computer Remotely".

Check the code of Services+ (Advanced Windows Service Manager) contains all what you need about WMI Win32_Service.
To Troubleshoot or debug:
Make sure the computer and server are on the same domain
Remove your code credential and make an EXE form your code then Run
the EXE as privileged user.
Use Services+ (mentioned above) or Services.msc to connect to the
server.
Make sure RPC service is running on Remote Server.
Try to trun off the firewall temporary on the server.

Related

Access denied when reading / writing to network location as a remote process

I'm currently trying to launch a process on a remote machine using WMI in C#. The process reads and writes to a file that is stored on a separate server.
When I manually login to the remote machine, I can run the process and it all works fine.
However, when I try to launch the process on the remote from my local machine using WMI, I get the following error:
System.UnauthorizedAccessException: Access to the path '\\server\path\input.txt' is denied.
I've tried multiple connection options, but I'm not sure how to re-create the permissions that I seem to have when I login manually... What do I need to do?
Local machine code
static void LaunchRemoteProcess(string remoteMachine, string command)
{
ConnectionOptions connectionOptions = new ConnectionOptions
{
Impersonation = ImpersonationLevel.Impersonate,
EnablePrivileges = true
};
var managementScope = new ManagementScope(string.Format(#"\\{0}\root\cimv2", remoteMachine), connectionOptions);
managementScope.Connect();
var managementPath = new ManagementPath("Win32_Process");
var objectGetOptions = new ObjectGetOptions();
var managementClass = new ManagementClass(managementScope, managementPath, objectGetOptions);
// Launch the command asynchronously
var inParams = managementClass.GetMethodParameters("Create");
inParams["CommandLine"] = command;
var outParams = managementClass.InvokeMethod("Create", inParams, null);
}
Remote machine code
string networkPath = #"\\server\path";
string inputFile = "input.txt";
string inputText = File.ReadAllText(Path.Combine(networkPath, inputFile));
string outputFile = "output.txt";
File.WriteAllText(Path.Combine(networkPath, outputFile), inputText);
Edit 1
I have already tried using the credentials of the user for which the process works if I log on to the remote machine manually and the process still fails with the same error:
ConnectionOptions connectionOptions = new ConnectionOptions
{
Username = "username",
Password = "password",
Authority = "ntlmdomain:COMPANYNAME.CO.UK,
EnablePrivileges = true
};
Am I missing something with regards to the Authority, Authentication, or Impersonation attributes?
Impersonation vs Delegation
Your WMI code uses impersonation, so the server side runs in the security context of the user who calls the code on the client. But this is only valid on the server itself, not for accessing e.g. a remote CIFS share (as in your case).
You have to use delegation.
First, change
Impersonation = ImpersonationLevel.Impersonate,
to
Impersonation = ImpersonationLevel.Delegate,
If you get an exception then, delegation does not yet work in your environment.
Check:
Calling user account: "Account is sensitive and cannot be delegated" must not be checked in the user properties (Active Directory Users and Computers)
server machine account: "Trust this computer for delegation to any service..." must be checked
local security policy on the server: "Enable computer and user accounts to be trusted for delegation" must include the calling user.
See
https://msdn.microsoft.com/en-us/library/aa389288%28VS.85%29.aspx
for further information on this topic.
Added: (see the comments below):
If Delegate is not an option in your environment (e.g. group policies do not allow for this, and you do not have the rights to change them), you may check some alternative ways.
You probably heard of psexec.
Or, what I did some years ago, and which runs in production in a enterprise environment on a few servers for many years very successfull:
I created a scheduled task which starts a program and set the technical user + password for this task. The task was configured for "run once in year 2200 :-)".
Then I wrote commands in a queue (I used a simple command file) and started the task from a remote machine.
Doing it this way, delegation is not required, since the scheduled task itself logs on as the technical user account ("logon as batch" privs are required).
As the reason states, the user id you are using on your PC does not seem to have access for to another computer's location (though it is a server, it is some other computer).
You may get access for your user id or use Impersonation to use an user id that already has access to the location.
Find more details here: https://msdn.microsoft.com/en-us/library/w070t6ka%28v=vs.110%29.aspx
Edited: Add user name password too. That may help.

ManagementScope.Connect failing with error E_ACCESSDENIED error while being run from Windows Service

I am trying to connect to Windows WMI through service by filling the ManagementScope variables and trying to connect to remote machine. The Connect is succeeding if I am running as windows console, but failing when I am running the same code from windows service.
The code Iam using is as follows:
ManagementScope scope = null;
scope = new ManagementScope("\\\\" + m_sComputerName + "\\root\\cimv2");
if (m_sLoginName != null && m_sPassword != null)
{
scope.Options.Username = m_sLoginName;
scope.Options.Password = m_sPassword;
}
scope.Options.EnablePrivileges = true;
scope.Options.Authentication = AuthenticationLevel.PacketPrivacy;
scope.Options.Impersonation = ImpersonationLevel.Impersonate;
scope.Connect();
I am running the windows service as Local System. The code is being written in C# with .net version 4.0
Any help much appreciated.
Thanks
By default, the LocalSystem account does not have access to network resources - see here. If you need to access network resources from your service, consider running it as a domain account. While it is possible to authorize access to remote resources for LocalSystem, doing so is not recommended. Another option would be to run the service as NT AUTHORITY\NetworkService - see here, in which case the service will be authenticated as the machine account when accessing network resources.

RabbitMQ C# connection trouble when using a username and password

I am at a loss here so I'm reaching out to the collective knowledge in hope of a miracle.
I have installed RabbitMQ on a Linux box using the defaults.
When I use this code (and the default RabbitMQ installation configuration) everything works nice.
var connectionFactory = new ConnectionFactory();
connectionFactory.HostName = "192.168.0.12";
IConnection connection = connectionFactory.CreateConnection();
But when I add a user to RabbitMQ and try to use the following code (username and password has been changed to protect the innocent. :) )
var connectionFactory = new ConnectionFactory();
connectionFactory.HostName = "192.168.0.12";
connectionFactory.UserName = "user";
connectionFactory.Password = "password";
IConnection connection = connectionFactory.CreateConnection();
the connectionFactory.CreateConnection() method throws the following exception:
BrokerUnreachableException
None of the specified endpoints were reachable
Checking the RabbitMQ logfile I can see it complaining about the credentials:
{amqp_error,access_refused,
"PLAIN login refused: user 'user' - invalid credentials",
'connection.start_ok'}}
The thing is that I am confident about the username and password and I cannot for the love of coding find a solution to this anywhere.
I must be missing something obvious but I can't figure out what it is.
I would be grateful for any helpful pointers.
It seems that I have found a solution to my own problem.
The following code works:
ConnectionFactory factory = new ConnectionFactory();
factory.UserName = "user";
factory.Password = "password";
factory.VirtualHost = "/";
factory.Protocol = Protocols.FromEnvironment();
factory.HostName = "192.168.0.12";
factory.Port = AmqpTcpEndpoint.UseDefaultPort;
IConnection conn = factory.CreateConnection();
Thanks for listening and perhaps this at least could be useful to someone else. :)
Here is how to create a user called agent with password agent, set it to be administrator and give it read and write access to all queues in the vhost /
rabbitmqctl add_user agent agent
rabbitmqctl set_user_tags agent administrator
rabbitmqctl set_permissions -p / agent ".*" ".*" ".*"
The accepted answer didn't work for me (on Windows).
I had to install the management tools:
rabbitmq-plugins enable rabbitmq_management
N.B. rabbitmq-plugins is in C:\Program Files (x86)\RabbitMQ Server\rabbitmq_server-3.3.1\sbin
Then, restart the RabbitMQ service.
I then installed EasyNetQ in Visual Studio in the package manager:
install-package easynetq
With this installed, I could use the admin web site located at:
http://localhost:15672
N.B. The default username and password is: guest
From here, I selected the Admin tab and the cause was clearly displayed in yellow at the top of the screen:
This user does not have permission to access any virtual hosts.
Use "Set Permission" below to grant permission to access virtual hosts.
To fix the issue I just pressed the Set permission button on the same screen et voila
N.B. for this to have worked you need to have added the user using rabbitmqctl add_user username password or similar (rabbitmqctl is also in the directory above).

Cannot connect to the ManagementScope via C#. Access denied

I'm trying to connect to the ManagementScope as follows:
ManagementScope scope = new ManagementScope( #"\\mydomain\root\RSOP\Computer"));
scope.Connect();
But an exception (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)) is thrown if the current user is not a domain administrator. How can a simple domain user connect to this management scope?
Thanks.
try this.....
ConnectionOptions con = new ConnectionOptions();
con.Username = "Administrator";
con.Password = "Password";
ManagementScope scope = new ManagementScope(#"\\" + strIPAddress + #"\root\cimv2", con);
scope.Connect();
Unfortunately you can't without elevating the domain user's privileges.
If you were writing a deployable application you could sandbox WMI access in a Windows Service hosting a WCF or Remoting application.
This service would be configured to run under an account with sufficient rights to access WMI. Your WCF/Remoting application would expose whatever functionality or data you need access to via wrapper methods. These methods could be called by client applications without elevated rights.

How to programmatically connect to IIS 7

I am trying to connect to IIS programmatically. I find there are a ton of examples online, but I can't seem to get any to work and have tried quite a few variations
Every time I try the following code the object that is returned has this error for each property: ..."threw an exception of type 'System.Runtime.InteropServices.COMException'"
using System.DirectoryServices;
String serverName = "serverName";
DirectoryEntry IIS = new DirectoryEntry("IIS://" + serverName + "/W3SVC");
IIS = new DirectoryEntry("IIS://" + serverName + "/W3SVC", "administrator", "mypassword");
IIS = new DirectoryEntry("IIS://" + serverName + "/W3SVC/1/ROOT", "administrator", "mypassword");
I am using Windows Directory user accounts and I have a bunch of sites running on IIS. I am trying this code on a windows xp development machine trying to connect to a windows 2008 Server with IIS 7. Anyone know what I am doing wrong?
Your account may not have launch permissions on the COM object wrapping the IIS calls. You may need to try adding yourself to the admin group on the box hosting IIS to get this to work.
Make sure you have the IIS6 management compatibility feature installed on the target server- you can't do remote management via ADSI on IIS7 without it.
Make sure that IIS is installed on your client machine - your program will throw a System.Runtime.InteropServices.COMException if it isn't installed.
This counts when you are looking at IIS on a remote machine too, the machine running your app will need IIS too.
EDIT: Also, I've recently discovered an assembly specifically for connecting to and configuring IIS7 - Microsoft.Web.Administration. Might be worth looking at whether you have access to this (or can get access, it should be on the machine with IIS7 in any case) and see what it can do. I'm afraid I've not used it myself, so I can't tell you if it'll do what you want, but it's another option to look into.
Finally, there's the option of System.Management and WMI scripts.
Dim scope As New Management.ManagementScope("\\" & server & "\root\MicrosoftIISv2")
scope.Connect()
Dim query As New Management.ObjectQuery("select * from IISWebVirtualDirSetting")
Dim searcher As New Management.ManagementObjectSearcher(scope, query)
For Each obj As Management.ManagementObject In searcher.Get()
DoSomethingWith(obj)
Next
The list of properties on obj is at http://msdn.microsoft.com/en-us/library/ms525005.aspx, there's also some more different queries you can run - just dig around on MSDN for more.

Categories