Esempio n. 1
0
        private static void SetAcl(string path, SearchResult user, FileSystemRights right)
        {
            var userId = user.Properties["userPrincipalName"][0].ToString();
            var fullUserName = user.Properties["name"][0].ToString();
            var fullPath = path + fullUserName;
            var dir = new DirectoryInfo(fullPath);
            var ds = new DirectorySecurity();
            ds.SetAccessRuleProtection(true, false);

            var uacl = new FileSystemAccessRule(userId,
                right,
                InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                PropagationFlags.None,
                AccessControlType.Allow);
            ds.AddAccessRule(uacl);

            var domainAdmins = new SecurityIdentifier(WellKnownSidType.AccountDomainAdminsSid, AppSettings.GeneralSettings.DomainSid);
            var pacl = new FileSystemAccessRule(domainAdmins,
                FileSystemRights.FullControl,
                InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                PropagationFlags.None,
                AccessControlType.Allow);
            ds.AddAccessRule(pacl);

            var system = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null);
            var sacl = new FileSystemAccessRule(system,
                FileSystemRights.FullControl,
                InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                PropagationFlags.None,
                AccessControlType.Allow);
            ds.AddAccessRule(sacl);

            dir.SetAccessControl(ds);
        }
Esempio n. 2
0
 private static void AddAclRuleOnDirectory(string directory, IdentityReference identity, FileSystemRights rights, AccessControlType type)
 {
     var acl = Directory.GetAccessControl(directory);
     acl.PurgeAccessRules(identity);
     acl.AddAccessRule(new FileSystemAccessRule(identity, rights, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, type));
     Directory.SetAccessControl(directory, acl);
 }
Esempio n. 3
0
 private static void AddAclRuleOnFile(string file, IdentityReference identity, FileSystemRights rights, AccessControlType type)
 {
     var acl = File.GetAccessControl(file);
     acl.PurgeAccessRules(identity);
     acl.AddAccessRule(new FileSystemAccessRule(identity, rights, type));
     File.SetAccessControl(file, acl);
 }
        public bool HasAccess(FileSystemRights rights)
        {
            WindowsIdentity user = (WindowsIdentity)principal.Identity;
              // Get the collection of authorization rules that apply to the specified directory
              AuthorizationRuleCollection acl = directory.GetAccessControl().GetAccessRules(true, true, typeof(SecurityIdentifier));

              // These are set to true if either the allow access or deny access rights are set
              bool allowAccess = false;
              bool denyAccesss = false;

              foreach (FileSystemAccessRule currentRule in acl)
              {
            // If the current rule applies to the current user
            if (user.User.Equals(currentRule.IdentityReference) || principal.IsInRole((SecurityIdentifier)currentRule.IdentityReference))
            {
              if (currentRule.AccessControlType.Equals(AccessControlType.Deny))
              {
            if ((currentRule.FileSystemRights & rights) == rights)
            {
              denyAccesss = true;
            }
              }
              else if (currentRule.AccessControlType.Equals(AccessControlType.Allow))
              {
            if ((currentRule.FileSystemRights & rights) == rights)
            {
              allowAccess = true;
            }
              }
            }
              }

              return allowAccess & !denyAccesss;
        }
	public FileSystemAuditRule
				(String identity, FileSystemRights fileSystemRights,
				 InheritanceFlags inheritanceFlags,
				 PropagationFlags propagationFlags, AuditFlags auditFlags)
			: base(IdentityReference.IdentityFromName(identity),
				   (int)fileSystemRights, false, inheritanceFlags,
				   propagationFlags, auditFlags) {}
Esempio n. 6
0
        public static void AddFileSecurity(string fileName, string WindowsAccount, FileSystemRights rights, AccessControlType accessControlType)
        {
            FileSecurity fSecurity = File.GetAccessControl(fileName);
            fSecurity.AddAccessRule(new FileSystemAccessRule(WindowsAccount, rights, accessControlType));
            File.SetAccessControl(fileName, fSecurity);

        }
Esempio n. 7
0
		private static void AddDirectorySecurity(string folderName, string account, FileSystemRights rights, InheritanceFlags inheritance, PropagationFlags propogation, AccessControlType controlType)
		{
			DirectoryInfo directoryInfo = new DirectoryInfo(folderName);
			DirectorySecurity accessControl = directoryInfo.GetAccessControl();
			accessControl.AddAccessRule(new FileSystemAccessRule(account, rights, inheritance, propogation, controlType));
			directoryInfo.SetAccessControl(accessControl);
		}
	public FileSystemAccessRule
				(String identity, FileSystemRights fileSystemRights,
				 InheritanceFlags inheritanceFlags,
				 PropagationFlags propagationFlags, AccessControlType type)
			: base(IdentityReference.IdentityFromName(identity),
				   (int)fileSystemRights, false, inheritanceFlags,
				   propagationFlags, type) {}
