Windows service access to UNC path - c#

I have a windows service written in C# running on Windows Server 2012. The service is running as a domain user with permissions on the local machine and NTFS permissions to shared network resources
can access shared files and directories in Windows Explorer when logged on as this user
I reboot the server, the file system calls succeed at first. Then after some amount of time, or after accesses to the same file path from that computer, the programmatic calls will start to fail and will never spontaneously succeed again. Rebooting the server fixes the issue for a very short while.
I referred
Windows service cannot access UNC path
I am facing the same issue as in the above link. But the network share is between Windows server 2012 R2 and another server with same OS.
Exception stack trace :
MESSAGE:
An unexpected network error occurred.
STACK TRACE:
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileSystemEnumerableIterator1.MoveNext()
at System.Linq.Enumerable.Any[TSource](IEnumerable1 source)
Can anypne please help?

Related

Unable to access network path using WMI managementClass.InvokeMethod

I have been trying to launch text pad installation from network path to a remote machine using WMI managementclass.InvokeMethod.
However several attempts have failed with
error code 1602
So I created a batch file containing script to launch installation executable from network path in a remote machine, and tried to invoke it with managementclass.InvokeMethod.
However, even this didn't work.
I tried the same by changing the executable from network path to remote machine C:\path.
And it worked!!!
But I want to launch the installation executable from a network path.
I would be grateful if somebody would help me.

Windows, Start service System.InvalidOperationException: Cannot start service on computer '.' Access in Denied(Running as Admin)

I am trying to start service using the below code. This works fine for 99% machines but i get this issue on user machines. Any help to be able to reproduce this error or why this issue happens.
ServiceController sc = new ServiceController(name);
if (sc.Status == ServiceControllerStatus.Running ||
sc.Status == ServiceControllerStatus.StartPending)
{
sc.WaitForStatus(ServiceControllerStatus.Running);
Logger.Info("Service already running");
return true;
}
sc.Start();
Error I receive is
System.InvalidOperationException: Cannot start service on computer
'.'. ---> System.ComponentModel.Win32Exception: Access is denied
I am running with Administrator privileges
When creating the service I also run sc sdset command to make service start stop by non admin processes.
There is a whole thread about it in social msdn. The issue persisted for numerous users and it seems you do not have enough privileges to start the service, in which case you will have to change the service into Administrative account:
make sure that the service is set to Local Account by:
Rightclick on the property(in Services.msc panel).
select the Log on option
And then check again to see if it's working.
I am assuming you are trying to achieve a scenario similar to this, i.e., install a service and start it automatically.
Assuming you have made sure that you are really running as Administrator, i.e., the Admin command prompt or Run As Administrator.
Also, assuming you have restarted the machine to make sure that old version of your service is really removed, as you have tried multiple times to install / uninstall your service.
The error Access is denied essentially means that the user running it does not have access. Since you have said that you are running as Administrator, it is possibly that even Administrator does not have access to start the service. May be you are in a locked down environment (likely via Group Policy), where only the Domain Administrator is the "most powerful" !
The next step would be to investigate the permissions your service has. A useful tool for this is: SubInAcl
https://ss64.com/nt/subinacl.html
Display or modify Access Control Entries (ACEs) for file and folder Permissions, Ownership and Domain.
SubInAcl /service "your service name"
The above command is not easy to use ! You need to download it from the Microsoft web site.
Another useful tool is the SC command. This would normally be available by default.
Service Control - Create, Start, Stop, Query or Delete any Windows SERVICE.
SC sdshow "your service name"
would give details of the permission.
This would give you data which can help in further investigation.
You could also start / stop the service with this command. You can try with this to check whether you are getting the same exception when using this tool as well.
The following serverfault question gives some details about setting permission to a service
https://serverfault.com/questions/187302/how-do-i-grant-start-stop-restart-permissions-on-a-service-to-an-arbitrary-user
If you want to see the Stack trace from installutil you can use the /ShowcallStack option
https://learn.microsoft.com/en-us/dotnet/framework/tools/installutil-exe-installer-tool
/ShowCallStack
Outputs the call stack to the log file if an exception occurs at any point during installation.
This is not an answer, it is my further exploration of the question.
Here is the log
Running a transacted installation.
Beginning the Install phase of the installation.
See the contents of the log file for the
D:\devnet10\Flight\Flight.ServiceHost\bin\Debug\flight.servicehost.exe assembly's progress.
The file is located at D:\devnet10\Flight\Flight.ServiceHost\bin\Debug\flight.servicehost.InstallLog.
An exception occurred during the Install phase.
System.InvalidOperationException: An exception occurred in the OnAfterInstall event handler of Flight.ServiceHost.Installation.
at System.Configuration.Install.Installer.Install(IDictionary stateSaver)
at Flight.ServiceHost.Installation.Install(IDictionary stateSaver) in D:\devnet10\Flight\Flight.ServiceHost\Installation.cs:line 36
at System.Configuration.Install.Installer.Install(IDictionary stateSaver)
at System.Configuration.Install.AssemblyInstaller.Install(IDictionary savedState)
at System.Configuration.Install.Installer.Install(IDictionary stateSaver)
at System.Configuration.Install.TransactedInstaller.Install(IDictionary savedState)
The inner exception System.InvalidOperationException was thrown with the following error message: Cannot start service PreFlight on computer '.'..
at System.ServiceProcess.ServiceController.Start(String[] args)
at System.ServiceProcess.ServiceController.Start()
at Flight.ServiceHost.Installation.OnAfterInstall(IDictionary savedState) in D:\devnet10\Flight\Flight.ServiceHost\Installation.cs:line 49
at System.Configuration.Install.Installer.Install(IDictionary stateSaver)
The inner exception System.ComponentModel.Win32Exception was thrown with the following error message: Access is denied.
The Rollback phase of the installation is beginning.
See the contents of the log file for the D:\devnet10\Flight\Flight.ServiceHost\bin\Debug\flight.servicehost.exe assembly's progress.
The file is located at D:\devnet10\Flight\Flight.ServiceHost\bin\Debug\flight.servicehost.InstallLog.
The Rollback phase completed successfully.
The transacted install has completed.
[Update]
I should mention that I am running WIndows 10
I managed to create an installer using an installer project, which does work.
The issue by me was RunningAsLocalService in topshelf, hope this helps someone.

