C# Impersonation technique - c#

I wanted to remove a config file from a remote machine having IP as : sj1slm612. Now the problem is i do not have full modification rights to that remote machine, so I'm using impersonation technique to do this. Normally when I'm connected to this remote machine via putty, I use 'sudo'. So my question is will the following code be able to solve my problem ? Thanks.
My Code :
AppDomain.CurrentDomain.SetPrincipalPolicy(System.Security.Principal.PrincipalPolicy.WindowsPrincipal);
using (WindowsIdentity Authorized_user = new WindowsIdentity("sj1slm612\\wtsnqa", "password"))
{
using (WindowsImpersonationContext context = Authorized_user.Impersonate())
{
File.Delete(#"/apps/instances/express_13000/configuration/standalone-full.xml");
File.Delete(#"/apps/instances/query_13100/configuration/standalone-full.xml");
File.Delete(#"/apps/instances/wppapi_13200/configuration/standalone-full.xml");
File.Delete(#"/apps/instances/wppgui_13300/configuration/standalone-full.xml");
Console.WriteLine("All config files removed from sj1slm612");
Console.ReadLine();

There are 2 problems with your approach:
You are trying to impersonate a remote machine account on a local machine; this won't work. The credentials of a machine account can only be validated by that machine. In addition, that account has no rights on the local machine, so it doesn't really make sense to impersonate it. You need to impersonate a domain account. When you use a tool like putty, the credentials are sent to the remote machine and not validated by the local machine. This is why you can use a machine account of the remote machine.
You need to give proper paths for the files. Nowhere do you indicate that these files are on the remote machine. Use something like "\\machine\c$\path\to\file".
The details on what are going to work or not will depend on your network and OS, which you didn't specify, though it sounds Linux-ish. There may be a different syntax for referring to remote files that you need to use.

Related

Remote Shared folders and drives C#

I want to access drives/folders/sub-folders/files on remote machines over network for a machine in C#.
I know of a using WMI for this. However WMI might not be executable over remote machines due to security permissions.
What are alternative way in C# to enumerate the folders/subfolders/files for remote machines over the network.
Thanks!
Gagan
Shared folders on a UNC path can be enumerated just like local directories, using the classes in the System.IO namespace, like Directory.EnumerateFiles.
foreach (var file in Directory.EnumerateFiles(#"\\machine\c$"))
{
}
However, as you say, there's a question of credentials. If you need to specify different credentials to access the shares, you'll have to authenticate against the remote machine. Luckily, there's a great solution in this answer for creating ad-hoc network connections:
using (new NetworkConnection("\\machine\c$", new NetworkCredential("username", "password")))
{
foreach (var file in Directory.EnumerateFiles(#"\\machine\c$"))
{
}
}
You can use forfiles, i am assuming all the machines are Windows.
Refer to this link for more information: Forfiles

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.

Streamwriter issue with remote machine

I am trying to create a file on the remote machine but I am getting The "Network name cannot be found". I checked the network path and I was able to access the path from my machine. Could you please let me know what could be wrong?
Here is my code.
using (StreamWriter sw = new StreamWriter("\\\\servername\\TEST1\\TEST\\NEWFILE.csv", true))
{
sw.WriteLine(sw);
}
Go to \servername\TEST1 and give write permission to the user or aspnet (if you have a web application) on test folder and then re-run your program. It will work.
To give write permissions, just refer to this article:
How to share a folder/File
In case it still does not work, replace servername with server IP address and do the same as stated above.
Give the access rights to the user under which this application runs either it is a IIS pool or windows service etc
it is surely a security isssue. you need to give Write access to the remote machine

Reading UNC path with FileSystemWatcher [duplicate]

I am trying to run a file watcher over some server path using windows service.
I am using my windows login credential to run the service, and am able to access this "someServerPath" from my login.
But when I do that from the FileSystemWatcher it throws:
The directory name \someServerPath is invalid" exception.
var fileWatcher = new FileSystemWatcher(GetServerPath())
{
NotifyFilter=(NotifyFilters.LastWrite|NotifyFilters.FileName),
EnableRaisingEvents=true,
IncludeSubdirectories=true
};
public static string GetServerPath()
{
return string.Format(#"\\{0}", FileServer1);
}
Can anyone please help me with this?
I have projects using the FileSystemWatcher object monitoring UNC paths without any issues.
My guess from looking at your code example may be that you are pointing the watcher at the root share of the server (//servername/) which may not be a valid file system share? I know it returns things like printers, scheduled tasks, etc. in windows explorer.
Try pointing the watcher to a share beneath the root - something like //servername/c$/ would be a good test example if you have remote administrative rights on the server.
With regards to the updated question, I agree that you probably need to specify a valid share, rather than just the remote server name.
[Update] Fixed previous question about the exception with this:
specify the name as #"\\someServerPath"
The \ is being escaped as a single \
When you prefix the string with an # symbol, it doesn't process the escape sequences.
I was just asked this question in regards to FileSystemWatcher code running as a service and the issue is permissions. I searched and found this question and answer but unfortunately none of the answers here solved the problem. Anyway, I just solved it, so I thought I would throw in the solution here for next guy who searches and find this question.
The drive was mapped as a logged in user but the service was running as LocalSystem. LocalSystem is a different account and does not have access to drives mapped by a user.
The fix is to either:
Authenticate first (I use a C# Class to establish a network connection with credentials)
Run your service as a user that has access to the share.
You can test LocalSystem authentication by using a LocalSystem command prompt, see How to open a command prompt running as Local System?
Even though this is already answered I thought I would put in my two cents worth becaus eyou can see this same error even if you supply valid paths.
You will get the same error when the process running the watcher does not have access to the remote share. This will happen if the watcher is in a service running under the System account and the share is created by a user. System does not have access to that share and wont recognize it, you will need to impersonate the user to get access to it.
although you can use a FileWatcher over the network, you will have to account for other factors, like disconnection of the network share. If your connection to the share is terminated (maintenance, lag, equipment reset, etc) you will no longer have a valid handle on the share in your filewatcher
You can't use directory watches over network shares, this is a limitation of the OS, not of .NET.

File.GetAttributes(unc) generating "Network path not found" error

I'm passing a UNC path to File.GetAttributes(). This works fine when running off my local, but when I move the site to the test server, I get a "Network path not found" error. I am able to navigate to the path from the test server, so I don't know why I would be getting this error. The code is very simple. This is where it errors out:
try
{
if (FileAttributes.Directory != (FileAttributes.Directory & File.GetAttributes(directory)))
directory = GetPath(directory);
}
catch...
Being able to navigate to the share from the server doesn't mean much - remember your application is running under another account, usually whatever the app pool is set to. That account normally does not have access to anything other than the resources in the local machine, because it's not a domain account.
Check what account the app pool is running under. You might have to change that to a domain account on your AD forest to be able to access things on other servers.
Most likely it is "NTLM one hop" issue - credentials of a remote user can't be passed to thrird server.
Machine 1:Browser -(credentials)-> Machine 2:ASP.Net site -(no credentials)-> Machine 3.
Solution is to access "machine 3" under known (i.e. process) account or use Kerberos.

Categories

Resources