Esempio n. 9
0
 /// <summary>
 /// Add an access rule to a folder
 /// </summary>
 /// 
 /// <param name="Path">Folder path</param>
 /// <param name="User">UNC path to user profile ex. Environment.UserDomainName + "\\" + Environment.UserName</param>
 /// <param name="Rights">Desired file system rights</param>
 /// <param name="Access">Desired level of access</param>
 public static void AddAccessRule(string Path, string User, FileSystemRights Rights, AccessControlType Access)
 {
     // Get a DirectorySecurity object that represents the current security settings
     System.Security.AccessControl.DirectorySecurity sec = System.IO.Directory.GetAccessControl(Path);
     // Add the FileSystemAccessRule to the security settings
     FileSystemAccessRule accRule = new FileSystemAccessRule(User, Rights, Access);
     sec.AddAccessRule(accRule);
 }
    private static bool HasFilePermissions(string path, IdentityReference identity, FileSystemRights permissions)
    {
      var dirInfo = new FileInfo(path);
      var dirSecurity = dirInfo.GetAccessControl(AccessControlSections.All);
      AuthorizationRuleCollection rules = dirSecurity.GetAccessRules(true, true, typeof(NTAccount));

      return HasPermissions(rules, identity, permissions);
    }
Esempio n. 11
0
 public static bool CheckAccessRight(DirectoryInfo directory, FileSystemRights right)
 {
     var user = WindowsIdentity.GetCurrent();
     var p = new WindowsPrincipal(user);
     AuthorizationRuleCollection acl =
     directory.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
     return CheckAccessRight(user, p, acl, right);
 }
Esempio n. 12
0
 static void ReplacePermissions(string filepath, WellKnownSidType sidType, FileSystemRights allow)
 {
     FileSecurity sec = File.GetAccessControl(filepath);
     SecurityIdentifier sid = new SecurityIdentifier(sidType, null);
     sec.PurgeAccessRules(sid); //remove existing
     sec.AddAccessRule(new FileSystemAccessRule(sid, allow, AccessControlType.Allow));
     File.SetAccessControl(filepath, sec);
 }
Esempio n. 13
0
		public FileSystemAccessRule (IdentityReference identity,
					     FileSystemRights fileSystemRights,
					     InheritanceFlags inheritanceFlags,
					     PropagationFlags propagationFlags,
					     AccessControlType type)
			: this (identity, fileSystemRights, false, inheritanceFlags, propagationFlags, type)
		{
		}
Esempio n. 14
0
		public FileSystemAccessRule (string identity,
					     FileSystemRights fileSystemRights,
					     InheritanceFlags inheritanceFlags,
					     PropagationFlags propagationFlags,
					     AccessControlType type)
			: this (new NTAccount (identity), fileSystemRights, inheritanceFlags, propagationFlags, type)
		{
		}
 public FileAccessDenier(FileInfo file, FileSystemRights rights)
 {
     this.file = file;
     this.access = this.file.GetAccessControl();
     this.denial = new FileSystemAccessRule(WindowsIdentity.GetCurrent().Name, rights, AccessControlType.Deny);
     this.access.AddAccessRule(this.denial);
     this.file.SetAccessControl(this.access);
 }
Esempio n. 16
0
		public FileSystemAuditRule (IdentityReference identity,
					    FileSystemRights fileSystemRights,
					    InheritanceFlags inheritanceFlags,
					    PropagationFlags propagationFlags,
					    AuditFlags flags)
			: this (identity, fileSystemRights, false, inheritanceFlags, propagationFlags, flags)
		{
		}
