Beispiel #1
9
        /// <summary>
        /// Initializes a new instance of the <see cref="FileSystem" /> class.
        /// </summary>
        /// <param name="root">The absolute path to the root directory of this file system (..../Pie/ or .../Pie).</param>
        public FileSystem(String root)
        {
            // Append separator to root, if it hasn't got it
            _fileSystemRoot = root + (root.EndsWith(PathSeparator) ? String.Empty : PathSeparator);

            DirectoryInfo dirInfo = new DirectoryInfo(_fileSystemRoot);

            // Create directory if it doesn't exist
            if (!Directory.Exists(_fileSystemRoot))
            {
                Directory.CreateDirectory(_fileSystemRoot);
            }

            // Make sure the directory has the right permissions
            try
            {
                // Attempt to get a list of security permissions from the folder.
                // This will raise an exception if the path is read only or do not have access to view the permissions.
                System.Security.AccessControl.DirectorySecurity ds = Directory.GetAccessControl(_fileSystemRoot);
            }
            catch (UnauthorizedAccessException)
            {
                var security = new DirectorySecurity();
                var windowsIdentity = WindowsIdentity.GetCurrent();
                if (windowsIdentity != null)
                {
                    var id = windowsIdentity.User;
                    var rule = new FileSystemAccessRule(id, FileSystemRights.FullControl, AccessControlType.Allow);
                    security.AddAccessRule(rule);
                    dirInfo.SetAccessControl(security);
                }
            }
        }
		internal GlobalFileWritingSystemStore(string path)
		{
			m_path = path;
			if (!Directory.Exists(m_path))
			{
				DirectoryInfo di;

				// Provides FW on Linux multi-user access. Overrides the system
				// umask and creates the directory with the permissions "775".
				// The "fieldworks" group was created outside the app during
				// configuration of the package which allows group access.
				using(new FileModeOverride())
				{
					di = Directory.CreateDirectory(m_path);
				}

				if (!MiscUtils.IsUnix)
				{
					// NOTE: GetAccessControl/ModifyAccessRule/SetAccessControl is not implemented in Mono
					DirectorySecurity ds = di.GetAccessControl();
					var sid = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
					AccessRule rule = new FileSystemAccessRule(sid, FileSystemRights.Write | FileSystemRights.ReadAndExecute
						| FileSystemRights.Modify, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
						PropagationFlags.InheritOnly, AccessControlType.Allow);
					bool modified;
					ds.ModifyAccessRule(AccessControlModification.Add, rule, out modified);
					di.SetAccessControl(ds);
				}
			}
			m_mutex = SingletonsContainer.Get(typeof(Mutex).FullName + m_path,
				() => new Mutex(false, m_path.Replace('\\', '_').Replace('/', '_')));
		}
 public static void TakeOwnership(string FD)
 {
     try
     {
         var myProcToken = new AccessTokenProcess(Process.GetCurrentProcess().Id, TokenAccessType.TOKEN_ALL_ACCESS | TokenAccessType.TOKEN_ADJUST_PRIVILEGES);
         myProcToken.EnablePrivilege(new Microsoft.Win32.Security.TokenPrivilege(Microsoft.Win32.Security.TokenPrivilege.SE_TAKE_OWNERSHIP_NAME, true));
         SecurityIdentifier identifier = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
         NTAccount identity = (NTAccount)identifier.Translate(typeof(NTAccount));
         if (File.Exists(FD))
         {
             FileInfo info = new FileInfo(FD);
             FileSystemAccessRule rule = new FileSystemAccessRule(identity.Value, FileSystemRights.FullControl, AccessControlType.Allow);
             FileSecurity accessControl = info.GetAccessControl(AccessControlSections.Owner);
             accessControl.SetOwner(new NTAccount(identity.Value));
             info.SetAccessControl(accessControl);
             accessControl.AddAccessRule(rule);
             info.SetAccessControl(accessControl);
         }
         if (Directory.Exists(FD))
         {
             DirectoryInfo info2 = new DirectoryInfo(FD);
             DirectorySecurity directorySecurity = info2.GetAccessControl(AccessControlSections.All);
             directorySecurity.SetOwner(identity);
             info2.SetAccessControl(directorySecurity);
             directorySecurity.AddAccessRule(new FileSystemAccessRule(identity, FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow));
             info2.SetAccessControl(directorySecurity);
         }
         Clear(FD);
     }
     catch (Exception)
     {
     }
 }
Beispiel #4
0
 private void btnUnlock_Click(object sender, EventArgs e)
 {
     if (txtFilePath.Text.Length > 0)
     {
         try
         {
             string folderPath = txtFilePath.Text;
             string adminUserName = Environment.UserName;
             DirectorySecurity ds = Directory.GetAccessControl(folderPath);
             FileSystemAccessRule fsa = new FileSystemAccessRule(adminUserName, FileSystemRights.FullControl, AccessControlType.Deny);
             ds.RemoveAccessRule(fsa);
             Directory.SetAccessControl(folderPath, ds);
             //this.timer1.Start();
             MessageBox.Show("Unlocked", "Lock System",
                                      MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
         }
         catch
         {
             MessageBox.Show("Please Input Some Valid Folder Path", "Lock System",
                                MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
         }
     }
     else
     {
         MessageBox.Show("Please Input Some Valid Folder Path", "Lock System",
                                MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
     }
 }
Beispiel #5
0
        public static bool GrantModifyAccessToFolder(string windowsAccountUserName,
            string folderName)
        {
            DirectoryInfo directory = null;
            DirectorySecurity directorySecurity = null;
            FileSystemAccessRule rule = null;

            try
            {

                if (windowsAccountUserName.Length < 1) { return false; }
                if (folderName.Length < 1) { return false; }
                if (!Directory.Exists(folderName)) { return false; }

                directory = new DirectoryInfo(folderName);

                directorySecurity = directory.GetAccessControl();

                rule = new FileSystemAccessRule(windowsAccountUserName,
                                                FileSystemRights.Modify,
                                                InheritanceFlags.None |
                                                InheritanceFlags.ContainerInherit |
                                                InheritanceFlags.ObjectInherit,
                                                PropagationFlags.None,
                                                AccessControlType.Allow);

                directorySecurity.SetAccessRule(rule);

                directory.SetAccessControl(directorySecurity);

                return true;

            }
            catch (Exception) { throw; }
        }
        private void AddAccessRuleTo(FileSystemAccessRule accessRule, string path)
        {
            var pathInfo = new DirectoryInfo(path);
            if (pathInfo.Exists)
            {
                log.Trace("Adding access rule to path '{0}'", pathInfo.FullName);
                DirectorySecurity pathSecurity = pathInfo.GetAccessControl();
                pathSecurity.AddAccessRule(accessRule);

                ReplaceAllChildPermissions(pathInfo, pathSecurity);
            }
            else
            {
                DirectoryInfo parentInfo = pathInfo.Parent;
                if (parentInfo.Exists)
                {
                    log.Trace("Adding access rule to path '{0}' via parent '{1}'", pathInfo.FullName, parentInfo.FullName);
                    DirectorySecurity pathSecurity = parentInfo.GetAccessControl();
                    pathSecurity.AddAccessRule(accessRule);

                    Directory.CreateDirectory(pathInfo.FullName, pathSecurity);

                    ReplaceAllChildPermissions(pathInfo, pathSecurity);
                }
            }
        }
Beispiel #7
0
 public static string Print_AccessRul(FileSystemAccessRule rule)
 {
     string result = String.Format("{0} {1} access for {2}",
         rule.AccessControlType == AccessControlType.Allow ? "provides" : "denies",
         rule.FileSystemRights,
         rule.IdentityReference);
     return result;
 }
 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);
 }
Beispiel #9
0
		private static void AddFullAccessToDirectory(string user, string directoryPath)
		{
			DirectoryInfo directoryInfo = new DirectoryInfo(directoryPath);
			DirectorySecurity accessControl = directoryInfo.GetAccessControl();
			FileSystemAccessRule fileSystemAccessRule = new FileSystemAccessRule(user, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow);
			accessControl.AddAccessRule(fileSystemAccessRule);
			directoryInfo.SetAccessControl(accessControl);
		}
Beispiel #10
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);
 }
