Setting ACE slow for folder with many files - c#

we have created an application which provides the ability to set a recursive "Deny" on a windows folder for a certain Active Directory group. Basically the same as going into the properties dialog in windows explorer and clicking on security and the adding an AD group with the permission of Deny.
We are using this code:
public void DenyAccessInherited(string DomainAndSamAccountName)
{
SetPermissionAndInherit(this.FolderPath,
NTFSPermission.PropagationFlags.CONTAINER_AND_OBJECT_INHERIT_ACE,
NTFSPermission.NTFSPermission_FULL_CONTROL, NTFSPermission.ACETypes.ADS_ACETYPE_ACCESS_DENIED,
DomainAndSamAccountName);
}
public static void SetPermissionAndInherit(string FolderPath, PropagationFlags Inheritance, int Permission, ACETypes ACETypeAccessAllowedDenied, string DomainAndUsername)
{
AccessControlList dacl = new AccessControlList();
SecurityDescriptor sd = new SecurityDescriptor();
AccessControlEntry newAce = new AccessControlEntry();
ADsSecurityUtility sdUtil = new ADsSecurityUtility();
OnProgress(DomainAndUsername, FolderPath);
sd = sdUtil.GetSecurityDescriptor(FolderPath, ADS_PATH_FILE, ADS_SD_FORMAT_IID);
dacl = sd.DiscretionaryAcl;
RemoveTrusteeFromDACL(dacl, DomainAndUsername);
newAce.Trustee = DomainAndUsername;
newAce.AccessMask = Permission;
newAce.AceFlags = (int)Inheritance;
newAce.AceType = (int)ACETypeAccessAllowedDenied;
dacl.AddAce(newAce);
sdUtil.SetSecurityDescriptor(FolderPath, ADS_PATH_FILE, sd, ADS_SD_FORMAT_IID);
foreach (string File in Directory.GetFiles(FolderPath))
{
SetACE(File, DomainAndUsername, Permission, PropagationFlags.INHERITED_ACE, ACETypeAccessAllowedDenied);
}
foreach (string SubFolderPath in Directory.GetDirectories(FolderPath))
{
SetInheritedPermission(SubFolderPath, DomainAndUsername, Permission, ACETypeAccessAllowedDenied);
}
}
private static void SetInheritedPermission(string FolderPath, string DomainAndUsername, int PermissionFlags, ACETypes AccessFlags)
{
AccessControlList dacl = new AccessControlList();
SecurityDescriptor sd = new SecurityDescriptor();
AccessControlEntry newAce = new AccessControlEntry();
ADsSecurityUtility sdUtil = new ADsSecurityUtility();
SetACE(FolderPath, DomainAndUsername, PermissionFlags, (PropagationFlags)(PropagationFlags.CONTAINER_AND_OBJECT_INHERIT_ACE | PropagationFlags.INHERITED_ACE), AccessFlags);
foreach (string File in Directory.GetFiles(FolderPath))
{
SetACE(File, DomainAndUsername, PermissionFlags, PropagationFlags.INHERITED_ACE, AccessFlags);
}
foreach (string SubFolderPath in Directory.GetDirectories(FolderPath))
{
SetInheritedPermission(SubFolderPath, DomainAndUsername, PermissionFlags, AccessFlags);
}
}
private static void SetACE(string FileOrFolder, string DomainAndUsername, int PermissionFlags, PropagationFlags InheritanceFlags, ACETypes AccessFlags)
{
AccessControlList dacl = new AccessControlList();
SecurityDescriptor sd = new SecurityDescriptor();
AccessControlEntry newAce = new AccessControlEntry();
ADsSecurityUtility sdUtil = new ADsSecurityUtility(); sd = sdUtil.GetSecurityDescriptor(FileOrFolder, ADS_PATH_FILE, ADS_SD_FORMAT_IID);
sd.Control = sd.Control;
OnProgress(DomainAndUsername, FileOrFolder);
dacl = sd.DiscretionaryAcl;
RemoveTrusteeFromDACL(dacl, DomainAndUsername);
newAce.Trustee = DomainAndUsername;
newAce.AccessMask = PermissionFlags;
newAce.AceFlags = (int)InheritanceFlags;
newAce.AceType = (int)AccessFlags;
dacl.AddAce(newAce);
sdUtil.SetSecurityDescriptor(FileOrFolder, ADS_PATH_FILE, sd, ADS_SD_FORMAT_IID);
}
Now we have encountered a large folder with lots of html documents, about 12000 files, and the method above is very slow. It takes about 7 minutes to process the file security. However, when managing security through windows explorer/security it only takes about 20 seconds so there must be some way to optimize this in C#.
Edit: When I leave out the recursion and only set the SecurityDescriptor on the top folder, none of the files below it have the deny for the AD group, only the top folder.

