Using WindowsIdentity to connect to ManagementScope(WMI) - c#

I have a .net core application that is hosted on IIS. This application utilizes System.Management to connect to other machines to gather information.
I am noticing that some of my calls are getting an access denied response. The application pool is running as a user that is an admin on the remote machines. However the ManagementScope does not appear to be using the Application pool's identity.
I was wondering if there is a way to use the WindowsIdentity while connecting to the remote machine?
I am looking for something like the following.
private ManagementScope GetManagementScope(string machineName)
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
ConnectionOptions options = new ConnectionOptions
{
Impersonation = ImpersonationLevel.Impersonate,
Username = identity.Name
// Something here to pass along the password?
};
ManagementPath path = new ManagementPath
{
Server = machineName,
NamespacePath = "\\root\\MicrosoftIISv2"
};
return new ManagementScope(path, options);
}
I have tried hard coding the User name and password and that works fine but I would really like to use the Application pools identity.

I think, and hope, there is no way to retrieve the password.
The only way is to pass it as external parameter and possibly stored in a secure application.
Maybe you can consider to store this secret in Azure Key Vault and retrieve that setting.

Related

IBMMQDotnetClient using windows credentials instead of application specified credentials

In using IBMMQDotnetClient v9.2.0.1 in .NET Core, I attempt to connect to a client using
private MQQueueManager Connect()
{
System.Collection.Hashtable properties = new System.Collections.Hashtable();
properties.Add(MQC.USER_ID_PROPERTY, "username");
properties.Add(MQC.PASSWORD_PROPERTY, "password");
// more settings below
return new MQQueueManager(QueueManagerName, properties);
}
The issue is this still attempts to pass my personal windows credentials even after having set the userid and password when configuring the queue manager properties. How do I ensure that the credentials passed by the application replace my personal windows creds when running the application.
Edit:
For more context, the output options are configured as:
public static readonly int OUTPUT_OPTIONS = MQC.MQOO_OUTPUT;
I am not sure if there can be other options that can ensure the passed creds are used as opposed to the windows creds.
For anyone in the future that runs into a similar situation I wanted to give an update on my resolution. I ended up running the IIS server with the credentials that were authenticated with MQ as opposed to a Network Service and this fixed the issue. This allowed me to use the queue manager that had already been set up, without changing its settings in any way.

Connecting to TfsTeamProjectCollection fails due to Application Pool Identity

I have ASP.Net application which uses TFS API and works under Domain. The problem is that locally everything works fine. After deployment to IIS, which is configured to use ApplicationPoolIdentity, my app is giving me 500 Internal Server Error. When I set Identity to use my username and password everything works fine again. App uses Windows authentication, and is used by multiple users.
We're submitting data to TFS, and if Identity is configured to my username, the in TFS history it shows that I have modified that item. We need it to be the user that actually made the modification.
Before in some places, like "Assigned To" or "Deployed By" I used
var currentDisplayName = System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName;
After I discovered this issue, resolved it by using
var currentDisplayName = System.Web.HttpContext.Current.User.Identity.Name;
But the issue where when i use Identity - ApplicationPoolIdentity, the app is not working.
Method where i get Team Project Collection:
var tfsTeamProjectUrl = ConfigurationProvider.TfsTeamProjectUrl;
var teamProjectCollection = new TfsTeamProjectCollection(new Uri(tfsTeamProjectUrl));
teamProjectCollection.EnsureAuthenticated();
return teamProjectCollection;
Locally this works fine, but on IIS, it wants to use Identity from IIS App Pools, But i need it to use credentials from the actual user.
UPDATE
I tried to Impersonate the actual user by doing this:
var tfsTeamProjectUrl = ConfigurationProvider.TfsTeamProjectUrl;
var baseUserConnection = new TfsTeamProjectCollection(new Uri(tfsTeamProjectUrl));
var ims = baseUserConnection.GetService<IIdentityManagementService>();
var username = System.Web.HttpContext.Current.User.Identity.Name;
var identity = ims.ReadIdentity(IdentitySearchFactor.AccountName, username,
MembershipQuery.None, ReadIdentityOptions.None);
var teamProjectCollection = new TfsTeamProjectCollection(new Uri(tfsTeamProjectUrl), identity.Descriptor);
teamProjectCollection.EnsureAuthenticated();
return teamProjectCollection;
But now i'm gettin
An exception of type 'Microsoft.TeamFoundation.TeamFoundationServerInvalidResponseException' occurred in Microsoft.TeamFoundation.Client.dll but was not handled in user code
Additional information: Please contact your administrator. There was an error contacting the server.
Technical information (for administrator):
HTTP code 500: Internal Server Error
It seems like IIS is deciding to try to access TFS with the app pool identity instead of the credentials that you are explicitly supplying. You are authenticating to the server but then not using the server object, so the app was reverting to whatever identity it was running under.
Try to use the authentication with below code:
string tfsServerUrl = "http://servername:8080/tfs";
System.Net.NetworkCredential tfsCredential = new System.Net.NetworkCredential("ServiceAccountName", "password", "DOMAIN");
TfsConfigurationServer tfs = new TfsConfigurationServer(new Uri(tfsServerUrl), tfsCredential);
tfs.Authenticate();