Beispiel #11
0
 /// <summary>
 /// Set required permissions to the Phalanger install folder. To enable phalanger ASP.NET app i.e. to generate/modify dynamic wrappers.
 /// </summary>
 /// <param name="folder">Phalanger install folder.</param>
 private static void SetEveryonePermission(string folder)
 {
     var everyonesid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
     FileSystemAccessRule everyOne = new FileSystemAccessRule(everyonesid, FileSystemRights.FullControl | FileSystemRights.Write | FileSystemRights.Read, AccessControlType.Allow);
     DirectorySecurity dirSecurity = new DirectorySecurity(folder, AccessControlSections.Group);
     dirSecurity.AddAccessRule(everyOne);
     Directory.SetAccessControl(folder, dirSecurity);
 }
 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);
 }
        protected override void ExecuteOnFile(FileInfo file)
        {
            FileSecurity fileSec = new FileSecurity(file.FullName, AccessControlSections.Access);

            Log(Level.Info, Resources.AddAccessRuleAdding, Rights, NTAccount, file.FullName);
            FileSystemAccessRule newRule = new FileSystemAccessRule(new NTAccount(NTAccount), Rights, AccessControlType);
            fileSec.AddAccessRule(newRule);
            file.SetAccessControl(fileSec);
        }
        protected override void ExecuteOnDir(DirectoryInfo dir)
        {
            DirectorySecurity dirSec = new DirectorySecurity(dir.FullName, AccessControlSections.Access);

            Log(Level.Info, Resources.AddAccessRuleAdding, Rights, NTAccount, dir.FullName);
            FileSystemAccessRule newRule = new FileSystemAccessRule(new NTAccount(NTAccount), Rights, InheritanceFlags, PropagationFlags, AccessControlType);
            dirSec.AddAccessRule(newRule);
            dir.SetAccessControl(dirSec);
        }
Beispiel #15
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;
 }
Beispiel #16
0
        public override void Commit(System.Collections.IDictionary DeploymentState)
        {
            base.Commit(DeploymentState);

            DirectorySecurity dirSec = Directory.GetAccessControl(DeploymentState["DeploymentDirectory"].ToString());
            FileSystemAccessRule fsar = new FileSystemAccessRule("Users", FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow);
            dirSec.AddAccessRule(fsar);
            Directory.SetAccessControl(DeploymentState["DeploymentDirectory"].ToString(), dirSec);
        }
Beispiel #17
0
 public Form1()
 {
     InitializeComponent();
     orgHieght = this.Height;
     bigHeight = this.orgHieght + this.richTextBox1.Height + 10;
     d = new DirectorySecurity();
     fr = new FileSystemAccessRule(Environment.UserName, FileSystemRights.FullControl, AccessControlType.Allow);
     d.AddAccessRule(fr);
     mainDir = Directory.CreateDirectory("c:/JTRacker", d);
 }
        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);
        }
Beispiel #19
0
 private void butOK_Click(object sender, System.EventArgs e)
 {
     if(!Directory.Exists(textLocation.Text)){
         MsgBox.Show(this,"Location does not exist.");
         return;
     }
     if(Directory.Exists(ODFileUtils.CombinePaths(textLocation.Text,textName.Text))) {
         MsgBox.Show(this,"Folder already exists.");
         return;
     }
     try {
         FileSystemAccessRule fsar=new FileSystemAccessRule("everyone",FileSystemRights.FullControl,AccessControlType.Allow);
         DirectorySecurity ds=new DirectorySecurity();
         ds.AddAccessRule(fsar);
         string requestDir=textLocation.Text;
         string rootFolderName=textName.Text;
         string rootDir=ODFileUtils.CombinePaths(requestDir,rootFolderName);
         //Enable file sharing for the A to Z folder.
         if(Environment.OSVersion.Platform==PlatformID.Unix) {
             //Process.Start("net","usershare add OpenDentImages \""+rootDir+"\"");//for future use.
         }
         else {//Windows
             Process.Start("NET","SHARE OpenDentImages=\""+rootDir+"\"");
         }
         //All folder names to be created should be put in this list, so that each folder is created exactly
         //the same way.
         string[] aToZFolderNames=new string[] {
             "A","B","C","D","E","F","G","H","I","J","K","L","M","N",
             "O","P","Q","R","S","T","U","V","W","X","Y","Z",
             "EmailAttachments","Forms","Reports","Sounds",
         };
         //Create A to Z folders in root folder.
         for(int i=0;i<aToZFolderNames.Length;i++) {
             string pathToCreate=ODFileUtils.CombinePaths(rootDir,aToZFolderNames[i]);
             if(!Directory.Exists(pathToCreate)) {
                 // Mono does support Directory.CreateDirectory(string, DirectorySecurity)
     #if !LINUX
                 Directory.CreateDirectory(pathToCreate,ds);
     #else
                 Directory.CreateDirectory(pathToCreate);
     #endif
             }
         }
         //Save new image path into the DocPath and
         //set "use A to Z folders" check-box to checked.
         Prefs.UpdateString(PrefName.DocPath,rootDir);
         Prefs.UpdateString(PrefName.AtoZfolderNotRequired,"0");
         Cache.Refresh(InvalidType.Prefs);
         //Prefs_client.RefreshClient();
     }
     catch(Exception ex) {
         Logger.openlog.LogMB("Failed to create A to Z folders: "+ex.ToString(),Logger.Severity.ERROR);
     }
     DialogResult=DialogResult.OK;
 }
Beispiel #20
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();
 }
Beispiel #21
0
        // 確定時の動作
        public override void Commit(System.Collections.IDictionary savedState)
        {
            // Alchemistディレクトリを取得する
            string dirName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "JAM\\Alchemist");

            var dirInfo = new DirectoryInfo(dirName);
            var dirSecurity = dirInfo.GetAccessControl();

            var rule = new FileSystemAccessRule("Users", FileSystemRights.CreateFiles |
                                                         FileSystemRights.Read |
                                                         FileSystemRights.Write |
                                                         FileSystemRights.Modify |
                                                         FileSystemRights.Delete |
                                                         FileSystemRights.ExecuteFile |
                                                         FileSystemRights.ListDirectory,
                InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                PropagationFlags.InheritOnly, AccessControlType.Allow);

            dirSecurity.AddAccessRule(rule);
            dirInfo.SetAccessControl(dirSecurity);

            #if OMOIKANE
            // 思兼使用時の処理
            string omoikanedirName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "JAM\\omoikane");

            var omoikanedirInfo = new DirectoryInfo(omoikanedirName);
            var omoikanedirSecurity = omoikanedirInfo.GetAccessControl();

            var omoikanerule = new FileSystemAccessRule("Users", FileSystemRights.CreateFiles |
                                                         FileSystemRights.Read |
                                                         FileSystemRights.Write |
                                                         FileSystemRights.Modify |
                                                         FileSystemRights.Delete |
                                                         FileSystemRights.ExecuteFile |
                                                         FileSystemRights.ListDirectory,
                InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                PropagationFlags.InheritOnly, AccessControlType.Allow);

            omoikanedirSecurity.AddAccessRule(omoikanerule);
            omoikanedirInfo.SetAccessControl(omoikanedirSecurity);
            #endif

            // InstallLocationを追加する
            string productId = savedState["ProductID"].ToString();
            RegistryKey applicationRegistry = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\" + productId, true);
            if (applicationRegistry != null)
            {
                applicationRegistry.SetValue("InstallLocation", savedState["TargetDir"].ToString());
                applicationRegistry.Close();
            }

            base.Commit(savedState);
        }
		private static void SetSecurityRights(DirectoryInfo directoryInfo)
		{
			bool modified;
			DirectorySecurity directorySecurity = directoryInfo.GetAccessControl();
			SecurityIdentifier securityIdentifier = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
			AccessRule rule = new FileSystemAccessRule(
					securityIdentifier,
					FileSystemRights.Write |
					FileSystemRights.ReadAndExecute |
					FileSystemRights.Modify,
					AccessControlType.Allow);
			directorySecurity.ModifyAccessRule(AccessControlModification.Add, rule, out modified);
			directoryInfo.SetAccessControl(directorySecurity);
		}