I solved it. I completely dumped the above code and went another way:
public override void DenyAccessInherited(string FolderPath,string DomainAndSamAccountName)
{
using (Impersonator imp = new Impersonator(this.connection.GetSamAccountName(), this.connection.GetDomain(), this.connection.Password))
{
FileSystemAccessRule rule = new FileSystemAccessRule(DomainAndSamAccountName, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, System.Security.AccessControl.PropagationFlags.InheritOnly, AccessControlType.Deny);
DirectoryInfo di = new DirectoryInfo(FolderPath);
DirectorySecurity security = di.GetAccessControl(AccessControlSections.All);
bool modified;
security.ModifyAccessRule(AccessControlModification.Add, rule, out modified);
if (modified)
di.SetAccessControl(security);
}
}
This is very slim and very fast.

Nested folders and files should inherit parent's security settings so you don't need to set it recursively for all. Try to set it only for root folder.

Related

set access permission works in debug mode but not in release mode

I'm developing a UWP software in which i need to write into "input.txt" file located in the Temp directory. however, when giving permission to this directory in release mode i have problem and it seen like the permission is not set:
string str = inputmessage.Text;
string path = #"input.txt";
try
{
SetAccess(WindowsIdentity.GetCurrent().Name,
Path.GetTempPath());// Path.GetFullPath("."));
// FileStream.SetAccessControl();
File.WriteAllText(Path.GetTempPath()+path,str);
}
and set access is defined as:
private static bool SetAccess(string user, string folder)
{
const FileSystemRights Rights = FileSystemRights.FullControl;
// *** Add Access Rule to the actual directory itself
var AccessRule = new FileSystemAccessRule(user, Rights,
InheritanceFlags.None,
PropagationFlags.NoPropagateInherit,
AccessControlType.Allow);
var Info = new DirectoryInfo(folder);
var Security = Info.GetAccessControl(AccessControlSections.Access);
bool Result;
Security.ModifyAccessRule(AccessControlModification.Set, AccessRule, out Result);
if (!Result) return false;
// *** Always allow objects to inherit on a directory
const InheritanceFlags iFlags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
// *** Add Access rule for the inheritance
AccessRule = new FileSystemAccessRule(user, Rights,
iFlags,
PropagationFlags.InheritOnly,
AccessControlType.Allow);
Security.ModifyAccessRule(AccessControlModification.Add, AccessRule, out Result);
if (!Result) return false;
Info.SetAccessControl(Security);
return true;
}
FileSystemAccessRule is belong to System.Security.AccessControl Namespace, and it is not compatible with uwp. You could not use it to access TemporaryFolder.
If you want to write into "input.txt" file located in the Temp directory. Please refer the following process.
private async void writeTextToTem(string info)
{
var file = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("info.text", CreationCollisionOption.OpenIfExists);
if (file != null)
{
await Windows.Storage.FileIO.WriteTextAsync(file, info);
}
}
And Path.GetTempPath() also work in uwp, and the matching folder is
C:\Users\Administrator\AppData\Local\Packages\497f6a93-9de3-4985-b27e-c2215ebabe72_75crXXXXXXX\AC\Temp\, it is contained in the app's sandbox you could access it directly.
var path = Path.GetTempPath();
var folder = await StorageFolder.GetFolderFromPathAsync(path);
var file = await folder.CreateFileAsync("info.text", CreationCollisionOption.OpenIfExists);
if (file != null)
{
await Windows.Storage.FileIO.WriteTextAsync(file, str);
}
For more detail you could refer File access permissions.

Cannot find public folder using Exchange web service API 2.0?

