Monitoring Windows service status remotely as non-administrator? - c#

Background: I have an application that, among other parts of its back-end, uses a server-side Windows service to do some of the computation.
What I'm trying to do is display the status of the service (Running vs. Stopped, essentially) on the client, such that the users can know (a) if the background computation is happening, or (b) if they need to go poke their IT guy to check the server. (It's written for an SME customer that doesn't have a full-time IT department or a budget that wants to be spent on fancy service-monitoring-and-alerting software.)
In itself, that's easy enough to do with ServiceController - if you're an administrator on the server, which the users, of course, aren't. Is there a way to read service status from a remote server in .NET as a non-administrative user? (All I need is to read the status; I don't need, and actually specifically don't want, to give the users the rights to stop/restart/alter the service in any way.)

If the user under which your application works doesn't have sufficient permissions for accessing services, you're likely to get an error like this:
service.Status threw an exception of type 'System.InvalidOperationException'
Cannot open MyService service on computer '192.168.0.7'. Access is denied.
You need to switch to another user context to be able to monitor it. If you don't want to do it for entire application (which is rather obvious), try impersonation for the actual piece of code which does the status checking. What should be the user? Actually for the safety reasons, it definitely shouldn't be the user who has an access for entire machine. It should has access just for controlling the services. Ask the administrator to create such a user for you. The status monitoring can be then executed like this:
public string GetServiceStatus(string machine, string service)
{
return Impersonate(
() =>
{
var service = new ServiceController(machine, service);
service.Refresh();
return service.Status;
}, USER, DOMAIN, PASSWORD
);
}
The entire thread with detailed solution can be found here.
Edit:
Let me explain the topic further. The solution I've provided gives the opportunity to change the user context, for some particular piece of code. It can be whatever you want e.g. service status checking. User, under context such an operation is going to be executed, can have granted the access to perform it, or not. It's completely different story though. It's the computer administrator responsibility to grant such an access. In the simplest case he can just add such a user to the Administrators group, which will be reckless, but he can also grant granular access using Group Policy. More detailed information regarding such an administration issues can be found here and here.

Related

Active Directory LDAP connection using System.DirectoryServices - The server is not operational

I'm working on an application that uses some kind of single sign on with Active Directory.
On my side, I'm trying to get some groups to see if the user is member of them.
Sometimes, I get the following error:
The server is not operational
The DirectoryEntry object is created like this:
using(DirectoryEntry ldapConnection = new DirectoryEntry(ldapDomain))
{ Path = ldapPath, AuthenticationType = AuthenticationTypes.Secure }
where ldapDomain is x.y.corp and the ldapPath is
LDAP://OU=someAppId,OU=someGroupName,OU=someClusterName,OU=someResourceName,DC=x,DC=y,DC=corp
After some analysis with the AD team we find out that the controller was removed from the x.y.corp domain but for some reason the Domain Controller is still redirecting to it but the server is down. This generates the error message shown above.
My questions are:
is there any possible retry mechanism or error handling on my side? (The exception is indeed catch now but is thrown further)
is there a way to tell the domain controller to not use the server anymore from backend code?
is there a problem with the construction of the DirectoryEntry? Is it possible to request the "DC" parameters one at a time and to redirect outside the domain...?
is there any cache on my side for domain controllers?
Thank you!
This is something your administrators need to fix. It sounds like DNS is still advertising the DC that is down. You can confirm this by typing this in the command line:
nslookup x.y.corp
The DNS lookup will show several IPs in a different order each time you do the lookup. Whichever one shows up first is the one that will be used.
If the IP address of the decommissioned DC still shows up in the list, then they need to fix that. Anything you do in code will just be a hack to get around something that shouldn't be happening in the first place.

Check if an Azure VM is running

