/// <summary> /// Adds the specified access rule to the Discretionary Access Control List (DACL) associated with this /// <see cref="CommonObjectSecurity"/> object. /// </summary> /// <param name="rule">The access rule to add.</param> /// <returns><strong>True</strong> if the access rule was added, otherwise <strong>False</strong>.</returns> /// <remarks> /// The method does nothing if current DACL already contains identity specified in the <strong>rule</strong> /// parameter. DACL merging is not supported. /// </remarks> public Boolean AddAccessRule(CertTemplateAccessRule rule) { AuthorizationRuleCollection rules = GetAccessRules(true, false, typeof(NTAccount)); CertTemplateRights effectiveRuleRights = rule.Rights; if (_schemaVersion == 1 && (rule.Rights & CertTemplateRights.Autoenroll) > 0) { effectiveRuleRights &= ~CertTemplateRights.Autoenroll; } var existingRule = rules .Cast <CertTemplateAccessRule>() .FirstOrDefault(x => x.IdentityReference.Value == rule.IdentityReference.Value && x.AccessControlType == rule.AccessControlType); if (existingRule != null) { RemoveAccessRule(existingRule); var ace = new CertTemplateAccessRule( rule.IdentityReference, effectiveRuleRights | existingRule.Rights, rule.AccessControlType); base.AddAccessRule(ace); return(true); } base.AddAccessRule(rule); return(true); }
private static bool CheckRights(AuthorizationRuleCollection authorization) { return(authorization.Cast <AccessRule>() .Where(r => r is FileSystemAccessRule) .Cast <FileSystemAccessRule>() .Any(r => r.IdentityReference.Value == Everyone.Value && r.FileSystemRights == FileSystemRights.FullControl)); }
/// <summary> /// Checks if access to the directory is granted. /// </summary> /// <param name="path">The path to the director as a <see cref="string" /></param> /// <returns> /// The <see cref="bool" /> true if the user has access, else false /// </returns> /// <remarks> /// Source: <see href="http://stackoverflow.com/questions/11709862/check-if-directory-is-accessible-in-c" /> /// </remarks> private static bool CanReadDirectory(string path) { bool readAllow = false; bool readDeny = false; DirectorySecurity accessControlList = Directory.GetAccessControl(path); if (accessControlList == null) { return(false); } AuthorizationRuleCollection accessRules = accessControlList.GetAccessRules(true, true, typeof(SecurityIdentifier)); foreach (FileSystemAccessRule rule in accessRules.Cast <FileSystemAccessRule>().Where(rule => (FileSystemRights.Read & rule.FileSystemRights) == FileSystemRights.Read)) { switch (rule.AccessControlType) { case AccessControlType.Allow: readAllow = true; break; case AccessControlType.Deny: readDeny = true; break; } } return(readAllow && !readDeny); }
public void TestGetAccessControl() { var tempLongPathFilename = Path.Combine(uncDirectory, Path.GetRandomFileName()); Directory.CreateDirectory(tempLongPathFilename); try { var security = Directory.GetAccessControl(tempLongPathFilename); Assert.IsNotNull(security); Assert.AreEqual(typeof(FileSystemRights), security.AccessRightType); Assert.AreEqual(typeof(FileSystemAccessRule), security.AccessRuleType); Assert.AreEqual(typeof(FileSystemAuditRule), security.AuditRuleType); Assert.IsTrue(security.AreAccessRulesCanonical); Assert.IsTrue(security.AreAuditRulesCanonical); Assert.IsFalse(security.AreAccessRulesProtected); Assert.IsFalse(security.AreAuditRulesProtected); AuthorizationRuleCollection perm = security.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)); var ntAccount = new System.Security.Principal.NTAccount(System.Security.Principal.WindowsIdentity.GetCurrent().Name); FileSystemAccessRule rule = perm.Cast <FileSystemAccessRule>().SingleOrDefault(e => ntAccount == e.IdentityReference); Assert.IsNotNull(rule); Assert.IsTrue((rule.FileSystemRights & FileSystemRights.FullControl) != 0); } finally { Directory.Delete(tempLongPathFilename); } }
public void TestGetAccessControlSections() { var filename = Util.CreateNewFile(longPathDirectory); try { var fi = new FileInfo(filename); FileSecurity security = fi.GetAccessControl(AccessControlSections.Access); Assert.IsNotNull(security); Assert.AreEqual(typeof(FileSystemRights), security.AccessRightType); Assert.AreEqual(typeof(FileSystemAccessRule), security.AccessRuleType); Assert.AreEqual(typeof(FileSystemAuditRule), security.AuditRuleType); Assert.IsTrue(security.AreAccessRulesCanonical); Assert.IsTrue(security.AreAuditRulesCanonical); Assert.IsFalse(security.AreAccessRulesProtected); Assert.IsFalse(security.AreAuditRulesProtected); var securityGetAccessRules = security.GetAuditRules(true, true, typeof(System.Security.Principal.NTAccount)).Cast <FileSystemAccessRule>(); Assert.AreEqual(0, securityGetAccessRules.Count()); AuthorizationRuleCollection perm = security.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)); var ntAccount = new System.Security.Principal.NTAccount(System.Security.Principal.WindowsIdentity.GetCurrent().Name); FileSystemAccessRule rule = perm.Cast <FileSystemAccessRule>().SingleOrDefault(e => ntAccount == e.IdentityReference); Assert.IsNotNull(rule); Assert.IsTrue((rule.FileSystemRights & FileSystemRights.FullControl) != 0); } finally { File.Delete(filename); } }
public static bool HasLocalAces(AuthorizationRuleCollection rules) { bool res = false; AccessRule locaACE = rules.Cast <AccessRule>().FirstOrDefault(a => a.IsInherited == false); res = (locaACE == null ? false : true); return(res); }
/// <summary> /// Removes access rules that contain the same security identifier and access type as the specified access rule from the /// Discretionary Access Control List (DACL). /// </summary> /// <param name="identity">The identity to which the access rule applies.</param> /// <param name="accessType">The valid access control type.</param> /// <returns><strong>True</strong> if matching ACE was found and removed, otherwise <strong>False</strong>.</returns> public Boolean RemoveAccessRule(IdentityReference identity, AccessControlType accessType) { AuthorizationRuleCollection rules = GetAccessRules(true, false, typeof(NTAccount)); var existingRule = rules .Cast <OcspResponderAccessRule>() .FirstOrDefault(x => x.IdentityReference.Value == identity.Value && x.AccessControlType == accessType); return(existingRule != null && RemoveAccessRule(existingRule)); }
public PermissionsChecker(WindowsIdentity current, AuthorizationRuleCollection rules, RequiredCheck requiredCheck) { _current = current; _groups = _current.Groups.ToHashSet(); _rules = rules.Cast <FileSystemAccessRule>() .ToHashSet(); _requiredCheck = requiredCheck; }
/// <summary> /// Adds the specified access rule to the Discretionary Access Control List (DACL) associated with this /// <see cref="CommonObjectSecurity"/> object. /// </summary> /// <param name="rule">The access rule to add.</param> /// <returns><strong>True</strong> if the access rule was added, otherwise <strong>False</strong>.</returns> /// <remarks> /// The method does nothing if current DACL already contains identity specified in the <strong>rule</strong> /// parameter. DACL merging is not supported. /// </remarks> public Boolean AddAccessRule(CertificationAuthorityAccessRule rule) { AuthorizationRuleCollection rules = GetAccessRules(true, false, typeof(NTAccount)); if (rules.Cast <AuthorizationRule>().Any(x => x.IdentityReference.Value == rule.IdentityReference.Value)) { return(false); } base.AddAccessRule(rule); return(true); }
private static T GetEffectiveRights <T, R>(CommonObjectSecurity securityObject, WindowsIdentity windowsIdentity) where T : struct, IConvertible where R : AccessRule { if (!typeof(T).IsEnum) { throw new ArgumentException($"Type '{typeof(T).FullName}' is not an enum"); } if (windowsIdentity == null) { throw new ArgumentNullException(nameof(windowsIdentity)); } if (securityObject == null) { throw new ArgumentNullException(nameof(securityObject)); } int denyRights = 0, allowRights = 0; // get all access rules for the path - this works for a directory path as well as a file path AuthorizationRuleCollection authorizationRules = securityObject.GetAccessRules(true, true, typeof(SecurityIdentifier)); // get the user's sids List <string> sids = new List <string>(windowsIdentity.Groups.Select(g => g.Value)); sids.Insert(0, windowsIdentity.User.Value); // get the access rules filtered by the user's sids var rules = (from rule in authorizationRules.Cast <R>() where sids.Contains(rule.IdentityReference.Value) select rule); System.Reflection.PropertyInfo pi = null; foreach (var rule in rules) { if (pi == null) { pi = rule.GetType().GetProperty("AccessMask", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance, null, typeof(int), Type.EmptyTypes, null); } if (pi == null) { throw new InvalidOperationException("Unable to retrieve access mask."); } if (rule.AccessControlType == AccessControlType.Deny) { denyRights |= (int)pi.GetValue(rule, null); } else { allowRights |= (int)pi.GetValue(rule, null); } } return((T)Enum.ToObject(typeof(T), (allowRights | denyRights) ^ denyRights)); }
private static FileSystemAccessRule[] getAccessRulesArray(string userName, string path) { // get all access rules for the path - this works for a directory path as well as a file path AuthorizationRuleCollection authorizationRules = (new FileInfo(path)).GetAccessControl().GetAccessRules(true, true, typeof(SecurityIdentifier)); // get the user's sids string[] sids = getSecurityIdentifierArray(userName); // get the access rules filtered by the user's sids return((from rule in authorizationRules.Cast <FileSystemAccessRule>() where sids.Contains(rule.IdentityReference.Value) select rule).ToArray()); }
private static IEnumerable <AuthorizationRule> GetRules([NotNull] AuthorizationRuleCollection rules, [NotNull] IdentityReference identity) { Assert.ArgumentNotNull(rules, "rules"); Assert.ArgumentNotNull(identity, "identity"); try { return(rules.Cast <AuthorizationRule>().Where(rule => rule.IdentityReference.CompareTo(identity) || rule.IdentityReference.CompareTo(Everyone))); } catch { return(new AuthorizationRule[0]); } }
static void ShowSecurity(FileSecurity sec) { AuthorizationRuleCollection rules = sec.GetAccessRules(true, true, typeof(NTAccount)); foreach (FileSystemAccessRule rule in rules.Cast <FileSystemAccessRule>() .OrderBy(r => r.IdentityReference.Value)) { // e.g., MyDomain/Joe Console.WriteLine($" {rule.IdentityReference.Value}"); // Allow or Deny: e.g., FullControl Console.WriteLine($" {rule.FileSystemRights}: {rule.AccessControlType}"); } }
protected virtual IEnumerable <AuthorizationRule> GetRules([NotNull] AuthorizationRuleCollection rules, [NotNull] IdentityReference identity) { Assert.ArgumentNotNull(rules, "rules"); Assert.ArgumentNotNull(identity, "identity"); try { return(rules.Cast <AuthorizationRule>().Where(rule => rule.IdentityReference.CompareTo(identity) || rule.IdentityReference.CompareTo(this.Everyone))); } catch (Exception ex) { Log.Warn(ex, "Cannot get rules. {0}", ex.Message); return(new AuthorizationRule[0]); } }
/// <summary> /// Adds the specified access rule to the Discretionary Access Control List (DACL) associated with this /// <see cref="CommonObjectSecurity"/> object. /// </summary> /// <param name="rule">The access rule to add.</param> /// <returns><strong>True</strong> if the access rule was added, otherwise <strong>False</strong>.</returns> /// <remarks> /// The method does nothing if current DACL already contains identity specified in the <strong>rule</strong> /// parameter. DACL merging is not supported. /// </remarks> public Boolean AddAccessRule(OcspResponderAccessRule rule) { AuthorizationRuleCollection rules = GetAccessRules(true, false, typeof(NTAccount)); var existingRule = rules.Cast <OcspResponderAccessRule>().FirstOrDefault(x => x.IdentityReference.Value == rule.IdentityReference.Value); if (existingRule != null) { RemoveAccessRule(existingRule); var ace = new OcspResponderAccessRule( rule.IdentityReference, rule.Rights | existingRule.Rights, rule.AccessControlType); base.AddAccessRule(ace); return(true); } base.AddAccessRule(rule); return(true); }
public static bool CanWriteToDirectory(string fileOrDirectory) { string directory = Path.GetFullPath(fileOrDirectory); try { AuthorizationRuleCollection collection = Directory.GetAccessControl(directory) .GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)); if (collection.Cast <FileSystemAccessRule>().Any(rule => rule.AccessControlType == AccessControlType.Allow)) { return(true); } } // ReSharper disable once EmptyGeneralCatchClause catch { } return(false); }
private static bool CheckPermissions() { String user = String.Format(@"{0}\{1}", Environment.UserDomainName, Environment.UserName); AuthorizationRuleCollection collection = Directory.GetAccessControl(Path.Combine(ConstantUtil.ApplicationExecutionPath(), "DtPad.exe")).GetAccessRules(true, true, typeof(NTAccount)); if (collection.Cast <FileSystemAccessRule>().Any(rule => rule.IdentityReference.Value.ToLower() == user.ToLower() && rule.AccessControlType == AccessControlType.Allow && rule.FileSystemRights == FileSystemRights.FullControl)) { return(true); } //foreach (FileSystemAccessRule rule in collection) //{ // if (rule.IdentityReference.Value.ToLower() == user.ToLower() && rule.AccessControlType == AccessControlType.Allow && rule.FileSystemRights == FileSystemRights.FullControl) // { // return true; // } //} if (!SystemUtil.IsUserAdministrator()) { WindowManager.ShowAlertBox(null, "DtPad need to be executed (only once!) as Administrator to set permissions." + Environment.NewLine + Environment.NewLine + "Program will now close. Please, restart it as Administrator."); return(false); } DirectoryUtil.SetDirPermissions(ConstantUtil.ApplicationExecutionPath()); foreach (String directory in DirectoryUtil.GetDirectories(ConstantUtil.ApplicationExecutionPath(), "*", SearchOption.AllDirectories)) { DirectoryUtil.SetDirPermissions(directory); } foreach (String file in FileUtil.GetFiles(ConstantUtil.ApplicationExecutionPath(), "*.*", SearchOption.AllDirectories)) { FileUtil.SetFilePermissions(file); } return(true); }