My outlook client has a shared folder "xxxx yyyy". However, the following code, which iterates all the folder and sub folder recursively, doesn't print out the folder. Why the code cannot get the folder?
private static void PrintAllPubFolder(ExchangeService service)
{
var folderView = new FolderView(int.MaxValue);
var findFolderResults = service.FindFolders(WellKnownFolderName.PublicFoldersRoot, folderView);
foreach (var folder in findFolderResults.Where(x => !ignore.Any(i => i == x.DisplayName)))
{
Console.WriteLine(folder.DisplayName);
PrintSubFolder(service, folder.Id, " ");
}
}
private static void PrintSubFolder(ExchangeService service, FolderId folderId, string p)
{
var folderView = new FolderView(int.MaxValue);
var findFolderResults = service.FindFolders(folderId, folderView);
foreach (var folder in findFolderResults.Where(x => !ignore.Any(i => i == x.DisplayName)))
{
Console.WriteLine("{0}{1}", p, folder.DisplayName);
PrintSubFolder(service, folder.Id, p + " ");
}
}
If your using Exchange 2010 or later don't use
var folderView = new FolderView(int.MaxValue);
Throttling will limit the results returned to 1000 so if you expect more the 1000 entries to be return then you'll need to page the results. However it doesn't make much sense to enumerate through every public folder to get the target look at the method in the following link
Searching Of Folders in Public Folders by giving its PATH Name
if the folder is in your mailbox then just do a search for that based on the name eg
FolderView ffView = new FolderView(1000);
ffView.Traversal = FolderTraversal.Deep;
SearchFilter fSearch = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, "xxxx yyyy");
FindFoldersResults ffResults = service.FindFolders(WellKnownFolderName.MsgFolderRoot, fSearch, ffView);
Cheers
Glen

Get to an Exchange folder by path using EWS

