Unwanted files cannot be removed with SetAccessControl - c#

We have an application on a shared server, and some unwanted files appeared on our ftp (asp file, certainly by injection or lack of security). The application is in C#.
Impossible to remove those files by FTP (unauthorized).
I've made a GetOwner request and those files seem to have as owner DOMAIN\IISUSR.
I try to change owner or to add ACL on the file, but I receive an unauthorized exception.
System.IO.FileInfo sFile = new System.IO.FileInfo(sPathFile);
System.Security.AccessControl.FileSecurity sFS = sFile.GetAccessControl();
if (System.IO.File.Exists(sPathFile))
{
try
{
IdentityReference sGet = new NTAccount(#"DOMAIN\MYUSER");
sFS.AddAccessRule(new FileSystemAccessRule(#"DOMAIN\IISUSR", FileSystemRights.FullControl, AccessControlType.Allow));
sFile.SetAccessControl(sFS);
}
}
I've tried with MYUSER = the ftp account (to be able to remove it by ftp.
I've tried with MYUSER = IISUSR, if the file had the ownership but without rights.
But I can get rid of the exception.
As far as its a shared server, I have IIS Admin Remote access, but so only on read level; I have access on ftp and so access through C# local execution...
Do you have an idea ?
TY !

Related

How to read files in a mapped drive on asp.net website/page

I want to make a list of files from a provided path. actually I need to read all files from a given folder that is on some other server and not on my iis server.
I mapped the drive on my iis server to read it but its asking me for credentials when page loads. I dont want this. I have saved the credential on where the page has been uploaded on iis and mapped the drive.
string xrayPath = #"\\172.18.0.23\or\CARM\" + xrayPath;
List<FileInformation> directories = new List<FileInformation>();
List<FileInformation> lstFiles = new List<FileInformation>();
List<FileInformation> lstAllFiles = new List<FileInformation>();
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(xrayPath);
int fileId = 0;
PoplateFiles(ref lstFiles, ref directories, dir, 0, ref fileId);
foreach (var file in directories)
{
file.isDirectory = true;
lstAllFiles.Add(file);
}
foreach (var file in lstFiles)
{
file.isDirectory = false;
lstAllFiles.Add(file);
}
//////////
Please help me out, it works in visual studio when I test it but when I deploy it on iis on server, then it's asking me for credential and I am providing the credentials on browser, even then nothing happens. Please guide me.
I think I have resolved the issue myself. On the server where I mapped the drive, I created an application pool and selected the user that has access to the mapped drive in the identity field of application pool and set the Load User Profile to true.
then I assigned that application pool to my application virtual directory. Now, this code worked fine. Before that actually the identity user on application pool had no access to the other network path/mapped drive. So, I provided that user who had access to the path ie. in the security tab of the mapped folder. Now it runs under that user, so it doesnt ask for credentials. I hope it works....

How can I take ownership of files with incorrect security?

I have a folder structure on a (Server 2003 SP2) file server and I need to delete it using C#. I can't do that because I get System.UnauthorizedAccessException: Access to the path '\\xyz\blah\...' is denied. (where the path points to a sub-folder) because the permissions on the sub-folder are incorrect. So, I've been trying to take ownership of the files and this fails with System.UnauthorizedAccessException: and now I'm stuck.
Detail
I have an admin tool used by users with minimal privs. They need to delete folders and files to which they don't have access, so I wrote a UI which calls a web service. The web service runs under an AppPool with a domain account which is (now) a member of Administrators on the file server, so it should have access to delete the files and folders. But some of the folders have incorrect permissions. For example, when I log onto the file server with an account in Administrators and open the security tab for the folder, I see:
And for these folders my code doesn't work.
I've given the appPool account 'Take ownership of files or other objects' on the web server using Local Security Policy. Other posts (e.g. this one) have pointed out that you need to explicitly enable SeTakeOwnershipPrivilege in code and recommended Process Privileges which I'm using in my web service:
using (new PrivilegeEnabler(process, Privilege.TakeOwnership))
{
System.Diagnostics.Debug.WriteLine(String.Format(
"Privilege:TakeOwnership status: {0}.",
process.GetPrivilegeState(Privilege.TakeOwnership)));
SetFolderOwnerToCurrentUser(folderName, groupName);
}
When I run this, I see:
Privilege:TakeOwnership status: Enabled.
(Before adding the priv via LSP, I was seeing Privilege:TakeOwnership status: Removed.)
In SetFolderOwnerToCurrentUser if I just use
var directorySecurity = new System.Security.AccessControl.DirectorySecurity();
directorySecurity.SetOwner(WindowsIdentity.GetCurrent().User);
System.IO.Directory.SetAccessControl(folderPath, directorySecurity);
I also get System.UnauthorizedAccessException: Access to the path '\\fs\blah' is denied. Again, it's the sub-folder it's complaining about.

Reading File From Network Location

I am having Bunch of Files in A folder which is shared on Network Drive . I am trying to Access those Files into my Code . But It is giving an error:
System.IO.DirectoryNotFoundException was unhandled by user code
Fname = txtwbs.Text;
DirectoryInfo objDir = new DirectoryInfo("Y:\\");
_xmlpath = objDir + "\\" + Fname + "\\" + Fname + ".xml";
if (File.Exists(_xmlpath ))
{
reader(_xmlpath);
}
I have Also used:
file = fopen("\\\\10.0.2.20\\smartjobs\\Eto\\"+Fname);
I am Able to Read File from My Local PC But it is giving Exception Only for Network Location .Please let me know how can I read File From Network Shared Location .
And Also How Can I Make A tree view of Folders into Asp.net Web Application .
Directory Structure is Like that
\\10.0.2.20\Smartjobs\Eto\
this is Parent Directory It is congaing Nos of Folder having XML Documents.
In asp.net, you cannot access network folder directly because asp.net runs under anonymous user account, that account does not have access to that location.
You can give rights to "Everyone" in that shared location and see if it is working. However this is not advisable.
Alternativly You may have to do impersonation in asp.net code when accessing network location. You will have to do implersonation with the user who has access to that shared location.
You may have map the shared directory as a user, but you forget that the asp.net is running under the account of the pool, and there you do not have connect the y:\ with the shared directory.
The next think that you can do is to direct try to connect via the network shared name, eg: \\SharedCom\fulldir\file.xml
You need to specify that the ASP.net page run as a certain user with access to the file. Then, you need to enable impersonation in your web.config file in order for ASP.net to actually access the file as that user.
Your Y drive is a mapped network drive. You need to use the network
url eg \\server\Smartjobs\Eto\xyz.xml
You specify the name of the file on the network just like you do from anywhere else:
Dim myStream As IO.FileStream = IO.File.Open("\\myserver\myshare\myfile", IO.FileMode.Open)
Dim myBytes As Byte()
myStream.Read(myBytes, 0, numberOfBytesToRead)
More reference:
Unable to List File or Directory Contents on ASP.NET Page using Shared Drive
Using file on network via IIS

File Access Denied

I am using an FTPClient library to transfer files from a Windows share to an FTP server.
The SendFile method of the library uses the following code:
FileStream stream = new FileStream(localFileName, FileMode.Open);
This results in a System.UnauthorizedAccessException being thrown, however I am able to open, rename, and move the file using Windows Explorer under the same user account which the code is being executed.
Can anyone tell me why this is happening?
Edit:
The strange thing is that I can access other files on the share which have been granted the same NTFS permissions as the one that I can't.
This is also a Windows forms app.
Update:
Still no luck with this. I am able to read the file using a StreamReader but not a file stream. I can't understand why the two behave differently.
Are you sure it's the same user account?
Can you try something like
MessageBox.Show(WindowsIdentity.GetCurrent().Name);
?
Also, are you sure the file isn't read-only? Do you need write access to the file?
Otherwise you could try:
FileStream stream = new FileStream(localFileName, FileMode.Open, FileAccess.Read);
The process that is running your code does not have permissions on the file.
Is it part of a web application - if so you need to give access to the ASPNET account.
Give permission to 'everyone' on the file, and see if it still has problems.
Is your project being run from a network drive? If so that that will mean it runs in a restricuted priviliges mode that could cause this. Try copying the project to your C drive and running it again.
It's near FileSecurity class.
See at FileSecurity class
and try:
// Get a FileSecurity object that represents the
// current security settings.
FileSecurity fSecurity = File.GetAccessControl(localFileName);
// Add the FileSystemAccessRule to the security settings.
fSecurity.AddAccessRule(new FileSystemAccessRule("DOMAIN\USERNAME",
FileSystemRights.ReadData, AccessControlType.Allow));
// Set the new access settings.
File.SetAccessControl(localFileName, fSecurity);
1) NTFS permissions on the physical directory using explorer
2) Within the IIS MMC console FTP Site to allow read/write on the FTP folder
3) Ensure that the FTP Site or virtual directory actually exists, when checking the above step
http://www.eggheadcafe.com/forumarchives/inetserveriisftp/Jan2006/post25322215.asp