Esempio n. 17
0
		public FileSystemAuditRule (string identity,
					    FileSystemRights fileSystemRights,
					    InheritanceFlags inheritanceFlags,
					    PropagationFlags propagationFlags,
					    AuditFlags flags)
			: this (new SecurityIdentifier (identity), fileSystemRights, inheritanceFlags, propagationFlags, flags)
		{
		}
        public static void SetDrectorySecurity(string userName, string path, FileSystemRights fileSystemRights)
        {
            DirectorySecurity directorySecurity = Directory.GetAccessControl(path);

            directorySecurity.AddAccessRule(new FileSystemAccessRule(userName, fileSystemRights, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));

            Directory.SetAccessControl(path, directorySecurity);
        }
 public DirectoryAccessDenier(DirectoryInfo directory, FileSystemRights rights)
 {
     this.directory = directory;
     this.access = this.directory.GetAccessControl();
     this.denial = new FileSystemAccessRule(WindowsIdentity.GetCurrent().Name, rights, AccessControlType.Deny);
     this.access.AddAccessRule(this.denial);
     this.directory.SetAccessControl(this.access);
 }
            public void DeniedRight(FileSystemRights deniedRight)
            {
                AddFileDenyACE(TestFile.FullName, CurrentIdentity, deniedRight);

                var rights = EffectiveAccess.ComputeAccess(TestFile.FullName, CurrentIdentity);

                Assert.False(rights.HasFlag(deniedRight));
            }
Esempio n. 21
0
 public static void AddFileSecurity(string filename, string account, FileSystemRights rights, AccessControlType controlType)
 {
     if (File.Exists(filename))
     {
         FileSecurity fSecurity = File.GetAccessControl(filename, AccessControlSections.All);
         fSecurity.AddAccessRule(new FileSystemAccessRule(account, rights, controlType));
         File.SetAccessControl(filename, fSecurity);
     }
 }
Esempio n. 22
0
		internal FileSystemAuditRule (IdentityReference identity,
					      FileSystemRights fileSystemRights,
					      bool isInherited,
					      InheritanceFlags inheritanceFlags,
					      PropagationFlags propagationFlags,
					      AuditFlags flags)
			: base (identity, (int)fileSystemRights, isInherited, inheritanceFlags, propagationFlags, flags)
		{
		}
Esempio n. 23
0
		internal FileSystemAccessRule (IdentityReference identity,
					       FileSystemRights fileSystemRights,
					       bool isInherited,
					       InheritanceFlags inheritanceFlags,
					       PropagationFlags propagationFlags,
					       AccessControlType type)
			: base (identity, (int) fileSystemRights, isInherited, inheritanceFlags, propagationFlags, type)
		{
		}
Esempio n. 24
0
 public static bool SetFolderACL(String FolderPath, String UserName, FileSystemRights Rights, AccessControlType AllowOrDeny, InheritanceFlags Inherits, PropagationFlags PropagateToChildren, AccessControlModification AddResetOrRemove)
 {
     bool ret;
     DirectoryInfo folder = new DirectoryInfo(FolderPath);
     DirectorySecurity dSecurity = folder.GetAccessControl(AccessControlSections.All);
     FileSystemAccessRule accRule = new FileSystemAccessRule(UserName, Rights, Inherits, PropagateToChildren, AllowOrDeny); dSecurity.ModifyAccessRule(AddResetOrRemove, accRule, out ret);
     folder.SetAccessControl(dSecurity);
     return ret;
 }
        public void AddFileDenyACE(string filePath, IdentityReference identity, FileSystemRights right)
        {
            const AccessControlSections accessSections = AccessControlSections.Owner | AccessControlSections.Group |
                                                         AccessControlSections.Access;

            var security = File.GetAccessControl(filePath, accessSections);
            var rule = new FileSystemAccessRule(identity, right, AccessControlType.Deny);
            security.AddAccessRule(rule);
            File.SetAccessControl(filePath, security);
        }
Esempio n. 26
0
 /// <summary>
 /// Add a file system right to a directory
 /// </summary>
 /// 
 /// <param name="Path">Full path to directory</param>
 /// <param name="Account">UNC path to user profile</param>
 /// <param name="Rights">Desired file system rights</param>
 /// <param name="ControlType">Access control type</param>
 public static void AddSecurity(string Path, string Account, FileSystemRights Rights, AccessControlType ControlType)
 {
     // Create a new DirectoryInfo object
     DirectoryInfo dInfo = new DirectoryInfo(Path);
     // 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);
 }
        private static void AddFileSecurity(string path, string account, FileSystemRights rights)
        {
            FileInfo fileInfo = new FileInfo(path.Replace('\\', '/'));
            FileSecurity fileSecurity = fileInfo.GetAccessControl();
            fileSecurity.AddAccessRule(new FileSystemAccessRule(account,
                                                            rights,
                                                            AccessControlType.Allow
                                                            ));

            fileInfo.SetAccessControl(fileSecurity);
        }
