Accessing Network Path in Windows Service C# - c#

I have developed a windows service using local system as Account. I have used
network path of file
FileInfo fi = new FileInfo(#"\\epm-server\penDocuments_LabMeds\" + Convert.ToString(dr["mrn"]) + "\\SyncedXML\\" + Convert.ToString(dr["xmlfile"]));
if (!fi.Exists)
boolFileNotFound = true;
A dynamic path of a file that is built from database.
It works fine when I run Windows Service in Debug Mode, but when I install it then fileNotExists returns TRUE always like the file doesnt exist but infact it does exist.
This is bugging me a lot now. Kindly help me why its not working. Its a server path. Its getting opened in my PC.
Thanks

Did you notice the double backslashes in front and after SyncedXML (\\SyncedXML\\)?
This is probably the cause of your error.
Additionally I'd use string.Format in such cases to reduce the inadvertently addition of unwanted characters:
var path = string.Format(#"\\epm-server\penDocuments_LabMeds\{0}\SyncedXML\{1}", dr[mrn], dr[xmlfile]);
var fi = new FileInfo(path);
Edit:
If it's permission-related, then it's very likely that your local system account (in whose context the service is running) isn't allowed to access the epm-server.
The path is accessible if you're opening it directly or if you're running the service in debug mode as this is happening in your user context (e.g. YOURDOMAIN\vickyshazad), and you're allowed to access the ressource, whereas NT AUTHORITY\SYSTEM is not.
It's usually a good practise to have a special service account for your developed windows service and grant this user only and exactly the required permissions (least privilege). Maybe ask your system administrator for a service user.
Local System (NT AUTHORITY\SYSTEM) is a highly privileged account that's not recommended to use in general (see MSDN).
Most services do not need such a high privilege level. If your service does not need these privileges, and it is not an interactive service, consider using the LocalService account or the NetworkService account.

Related

Access to the path is denied in ASP.Net

I have an ASP.Net application running in IIS which creates a file in a specified location using CsvWriter. If I use the full UNC path I get error that Access to the path is denied, however if I use Drive letter it works fine. What is puzzling me is that it does work with UNC path in development environment.
This code which creates the file
using (var writer = new StreamWriter(fileName))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
csv.WriteField("Foo");
csv.WriteField("Bar");
csv.NextRecord();
}
Following advice various posts such as Access to the path is denied and IIS7 Permissions Overview - ApplicationPoolIdentity and MS Documentation: Application Pool Identities. I was initially convinced my problem was security related. This was supported by the fact that the application would run perfectly in development environment (IIS Express) which uses my user credentials but not under IIS which uses Application Pool Identity. I gave MyApplicationPoolIdentity full access to the specific directory to no avail.
However, I discovered that if I use the drive letter (C:\myDirectory\mySubDirectory\myFile.csv) as opposed to the UNC path (\\myServer\myDirectory\mySubDirectory\myFile.csv) in production the file is created perfectly. Even though I have the application working my concern is that I may have some configuration issue with IIS or my server which may bite me later. So my question is what would cause the create file/write to fail using UNC path and not using Drive letter?
I am using Windows Server 2016.
Thanks
Tony
I think it is caused by permission issues. First, did you get any related error messages? Or you can try the following methods:
1.you can use Process Monitor to see which account is being used to access the share and what permission are required.
2.Check to ensure the account that IIS is running under has needed rights to the troublesome UNC.

Requested registry allow access without security leaks

Right now i am using an web application with code to read from and write to the registry. While debugging in Visual studio everything went fine but on the online test server it didn't run. the error exception message i am getting is:
System.Security.SecurityException: Requested registry access is not
allowed.
This is the code i am using:
private RegistryKey GetWritableBaseRegistryKey(string extendedPath)
{
var path = "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall";
return RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Default).OpenSubKey($"{path}\\{extendedPath}", true);
}
The sollutions i found where:
Solution 1
you will not be able to set AppPoolIdentity to a specific group, but
you can
create a local user (compmgmt.msc)
add the user to the administrator group (compmgmt.msc)
Set the application pool to run under that user, under Advanced Settings.
Obviously you know this is a very bad idea from a security
perspective, and should never ever ever be performed on a forward
facing server.
source
Solution 2
Create a separate console application to run the service in admin
modus so you could access the registry. This solution was performance
heavy because you need to run 2 separate applications.
Solution 3
Use this code to allow access to the registry.
RegistryPermission perm1 = new RegistryPermission(RegistryPermissionAccess.AllAccess, "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall");
perm1.Demand();
Or this code
RegistrySecurity rs = new RegistrySecurity();
string currentUserStr = Environment.UserDomainName + "\\" + Environment.UserName;
RegistryAccessRule accessRule = new RegistryAccessRule(currentUserStr, RegistryRights.WriteKey | RegistryRights.ReadKey | RegistryRights.Delete | RegistryRights.FullControl, AccessControlType.Allow);
rs.AddAccessRule(accessRule);
But these didn't work on the server however while debugging in visual studio the code ran fine.
In order for the web application to access the registry it must have sufficient permission. Consequently Solution 1 is the only one likely to work. It describes setting the web sites application pool to a user in the local administrators group. Its misses the steps about actually setting your IIS web site to use the newly created App Pool, which is why it might not work for you.
The technical process of reading a restricted registry, especially the application Uninstall registry key, inside a web server is really unlikely to be useful to you. Of what possible use is allowing a web server to access the servers own Application uninstall list going to be ?
I suspect you intend to open that registry key on the client's PC (my speculation) which is not going to be possible.