AccessDenied Exception on AppPool properties, cannot call ApplPool.Recycle() - C#

Running on Windows Server 2012 R2 Standard, with IIS 8.5.9600
In C#, after setting up a site, I'm retrieving the DefaultAppPool from the site.
Upon retrieval of the pool, the following properties have exceptions on them:
appPool.State:
Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
appPool.WorkerProcesses
at Microsoft.Web.Administration.Interop.IAppHostElement.get_Collection()
at Microsoft.Web.Administration.ConfigurationElement.GetCollection(String collectionName, Type collectionType)
at Microsoft.Web.Administration.ApplicationPool.get_WorkerProcesses()
So I cannot call
AppPool.Recycle()
It throws this exception:
Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
at Microsoft.Web.Administration.Interop.IAppHostMethodInstance.Execute()
at Microsoft.Web.Administration.ConfigurationMethodInstance.Execute()
at Microsoft.Web.Administration.ConfigurationElement.ExecuteMethod(String methodName)
at Microsoft.Web.Administration.ApplicationPool.Stop()
at EBI.Core.Common.WebHelper.IISHelper.AddApplicationIis7(String serverName, String applicationPool, String siteName, String applicationPath, String virtualDirectoryPath, String physicalPath, String defaultPage, Int32 deploymentType, String siteUrl)
Online research says to add high privileges to this folder:
C:\Windows\System32\inetsrv\config
So I have increasingly added the following:
SYSTEM
Administrators
IIS_IUSRS
INTERACTIVE
NETWORK
SERVICE
DefaultAppPool
NETWORK SERVICE
CREATOR OWNER
IUSR
BUT STILL SAME ERRORS.
It's probably a bad idea to add all those rights to that folder, so perhaps there is something else I might be missing, but I cannot find what it is. Any ideas?
Thanks for any help!
Whether you are trying to access the app-pool from any console application or windows service? If so then the console application or windows service should be executed with a username which has admin rights on the server. The username should also be part of IIS_WPG group. May be I have got your question totally wrong.
If using c# code and deploying to IIS Server then running AppPool.Recycle() can generate 'Access is denied' error.
Visit the application pool you are running the c# code under, and go to advanced Settings -> Identity and change the Identity to 'Administrator' or some user with Admin rights.