Esempio n. 28
0
 public static void AllowPermissions(string userOrGroupNameWithDomainPrefix, DirectoryInfo directoryInfo, FileSystemRights rights)
 {
     DirectorySecurity dirSec = directoryInfo.GetAccessControl();
     FileSystemAccessRule newRule = new FileSystemAccessRule(userOrGroupNameWithDomainPrefix,
         rights,
         InheritanceFlags.ObjectInherit ^ InheritanceFlags.ContainerInherit,
         PropagationFlags.None, AccessControlType.Allow);
     dirSec.AddAccessRule(newRule);
     directoryInfo.SetAccessControl(dirSec);
     directoryInfo.Refresh();
 }
 public BackupFileStream(KernelTransaction transaction, string path, FileMode mode, FileSystemRights access, FileShare share, ExtendedFileAttributes attributes, FileSecurity security)
     : this(File.CreateFileCore(transaction, path, attributes, security, mode, access, share, true, PathFormat.RelativePath), access)
 {
 }
Esempio n. 30
0
 public bool HasPermission(FileSystemRights perm) => GetEffectiveRights().HasFlag(perm);
Esempio n. 31
0
 public FileSystemAccessRule(IdentityReference identity,
                             FileSystemRights fileSystemRights,
                             AccessControlType type)
     : this(identity, fileSystemRights, InheritanceFlags.None, PropagationFlags.None, type)
 {
 }
Esempio n. 32
0
 /// <span class="code-SummaryComment">
 ///     <summary>
 /// </span>
 /// Convenience method to test if the right exists within the given rights
 /// <span class="code-SummaryComment"></summary></span>
 /// <span class="code-SummaryComment">
 ///     <param name="right"></param>
 /// </span>
 /// <span class="code-SummaryComment">
 ///     <param name="rule"></param>
 /// </span>
 /// <span class="code-SummaryComment">
 ///     <returns></returns>
 /// </span>
 public bool contains(FileSystemRights right,
                      FileSystemAccessRule rule)
 {
     return(((int)right & (int)rule.FileSystemRights) == (int)right);
 }
Esempio n. 33
0
        /// <summary>
        /// Checks whether the client has specific file system rights to a directory.
        /// See ssds's answer at https://stackoverflow.com/questions/1410127/c-sharp-test-if-user-has-write-access-to-a-folder
        /// </summary>
        /// <param name="path">The path to the directory.</param>
        /// <param name="accessRights">The file system rights.</param>
        private static bool UserHasDirectoryAccessRights(string path, FileSystemRights accessRights)
        {
#if WINDOWSGL
            // Mono doesn't implement everything necessary for the below to work,
            // so we'll just return to make the client able to run on non-Windows
            // platforms
            // On Windows you rarely have a reason for using the OpenGL build anyway
            return(true);
#endif

#pragma warning disable 0162
            var currentUser = WindowsIdentity.GetCurrent();
#pragma warning restore 0162
            var principal = new WindowsPrincipal(currentUser);

            // If the user is not running the client with administrator privileges in Program Files, they need to be prompted to do so.
            if (!principal.IsInRole(WindowsBuiltInRole.Administrator))
            {
                string progfiles    = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
                string progfilesx86 = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);
                if (Environment.CurrentDirectory.Contains(progfiles) || Environment.CurrentDirectory.Contains(progfilesx86))
                {
                    return(false);
                }
            }

            var isInRoleWithAccess = false;

            try
            {
                var di    = new DirectoryInfo(path);
                var acl   = di.GetAccessControl();
                var rules = acl.GetAccessRules(true, true, typeof(NTAccount));

                foreach (AuthorizationRule rule in rules)
                {
                    var fsAccessRule = rule as FileSystemAccessRule;
                    if (fsAccessRule == null)
                    {
                        continue;
                    }

                    if ((fsAccessRule.FileSystemRights & accessRights) > 0)
                    {
                        var ntAccount = rule.IdentityReference as NTAccount;
                        if (ntAccount == null)
                        {
                            continue;
                        }

                        if (principal.IsInRole(ntAccount.Value))
                        {
                            if (fsAccessRule.AccessControlType == AccessControlType.Deny)
                            {
                                return(false);
                            }
                            isInRoleWithAccess = true;
                        }
                    }
                }
            }
            catch (UnauthorizedAccessException)
            {
                return(false);
            }
            return(isInRoleWithAccess);
        }
