How to give Folder Permission for IIS User in C#? - c#

I need to give Folder Permission for IIS User.
Actually I wrote code like this..
public static void AddDirectorySecurity(string FileName, string Account, FileSystemRights Rights,AccessControlType ControlType)
{
DirectoryInfo dInfo = new DirectoryInfo(FileName);
DirectorySecurity dSecurity = dInfo.GetAccessControl();
dSecurity.AddAccessRule(
new System.Security.AccessControl.FileSystemAccessRule(objUser, Rights, ControlType));
dInfo.SetAccessControl(dSecurity);
}
I calling this above method like this...
void givepermission()
{
DirectoryInfo a = new DirectoryInfo(Server.MapPath("~/resources"));
AddDirectorySecurity(Server.MapPath("~/"), "IUSR", FileSystemRights.FullControl,AccessControlType.Allow);
}
But Locally its working. When going server not working.
Instead of IUSR I tried following Account Names but that also not working ..
IIS_IUSRS
IIS_WPG
Network Service
Everyone
etc..
Instead IIS_IUSRS. I Tried like this also...
System.Environment.MachineName + "\\IIS_IUSRS"
IIS_IUSRS_System.Environment.MachineName
System.Environment.UserDomainName + "\\IIS_IUSRS"
etc..
but this also not working, but it's throwing
"Some or all identity references could not be translated"
Note:I Don't want to set the Permission Manually
Please can some one help me with this..?

public static void FolderPermission(String accountName, String folderPath)
{
try
{
FileSystemRights Rights;
//What rights are we setting? Here accountName is == "IIS_IUSRS"
Rights = FileSystemRights.FullControl;
bool modified;
var none = new InheritanceFlags();
none = InheritanceFlags.None;
//set on dir itself
var accessRule = new FileSystemAccessRule(accountName, Rights, none, PropagationFlags.NoPropagateInherit, AccessControlType.Allow);
var dInfo = new DirectoryInfo(folderPath);
var dSecurity = dInfo.GetAccessControl();
dSecurity.ModifyAccessRule(AccessControlModification.Set, accessRule, out modified);
//Always allow objects to inherit on a directory
var iFlags = new InheritanceFlags();
iFlags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
//Add Access rule for the inheritance
var accessRule2 = new FileSystemAccessRule(accountName, Rights, iFlags, PropagationFlags.InheritOnly, AccessControlType.Allow);
dSecurity.ModifyAccessRule(AccessControlModification.Add, accessRule2, out modified);
dInfo.SetAccessControl(dSecurity);
}
catch (Exception ex)
{
MessageBox.Show("Error");
}
}

Based on the Application Pool Identities article:
IIS introduces a new security feature in Service Pack 2 (SP2) of
Windows Server 2008 and Windows Vista. It's called Application Pool
Identities. Application Pool Identities allow you to run Application
Pools under a unique account without having to create and manage
domain or local accounts. The name of the Application Pool account
corresponds to the name of the Application Pool.
Here's a good explanation of what happens:
In Windows 7, IIS application pool isolation was taken yet to a
different level. The new change introduced in IIS7 (Windows Server
2008) was a new option to run your application pool as AppPoolIdentiy.
However, the default for an application pool identity in IIS7 remained
the same – NetworkService. In IIS7.5, AppPoolIdentiy becomes a
default. Thus, scripts previously expecting permissions for their
application pool identity to be set to “NT Service\NetworkService”
will now have to set permissions (ACLs) for “IIS AppPool\” – the user account created for each new application pool.
Thus, to set permissions for the DefaultAppPool, the scripts will
need to set ACLs for “IIS AppPool\DefaultAppPool”.

Related

how to modify hosts file using c# with an admin rights and without manual intervention