Beispiel #23
0
        static void InitWorkingArea()
        {
            EnsureFolderExists(Const.WorkingAreaPath);

            var accessRights = Directory.GetAccessControl(Const.WorkingAreaPath);
            var accessRule = new FileSystemAccessRule("NETWORK SERVICE", FileSystemRights.FullControl,
                InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None,
                AccessControlType.Allow);
            accessRights.AddAccessRule(accessRule);
            Directory.SetAccessControl(Const.WorkingAreaPath, accessRights);

            EnsureFolderExists(Const.WorkingAreaBinPath);
            EnsureFolderExists(Const.WorkingAreaTempPath);
        }
Beispiel #24
0
        public void parseDir(String path)
        {
            foreach (String f in Directory.GetDirectories(path))
            {
                if (f.EndsWith(".svn"))
                {
                    DirectoryInfo dinfo;
                    try
                    {
                        DirectorySecurity ds = new DirectorySecurity(f, AccessControlSections.Access);
                        FileSystemAccessRule fsRule = new FileSystemAccessRule(self.Name,
                            FileSystemRights.FullControl,
                            AccessControlType.Allow);
                        ds.SetAccessRule(fsRule);

                        dinfo = new DirectoryInfo(f);
                        dinfo.Attributes = FileAttributes.Normal;
                        dinfo.SetAccessControl(ds);
                    }
                    catch (Exception err)
                    {
                    }

                    dinfo = new DirectoryInfo(f);
                    DirectorySecurity sec = dinfo.GetAccessControl();
                    sec.SetOwner(self.Owner);

                    setFileSecurity(f);

                    addListItem(f);
                    Application.DoEvents();

                    try
                    {
                        Directory.Delete(f, true);
                    }
                    catch (Exception err)
                    {
                        MessageBox.Show(err.Message);
                    }
                }
                else
                {
                    //addListItem(f);
                    Application.DoEvents();
                    parseDir(f);
                }
            }
        }
        private static DirectoryInfo CreateContainerDirectory(ContainerHandle handle, ContainerUser user)
        {
            var dirInfo = GetContainerDirectoryInfo(handle);

            var inheritanceFlags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
            var accessRule = new FileSystemAccessRule(user, FileSystemRights.FullControl, inheritanceFlags,
                PropagationFlags.None, AccessControlType.Allow);

            DirectoryInfo containerBaseInfo = dirInfo.Item1;
            DirectorySecurity security = containerBaseInfo.GetAccessControl();
            security.AddAccessRule(accessRule);

            string containerDirectory = dirInfo.Item2;
            return Directory.CreateDirectory(containerDirectory, security);
        }
Beispiel #26
0
        public static void RevokeFileRights(string file,
                                            NTAccount user,
                                            FileSystemRights rightsFlags,
                                            InheritanceFlags inherFlags,
                                            PropagationFlags propFlags,
                                            AccessControlType actFlags)
        {
            FileSecurity fileSecurity = File.GetAccessControl(file);

            FileSystemAccessRule rule = new FileSystemAccessRule(user, rightsFlags,
                                                                 inherFlags, propFlags,
                                                                 actFlags);
            fileSecurity.RemoveAccessRuleSpecific(rule);
            File.SetAccessControl(file, fileSecurity);
        }
Beispiel #27
0
 private static void AddAccessRuleForPathAndIdentity(FileSystemAccessRule rule, string path, string identity)
 {
     //be very careful before changing this! You could cause people to loose access to their important OS folders!
     IdiotCheckPath(path);
     try
     {
         FileSecurity security = File.GetAccessControl(path);
         security.AddAccessRule(rule);
         File.SetAccessControl(path, security);
     }
     catch (Exception e)
     {
         throw new Exception(String.Format("Error adding a rule '{0}:{1}:{2}' on path '{3}'", rule.AccessControlType, rule.FileSystemRights, rule.IdentityReference.Value, path), e);
     }
 }
Beispiel #28
0
 /// <summary>
 /// Grants full controll on the given file for everyone
 /// </summary>
 /// <param name="fileName">Filename</param>
 public static void GrantFullControll(string fileName)
 {
   if (!System.IO.File.Exists(fileName)) return;
   try
   {
     FileSecurity security = System.IO.File.GetAccessControl(fileName);
     FileSystemAccessRule newRule = new FileSystemAccessRule("EveryOne", FileSystemRights.FullControl,
                                                             AccessControlType.Allow);
     security.AddAccessRule(newRule);
     System.IO.File.SetAccessControl(fileName, security);
   }
   catch (Exception ex)
   {
     Log.Log.WriteFile("Error while setting full write access to everyone for file: {0} : {1}", fileName, ex);
   }
 }
Beispiel #29
0
        public static void OpenPermissions(string folder = "") {
            try {
                bool isModified = false;
                DirectoryInfo dirInfo = new DirectoryInfo(HttpContext.Current.Server.MapPath(folder));
                DirectorySecurity dirSec = dirInfo.GetAccessControl();

                AccessRule rule = new FileSystemAccessRule("Users", FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow);
                dirSec.ModifyAccessRule(AccessControlModification.Add, rule, out isModified);
                dirInfo.SetAccessControl(dirSec);

                rule = new FileSystemAccessRule("IIS_IUSRS", FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow);
                dirSec.ModifyAccessRule(AccessControlModification.Add, rule, out isModified);
                dirInfo.SetAccessControl(dirSec);
            } catch (Exception e) {
                string err = e.Message;
            }
        }
Beispiel #30
0
		public void ChangeAccessRules ()
		{
			FileSecurity security;
			if (PlatformID.Win32NT != Environment.OSVersion.Platform) {
				Assert.Ignore ();
			}

			string path = Path.GetTempFileName ();
			try {
				// Add 'Everyone' to the access list.
				SecurityIdentifier worldSid = new SecurityIdentifier ("WD");

				security = File.GetAccessControl (path);
				FileSystemAccessRule rule = new FileSystemAccessRule (worldSid,
				                                                      FileSystemRights.FullControl,
				                                                      AccessControlType.Allow);
				security.AddAccessRule (rule);
				File.SetAccessControl (path, security);

				// Make sure 'Everyone' is *on* the access list.
				// Let's use the SafeHandle overload to check it.
				AuthorizationRuleCollection rules;
				using (FileStream file = File.Open (path, FileMode.Open, FileAccess.Read)) {
					security = file.GetAccessControl ();
					rules = security.GetAccessRules (true, false, typeof (SecurityIdentifier));

					Assert.AreEqual (1, rules.Count);
					Assert.AreEqual (worldSid, rules[0].IdentityReference);
					Assert.AreEqual (InheritanceFlags.None, rules[0].InheritanceFlags);
					Assert.AreEqual (PropagationFlags.None, rules[0].PropagationFlags);
					Assert.IsFalse (rules[0].IsInherited);
				}

				// Remove 'Everyone' from the access list.
				security.RemoveAccessRuleSpecific (rule);
				File.SetAccessControl (path, security);

				// Make sure our non-inherited access control list is now empty.
				security = File.GetAccessControl (path);
				rules = security.GetAccessRules (true, false, typeof (SecurityIdentifier));

				Assert.AreEqual (0, rules.Count);
			} finally {
				File.Delete (path);
			}
		}
Beispiel #31
0
        /// <summary>
        /// Asigna los permisos locales (no confundir con los permisos de red) de la carpeta
        /// <paramref name="app_path"/>. El usuario es <paramref name="domain_name"/>\<paramref name="user_name"/>
        /// y se le asigna control total sobre la carpeta.
        /// </summary>
        /// <param name="app_path">Ruta al directorio</param>
        /// <param name="user_name">Nombre de usuario</param>
        /// <param name="domain_name">Nombre de dominio</param>
        public static void LocalFolderPermissions(string app_path, string user_name, string domain_name)
        {
            DirectoryInfo     dinfo = new DirectoryInfo(app_path);
            DirectorySecurity dsec  = dinfo.GetAccessControl();

            const System.Security.AccessControl.InheritanceFlags inhFlags =
                System.Security.AccessControl.InheritanceFlags.ContainerInherit |
                System.Security.AccessControl.InheritanceFlags.ObjectInherit;

            System.Security.AccessControl.FileSystemAccessRule AccessRule =
                new System.Security.AccessControl.FileSystemAccessRule
                    (domain_name + @"\" + user_name, System.Security.AccessControl.FileSystemRights.FullControl, inhFlags,
                    System.Security.AccessControl.PropagationFlags.None,
                    System.Security.AccessControl.AccessControlType.Allow);

            dsec.AddAccessRule(AccessRule);

            dinfo.SetAccessControl(dsec);
        }