Esempio n. 34
0
        public static void CreateApplication(string appName, string appPath, string virtualAppPath, IisConfig config = null, int siteIndex = 0)
        {
            //create app
            using (var mgr = new ServerManager())
            {
                var iisAppPool = mgr.ApplicationPools[appName];
                var hasChange  = false;
                if (iisAppPool == null)
                {
                    //directory permission
                    var dirInfo  = new DirectoryInfo(appPath);
                    var security = dirInfo.GetAccessControl(AccessControlSections.Access);
                    const FileSystemRights right = FileSystemRights.FullControl ^ FileSystemRights.ReadAndExecute;
                    var acl = new FileSystemAccessRule("NETWORK SERVICE", right, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Deny);
                    security.AddAccessRule(acl);
                    dirInfo.SetAccessControl(security);

                    //apppool permission
                    iisAppPool = mgr.ApplicationPools.Add(appName);
                    iisAppPool.ManagedRuntimeVersion     = "v4.0";
                    iisAppPool.ProcessModel.IdentityType = ProcessModelIdentityType.NetworkService;
                    hasChange = true;
                }
                config = config ?? IisConfig.Default;
                var startMode = iisAppPool["startMode"] as string;
                var target    = config.AutoStart ? "AlwaysRunning" : "OnDemand";
                if (startMode != target)
                {
                    iisAppPool["startMode"] = target;
                    hasChange = true;
                }
                var target2 = TimeSpan.FromMinutes(config.IdleTimeout);
                if (iisAppPool.ProcessModel.IdleTimeout != target2)
                {
                    iisAppPool.ProcessModel.IdleTimeout = target2;
                    hasChange = true;
                }
                if (iisAppPool.Enable32BitAppOnWin64 != config.Enable32Bit)
                {
                    iisAppPool.Enable32BitAppOnWin64 = config.Enable32Bit;
                    hasChange = true;
                }
                if (hasChange)
                {
                    mgr.CommitChanges();
                }

                hasChange = false;
                var iisApp = mgr.Sites[siteIndex].Applications[virtualAppPath];
                if (iisApp == null)
                {
                    iisApp = mgr.Sites[siteIndex].Applications.Add(virtualAppPath, appPath);
                    iisApp.ApplicationPoolName = appName;
                    iisApp.EnabledProtocols    = "https,http";
                    hasChange = true;
                }
                var preloadEnabled = Equals(iisApp["preloadEnabled"], true);
                if (preloadEnabled != config.AutoStart)
                {
                    iisApp["preloadEnabled"] = config.AutoStart;
                    hasChange = true;
                }
                if (hasChange)
                {
                    mgr.CommitChanges();
                }
            }
        }
Esempio n. 35
0
        public static string CollectFilePermissionInformation(string filePath)
        {
            var bldr = new StringBuilder();

            try
            {
                if (Platform.IsWindows)
                {
                    var currentUser = WindowsIdentity.GetCurrent();
                    bldr.AppendLine($"current user is {currentUser.Name}");
                    var              principal          = new WindowsPrincipal(currentUser);
                    bool             isInRoleWithAccess = false;
                    bool             accessDenied       = false;
                    bool             accessAllowed      = false;
                    FileSystemRights accessRights       = FileSystemRights.Write;
                    var              acl   = File.GetAccessControl(filePath);
                    var              rules = acl.GetAccessRules(true, true, typeof(NTAccount));
                    var              sid   = acl.GetOwner(typeof(SecurityIdentifier));
                    var              acct  = sid.Translate(typeof(NTAccount)) as NTAccount;
                    if (acct != null)
                    {
                        bldr.AppendLine($"owner of \"{filePath}\" is {acct.Value}");
                    }
                    var fileAttributes = RobustFile.GetAttributes(filePath);
                    bldr.AppendLine($"{filePath} current ReadOnly attribute of {filePath} is {(fileAttributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly}");
                    foreach (AuthorizationRule rule in rules)
                    {
                        var fsAccessRule = rule as FileSystemAccessRule;
                        if (fsAccessRule == null)
                        {
                            continue;
                        }
                        if ((fsAccessRule.FileSystemRights & accessRights) > 0)
                        {
                            var ntAccount = rule.IdentityReference as NTAccount;
                            if (ntAccount == null)
                            {
                                continue;
                            }
                            if (principal.IsInRole(ntAccount.Value))
                            {
                                if (fsAccessRule.AccessControlType == AccessControlType.Deny)
                                {
                                    bldr.AppendLine($"current user is denied write access to {filePath} by {ntAccount.Value}{(rule.IsInherited ? " (inherited)":"")}");
                                    accessDenied = true;
                                }
                                if (fsAccessRule.AccessControlType == AccessControlType.Allow)
                                {
                                    bldr.AppendLine($"current user is allowed write access to {filePath} by {ntAccount.Value}{(rule.IsInherited ? " (inherited)":"")}");
                                    accessAllowed = true;
                                }
                                isInRoleWithAccess = true;
                            }
                        }
                    }
                    if (isInRoleWithAccess)
                    {
                        if (!accessAllowed)
                        {
                            bldr.AppendLine($"current user is not explicitly allowed write access to {filePath}");
                        }
                        if (!accessDenied)
                        {
                            bldr.AppendLine($"current user is not explicitly denied write access to {filePath}");
                        }
                    }
                    else
                    {
                        bldr.AppendLine($"current user is not explicitly given access to {filePath}");
                    }
                }
                else
                {
                    var folder   = Path.GetDirectoryName(filePath);
                    var fileInfo = new UnixFileInfo(filePath);
                    var dirInfo  = new UnixDirectoryInfo(folder);
                    var userInfo = UnixUserInfo.GetRealUser();
                    bldr.AppendLine($"current user is {userInfo.UserName}");
                    bldr.AppendLine($"owner of \"{filePath}\" is {fileInfo.OwnerUser.UserName}");
                    bldr.AppendLine($"permissions of \"{filePath}\" = {fileInfo.FileAccessPermissions.ToString()}");
                    bldr.AppendLine($"owner of \"{folder}\" is {dirInfo.OwnerUser.UserName}");
                    bldr.AppendLine($"permissions of \"{folder}\" = {dirInfo.FileAccessPermissions.ToString()}");
                }
            }
            catch (Exception e)
            {
                bldr.AppendLine($"Caught exception {e} while trying to collect information about {filePath}");
            }
            return(bldr.ToString());
        }