Service in Windows 7 operating system not using the hosts file as local service

I have programmed a Windows Service that is calling another service over the network.
The other service's IP is defined in the hosts file.
The Windows Service is running as local system.
On Windows Server 2008 this works fine. The IP from the hosts file is used.
On Windows 7, the IP from the hosts file is not used. Instead it uses normal DNS.
If I use a normal user instead of local system, the behaviour is correct. The same as on Windows Server 2008. The host file is used.
I can reliably switch between local system and a normal user for the same service binary without touching the hosts file, the error is reproducable. So it's not about caching anything anywhere or having a wrong hosts file.
Is there anything in Windows 7 I missed? Why would a service running as local system not use the hosts file?
The reason why it works as normal user could be this: you could have a duplicate hosts file in %LOCALAPPDATA%\VirtualStore, which is a redirection folder for programs running as non-admin and trying to write to system locations. If this is the case, then you actually see wrong hosts file when you think you edit the system's one!
The other reason could be wrong permissions set to file. Please try point 5 from https://serverfault.com/a/452269
First close other runnings applications and have a look at your system logs
You can run anything as system to debug like explorer.exe or cmd.exe
with the folowing command using PSTools you could then browser your hosts and check it
psexec -i -s cmd.exe
psexec -i -s ping your.host
Avoid multiple entry for the same host on hosts file
Even if you talked about it i post some debug commands
ipconfig /flushdns
nbtstat -R (reset netbios)
You can check DNS Cache
ipconfig /displaydns | more
Windows set the hosts file location with this registry key
\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\DataBasePath
Check proxy config it could bypass hosts
Check "etc" directory permission and "hosts" file permission

C# PrincipalContext The network path was not found

I am trying to use PrincipalContext to check if a local user group exists on a remote computer.
I am having problems with PrincipalContext:
PrincipalContext ctx = new PrincipalContext(ContextType.Machine, machine, null, ContextOptions.Negotiate)
It works in such scenarios:
local to local machine
local to virtual machine
domain machine to workgroup machine
However it doesn't work in opposite direction:
virtual machine to local host
workgroup machine to domain machine
I am getting these errors:
Unhandled Exception: System.IO.FileNotFoundException: The network path was not found.
Unhandled Exception: System.Runtime.InteropServices.COMException: The network path was not found.
The first exception is for virtual machine, second for workgroup machine.
All machines have user with the same name and password and the code was executed from that user.
How to solve this issue?
I found the answer. It looks that DirectoryServices doesn't work on remote Windows 7 or newer.
I guess when a computer is in a workgroup then it is local and we can connect and when it is in a domain then it is remote.
I followed steps described here:
System.IO.FileNotFoundException: The network path was not found. Exception while using DirectoryEntry object on windows 7
and here:
http://www.peppercrew.nl/index.php/2011/09/connect-to-remote-registry-fails-with-an-error-is-preventing-this-key-from-being-opened/
Enable File and Print sharing in the Firewall
Start the Remote Registry Service
Add remote user access to this registry entry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurePipeServers\winreg
However I can't change services and registry settings on production servers. I found such way to get group:
var server = new DirectoryEntry(string.Format("WinNT://{0},Computer", machine));
DirectoryEntry group = server.Children.Cast<DirectoryEntry>().Where(
d => d.SchemaClassName.Equals("Group") && d.Name.Equals("Administrators")
).Single<DirectoryEntry>();

Categories

Resources