How to use EWS on hosted Exchange with Impersonation?

I want to create a service which to crawl all inboxes of all users on a hosted exchange server (“myclient.onmicrosoft.com”) via EWS.
This already works well when I connect to on-premise exchange servers in the same domain. But when I try to connect this service to a hosted exchange, it throws 401 (wrong authorization) errors. Of course, this is a different domain as the hosted exchange server.
My service runs on an on-premise server and uses a “god-mode” user to impersonalise to all active directory users. My question is: How to connect the users of my on-premise system correctly to the hosted exchange in a different domain?
Note: It works when I use the credentials directly and the impersonation way does work on on-premise installations.
What I did so far (and I wonder of this is the right way to do it): On our on-premise server I created a domain “myclient.onmicrosoft.com” just like on the hosted server and an AD user with the same name and password as on the hosted exchange (called “mytest#myclient.onmicrosoft.com”).
On my crawler service I did:
I got all AD users in our on premise server
var allUsers = SearchAllActiveDirectoryUsers();
foreach (DataRow user in allUsers.Rows)
{
String domainName = (String)user["DomainName"];
String samAccountName = (String)user["SamAccountName"];
String principalName = (String)user["PrincipalName"];
String principalDomainName = (String)user["PrincipalDomainName"];
String mail = (String)user["Mail"];
}
Then for each AD user I connected the user with the exchange service like this:
ExchangeService ex = new ExchangeService(version);
ex.Url = new Uri(“https://outlook.office365.com/EWS/Exchange.asmx”);
ex.Credentials = new WebCredentials("mytest#myclient.onmicrosoft.com", “XXX”, " myclient.onmicrosoft.com");
// THIS DOES WORK CORRECTLY!
ex.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, “mytest#myclient.onmicrosoft.com”);
//this does NOT work!
Any ideas what I am missing?
You need to use the credentials of your "god-mode" user, but set the ImpersonatedUserId to the AD user. Something like:
ex.Credentials = new WebCredentials("account_with_impersonation_rights#myclient.onmicrosoft.com", "password");
ex.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, "mytest#myclient.onmicrosoft.com");
When you connect to Office 365 via EWS, you always need to supply credentials. You can't use UseDefaultCredentials = true.

WMI remote connect in c# uses wrong username

I'm trying to create program in C#, that will retrieve some data from local or remote server. Local part is working great, remote connection does not at all. I'm getting access denied.
Here is the code
public void ConnectToWmi()
{
var options = new ConnectionOptions();
options.Username = "admin";
options.Password = "admin";
options.Impersonation = ImpersonationLevel.Impersonate;
options.EnablePrivileges = true;
var scope = new ManagementScope("\\SERVER_NAME\root\cimv2",options);
scope.Connect();
}
I have verified using wbemtest.exe, that connection acctually works.
When I examinated both connections using Wireshark I noticed strange thing - wbemtest is sending correct username "admin" but my program is sending username of current user logged on computer.
So i experimented a little and created administrator account with credentials username "admin" password "admin" on computer that I'm running my program on. And it works!
So in short: Why is my C# program using credentials of currently logged in user instead of credentials that I supplied to it in the code?
more info
server is running as virtual machine in Hyper V on my notebook
client OS is win 8.1, server is win 7
connection between client and server works and all firewalls are disabled

Why does ActiveDirectory authentication using .Net DirectoryServices work for all but one user?

I'm using the following C#/.Net code on Windows(7/2008/etc) to authenticate users against active directory:
DirectoryEntry entry =
new DirectoryEntry(domainPath, domain + #"\" + username, password);
object obj = entry.NativeObject;
This works for hundreds of users, but not for one. I suspect it's something in the active directory account setup. The user has no problem authenticating on Windows with the exact same credentials or accessing network resources using windows integrated authentication. The user is a sys admin and is also set up as a remote admin.

Categories

Resources