Esempio n. 36
0
        public static Boolean ReplaceFileSecurity(string File, IdentityReference[] Account, FileSystemRights Rights, AccessControlType ControlType, InheritanceFlags Inherit, PropagationFlags Propagation)
        {
            FileInfo     fInfo     = new FileInfo(File);
            FileSecurity fSecurity = fInfo.GetAccessControl();

            try
            {
                fSecurity.SetAccessRuleProtection(true, false);
                foreach (IdentityReference account in Account)
                {
                    fSecurity.ResetAccessRule(new FileSystemAccessRule(account, Rights, Inherit, Propagation, ControlType));
                }
                fInfo.SetAccessControl(fSecurity);
            }
            catch (Exception ex)
            {
                LibraryLogging.Error("unable to ReplaceFileSecurity for {0} error {1}", File, ex.Message);
                return(false);
            }

            return(true);
        }
Esempio n. 37
0
 public FileSystemAuditRule(System.Security.Principal.IdentityReference identity, FileSystemRights fileSystemRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) : base(default(System.Security.Principal.IdentityReference), default(int), default(bool), default(InheritanceFlags), default(PropagationFlags), default(AuditFlags))
 {
 }
Esempio n. 38
0
        /// <summary> Removes any existing access for the user SID supplied and adds the specified rights </summary>
        public static void ReplacePermissions(string filepath, WellKnownSidType sidType, FileSystemRights allow)
        {
            FileSecurity       sec = File.GetAccessControl(filepath);
            SecurityIdentifier sid = new SecurityIdentifier(sidType, null);

            sec.PurgeAccessRules(sid);             //remove existing
            if (allow != default(FileSystemRights))
            {
                sec.AddAccessRule(new FileSystemAccessRule(sid, allow, AccessControlType.Allow));
            }
            File.SetAccessControl(filepath, sec);
        }
Esempio n. 39
0
 internal XorFileStream(string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options, FileSecurity fileSecurity, byte xorByte) : base(path, mode, rights, share, bufferSize, options, fileSecurity)
 {
     this.XorByte = xorByte;
 }