I want to query an existing azure virtual machine to check whether it is fully deployed and able to be connected to remotely. Is there any way to do this using the Azure Rest API?
I've outlined my current process and why I desire such a call below.
I am using the Windows Azure management library to create a VM using ComputeManagementClient and the CreateDeploymentAsync function. This then returns a status of Succeeded, if I then do a get on the deployment it has a status of DeploymentStatus.Running.
After this has run I am trying to create a remote powershell connection so I can format the disk. I keep getting an error on this as it is unable to create the session.
WinRM cannot complete the operation. Verify that the specified computer name is valid, that the computer is accessible over the network, and that a firewall exception for the WinRM service is enabled and allows access from this computer. By default, the WinRM firewall exception for public profiles limits access to remote computers within the same local subnet. For more information, see the about_Remote_Troubleshooting Help topic.
If I go to the azure management portal the status is provisioning, I assume this is why i cannot create a session.
Process
CreateAzureVM()
CheckAzureVmCanBeConnectedTo() //I am unable to do this correctly
RunPowershellScriptOnVM() // this fails
You should be able to use Get Deployment to poll for the role's InstanceStatus (note that InstanceStatus != Status). When the InstanceStatus is ReadyRole, you should be able to log into your machine.
There's a distinction between a Deployment status and a Role InstanceStatus. Think of the role as an actual virtual machine, whereas a Deployment may describe multiple VMs.
SubscriptionCloudCredentials certificate = new CertificateCloudCredentials(subscriptionId, x509Certificate);
IComputeManagementClient ComputeManagementClient = new ComputeManagementClient(certificate);
var deployments = ComputeManagementClient.Deployments.GetBySlot(hostedServiceName, DeploymentSlot.YourDeploymentSlot);
var state = deployments.RoleInstances.First().PowerState;
I hope that this will help you.
Without seeing your code it's hard to say exactly what you need to do but I would recommend that you utilise the await keyword to wait for the completion of the call to the Azure API to create the VM. See the code samples under "Deploy a Virtual Machine" in this MSDN guide: http://msdn.microsoft.com/en-us/library/azure/dn722415.aspx#bk_createres

System.Runtime.InteropServices.COMException (0x80080005): Retrieving the COM class factory for component with CLSID