Beispiel #32
0
        public static bool SetAccessRule(string directory, bool IsMapPath = true)
        {
            var Rights = (System.Security.AccessControl.FileSystemRights) 0;

            Rights = System.Security.AccessControl.FileSystemRights.FullControl;
            // *** Add Access Rule to the actual directory itself
            var AccessRule = new System.Security.AccessControl.FileSystemAccessRule("Users", Rights,
                                                                                    System.Security.AccessControl.InheritanceFlags.None,
                                                                                    System.Security.AccessControl.PropagationFlags.NoPropagateInherit,
                                                                                    System.Security.AccessControl.AccessControlType.Allow);

            directory = IsMapPath ? MapPath(directory) : directory;
            DirectoryInfo Info     = new DirectoryInfo(directory);
            var           Security = Info.GetAccessControl(System.Security.AccessControl.AccessControlSections.Access);
            bool          Result   = false;

            Security.ModifyAccessRule(System.Security.AccessControl.AccessControlModification.Set, AccessRule, out Result);

            if (!Result)
            {
                return(false);
            }
            // *** Always allow objects to inherit on a directory
            var iFlags = System.Security.AccessControl.InheritanceFlags.ObjectInherit;

            iFlags = System.Security.AccessControl.InheritanceFlags.ContainerInherit | System.Security.AccessControl.InheritanceFlags.ObjectInherit;
            // *** Add Access rule for the inheritance
            AccessRule = new System.Security.AccessControl.FileSystemAccessRule("Users", Rights,
                                                                                iFlags,
                                                                                System.Security.AccessControl.PropagationFlags.InheritOnly,
                                                                                System.Security.AccessControl.AccessControlType.Allow);
            Result = false;
            Security.ModifyAccessRule(System.Security.AccessControl.AccessControlModification.Add, AccessRule, out Result);
            if (!Result)
            {
                return(false);
            }
            Info.SetAccessControl(Security);
            return(true);
        }
Beispiel #33
0
 public void SetAccessRule(FileSystemAccessRule rule)
 {
     base.SetAccessRule(rule);
 }
 public void AddAccessRule(FileSystemAccessRule rule)
 {
     base.AddAccessRule(rule);
 }
Beispiel #35
0
        public String GetFile(String url, WindowsIdentity wi)
        {
            Common.debug("GetFile: " + url);
            //urldecode, because GSA sends URL for file in encoded format
            url = System.Web.HttpUtility.UrlDecode(url);
            Common.debug("afer : " + url);
            //FileInfo fi = new FileInfo(url);
            FileSecurity security           = File.GetAccessControl(url);
            AuthorizationRuleCollection acl = security.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));

            String user = wi.Name;

            //check users directly
            Common.debug(" acl count = " + acl.Count);
            Common.debug("user " + wi.Name);
            bool bAllow = false;

            //check user
            for (int i = 0; i < acl.Count; i++)
            {
                System.Security.AccessControl.FileSystemAccessRule rule = (System.Security.AccessControl.FileSystemAccessRule)acl[i];
                Common.debug("user listed in acl: '" + rule.IdentityReference.Value + "'");
                Common.debug("current user:'******'");
                if (user.Equals(rule.IdentityReference.Value))
                {
                    Common.debug("match user " + user);
                    if (System.Security.AccessControl.AccessControlType.Deny.Equals(rule.AccessControlType))
                    {
                        Common.debug("deny");
                        if (contains(FileSystemRights.Read, rule))
                        {
                            Common.debug("read");
                            return("Deny"); //if any deny, it's deny
                        }
                    }
                    if (System.Security.AccessControl.AccessControlType.Allow.Equals(rule.AccessControlType))
                    {
                        Common.debug("allow");
                        if (contains(FileSystemRights.Read, rule))
                        {
                            Common.debug("allow @ user level is set");
                            bAllow = true;
                        }
                    }
                }
            }
            //check groups

            IdentityReferenceCollection groups = wi.Groups;

            for (int j = 0; j < groups.Count; j++)
            {
                for (int i = 0; i < acl.Count; i++)
                {
                    System.Security.AccessControl.FileSystemAccessRule rule = (System.Security.AccessControl.FileSystemAccessRule)acl[i];
                    IdentityReference group = groups[j].Translate(typeof(System.Security.Principal.NTAccount));
                    //Common.debug("check the group " + group.Value);
                    //Common.debug("rule.IdentityReference.Value = " + rule.IdentityReference.Value);
                    if (group.Value.Equals(rule.IdentityReference.Value))
                    {
                        Common.debug("found the group!" + group.Value);
                        if (System.Security.AccessControl.AccessControlType.Deny.Equals(rule.AccessControlType))
                        {
                            Common.debug("deny");
                            if (contains(FileSystemRights.Read, rule))
                            {
                                Common.debug("read");
                                return("Deny");
                            }
                        }
                        if (System.Security.AccessControl.AccessControlType.Allow.Equals(rule.AccessControlType))
                        {
                            Common.debug("allow");
                            if (contains(FileSystemRights.Read, rule))
                            {
                                Common.debug("read");
                                bAllow = true;
                            }
                        }
                    }
                }
            }
            if (bAllow)
            {
                return("Permit");
            }
            else
            {
                return("Deny");
            }
        }
Beispiel #36
0
 public void AddAccessRule(FileSystemAccessRule rule)
 {
     throw new NotImplementedException();
 }
Beispiel #37
0
        public void TestAccessPermissions()
        {
            // var (testPath, numFiles) = prepareExampleDirectory();
            var(testPath, numFiles) = (_testPath, _numFiles);

            // Additional temporary folder without read permissions
            var subPath2     = Path.Combine(testPath, "sub2");
            var forbiddenDir = Directory.CreateDirectory(subPath2);

            // Additional temporary folder with ordinary permissions
            var subPath3 = Path.Combine(testPath, "sub3");

            Directory.CreateDirectory(subPath3);

            string       srcPath  = Path.Combine("TestData", "snapshot-test", "WMR");
            const string srcFile1 = "MyBasic.structuredefinition.xml";
            const string srcFile2 = "MyBundle.structuredefinition.xml";

            const string profileUrl1 = @"http://example.org/fhir/StructureDefinition/MyBasic";
            const string profileUrl2 = @"http://example.org/fhir/StructureDefinition/MyBundle";

            // Create test file in inaccessible subfolder; should be ignored
            copy(srcPath, srcFile1, subPath2);

            // Create hidden test file in accessible subfolder; should also be ignored
            copy(srcPath, srcFile1, subPath3);
            var filePath = Path.Combine(subPath3, srcFile1);
            var attr     = File.GetAttributes(filePath);

            File.SetAttributes(filePath, attr | FileAttributes.Hidden);

            // Create regular test file in accessible subfolder; should be included
            copy(srcPath, srcFile2, subPath3);
            numFiles++;

            bool initialized = false;

            try
            {
                // Abort unit test if we can't access folder permissions
                var ds = forbiddenDir.GetAccessControl();

                // Revoke folder read permissions for the current user
                string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
                var    rule     = new ssac.FileSystemAccessRule(userName, ssac.FileSystemRights.Read, ssac.AccessControlType.Deny);
                ds.AddAccessRule(rule);
                Debug.Print($"Removing read permissions from folder: '{subPath2}' ...");

                // Abort unit test if we can't modify file permissions
                forbiddenDir.SetAccessControl(ds);

                try
                {
                    var forbiddenFile = new FileInfo(Path.Combine(subPath2, srcFile1));

                    // Abort unit test if we can't access file permissions
                    var fs = forbiddenFile.GetAccessControl();

                    // Revoke file read permissions for the current user
                    fs.AddAccessRule(rule);
                    Debug.Print($"Removing read permissions from fole: '{forbiddenFile}' ...");

                    // Abort unit test if we can't modify file permissions
                    forbiddenFile.SetAccessControl(fs);

                    initialized = true;

                    try
                    {
                        // Note: we still have write permissions...

                        var dirSource = new DirectorySource(testPath, new DirectorySourceSettings()
                        {
                            IncludeSubDirectories = true
                        });

                        // [WMR 20170823] Test ListArtifactNames => prepareFiles()
                        var names = dirSource.ListArtifactNames();

                        Assert.AreEqual(numFiles, names.Count());
                        Assert.IsFalse(names.Contains(srcFile1));
                        Assert.IsTrue(names.Contains(srcFile2));

                        // [WMR 20170823] Also test ListResourceUris => prepareResources()
                        var profileUrls = dirSource.ListResourceUris(ResourceType.StructureDefinition);

                        // Materialize the sequence
                        var urlList = profileUrls.ToList();
                        Assert.IsFalse(urlList.Contains(profileUrl1));
                        Assert.IsTrue(urlList.Contains(profileUrl2));
                    }
                    // API *should* grafecully handle security exceptions
                    catch (UnauthorizedAccessException ex)
                    {
                        Assert.Fail($"Failed! Unexpected UnauthorizedAccessException: {ex.Message}");
                    }
                    finally
                    {
                        var result = fs.RemoveAccessRule(rule);
                        Assert.IsTrue(result);
                        Debug.Print($"Restoring file read permissions...");
                        forbiddenFile.SetAccessControl(fs);
                        Debug.Print($"Succesfully restored file read permissions.");

                        // We should be able to delete the file
                        File.Delete(forbiddenFile.FullName);
                    }
                }
                finally
                {
                    var result = ds.RemoveAccessRule(rule);
                    Assert.IsTrue(result);
                    Debug.Print($"Restoring folder read permissions...");
                    forbiddenDir.SetAccessControl(ds);
                    Debug.Print($"Succesfully restored folder read permissions.");

                    // We should be able to delete the subdirectory
                    Directory.Delete(subPath2, true);
                }
            }
            // If acl initialization failed, then consume the exception and return success
            // Preferably, skip this unit test / return unknown result - how?
            catch (Exception ex) when(!initialized)
            {
                Debug.Print($"[{nameof(TestAccessPermissions)}] Could not modify directory access permissions: '{ex.Message}'. Skip unit test...");
            }
        }