Esempio n. 40
0
        /// <summary>
        /// Determines whether [has file or directory access] [the specified right].
        /// </summary>
        /// <param name="right">The right.</param>
        /// <param name="acl">The acl.</param>
        /// <returns><c>true</c> if [has file or directory access] [the specified right]; otherwise, <c>false</c>.</returns>
        private static bool HasFileOrDirectoryAccess(
            FileSystemRights right,
            AuthorizationRuleCollection acl)
        {
            var allow          = false;
            var inheritedAllow = false;
            var inheritedDeny  = false;

            Initialize();

            for (var i = 0; i < acl.Count; i++)
            {
                var currentRule = (FileSystemAccessRule)acl[i];
                // If the current rule applies to the current user.
                if (currentRule == null ||
                    _CurrentUser.User == null ||
                    !_CurrentUser.User.Equals(currentRule.IdentityReference) &&
                    !_CurrentPrincipal.IsInRole((SecurityIdentifier)currentRule.IdentityReference))
                {
                    continue;
                }

                if (currentRule.AccessControlType.Equals(AccessControlType.Deny))
                {
                    if ((currentRule.FileSystemRights & right) != right)
                    {
                        continue;
                    }

                    if (currentRule.IsInherited)
                    {
                        inheritedDeny = true;
                    }
                    else
                    {
                        // Non inherited "deny" takes overall precedence.
                        return(false);
                    }
                }
                else if (currentRule.AccessControlType.Equals(AccessControlType.Allow))
                {
                    if ((currentRule.FileSystemRights & right) != right)
                    {
                        continue;
                    }

                    if (currentRule.IsInherited)
                    {
                        inheritedAllow = true;
                    }
                    else
                    {
                        allow = true;
                    }
                }
            }

            if (allow)
            {
                // Non inherited "allow" takes precedence over inherited rules.
                return(true);
            }

            return(inheritedAllow && !inheritedDeny);
        }
 public BackupFileStream(string path, FileMode mode, FileSystemRights access, FileShare share, ExtendedFileAttributes attributes)
     : this(File.CreateFileCore(null, path, attributes, null, mode, access, share, true, PathFormat.RelativePath), access)
 {
 }
 public BackupFileStream(string path, FileMode mode, FileSystemRights access, FileShare share, FileOptions options)
     : this(path, mode, access, share, options, null)
 {
 }
 public BackupFileStream(string path, FileMode mode, FileSystemRights access, FileShare share)
     : this(path, mode, access, share, FileOptions.None)
 {
 }
Esempio n. 44
0
 public FileSystemAuditRule(string identity, FileSystemRights fileSystemRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) : base(default(System.Security.Principal.IdentityReference), default(int), default(bool), default(InheritanceFlags), default(PropagationFlags), default(AuditFlags))
 {
     Contract.Ensures(0 <= identity.Length);
     Contract.Ensures(identity.Length <= 512);
 }
Esempio n. 45
0
 public ACE(string principal, string principalSid, string accessType, FileSystemRights fsr)
 {
     _ACE(principal, principalSid, accessType, fsr);
 }
Esempio n. 46
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:SystemWrapper.IO.FileStreamWrap"/> class with the specified path, creation mode, access rights and sharing permission, the buffer size, additional file options, access control and audit security.
 /// </summary>
 /// <param name="path">A relative or absolute path for the file that the current FileStream object will encapsulate.</param>
 /// <param name="mode">A FileMode constant that determines how to open or create the file.</param>
 /// <param name="rights">A FileSystemRights constant that determines the access rights to use when creating access and audit rules for the file.</param>
 /// <param name="share">A FileShare constant that determines how the file will be shared by processes. </param>
 /// <param name="bufferSize">A positive Int32 value greater than 0 indicating the buffer size. For bufferSize values between one and eight, the actual buffer size is set to eight bytes.</param>
 /// <param name="options">A FileOptions value that specifies additional file options.</param>
 /// <param name="fileSecurity">A FileSecurity constant that determines the access control and audit security for the file.</param>
 public FileStreamWrap(string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options, FileSecurity fileSecurity)
 {
     Initialize(path, mode, rights, share, bufferSize, options, fileSecurity);
 }
Esempio n. 47
0
 private static void AddDenyACL(string path, FileSystemRights deny)
 {
     ModifyDenyACL(path, deny, add: true);
 }
Esempio n. 48
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:SystemWrapper.IO.FileStreamWrap"/> class with the specified path, creation mode, access rights and sharing permission, the buffer size, additional file options, access control and audit security.
 /// </summary>
 /// <param name="path">A relative or absolute path for the file that the current FileStream object will encapsulate.</param>
 /// <param name="mode">A FileMode constant that determines how to open or create the file.</param>
 /// <param name="rights">A FileSystemRights constant that determines the access rights to use when creating access and audit rules for the file.</param>
 /// <param name="share">A FileShare constant that determines how the file will be shared by processes. </param>
 /// <param name="bufferSize">A positive Int32 value greater than 0 indicating the buffer size. For bufferSize values between one and eight, the actual buffer size is set to eight bytes.</param>
 /// <param name="options">A FileOptions value that specifies additional file options.</param>
 /// <param name="fileSecurity">A FileSecurity constant that determines the access control and audit security for the file.</param>
 public void Initialize(string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options, FileSecurity fileSecurity)
 {
     FileStreamInstance = new FileStream(path, mode, rights, share, bufferSize, options, fileSecurity);
 }
 private static bool CheckAccessRuleLocal(FileSystemAccessRule fileSystemAccessRule, FileSystemRights fileSystemRights)
 {
     return((fileSystemRights & fileSystemAccessRule.FileSystemRights) == fileSystemRights);
 }