I am replacing MS Word MergeFields with data from SQL Server in a simple asp.net c# application and it works fine locally but when i publish it often i get the following:
System.Runtime.InteropServices.COMException (0x80080005): Retrieving the COM class factory for component with CLSID {00020906-0000-0000-C000-000000000046} failed due to the following error: 80080005.
I tried giving both IIS_IUSRS and NETWORK SERVICE full access, and also set the identity to interactive in the DCOM config but it didn't fix anything.
For nasty permissions stopping you from doing what you expect, (I've encountered in the past too). Sometimes I've had to change my DCOM/COM+ permissions to an object too. At the DCOM Config tab screen for your project, under security, make sure BOTH "Launch and Activation" and "Access" have been customized to explicitly include the user account you intend to allow.
Now, one more thing -- just to rule out all others. I've even gone the extent (for testing / confirmation only) is that on the "Identity" tab, you can select the "Interactive User", "Launching User" or "This User". I would put in your actual account that you KNOW has permissions (ensure your account is also in the launch and activation... and access permissions on previous tab). And also to enter/confirm your password.
If that still fails, then I would try adding the ADMIN account for permissions and try that... just for purposes of yes, its permissions based on a user. Once confirmed, you can scale it back, and even create some simplified restricted user who's primary purpose is to run this utility, and this new user has its adequate permissions to do so.
Once that is done, you should be good to go.
Now, that said, I've run into another flakey thing and its been a while, so it may not be an issue any more. Periodically, during certain "Windows" updates, the functionality would just stop working. However, if all I did was go back into user maintenance, do change password for the account (even if just keeping it the same original password) and saving it, then going back into DCOM and enter/re-confirm saving it there too, all became functional again.
You should share the folder where you save the document that is created from the template with the NETWORK SERVICE user.
Change the dcomcnfg identity to interactive instead of launching user.
Reference: Error : 80070005, there is something in this forum about
Retrieving the COM class factory for component with CLSID {7979FAA5-3A2A-4E50-A2C9-286C6F34C1D3} failed due to the following error: 80080005

Finding users' HOMEPATHs from a service

In the process of writing a service I have
//# Service Account Information
serviceProcessInstaller.Account = ServiceAccount.LocalSystem;
in the installer for it.
I was having problems writing a log to
static string USERS_HOME_DIR = Environment.GetEnvironmentVariable("HOMEDRIVE") + Environment.GetEnvironmentVariable("HOMEPATH");
since when the service was running (installed "as administrator") the event logger was reporting
Service cannot be started. System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Documents\Folder of Interest'
I need the HOMEPATHs of the users of the local_PC, any ideas how to get them?
UPDATE
Actually it would be better to just get the path for the currently logged on user, as their session and the service start. My sevice is not re-entrant but one user is better than none.
If I understand your question correctly what you're looking for are the special folder enumerations.
With something like:
String PersonalFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
If you want to run the service as the localsystem account there's a separate set of standards for storing the data. See this answer on serverfault.

Access Denied while trying to stop a C# Windows Service

I have created a C# web service using visual studio to stop the windows service 'Simple Mail Transfer Protocol (SMTP)' called SMTPSVC.
The following is the web method to do it:
[WebMethod]
public string StopService()
{
String status = "";
try
{
ServiceController scAlerter = new ServiceController("SMTPSVC");
Console.WriteLine(scAlerter.DisplayName);
Console.WriteLine(scAlerter.CanStop);
scAlerter.Stop();
Console.WriteLine("Service stopped");
status = "STOPPED";
}
catch (Exception e)
{
Console.WriteLine("Exception caught here" + e.ToString());
status = "Exception" + e.ToString();
}
return status;
}
I published this web service in my IIS 5.1 server. When I invoked the service it is throwing the following 'Access Denied' exception
<?xml version="1.0" encoding="utf-8" ?>
<string xmlns="http://y-square.org/">
ExceptionSystem.InvalidOperationException: Cannot open SMTPSVC service on
computer '.'. ---> System.ComponentModel.Win32Exception: Access is denied
--- End of inner exception stack trace --- at
System.ServiceProcess.ServiceController.GetServiceHandle(Int32 desiredAccess)
at System.ServiceProcess.ServiceController.Stop() at Service.RestartService()
in c:\Inetpub\wwwroot\RestartService\App_Code\Service.cs:line 38
</string>
By default the service is using the user account IUSER_system-name and I have added this user account into system Administrators group and also added ASPNET user account in Administrator group.
I was able to stop/start this windows service from C# standalone program successfully.
Can you kindly let me know what is the problem? Any permission settings or IIS user access rights shall I need to change in order to run this?
Also let me know which user account this C# service would use to stop the Windows Service?
Your help is much appreciated.
Thanks in advance,
Yogi
The IUSER_machinename (IUSER for short, in the following) account is, for good reasons, a relatively limited account, with little more privilege than a guest account. It isn't allowed to start and stop Windows services, or even to interrogate them (to get their status etc).
When run in the context of a stand-alone exe, the logic above is successful because the underlying account is [probably] you who is likely a member of the Administrators group, or a rather powerful account at any rate.
The easy, but unrecommended way out of this situation, is to give the IUSER account more privileges. Just to try add this account to the Administrators group, bam!, it will work (but will also introduce some potentially dangerous security hole).
A better approach is to make the explicit list of the particular Windows services that will be allowed to managed by way of IIS, and to set their individual service security descriptor to so that the IUSER account (or another account/group created for the occasion) be allowed to start and/or stop them as desired.
The difficulty in implementing this approach is that, to my knowledge, there's no GUI or intuitive admin tool to inspect and alter the services' security descriptor: you need to use sd and "learn" the SDDL language. Here are a few pointers to do so
MSDN Best practices and guidance for writers of service discretionary access control lists
sc sdshow command
sc sdset command

Categories

Resources