I've been trying with number of ways but I'm unable to avoid the alert which says 'Do you want to open the application as administrator'. can some one suggest such piece of code which avoids/handles the alert to add new entry into hosts file.
Thanks in advance..
public bool ModifyHostsFile(string sEntryIPAddr, string sEntryURL)
{
try
{
WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
bool administrativeMode = principal.IsInRole(WindowsBuiltInRole.Administrator);
if (!administrativeMode)
{
//ProcessStartInfo startInfo = new ProcessStartInfo();
//startInfo.Verb = "runas";
//startInfo.FileName = Application.ExecutablePath;
//Process.Start(startInfo);
//bool bStatus = GrantAccess(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), #"drivers\etc\hosts"));
using (StreamWriter w = File.AppendText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), #"drivers\etc\hosts")))
{
w.WriteLine(sEntryIPAddr + " " + sEntryURL);
}
Application.Exit();
}
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
}
private bool GrantAccess(string fullPath)
{
DirectoryInfo dInfo = new DirectoryInfo(fullPath);
DirectorySecurity dSecurity = dInfo.GetAccessControl();
dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
dInfo.SetAccessControl(dSecurity);
return true;
}
No, you definitely need admin access to modify the file - Or else any virus could hijack the hosts file and redirect all browsers requests to a malicious site.
I don't have the rep to comment to ask some question I have but instead I will answer based on assumptions.
Your goal
To run an application with administrative rights
Why the UAC popup?
The popup you get asking for Admin Rights is to prevent applications from simply taking admin rights without your knowledge and thereby modifying your system's critical files
How to prevent it?
I HIGHLY recommend not taking this step but the first option that comes to mind is to disable UAC (User Account Controls) from your control panel
Alternative
An alternative could be to run the program as a scheduled task, set to run with the highest privileges. Then you can execute the program by running the scheduled task and have admin access without the UAC popup.
This can be done via command-line or via the GUI and still requires admin privileges for the creation of the schedules task

Programmatically created file doesn't always inherit the permissions of the parent folder

(This may be better suited to ServerFault - if so please migrate it!)
We recently upgraded servers from Windows 2003 to Windows 2008. We have now been getting reports that certain PDF files which are dynamically generated are giving "access is denied" messages. I've verified that the folder has "Full Control" to the user group that is being utilized, yet it seems that intermittently files are created without inheriting the parent permissions.
For instance, the parent folder is called Paperwork. The "Users" group is set up to have full control to all files and subfolders within that directory. This works 95% of the time. Once in a while, though, a file will be created and when I view the security permission for that file, the "Users" group does not have Full Control access.
Is there something programmatic that needs to be changed for Windows Server 2008, or is this a configuration issue on the server itself?
take a look at this
try this :
private DirectorySecurity GetDirectorySecurity(string owner)
{
const string LOG_SOURCE = "GetDirectorySecurity";
DirectorySecurity ds = new DirectorySecurity();
System.Security.Principal.NTAccount ownerAccount =
new System.Security.Principal.NTAccount(owner);
ds.SetOwner(ownerAccount);
ds.AddAccessRule(
new FileSystemAccessRule(owner,
FileSystemRights.FullControl,
InheritanceFlags.ObjectInherit,
PropagationFlags.InheritOnly,
AccessControlType.Allow));
//AdminUsers is a List<string> that contains a list from configuration
// That represents the admins who should be allowed
foreach (string adminUser in AdminUsers)
{
ds.AddAccessRule(
new FileSystemAccessRule(adminUser,
FileSystemRights.FullControl,
InheritanceFlags.ObjectInherit,
PropagationFlags.InheritOnly,
AccessControlType.Allow));
}
return ds;
}
ref :
File permissions do not inherit directory permissions

Directory.CreateDirectory access to path is denied?

I have server-client application, it's a file manager
my problem is when I go inside a folder which requires access control like system folders, it becomes to read-only, but I need to move/delete or create new folder, how can I get the permission to do that?
here's how I create a new folder at the server side
public void NewFolder(string path)
{
try
{
string name = #"\New Folder";
string current = name;
int i = 0;
while (Directory.Exists(path + current))
{
i++;
current = String.Format("{0} {1}", name, i);
}
Directory.CreateDirectory(path + current);
Explore(path); //this line is to refresh the items in the client side after creating the new folder
}
catch (Exception e)
{
sendInfo(e.Message, "error");
}
}
There are often directories on a drive that even a user with administrator privileges cannot access. A directory with a name like "HDDRecovery" is quite likely to be troublesome like this. Surely it contains sensitive data that helps the user recover from disk failure. Another directory that fits this category is "c:\system volume information", it contains restore point data.
An admin can change the permissions on folders like this. But of course that doesn't solve the real problem nor is it a wise thing to do. Your user can't and shouldn't. Be sure to write code that deals with permission problems like this, simply catch the IOExeption. Keep the user out of trouble by never showing a directory that has the Hidden or System attribute set. They are the "don't mess with me" attributes.
If you want to remove directory read-only attribute use this: http://social.msdn.microsoft.com/Forums/en/vblanguage/thread/cb75ea00-f9c1-41e5-ac8e-296c302827a4
If you want to access system folders you can run your program as local administrator.
I had a similar problem (asp.net MVC vs2017) with this code:
Directory.CreateDirectory("~/temp");
Here is my solution:
// Create path on your web server
System.IO.Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath("~/temp"));
I also ran into an issue similar to this, but I was able to manually navigate through Windows Explorer and create directories.
However, my web app, running in VS on my laptop, hosted through my local IIS and not the built-in IIS deal for VS, was triggering the Access Denied issue.
So when I was hitting the error in code, I drilled down to glean more data from the System.Environment object and found the user, which of course was the App Pool that my app was running under in IIS.
So I opened IIS and opened the Advanced Settings for the app pool in question and changed the Identity to run under Network Service. Click OK. "cmd -> iisreset" for good measure. Try the app again, and SUCCESS!!!!
I had the same issue when creating a directory. I used DirectorySecurity as shown below:
DirectorySecurity securityRules = new DirectorySecurity();
securityRules.AddAccessRule(new FileSystemAccessRule(#"Domain\AdminAccount1", FileSystemRights.Read, AccessControlType.Allow));
securityRules.AddAccessRule(new FileSystemAccessRule(#"Domain\YourAppAllowedGroup", FileSystemRights.FullControl, AccessControlType.Allow));
DirectoryInfo di = Directory.CreateDirectory(path + current, securityRules);
Also keep in mind about the security as explained by Hans Passant's answer.
Full details can be found on MSDN.
So the complete code:
public void NewFolder(string path)
{
try
{
string name = #"\New Folder";
string current = name;
int i = 0;
while (Directory.Exists(path + current))
{
i++;
current = String.Format("{0} {1}", name, i);
}
//Directory.CreateDirectory(path + current);
DirectorySecurity securityRules = new DirectorySecurity();
securityRules.AddAccessRule(new FileSystemAccessRule(#"Domain\AdminAccount1", FileSystemRights.Read, AccessControlType.Allow));
securityRules.AddAccessRule(new FileSystemAccessRule(#"Domain\YourAppAllowedGroup", FileSystemRights.FullControl, AccessControlType.Allow));
DirectoryInfo di = Directory.CreateDirectory(path + current, securityRules);
Explore(path); //this line is to refresh the items in the client side after creating the new folder
}
catch (Exception e)
{
sendInfo(e.Message, "error");
}
}
My suspicion is that when you are running the application in client/server mode, the server portion needs to be running as Administrator, in addition to possibly removing read-only or system flags, to be able to do what you want.
That said, I agree with #HansPassant- it sounds like what you are trying to do is ill-advised.
Solved:
Directory created on remote server using below code & setting.
Share folder and give the full permission rights also in Advance
setting in the folder.
DirectoryInfo di = Directory.CreateDirectory(#"\\191.168.01.01\Test\Test1");
Test is destination folder where to create new Test1 folder(directory)

C# code to set a remote share to inherit permissions from its parent directory

I have two machines, call them client and server, in a Windows domain. The server has a shared directory which can be accessed from the client machine. I want to run a C# application on the client which sets the permission on this share to inherit the permissions of the share's parent directory on the server. How do I do this?
I have tried code along the following lines, but I don't think it has the right effect:
DirectoryInfo shareDirectoryInfo = new DirectoryInfo("\\server\share");
DirectorySecurity directorySecurity = shareDirectoryInfo.GetAccessControl();
directorySecurity.SetAccessRuleProtection(false, false);
InheritanceFlags iFlags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
FileSystemAccessRule accessRule = new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, iFlags, PropagationFlags.InheritOnly, AccessControlType.Allow);
bool modified;
directorySecurity.ModifyAccessRule(AccessControlModification.Set, accessRule, out modified);
if (modified)
{
Directory.SetAccessControl(name, directorySecurity);
}
I guess I don't understand why I have to create a FileSystemAccessRule for the directory - how can I just say inherit from parent?
Thanks for any help! Martin
You can set the folder to inherit from parent by using SetAccessRuleProtection
DirectoryInfo targetFolder = new DirectoryInfo(#"\\server\share");
DirectorySecurity folderSecurity = targetFolder.GetAccessControl(); // Existing security
folderSecurity.SetAccessRuleProtection(false, true); // This sets the folder to inherit
targetFolder.SetAccessControl(folderSecurity);
EDIT: The msdn document explains that if false is sent as the first argument, then the second argument is ignored.

C# Storing Folder Permissions

I'm having a little trouble with storing Folder Permissions. I was able to find a some documentation on writing them and reading them. What I'm trying to do is read the permissions on a folder for a specific user > Store it > change the permissions > after installer program finishes, change the permissions back.
I have all of it down (only due to code from many others) EXCEPT how to store the original folder permissions and set it back. I'll gladly read any material that you suggest, we receive several fatal errors with the software and this is one step to resolving many of them. All help is welcome and appreciated.
Below is an example of how I'm setting the permissions. Yes I know that I have everyone, but it is just for testing right now
public void setPermDir()
{
try
{
string DirectoryName = "C:\\Temp1\\";
Console.WriteLine("Adding access control entry for " + DirectoryName);
// Add the access control entry to the directory.
AddDirectorySecurity(DirectoryName, #"Everyone", FileSystemRights.FullControl, AccessControlType.Allow);
Console.WriteLine("Done.");
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.ReadLine();
}
// Adds an ACL entry on the specified directory for the specified account.
public static void AddDirectorySecurity(string FileName, string Account, FileSystemRights Rights, AccessControlType ControlType)
{
// Create a new DirectoryInfo object.
DirectoryInfo dInfo = new DirectoryInfo(FileName);
// Get a DirectorySecurity object that represents the
// current security settings.
DirectorySecurity dSecurity = dInfo.GetAccessControl();
// Add the FileSystemAccessRule to the security settings.
dSecurity.AddAccessRule(new FileSystemAccessRule(Account,
Rights,
ControlType));
// Set the new access settings.
dInfo.SetAccessControl(dSecurity);
}
If you return the DirectorySecurity dSecurity from AddDirectorySecurity then you could just call Directory.SetAccessControl(directoryName, dSecurity); once you were done with the modified access rules.
Update
If just SetAccessControl doesn't work the next step might be to explicitly remove the permissions you have granted using FileSystemSecurity.RemoveAccessRule.
Just keep a reference to the FileSystemAccessRule you create:
FileSystemAccessRule toRemoveWhenDone = new FileSystemAccessRule(Account, Rights, ControlType);

Categories