Esempio n. 50
0
 public FileStream(string path, FileMode mode,
                   FileSystemRights rights, FileShare share,
                   int bufferSize, FileOptions options)
     : this(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), share, bufferSize, false, options)
 {
 }
Esempio n. 51
0
 public FileSystemAccessRule(string identity,
                             FileSystemRights fileSystemRights,
                             AccessControlType type)
     : this(new SecurityIdentifier(identity), fileSystemRights, InheritanceFlags.None, PropagationFlags.None, type)
 {
 }
 public BackupFileStream(KernelTransaction transaction, string path, FileMode mode, FileSystemRights access)
     : this(transaction, path, mode, access, FileShare.None)
 {
 }
Esempio n. 53
0
        public static void AddFileSecurity(this FileInfo info, IdentityReference account, FileSystemRights rights, AccessControlType controlType)
        {
            FileSecurity fSecurity = info.GetAccessControl();

            fSecurity.AddAccessRule(new FileSystemAccessRule(account, rights, controlType));

            info.SetAccessControl(fSecurity);
        }
 public BackupFileStream(string path, FileMode mode, FileSystemRights access, FileShare share, FileOptions options, FileSecurity security)
     : this(File.CreateInternal(path, mode, access, share, options, security), access)
 {
 }
Esempio n. 55
0
        public static Boolean ReplaceDirectorySecurity(string dir, IdentityReference[] Account, FileSystemRights Rights, AccessControlType ControlType, InheritanceFlags Inherit, PropagationFlags Propagation)
        {
            DirectoryInfo     dInfo     = new DirectoryInfo(dir);
            DirectorySecurity dSecurity = new DirectorySecurity();

            try
            {
                dSecurity.SetAccessRuleProtection(true, false);
                foreach (IdentityReference account in Account)
                {
                    dSecurity.ResetAccessRule(new FileSystemAccessRule(account, Rights, Inherit, Propagation, ControlType));
                }
                dInfo.SetAccessControl(dSecurity);
            }
            catch (Exception ex)
            {
                LibraryLogging.Error("unable to ReplaceDirectorySecurity for {0} error {1}", dir, ex.Message);
                return(false);
            }

            return(true);
        }
 public BackupFileStream(KernelTransaction transaction, string path, FileMode mode, FileSystemRights access)
     : this(File.CreateFileCore(transaction, path, ExtendedFileAttributes.Normal, null, mode, access, FileShare.None, true, PathFormat.RelativePath), access)
 {
 }
Esempio n. 57
0
 private extern static SafeFileHandle CreateFile(string lpFileName, FileSystemRights dwDesiredAccess, FileShare dwShareMode, IntPtr securityAttrs, FileMode dwCreationDisposition, FileOptions dwFlagsAndAttributes, IntPtr hTemplateFile);
Esempio n. 58
0
 public static void CanCreate(DirectoryInfo di)
 {//是否具备权限在当前提供的目录下新建文件或者文件夹
     FileSystemRights  right = FileSystemRights.Write;
     DirectorySecurity ds    = di.GetAccessControl();
 }
Esempio n. 59
-1
 public static void Add(string Path, string UserName, FileSystemRights Role)
 {
     DirectoryInfo dirinfo = new DirectoryInfo(Path);
     DirectorySecurity sec = dirinfo.GetAccessControl();
     sec.AddAccessRule(new FileSystemAccessRule(UserName, Role, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
     dirinfo.SetAccessControl(sec);
 }
Esempio n. 60
-1
        /// <summary>
        /// Test a file for create file access permissions
        /// </summary>
        /// 
        /// <param name="FilePath">Full path to file</param>
        /// <param name="AccessRight">File System right tested</param>
        /// 
        /// <returns>State</returns>
        public static bool FileHasPermission(string FilePath, FileSystemRights AccessRight)
        {
            if (string.IsNullOrEmpty(FilePath)) return false;

            try
            {
                AuthorizationRuleCollection rules = File.GetAccessControl(FilePath).GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
                WindowsIdentity identity = WindowsIdentity.GetCurrent();

                foreach (FileSystemAccessRule rule in rules)
                {
                    if (identity.Groups.Contains(rule.IdentityReference))
                    {
                        if ((AccessRight & rule.FileSystemRights) == AccessRight)
                        {
                            if (rule.AccessControlType == AccessControlType.Allow)
                                return true;
                        }
                    }
                }
                return false;
            }
            catch
            {
                throw;
            }
        }