Is FileInfo.Copy accross network good solution? Is CAS required?

Seems that everything I do involves win services copying files across servers. I seem to get a lot of security & securityaccess type exceptions and never fully understand the causes. I am wondering if fileinfo or file.copy is a good solution or if there is a better. Is there a particular attribute I should be using or something to avoid these errors? Issue is not account or password related. example are \ipaddress\sharename \ipaddress\drive\path using domain accounts.
---Added Specific example.---
- I log on to serverA as domain\username. (including domain name)
- I open file eplorer in the address bar enter \\serverB\c$\folder hit enter, I right-click, create new file. No problem.
- I install service, go to properties select Log On, This Account and set the username as domain\username (including the domain name) same password I logged onto serverA with. It accepts it no problem.
Application does a FileSystemWatcher on \\serverA and copy to \\serverB when changed to keep the config files in sync.
private void CopyNewFileToClone()
{
FileInfo OriginalConfigFile = new FileInfo(Path.Combine(ConfigurationManager.AppSettings.Get("directoryToWatch"), ConfigurationManager.AppSettings.Get("fileToWatch")));
FileInfo CloneConfigFile = new FileInfo(Path.Combine(ConfigurationManager.AppSettings.Get("directoryToCopyTo"), ConfigurationManager.AppSettings.Get("fileToCopyTo")));
FileInfo tmp = new FileInfo(Path.Combine(CloneConfigFile.DirectoryName,"~" + CloneConfigFile.Name));
OriginalConfigFile.CopyTo(tmp.FullName, true);
tmp.CopyTo(CloneConfigFile.FullName, true);
tmp.Delete();
}
When I start the service I get Service cannot be started.
System.UnauthorizedAccessException: Access to the path '\\serverB\C$\folder\filename' is denied.
I use fileinfo to copy files from servers and it seems to work fine. If your sure it's not a account or password issue I would start looking at your DNS. If the network can't resolve what account is trying to access the network folder it won't matter if you are using a valid account. You may get lucky some/most of the time with cached accounts but there is no telling when it might not work and when it will work.
I would trace the network if you are getting a lot of broadcast messages for failed responses.
This was due to Code Access Security policy. Ran
c:\Windows\Microsoft.NET\Framework\v2.0.50727\CasPol.exe -af <path\application.exe>
and error resolved.
Adding as a installation step in all apps that need to write to HD, especially accross network via unc such as \server\share\file.

Categories