I need to retrieve items from the 'Inbox\test\final' Exchange folder using EWS. The folder is provided by a literal path as written above. I know I can split this string into folder names and recursively search for the necessary folder, but is there a more optimal way that can translate a string path into a folder instance or folder ID?
I'm using the latest EWS 2.0 assemblies. Do these assemblies provide any help, or am I stuck with manual recursion?
You could use an extended property as in this example
private string GetFolderPath(ExchangeService service, FolderId folderId)
{
var folderPathExtendedProp = new ExtendedPropertyDefinition(26293, MapiPropertyType.String);
var folderPropSet = new PropertySet(BasePropertySet.FirstClassProperties) { folderPathExtendedProp };
var folder = Folder.Bind(service, folderId, folderPropSet);
string path = null;
folder.TryGetProperty(folderPathExtendedProp, out path);
return path?.Replace("\ufffe", "\\");
}
Source: https://social.msdn.microsoft.com/Forums/en-US/e5d07492-f8a3-4db5-b137-46e920ab3dde/exchange-ews-managed-getting-full-path-for-a-folder?forum=exchangesvrdevelopment
Since Exchange Server likes to map everything together with Folder.Id, the only way to find the path you're looking for is by looking at folder names.
You'll need to create a recursive function to go through all folders in a folder collection, and track the path as it moves through the tree of email folders.
Another parameter is needed to track the path that you're looking for.
public static Folder GetPathFolder(ExchangeService service, FindFoldersResults results,
string lookupPath, string currentPath)
{
foreach (Folder folder in results)
{
string path = currentPath + #"\" + folder.DisplayName;
if (folder.DisplayName == "Calendar")
{
continue;
}
Console.WriteLine(path);
FolderView view = new FolderView(50);
SearchFilter filter = new SearchFilter.IsEqualTo(FolderSchema.Id, folder.Id);
FindFoldersResults folderResults = service.FindFolders(folder.Id, view);
Folder result = GetPathFolder(service, folderResults, lookupPath, path);
if (result != null)
{
return result;
}
string[] pathSplitForward = path.Split(new[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
string[] pathSplitBack = path.Split(new[] { #"\" }, StringSplitOptions.RemoveEmptyEntries);
string[] lookupPathSplitForward = lookupPath.Split(new[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
string[] lookupPathSplitBack = lookupPath.Split(new[] { #"\" }, StringSplitOptions.RemoveEmptyEntries);
if (ArraysEqual(pathSplitForward, lookupPathSplitForward) ||
ArraysEqual(pathSplitBack, lookupPathSplitBack) ||
ArraysEqual(pathSplitForward, lookupPathSplitBack) ||
ArraysEqual(pathSplitBack, lookupPathSplitForward))
{
return folder;
}
}
return null;
}
"ArraysEqual":
public static bool ArraysEqual<T>(T[] a1, T[] a2)
{
if (ReferenceEquals(a1, a2))
return true;
if (a1 == null || a2 == null)
return false;
if (a1.Length != a2.Length)
return false;
EqualityComparer<T> comparer = EqualityComparer<T>.Default;
for (int i = 0; i < a1.Length; i++)
{
if (!comparer.Equals(a1[i], a2[i])) return false;
}
return true;
}
I do all the extra array checking since sometimes my clients enter paths with forward slashes, back slashes, starting with a slash, etc. They're not tech savvy so let's make sure the program works every time!
As you go through each directory, compare the desired path to the iterated path. Once it's found, bubble up the Folder object that it's currently on. You'll need to create a search filter for that folder's id:
FindItemsResults<item> results = service.FindItems(foundFolder.Id, searchFilter, view);
Loop through the emails in results!
foreach (Item item in results)
{
// do something with item (email)
}
Here's my recursive descent implementation, which attempts to fetch as little information as possible on the way to the target folder:
private readonly FolderView _folderTraversalView = new FolderView(1) { PropertySet = PropertySet.IdOnly };
private Folder TraceFolderPathRec(string[] pathTokens, FolderId rootId)
{
var token = pathTokens.FirstOrDefault();
var matchingSubFolder = _exchangeService.FindFolders(
rootId,
new SearchFilter.IsEqualTo(FolderSchema.DisplayName, token),
_folderTraversalView)
.FirstOrDefault();
if (matchingSubFolder != null && pathTokens.Length == 1) return matchingSubFolder;
return matchingSubFolder == null ? null : TraceFolderPathRec(pathTokens.Skip(1).ToArray(), matchingSubFolder.Id);
}
For a '/'-delimited path, it can be called as follows:
public Folder TraceFolderPath(string folderPath)
{ // Handle folder names with '/' in them
var tokens = folderPath
.Replace("\\/", "<slash>")
.Split('/')
.Select(t => t.Replace("<slash>", "/"))
.ToArray();
return TraceFolderPathRec(tokens, WellKnownFolderName.MsgFolderRoot);
}
No, you don't need recursion and you efficiently go straight to the folder. This uses the same extended property as Tom, and uses it to apply a search filter:
using Microsoft.Exchange.WebServices.Data; // from nuget package "Microsoft.Exchange.WebServices"
...
private static Folder GetOneFolder(ExchangeService service, string folderPath)
{
var propertySet = new PropertySet(BasePropertySet.IdOnly);
propertySet.AddRange(new List<PropertyDefinitionBase> {
FolderSchema.DisplayName,
FolderSchema.TotalCount
});
var pageSize = 100;
var folderView = new FolderView(pageSize)
{
Offset = 0,
OffsetBasePoint = OffsetBasePoint.Beginning,
PropertySet = propertySet
};
folderView.Traversal = FolderTraversal.Deep;
var searchFilter = new SearchFilter.IsEqualTo(ExchangeExtendedProperty.FolderPathname, folderPath);
FindFoldersResults findFoldersResults;
var baseFolder = new FolderId(WellKnownFolderName.MsgFolderRoot);
var localFolderList = new List<Folder>();
do
{
findFoldersResults = service.FindFolders(baseFolder, searchFilter, folderView);
localFolderList.AddRange(findFoldersResults.Folders);
folderView.Offset += pageSize;
} while (findFoldersResults.MoreAvailable);
return localFolderList.SingleOrDefault();
}
...
public static class ExchangeExtendedProperty
{
/// <summary>PR_FOLDER_PATHNAME String</summary>
public static ExtendedPropertyDefinition FolderPathname { get => new ExtendedPropertyDefinition(0x66B5, MapiPropertyType.String); }
}
The path will need to be prefixed with a backslash, ie. \Inbox\test\final.

WMI call performance

I need to make a WMI call in the constructor of my service. But when I start/restart the system this call takes significant amount of time.
I am using the following code to get the path of the windows service....
Here I've used the EnumerationOptions to improve the query performance, now in order to use it I have to use the ManagementScope which is "root\civm2", every time I've to use "root'civm2" as Management scope,
Earlier I was using managementObjectCollection.Count to know whether it contains any items or not, now to improve the performance I am using managementObjectEnumerator.MoveNext, will it help, I've commented the count related code.
Is there any better way to improve the performance of the same code...
EnumerationOptions options = new EnumerationOptions();
// options.Rewindable = false; **// I HAVE TO COMMENT OUT THIS IN ORDER TO GET THE RESULTS....**
options.ReturnImmediately = true;
string query = string.Format("SELECT PathName FROM Win32_Service WHERE Name = '{0}'", "MyService");
ManagementScope ms12 = new ManagementScope(#"root\cimv2");
ms12.Connect();
using (var managementObjectSearcher = new ManagementObjectSearcher(query))
{
managementObjectSearcher.Scope = ms12;
managementObjectSearcher.Options = options;
var managementObjectCollection = managementObjectSearcher.Get();
//if (managementObjectCollection.Count > 0)
//{
var managementObjectEnumerator = managementObjectCollection.GetEnumerator();
if (managementObjectEnumerator.MoveNext())
{
var invalidChars = new Regex(string.Format(CultureInfo.InvariantCulture, "[{0}]", Regex.Escape(new string(Path.GetInvalidPathChars()))));
var path = invalidChars.Replace(managementObjectEnumerator.Current.GetPropertyValue("PathName").ToString(), string.Empty);
Console.WriteLine(path);
}
//}
else
{
Console.WriteLine("Else part...");
}
}
Am I using the scope and EnumerationOption in correct way??
Please guide.
As the answer to your another question suggest you can build the object path of the class and use the ManagementObject directly to improve the performance , now if you want to check if the ManagementObject return an instance you can use the private property IsBound.
string ServicePath = string.Format("Win32_Service.Name=\"{0}\"", "MyService");
var WMiObject = new ManagementObject(ServicePath);
PropertyInfo PInfo = typeof(ManagementObject).GetProperty("IsBound", BindingFlags.NonPublic | BindingFlags.Instance);
if ((bool)PInfo.GetValue(WMiObject, null))
{
string PathName = (string)WMiObject.GetPropertyValue("PathName");
var invalidChars = new Regex(string.Format(CultureInfo.InvariantCulture, "[{0}]", Regex.Escape(new string(Path.GetInvalidPathChars()))));
var path = invalidChars.Replace(PathName, string.Empty);
Console.WriteLine(path);
}
else
{
Console.WriteLine("Else part...");
}
It appears that in more recent versions of the .NET framework the binding happens as late as possible. At least this was the case for me when I was testing the existence of a specific shared folder.
Here is an update to #RRUZ 's solution which uses a try-catch instead of reflecting the IsBound internal property.
var servicePath = string.Format("Win32_Service.Name=\"{0}\"", "MyService");
string pathName = null;
try
{
var wmiObject = new ManagementObject(servicePath);
pathName = (string)wmiObject.GetPropertyValue("PathName");
}
catch {}
if (pathName != null)
{
var invalidChars = new Regex(string.Format(CultureInfo.InvariantCulture, "[{0}]", Regex.Escape(new string(Path.GetInvalidPathChars()))));
var path = invalidChars.Replace(pathName, string.Empty);
Console.WriteLine(path);
}
else
{
Console.WriteLine("Else part...");
}

File permissions do not inherit directory permissions

I have a program that's creating a secure directory for user output. This is working correctly, but the files I create in it (or copy to it) are ending up with only administrator access.
DirectoryInfo outputDirectory =
baseOutputDirectory.CreateSubdirectory(outputDirectoryName,
GetDirectorySecurity(searchHits.Request.UserId));
...
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,
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,
AccessControlType.Allow));
}
return ds;
}
/// <summary>
/// This method copies any static supporting files, such as javascripts
/// </summary>
/// <param name="outputDirectory"></param>
private void CopySupportingFiles(DirectoryInfo outputDirectory)
{
foreach (FileInfo file in SupportingFiles)
{
file.CopyTo(
Path.Combine(outputDirectory.FullName, file.Name));
}
}
etc, etc, etc.
What am I doing wrong? Why aren't the permissions cascading?
It looks like you should be setting the InheritanceFlags and PropagationFlags when setting the DirectorySecurity (I believe it overwrite whatever you've manually set).
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;
}

Categories