C# The network path was not found

Im having trouble with writing files to remote directory via network. The following code fails when I try to check if the directory exists:
if (!Directory.Exists(processingPath))
Directory.CreateDirectory(processingPath);
processingPath is composed like
processingPath = xxxObject.serverPath + "processing\\";
xxxObject.serverPath contains something like this
\\machineNetworkName\sharedFolder\
Its working properly, but when many requests are processing (running as tasks asynchronously), it stops working and failing into exception:
System.IO.IOException: The network path was not found.
Could you please help me what could be the problem and why it is failing after some time on network path???
Thanks for your solutions
I got the same error before, it was about authentication problems.
You have to be sure that you set properly the user on IIS, because it use a Default App Pool's identity which can't access to your NFS.
You can also use IIS virtual folders to set the identity.
(on IIS manager, see App Pool settings -> Identity and also virtual folders settings -> identity).
In my case, it worked better by using the Impersonation directly in the code, so I recommend you to use the VladL WrappedImpersonationContext Object: How to provide user name and password when connecting to a network share
Last thing to check, the owner of the files on your NFS server, if they were created under the root user, it might not work.
I had the same problem and solved it. The problem in my code and I see it in yours, too, is that you have the slash at the end of the network path.
Instead of processingPath = xxxObject.serverPath + "processing\\"; write: processingPath = xxxObject.serverPath + "processing";

Access problems to a local folder via a network share

I have a Windows service, running using the login localhost\administrator. This service is meant to invoke another executable (MyProcess.exe), which is supposed to write some stuff to a log file. The service uses Process.Start() to create the process, like so:
var p = new Process();
p.StartInfo.FileName = processFileName;
p.StartInfo.Arguments = arg;
p.Start();
Problem is, it appears that MyProcess.exe is being denied rights to write to the log file, even though localhost\administrator unquestionably has rights to the log folder. If I run MyProcess.exe from a command line, it works perfectly.
So, is it possible that the process is being executed using a different user login?
Can you think of any other reason why MyProcess.exe is being denied rights to write the log file?
UPDATE: the log file is being written to the local machine, but using a network address, i.e. \\MyPC\LogFolder. When I change the code to refer to C:\MyFolder, everything works fine. It's obviously having a problem with the network address (even though it's local).
What sharing settings do I need to put on the folder so that the local system account can access the file?
If you are using impersonating, than it impersonates a user that can be the currrent or a specified user. if not it will run under the Local System, with the privileges of the local system.
p.StartInfo.Domain = "UserName";
p.StartInfo.Password = "Passw0rd!";
You can get the username from:
Thread.CurrentPrincipal.Identity.Name
I've worked it out.
The problem, as noted in my update, is that the process was addressing the log folder using a network share address, \\MyPC\LogFolder, and when we switched the configuration so that it wrote instead to c:\Logfolder, it worked fine.
So it seems that when you address a local folder, the localhost\Administrator account is deemed to have sufficient rights. But when you go via the network share, you need to present valid network credentials, and localhost\Administrator just doesn't cut it. If you change to use MYDOMAIN\MyUser, it works even using the network share address.

a required privilege is not held by the client while uploading a temporary registry (C#)

While I am trying to upload a registry in my registries using the C# code , the application is throwing the error "a required privilege is not held by the client". If I am using the same code on some other machine it is working fine but not particularly on my machine
I am using below mentioned code to upload the registry files
Process my_p = new Process();
my_p.StartInfo.FileName = "reg";
my_p.StartInfo.Arguments = "load HKLM\TEST C:\Documents and Settings\Administrator\NTUSER.DAT";
my_p.Start();
my_p.WaitForExit();
System.IO.StreamReader srOutPut = my_p.StandardOutput;
System.IO.StreamReader srError = my_p.StandardError;
my_p.Close();
results = srOutPut.ReadToEnd().Trim();
Errors = srError.ReadToEnd().Trim();
Moreover One thing I have noticed that the above code I am using in http based web site, but when I am using it in a File Syatem based web site it is working fine. Please help I am not getting the error.
Regards,
Vikram
You can load RegLoadKey function directly to load the hive as a subkey. Another API is RegLoadAppKey but it works only starting from Windows Vista. Different versions of Reg.exe use the API. How you can read in the description the RegLoadKey you need have SE_RESTORE_NAME and SE_BACKUP_NAME privileges and enable these (see http://msdn.microsoft.com/en-us/library/ms717797.aspx). If you are in the Group of Administrators or Backup Operators you have these privileges. One more problem can be if Reg.exe use RegLoadKey function and you have a local administrative rights, but you start on Vista or Windows 7 a command without admin rights because of UAC (User Account Control).

Categories

Resources