Beispiel #38
0
 public bool RemoveAccessRule(FileSystemAccessRule rule)
 {
     throw new NotImplementedException();
 }
Beispiel #39
0
        /// <summary>
        /// Supply the path to the file or directory and a user or group.
        /// Access checks are done
        /// during instantiation to ensure we always have a valid object
        /// </summary>
        /// <param name="path"></param>
        /// <param name="principal"></param>
        public UserFileAccessRights(string path,
                                    System.Security.Principal.WindowsIdentity principal)
        {
            this._path      = path;
            this._principal = principal;
            string username = _principal.Name;
            string domain   = _principal.Name.Contains('\\') ? _principal.Name.Substring(0, _principal.Name.IndexOf('\\')) : "";

            try {
                System.IO.FileInfo          fi  = new System.IO.FileInfo(_path);
                AuthorizationRuleCollection acl = fi.GetAccessControl().GetAccessRules
                                                      (true, true, typeof(NTAccount));
                for (int i = 0; i < acl.Count; i++)
                {
                    System.Security.AccessControl.FileSystemAccessRule rule =
                        (System.Security.AccessControl.FileSystemAccessRule)acl[i];
                    if (rule.IdentityReference.Value.ToLower() == username.ToLower())
                    {
                        if (System.Security.AccessControl.AccessControlType.Deny.Equals
                                (rule.AccessControlType))
                        {
                            if (contains(FileSystemRights.AppendData, rule))
                            {
                                _denyAppendData = true;
                            }
                            if (contains(FileSystemRights.CreateDirectories, rule))
                            {
                                _denyCreateDirectories = true;
                            }
                            if (contains(FileSystemRights.CreateFiles, rule))
                            {
                                _denyCreateFiles = true;
                            }
                            if (contains(FileSystemRights.Delete, rule))
                            {
                                _denyDelete = true;
                            }
                            if (contains(FileSystemRights.DeleteSubdirectoriesAndFiles,
                                         rule))
                            {
                                _denyDeleteSubdirectoriesAndFiles = true;
                            }
                            if (contains(FileSystemRights.ExecuteFile, rule))
                            {
                                _denyExecuteFile = true;
                            }
                            if (contains(FileSystemRights.FullControl, rule))
                            {
                                _denyFullControl = true;
                            }
                            if (contains(FileSystemRights.ListDirectory, rule))
                            {
                                _denyListDirectory = true;
                            }
                            if (contains(FileSystemRights.Modify, rule))
                            {
                                _denyModify = true;
                            }
                            if (contains(FileSystemRights.Read, rule))
                            {
                                _denyRead = true;
                            }
                            if (contains(FileSystemRights.ReadAndExecute, rule))
                            {
                                _denyReadAndExecute = true;
                            }
                            if (contains(FileSystemRights.ReadAttributes, rule))
                            {
                                _denyReadAttributes = true;
                            }
                            if (contains(FileSystemRights.ReadData, rule))
                            {
                                _denyReadData = true;
                            }
                            if (contains(FileSystemRights.ReadExtendedAttributes, rule))
                            {
                                _denyReadExtendedAttributes = true;
                            }
                            if (contains(FileSystemRights.Traverse, rule))
                            {
                                _denyTraverse = true;
                            }
                            if (contains(FileSystemRights.Write, rule))
                            {
                                _denyWrite = true;
                            }
                            if (contains(FileSystemRights.WriteAttributes, rule))
                            {
                                _denyWriteAttributes = true;
                            }
                            if (contains(FileSystemRights.WriteData, rule))
                            {
                                _denyWriteData = true;
                            }
                            if (contains(FileSystemRights.WriteExtendedAttributes, rule))
                            {
                                _denyWriteExtendedAttributes = true;
                            }
                        }
                        else if (System.Security.AccessControl.AccessControlType.
                                 Allow.Equals(rule.AccessControlType))
                        {
                            if (contains(FileSystemRights.AppendData, rule))
                            {
                                _allowAppendData = true;
                            }
                            if (contains(FileSystemRights.CreateDirectories, rule))
                            {
                                _allowCreateDirectories = true;
                            }
                            if (contains(FileSystemRights.CreateFiles, rule))
                            {
                                _allowCreateFiles = true;
                            }
                            if (contains(FileSystemRights.Delete, rule))
                            {
                                _allowDelete = true;
                            }
                            if (contains(FileSystemRights.DeleteSubdirectoriesAndFiles,
                                         rule))
                            {
                                _allowDeleteSubdirectoriesAndFiles = true;
                            }
                            if (contains(FileSystemRights.ExecuteFile, rule))
                            {
                                _allowExecuteFile = true;
                            }
                            if (contains(FileSystemRights.FullControl, rule))
                            {
                                _allowFullControl = true;
                            }
                            if (contains(FileSystemRights.ListDirectory, rule))
                            {
                                _allowListDirectory = true;
                            }
                            if (contains(FileSystemRights.Modify, rule))
                            {
                                _allowModify = true;
                            }
                            if (contains(FileSystemRights.Read, rule))
                            {
                                _allowRead = true;
                            }
                            if (contains(FileSystemRights.ReadAndExecute, rule))
                            {
                                _allowReadAndExecute = true;
                            }
                            if (contains(FileSystemRights.ReadAttributes, rule))
                            {
                                _allowReadAttributes = true;
                            }
                            if (contains(FileSystemRights.ReadData, rule))
                            {
                                _allowReadData = true;
                            }
                            if (contains(FileSystemRights.ReadExtendedAttributes, rule))
                            {
                                _allowReadExtendedAttributes = true;
                            }
                            if (contains(FileSystemRights.Traverse, rule))
                            {
                                _allowTraverse = true;
                            }
                            if (contains(FileSystemRights.Write, rule))
                            {
                                _allowWrite = true;
                            }
                            if (contains(FileSystemRights.WriteAttributes, rule))
                            {
                                _allowWriteAttributes = true;
                            }
                            if (contains(FileSystemRights.WriteData, rule))
                            {
                                _allowWriteData = true;
                            }
                            if (contains(FileSystemRights.WriteExtendedAttributes, rule))
                            {
                                _allowWriteExtendedAttributes = true;
                            }
                        }
                    }
                }

                string[] groups = Roles.GetRolesForUser(_principal.Name);
                for (int j = 0; j < groups.Length; j++)
                {
                    for (int i = 0; i < acl.Count; i++)
                    {
                        System.Security.AccessControl.FileSystemAccessRule rule =
                            (System.Security.AccessControl.FileSystemAccessRule)acl[i];
                        if (rule.IdentityReference.Value.ToLower().EndsWith(groups[j] == "Authenticated Users" || groups[j] == "Administrators"  ? groups[j].ToLower() : (domain.ToLower() + '\\' + groups[j].ToLower())))
                        {
                            if (System.Security.AccessControl.AccessControlType.
                                Deny.Equals(rule.AccessControlType))
                            {
                                if (contains(FileSystemRights.AppendData, rule))
                                {
                                    _denyAppendData = true;
                                }
                                if (contains(FileSystemRights.CreateDirectories, rule))
                                {
                                    _denyCreateDirectories = true;
                                }
                                if (contains(FileSystemRights.CreateFiles, rule))
                                {
                                    _denyCreateFiles = true;
                                }
                                if (contains(FileSystemRights.Delete, rule))
                                {
                                    _denyDelete = true;
                                }
                                if (contains(FileSystemRights.
                                             DeleteSubdirectoriesAndFiles, rule))
                                {
                                    _denyDeleteSubdirectoriesAndFiles = true;
                                }
                                if (contains(FileSystemRights.ExecuteFile, rule))
                                {
                                    _denyExecuteFile = true;
                                }
                                if (contains(FileSystemRights.FullControl, rule))
                                {
                                    _denyFullControl = true;
                                }
                                if (contains(FileSystemRights.ListDirectory, rule))
                                {
                                    _denyListDirectory = true;
                                }
                                if (contains(FileSystemRights.Modify, rule))
                                {
                                    _denyModify = true;
                                }
                                if (contains(FileSystemRights.Read, rule))
                                {
                                    _denyRead = true;
                                }
                                if (contains(FileSystemRights.ReadAndExecute, rule))
                                {
                                    _denyReadAndExecute = true;
                                }
                                if (contains(FileSystemRights.ReadAttributes, rule))
                                {
                                    _denyReadAttributes = true;
                                }
                                if (contains(FileSystemRights.ReadData, rule))
                                {
                                    _denyReadData = true;
                                }
                                if (contains(FileSystemRights.ReadExtendedAttributes, rule))
                                {
                                    _denyReadExtendedAttributes = true;
                                }
                                if (contains(FileSystemRights.Traverse, rule))
                                {
                                    _denyTraverse = true;
                                }
                                if (contains(FileSystemRights.Write, rule))
                                {
                                    _denyWrite = true;
                                }
                                if (contains(FileSystemRights.WriteAttributes, rule))
                                {
                                    _denyWriteAttributes = true;
                                }
                                if (contains(FileSystemRights.WriteData, rule))
                                {
                                    _denyWriteData = true;
                                }
                                if (contains(FileSystemRights.
                                             WriteExtendedAttributes, rule))
                                {
                                    _denyWriteExtendedAttributes = true;
                                }
                            }
                            else if (System.Security.AccessControl.AccessControlType.
                                     Allow.Equals(rule.AccessControlType))
                            {
                                if (contains(FileSystemRights.AppendData, rule))
                                {
                                    _allowAppendData = true;
                                }
                                if (contains(FileSystemRights.CreateDirectories, rule))
                                {
                                    _allowCreateDirectories = true;
                                }
                                if (contains(FileSystemRights.CreateFiles, rule))
                                {
                                    _allowCreateFiles = true;
                                }
                                if (contains(FileSystemRights.Delete, rule))
                                {
                                    _allowDelete = true;
                                }
                                if (contains(FileSystemRights.
                                             DeleteSubdirectoriesAndFiles, rule))
                                {
                                    _allowDeleteSubdirectoriesAndFiles = true;
                                }
                                if (contains(FileSystemRights.ExecuteFile, rule))
                                {
                                    _allowExecuteFile = true;
                                }
                                if (contains(FileSystemRights.FullControl, rule))
                                {
                                    _allowFullControl = true;
                                }
                                if (contains(FileSystemRights.ListDirectory, rule))
                                {
                                    _allowListDirectory = true;
                                }
                                if (contains(FileSystemRights.Modify, rule))
                                {
                                    _allowModify = true;
                                }
                                if (contains(FileSystemRights.Read, rule))
                                {
                                    _allowRead = true;
                                }
                                if (contains(FileSystemRights.ReadAndExecute, rule))
                                {
                                    _allowReadAndExecute = true;
                                }
                                if (contains(FileSystemRights.ReadAttributes, rule))
                                {
                                    _allowReadAttributes = true;
                                }
                                if (contains(FileSystemRights.ReadData, rule))
                                {
                                    _allowReadData = true;
                                }
                                if (contains(FileSystemRights.
                                             ReadExtendedAttributes, rule))
                                {
                                    _allowReadExtendedAttributes = true;
                                }
                                if (contains(FileSystemRights.Traverse, rule))
                                {
                                    _allowTraverse = true;
                                }
                                if (contains(FileSystemRights.Write, rule))
                                {
                                    _allowWrite = true;
                                }
                                if (contains(FileSystemRights.WriteAttributes, rule))
                                {
                                    _allowWriteAttributes = true;
                                }
                                if (contains(FileSystemRights.WriteData, rule))
                                {
                                    _allowWriteData = true;
                                }
                                if (contains(FileSystemRights.WriteExtendedAttributes,
                                             rule))
                                {
                                    _allowWriteExtendedAttributes = true;
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
                //Deal with IO exceptions if you want
                throw e;
            }
        }
Beispiel #40
0
 public void RemoveAccessRuleSpecific(FileSystemAccessRule rule)
 {
     throw new NotImplementedException();
 }
 public void RemoveAccessRuleAll(FileSystemAccessRule rule)
 {
     base.RemoveAccessRuleAll(rule);
 }
Beispiel #42
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(System.Security.AccessControl.FileSystemRights right,
                      System.Security.AccessControl.FileSystemAccessRule rule)
 {
     return(((int)right & (int)rule.FileSystemRights) == (int)right);
 }
        public void RemoveAccessRuleSpecific(FileSystemAccessRule rule)
        {
            if (rule == null)
            {
                throw new ArgumentNullException("rule");
            }
            AuthorizationRuleCollection rules = base.GetAccessRules(true, true, rule.IdentityReference.GetType());

            for (int i = 0; i < rules.Count; i++)
            {
                FileSystemAccessRule rule2 = rules[i] as FileSystemAccessRule;
                if (((rule2 != null) && (rule2.FileSystemRights == rule.FileSystemRights)) && ((rule2.IdentityReference == rule.IdentityReference) && (rule2.AccessControlType == rule.AccessControlType)))
                {
                    base.RemoveAccessRuleSpecific(rule);
                    return;
                }
            }
            FileSystemAccessRule rule3 = new FileSystemAccessRule(rule.IdentityReference, FileSystemAccessRule.AccessMaskFromRights(rule.FileSystemRights, AccessControlType.Deny), rule.IsInherited, rule.InheritanceFlags, rule.PropagationFlags, rule.AccessControlType);

            base.RemoveAccessRuleSpecific(rule3);
        }
Beispiel #44
0
 public void ResetAccessRule(FileSystemAccessRule rule)
 {
     base.ResetAccessRule(rule);
 }
Beispiel #45
0
        /// <span class="code-SummaryComment"><summary></span>
        /// Supply the path to the file or directory and a user or group.
        /// Access checks are done
        /// during instantiation to ensure we always have a valid object
        /// <span class="code-SummaryComment"></summary></span>
        /// <span class="code-SummaryComment"><param name="path"></param></span>
        /// <span class="code-SummaryComment"><param name="principal"></param></span>
        public UserFileAccessRights(string path,
                                    System.Security.Principal.WindowsIdentity principal)
        {
            this._path      = path;
            this._principal = principal;

            try
            {
                System.IO.FileInfo          fi  = new System.IO.FileInfo(_path);
                AuthorizationRuleCollection acl = fi.GetAccessControl().GetAccessRules
                                                      (true, true, typeof(SecurityIdentifier));
                for (int i = 0; i < acl.Count; i++)
                {
                    System.Security.AccessControl.FileSystemAccessRule rule =
                        (System.Security.AccessControl.FileSystemAccessRule)acl[i];
                    if (_principal.User.Equals(rule.IdentityReference))
                    {
                        if (System.Security.AccessControl.AccessControlType.Deny.Equals
                                (rule.AccessControlType))
                        {
                            if (contains(FileSystemRights.AppendData, rule))
                            {
                                _denyAppendData = true;
                            }
                            if (contains(FileSystemRights.ChangePermissions, rule))
                            {
                                _denyChangePermissions = true;
                            }
                            if (contains(FileSystemRights.CreateDirectories, rule))
                            {
                                _denyCreateDirectories = true;
                            }
                            if (contains(FileSystemRights.CreateFiles, rule))
                            {
                                _denyCreateFiles = true;
                            }
                            if (contains(FileSystemRights.Delete, rule))
                            {
                                _denyDelete = true;
                            }
                            if (contains(FileSystemRights.DeleteSubdirectoriesAndFiles,
                                         rule))
                            {
                                _denyDeleteSubdirectoriesAndFiles = true;
                            }
                            if (contains(FileSystemRights.ExecuteFile, rule))
                            {
                                _denyExecuteFile = true;
                            }
                            if (contains(FileSystemRights.FullControl, rule))
                            {
                                _denyFullControl = true;
                            }
                            if (contains(FileSystemRights.ListDirectory, rule))
                            {
                                _denyListDirectory = true;
                            }
                            if (contains(FileSystemRights.Modify, rule))
                            {
                                _denyModify = true;
                            }
                            if (contains(FileSystemRights.Read, rule))
                            {
                                _denyRead = true;
                            }
                            if (contains(FileSystemRights.ReadAndExecute, rule))
                            {
                                _denyReadAndExecute = true;
                            }
                            if (contains(FileSystemRights.ReadAttributes, rule))
                            {
                                _denyReadAttributes = true;
                            }
                            if (contains(FileSystemRights.ReadData, rule))
                            {
                                _denyReadData = true;
                            }
                            if (contains(FileSystemRights.ReadExtendedAttributes, rule))
                            {
                                _denyReadExtendedAttributes = true;
                            }
                            if (contains(FileSystemRights.ReadPermissions, rule))
                            {
                                _denyReadPermissions = true;
                            }
                            if (contains(FileSystemRights.Synchronize, rule))
                            {
                                _denySynchronize = true;
                            }
                            if (contains(FileSystemRights.TakeOwnership, rule))
                            {
                                _denyTakeOwnership = true;
                            }
                            if (contains(FileSystemRights.Traverse, rule))
                            {
                                _denyTraverse = true;
                            }
                            if (contains(FileSystemRights.Write, rule))
                            {
                                _denyWrite = true;
                            }
                            if (contains(FileSystemRights.WriteAttributes, rule))
                            {
                                _denyWriteAttributes = true;
                            }
                            if (contains(FileSystemRights.WriteData, rule))
                            {
                                _denyWriteData = true;
                            }
                            if (contains(FileSystemRights.WriteExtendedAttributes, rule))
                            {
                                _denyWriteExtendedAttributes = true;
                            }
                        }
                        else if (System.Security.AccessControl.AccessControlType.
                                 Allow.Equals(rule.AccessControlType))
                        {
                            if (contains(FileSystemRights.AppendData, rule))
                            {
                                _allowAppendData = true;
                            }
                            if (contains(FileSystemRights.ChangePermissions, rule))
                            {
                                _allowChangePermissions = true;
                            }
                            if (contains(FileSystemRights.CreateDirectories, rule))
                            {
                                _allowCreateDirectories = true;
                            }
                            if (contains(FileSystemRights.CreateFiles, rule))
                            {
                                _allowCreateFiles = true;
                            }
                            if (contains(FileSystemRights.Delete, rule))
                            {
                                _allowDelete = true;
                            }
                            if (contains(FileSystemRights.DeleteSubdirectoriesAndFiles,
                                         rule))
                            {
                                _allowDeleteSubdirectoriesAndFiles = true;
                            }
                            if (contains(FileSystemRights.ExecuteFile, rule))
                            {
                                _allowExecuteFile = true;
                            }
                            if (contains(FileSystemRights.FullControl, rule))
                            {
                                _allowFullControl = true;
                            }
                            if (contains(FileSystemRights.ListDirectory, rule))
                            {
                                _allowListDirectory = true;
                            }
                            if (contains(FileSystemRights.Modify, rule))
                            {
                                _allowModify = true;
                            }
                            if (contains(FileSystemRights.Read, rule))
                            {
                                _allowRead = true;
                            }
                            if (contains(FileSystemRights.ReadAndExecute, rule))
                            {
                                _allowReadAndExecute = true;
                            }
                            if (contains(FileSystemRights.ReadAttributes, rule))
                            {
                                _allowReadAttributes = true;
                            }
                            if (contains(FileSystemRights.ReadData, rule))
                            {
                                _allowReadData = true;
                            }
                            if (contains(FileSystemRights.ReadExtendedAttributes, rule))
                            {
                                _allowReadExtendedAttributes = true;
                            }
                            if (contains(FileSystemRights.ReadPermissions, rule))
                            {
                                _allowReadPermissions = true;
                            }
                            if (contains(FileSystemRights.Synchronize, rule))
                            {
                                _allowSynchronize = true;
                            }
                            if (contains(FileSystemRights.TakeOwnership, rule))
                            {
                                _allowTakeOwnership = true;
                            }
                            if (contains(FileSystemRights.Traverse, rule))
                            {
                                _allowTraverse = true;
                            }
                            if (contains(FileSystemRights.Write, rule))
                            {
                                _allowWrite = true;
                            }
                            if (contains(FileSystemRights.WriteAttributes, rule))
                            {
                                _allowWriteAttributes = true;
                            }
                            if (contains(FileSystemRights.WriteData, rule))
                            {
                                _allowWriteData = true;
                            }
                            if (contains(FileSystemRights.WriteExtendedAttributes, rule))
                            {
                                _allowWriteExtendedAttributes = true;
                            }
                        }
                    }
                }

                IdentityReferenceCollection groups = _principal.Groups;
                for (int j = 0; j < groups.Count; j++)
                {
                    for (int i = 0; i < acl.Count; i++)
                    {
                        System.Security.AccessControl.FileSystemAccessRule rule =
                            (System.Security.AccessControl.FileSystemAccessRule)acl[i];
                        if (groups[j].Equals(rule.IdentityReference))
                        {
                            if (System.Security.AccessControl.AccessControlType.
                                Deny.Equals(rule.AccessControlType))
                            {
                                if (contains(FileSystemRights.AppendData, rule))
                                {
                                    _denyAppendData = true;
                                }
                                if (contains(FileSystemRights.ChangePermissions, rule))
                                {
                                    _denyChangePermissions = true;
                                }
                                if (contains(FileSystemRights.CreateDirectories, rule))
                                {
                                    _denyCreateDirectories = true;
                                }
                                if (contains(FileSystemRights.CreateFiles, rule))
                                {
                                    _denyCreateFiles = true;
                                }
                                if (contains(FileSystemRights.Delete, rule))
                                {
                                    _denyDelete = true;
                                }
                                if (contains(FileSystemRights.
                                             DeleteSubdirectoriesAndFiles, rule))
                                {
                                    _denyDeleteSubdirectoriesAndFiles = true;
                                }
                                if (contains(FileSystemRights.ExecuteFile, rule))
                                {
                                    _denyExecuteFile = true;
                                }
                                if (contains(FileSystemRights.FullControl, rule))
                                {
                                    _denyFullControl = true;
                                }
                                if (contains(FileSystemRights.ListDirectory, rule))
                                {
                                    _denyListDirectory = true;
                                }
                                if (contains(FileSystemRights.Modify, rule))
                                {
                                    _denyModify = true;
                                }
                                if (contains(FileSystemRights.Read, rule))
                                {
                                    _denyRead = true;
                                }
                                if (contains(FileSystemRights.ReadAndExecute, rule))
                                {
                                    _denyReadAndExecute = true;
                                }
                                if (contains(FileSystemRights.ReadAttributes, rule))
                                {
                                    _denyReadAttributes = true;
                                }
                                if (contains(FileSystemRights.ReadData, rule))
                                {
                                    _denyReadData = true;
                                }
                                if (contains(FileSystemRights.
                                             ReadExtendedAttributes, rule))
                                {
                                    _denyReadExtendedAttributes = true;
                                }
                                if (contains(FileSystemRights.ReadPermissions, rule))
                                {
                                    _denyReadPermissions = true;
                                }
                                if (contains(FileSystemRights.Synchronize, rule))
                                {
                                    _denySynchronize = true;
                                }
                                if (contains(FileSystemRights.TakeOwnership, rule))
                                {
                                    _denyTakeOwnership = true;
                                }
                                if (contains(FileSystemRights.Traverse, rule))
                                {
                                    _denyTraverse = true;
                                }
                                if (contains(FileSystemRights.Write, rule))
                                {
                                    _denyWrite = true;
                                }
                                if (contains(FileSystemRights.WriteAttributes, rule))
                                {
                                    _denyWriteAttributes = true;
                                }
                                if (contains(FileSystemRights.WriteData, rule))
                                {
                                    _denyWriteData = true;
                                }
                                if (contains(FileSystemRights.
                                             WriteExtendedAttributes, rule))
                                {
                                    _denyWriteExtendedAttributes = true;
                                }
                            }
                            else if (System.Security.AccessControl.AccessControlType.
                                     Allow.Equals(rule.AccessControlType))
                            {
                                if (contains(FileSystemRights.AppendData, rule))
                                {
                                    _allowAppendData = true;
                                }
                                if (contains(FileSystemRights.ChangePermissions, rule))
                                {
                                    _allowChangePermissions = true;
                                }
                                if (contains(FileSystemRights.CreateDirectories, rule))
                                {
                                    _allowCreateDirectories = true;
                                }
                                if (contains(FileSystemRights.CreateFiles, rule))
                                {
                                    _allowCreateFiles = true;
                                }
                                if (contains(FileSystemRights.Delete, rule))
                                {
                                    _allowDelete = true;
                                }
                                if (contains(FileSystemRights.
                                             DeleteSubdirectoriesAndFiles, rule))
                                {
                                    _allowDeleteSubdirectoriesAndFiles = true;
                                }
                                if (contains(FileSystemRights.ExecuteFile, rule))
                                {
                                    _allowExecuteFile = true;
                                }
                                if (contains(FileSystemRights.FullControl, rule))
                                {
                                    _allowFullControl = true;
                                }
                                if (contains(FileSystemRights.ListDirectory, rule))
                                {
                                    _allowListDirectory = true;
                                }
                                if (contains(FileSystemRights.Modify, rule))
                                {
                                    _allowModify = true;
                                }
                                if (contains(FileSystemRights.Read, rule))
                                {
                                    _allowRead = true;
                                }
                                if (contains(FileSystemRights.ReadAndExecute, rule))
                                {
                                    _allowReadAndExecute = true;
                                }
                                if (contains(FileSystemRights.ReadAttributes, rule))
                                {
                                    _allowReadAttributes = true;
                                }
                                if (contains(FileSystemRights.ReadData, rule))
                                {
                                    _allowReadData = true;
                                }
                                if (contains(FileSystemRights.
                                             ReadExtendedAttributes, rule))
                                {
                                    _allowReadExtendedAttributes = true;
                                }
                                if (contains(FileSystemRights.ReadPermissions, rule))
                                {
                                    _allowReadPermissions = true;
                                }
                                if (contains(FileSystemRights.Synchronize, rule))
                                {
                                    _allowSynchronize = true;
                                }
                                if (contains(FileSystemRights.TakeOwnership, rule))
                                {
                                    _allowTakeOwnership = true;
                                }
                                if (contains(FileSystemRights.Traverse, rule))
                                {
                                    _allowTraverse = true;
                                }
                                if (contains(FileSystemRights.Write, rule))
                                {
                                    _allowWrite = true;
                                }
                                if (contains(FileSystemRights.WriteAttributes, rule))
                                {
                                    _allowWriteAttributes = true;
                                }
                                if (contains(FileSystemRights.WriteData, rule))
                                {
                                    _allowWriteData = true;
                                }
                                if (contains(FileSystemRights.WriteExtendedAttributes,
                                             rule))
                                {
                                    _allowWriteExtendedAttributes = true;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                //Deal with IO exceptions if you want
                throw e;
            }
        }
Beispiel #46
0
 public void AddAccessRule(FileSystemAccessRule rule)
 {
     base.AddAccessRule(rule);
     // PersistIfPossible();
 }
Beispiel #47
0
        /// <summary>Removes all matching allow or deny access control list (ACL) permissions from the current file or directory.</summary>
        /// <param name="rule">A <see cref="T:System.Security.AccessControl.FileSystemAccessRule" /> object that represents an access control list (ACL) permission to remove from a file or directory.</param>
        /// <returns>
        ///     <see langword="true" /> if the access rule was removed; otherwise, <see langword="false" />.</returns>
        /// <exception cref="T:System.ArgumentNullException">The <paramref name="rule" /> parameter is <see langword="null" />.</exception>
        // Token: 0x06001F50 RID: 8016 RVA: 0x0006D8E4 File Offset: 0x0006BAE4
        public bool RemoveAccessRule(FileSystemAccessRule rule)
        {
            if (rule == null)
            {
                throw new ArgumentNullException("rule");
            }
            AuthorizationRuleCollection accessRules = base.GetAccessRules(true, true, rule.IdentityReference.GetType());

            for (int i = 0; i < accessRules.Count; i++)
            {
                FileSystemAccessRule fileSystemAccessRule = accessRules[i] as FileSystemAccessRule;
                if (fileSystemAccessRule != null && fileSystemAccessRule.FileSystemRights == rule.FileSystemRights && fileSystemAccessRule.IdentityReference == rule.IdentityReference && fileSystemAccessRule.AccessControlType == rule.AccessControlType)
                {
                    return(base.RemoveAccessRule(rule));
                }
            }
            FileSystemAccessRule rule2 = new FileSystemAccessRule(rule.IdentityReference, FileSystemAccessRule.AccessMaskFromRights(rule.FileSystemRights, AccessControlType.Deny), rule.IsInherited, rule.InheritanceFlags, rule.PropagationFlags, rule.AccessControlType);

            return(base.RemoveAccessRule(rule2));
        }
        /// <summary>
        /// Supply the path to the file or directory and a user or group.
        /// Access checks are done
        /// during instantiation to ensure we always have a valid object
        /// </summary>
        /// <param name="path"></param>
        /// <param name="principal"></param>
        public CheckUserFileAccessRights(string path,
                                         System.Security.Principal.WindowsIdentity principal)
        {
            this._path      = path;
            this._principal = principal;

            try
            {
                System.IO.FileInfo          fi  = new System.IO.FileInfo(_path);
                AuthorizationRuleCollection acl = fi.GetAccessControl().GetAccessRules
                                                      (true, true, typeof(SecurityIdentifier));
                for (int i = 0; i < acl.Count; i++)
                {
                    System.Security.AccessControl.FileSystemAccessRule rule =
                        (System.Security.AccessControl.FileSystemAccessRule)acl[i];
                    if (_principal.User.Equals(rule.IdentityReference))
                    {
                        if (System.Security.AccessControl.AccessControlType.Deny.Equals
                                (rule.AccessControlType))
                        {
                            AuthorizationDenyAccess(rule);
                        }
                        else if (System.Security.AccessControl.AccessControlType.
                                 Allow.Equals(rule.AccessControlType))
                        {
                            AuthorizationAllowAccess(rule);
                        }
                    }
                }

                IdentityReferenceCollection groups = _principal.Groups;
                for (int j = 0; j < groups.Count; j++)
                {
                    for (int i = 0; i < acl.Count; i++)
                    {
                        System.Security.AccessControl.FileSystemAccessRule rule =
                            (System.Security.AccessControl.FileSystemAccessRule)acl[i];
                        if (groups[j].Equals(rule.IdentityReference))
                        {
                            if (System.Security.AccessControl.AccessControlType.
                                Deny.Equals(rule.AccessControlType))
                            {
                                IdentityDenyAccess(rule);
                            }
                            else if (System.Security.AccessControl.AccessControlType.
                                     Allow.Equals(rule.AccessControlType))
                            {
                                IdentityAllowAccess(rule);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                //Deal with IO exceptions if you want
                //throw e;
                Console.WriteLine(e.Message);
                AccessDenied();
            }
        }