Inheritance: FileSystemSecurity
        public void GetOwnershipTest2()
        {
            // Arrange
            var tmpDir = Path.Combine(Path.GetTempPath(), "dirtools-test-" + Guid.NewGuid().ToString());
            Directory.CreateDirectory(tmpDir);

            var tmpFile = Path.Combine(tmpDir, "asdf");

            var localSystem = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);

            var fileSec = new FileSecurity();
            fileSec.SetOwner(localSystem);

            File.Create(tmpFile, 1, FileOptions.None, fileSec).Dispose();

            // Act
            var curIdentity = new NTAccount(Environment.UserDomainName, Environment.UserName);
            DirectoryTools.GetOwnershipForDirectory(tmpFile, curIdentity);

            // Assert
            var curFilesec = new FileSecurity(tmpFile, AccessControlSections.Owner);
            IdentityReference owner = curFilesec.GetOwner(typeof(NTAccount));
            Assert.IsTrue(curIdentity == owner);
        }
Exemplo n.º 2
0
    public static FileStream createFile0(string path, FileMode fileMode, FileSystemRights fileSystemRights, FileShare fileShare, int bufferSize, FileOptions fileOptions)
    {
#if !FIRST_PASS
        System.Security.AccessControl.FileSecurity security = null;
        if (System.IO.File.Exists(path))
        {
            //If the file already exists, we simply retrieve the current security object and use that
            System.IO.FileInfo file = new FileInfo(path);
            security = file.GetAccessControl();
        }
        else
        {
            //If the file does not exist, it is a little bit more complicated.
            Console.Error.WriteLine($"Getting for directory: {path}");
            Console.Error.WriteLine($"Parent is: {System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(path))}");
            System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(path)));
            Console.Error.WriteLine($"Getting security for: {System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(path))}");
            var parentSecurity = directory.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));
            security = new System.Security.AccessControl.FileSecurity();
            foreach (object ruleObject in parentSecurity)
            {
                var rule = ruleObject as FileSystemAccessRule;
                security.AddAccessRule(new FileSystemAccessRule(rule.IdentityReference, rule.FileSystemRights, rule.AccessControlType));
            }
            security.SetAccessRuleProtection(false, false);
        }

        return(FileSystemAclExtensions.Create(new FileInfo(path), fileMode, fileSystemRights, fileShare, bufferSize, fileOptions, security));
#else
        return(null);
#endif
    }
Exemplo n.º 3
0
        /// <summary>
        /// 文件/文件夹权限修改
        /// </summary>
        /// <param name="fileSystemAccessRule">传入修改权限对象</param>
        /// <param name="path">路径</param>
        /// <param name="ifisFolder">是否为文件夹</param>
        public static void setAtrribute(FileSystemAccessRule fileSystemAccessRule, string path, int ifisFolder)
        {
            if (ifisFolder == 0)
            {
                FileInfo fileInfo = new FileInfo(path);
                //获得该文件的访问权限
                System.Security.AccessControl.FileSecurity fileSecurity = fileInfo.GetAccessControl();
                //添加ereryone用户组的访问权限规则 完全控制权限
                fileSecurity.AddAccessRule(fileSystemAccessRule);
                //设置访问权限
                fileInfo.SetAccessControl(fileSecurity);
            }
            else
            {
                DirectoryInfo dir = new DirectoryInfo(path);
                //获得该文件夹的所有访问权限
                System.Security.AccessControl.DirectorySecurity dirSecurity = dir.GetAccessControl(AccessControlSections.All);

                //添加ereryone用户组的访问权限规则 完全控制权限
                FileSystemAccessRule everyoneFileSystemAccessRule = fileSystemAccessRule;
                bool isModified = false;
                dirSecurity.ModifyAccessRule(AccessControlModification.Add, everyoneFileSystemAccessRule, out isModified);
                //设置访问权限
                dir.SetAccessControl(dirSecurity);
            }
        }
Exemplo n.º 4
0
 public static void AddFileSecurity(string path, string Account, System.Security.AccessControl.FileSystemRights Rights, System.Security.AccessControl.AccessControlType ControlType)
 {
     System.IO.FileInfo FINFO = new System.IO.FileInfo(path);
     System.Security.AccessControl.FileSecurity FSECURITY = FINFO.GetAccessControl();
     FSECURITY.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(Account, Rights, ControlType));
     FINFO.SetAccessControl(FSECURITY);
 }
Exemplo n.º 5
0
    public static Stream open(string name, FileMode fileMode, FileAccess fileAccess)
    {
        if (VirtualFileSystem.IsVirtualFS(name))
        {
            return(VirtualFileSystem.Open(name, fileMode, fileAccess));
        }
        else if (fileMode == FileMode.Append)
        {
            System.Security.AccessControl.FileSecurity security;
            if (System.IO.File.Exists(name))
            {
                System.IO.FileInfo file = new FileInfo(name);
                security = file.GetAccessControl();
            }
            else
            {
                System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(name)));
                var parentSecurity = directory.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));
                security = new System.Security.AccessControl.FileSecurity();
                foreach (object ruleObject in parentSecurity)
                {
                    var rule = ruleObject as FileSystemAccessRule;
                    security.AddAccessRule(new FileSystemAccessRule(rule.IdentityReference, rule.FileSystemRights, rule.AccessControlType));
                }

                security.SetAccessRuleProtection(false, false);
            }

            return(FileSystemAclExtensions.Create(new FileInfo(name), FileMode.Append, FileSystemRights.AppendData, FileShare.ReadWrite, 1, FileOptions.None, security));
        }
        else
        {
            return(new FileStream(name, fileMode, fileAccess, FileShare.ReadWrite, 1, false));
        }
    }
        private static void setAccesssToCurrentUserOnly(string filePath)
        {
            FileInfo file = new FileInfo(filePath);
            AuthorizationRuleCollection accessRules = file.GetAccessControl().GetAccessRules(true, true,
                                                                                             typeof(System.Security.Principal.SecurityIdentifier));

            System.Security.AccessControl.FileSecurity fileSecurity = file.GetAccessControl();
            IList <FileSystemAccessRule> existsList = new List <FileSystemAccessRule>();

            foreach (FileSystemAccessRule rule in accessRules)
            {
                //all rule.
                existsList.Add(rule);
            }
            //Add full control to curent user.
            WindowsIdentity   wi = WindowsIdentity.GetCurrent();
            IdentityReference ir = wi.User.Translate(typeof(NTAccount));

            fileSecurity.AddAccessRule(new FileSystemAccessRule(ir, FileSystemRights.FullControl, AccessControlType.Allow));
            //administrators
            IdentityReference BuiltinAdministrators = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);

            fileSecurity.AddAccessRule(new FileSystemAccessRule(BuiltinAdministrators, FileSystemRights.FullControl, AccessControlType.Allow));

            //Clear all rules.
            foreach (FileSystemAccessRule rule in existsList)
            {
                if (!rule.IdentityReference.Equals(ir) && !rule.Equals(BuiltinAdministrators))
                {
                    fileSecurity.RemoveAccessRuleAll(rule);
                }
            }
            file.SetAccessControl(fileSecurity);
        }
Exemplo n.º 7
0
 bool getPer()
 {
     try
     {
         System.Diagnostics.Process p = new System.Diagnostics.Process();
         p.StartInfo.FileName               = "cmd.exe";
         p.StartInfo.UseShellExecute        = false; //是否使用操作系统shell启动
         p.StartInfo.RedirectStandardInput  = true;  //接受来自调用程序的输入信息
         p.StartInfo.RedirectStandardOutput = true;  //由调用程序获取输出信息
         p.StartInfo.RedirectStandardError  = true;  //重定向标准错误输出
         p.StartInfo.CreateNoWindow         = true;  //不显示程序窗口
         p.Start();
         p.StandardInput.WriteLine(@"Takeown /f 'C:\Windows\System32\sethc.exe'");
         p.StandardInput.WriteLine(@"exit");
         p.StandardInput.AutoFlush = true;
         p.WaitForExit();
         p.Close();
         FileInfo fileInfo = new FileInfo(@"C:\Windows\System32\sethc.exe");
         System.Security.AccessControl.FileSecurity fileSecurity = fileInfo.GetAccessControl();
         fileSecurity.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow));
         fileInfo.SetAccessControl(fileSecurity);
         return(true);
     }
     catch { return(false); }
 }
Exemplo n.º 8
0
		public static void SetAccessControl(this FileInfo fileInfo, FileSecurity fileSecurity)
		{
			if (fileInfo == null)
				throw new ArgumentNullException (nameof (fileInfo));

			fileInfo.SetAccessControl (fileSecurity);
		}
Exemplo n.º 9
0
    public static FileStream openStreamForAtomicAppend(string name)
    {
#if !FIRST_PASS
        System.Security.AccessControl.FileSecurity security;
        if (System.IO.File.Exists(name))
        {
            System.IO.FileInfo file = new FileInfo(name);
            security = file.GetAccessControl();
        }
        else
        {
            System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(name)));
            var parentSecurity = directory.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));
            security = new System.Security.AccessControl.FileSecurity();
            foreach (object ruleObject in parentSecurity)
            {
                var rule = ruleObject as FileSystemAccessRule;
                security.AddAccessRule(new FileSystemAccessRule(rule.IdentityReference, rule.FileSystemRights, rule.AccessControlType));
            }

            security.SetAccessRuleProtection(false, false);
        }

        return(FileSystemAclExtensions.Create(new FileInfo(name), FileMode.Append, FileSystemRights.AppendData, FileShare.ReadWrite, 1, FileOptions.None, security));
#else
        return(null);
#endif
    }
Exemplo n.º 10
0
        public void ProcessRequest(HttpContext context)
        {//存储图片并把url存储到对应的人,图片的名字由客户名称和随机码以及时间组成
         //Random ran = new Random();
         //int RandKey = ran.Next(1000, 9999);//
         //                                   // string khstr = context.Session["userid"].ToString();
         //时间相同批号标记相同则是同一个客户同一次的回款和图片
            string khstr = context.Session["userid"].ToString();
            // string khstr = "fly_jaysue";
            // string date = System.DateTime.Today.ToString("yyyyMMdd");
            string rand  = context.Request["rand"].ToString();
            string numid = context.Request["i"].ToString();
            //string Pic_Path = HttpContext.Current.Server.MapPath("MyPicture.jpg");
            //  string path = "D:/wxvivo/image/"+ khstr+"_"+ rand +"_"+ numid + ".jpg";//前八个数表示是同一批次的
            string   imageData = context.Request["imageData"].ToString();//接受png格式的图片数据字符串流
            FileInfo fi        = new FileInfo("D:/image");

            System.Security.AccessControl.FileSecurity fileSecurity = fi.GetAccessControl();
            fileSecurity.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow));
            fileSecurity.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow));
            fi.SetAccessControl(fileSecurity);
            string path = "D:/image/" + khstr + "_" + rand + "_" + numid + ".jpg";                    //前八个数表示是同一批次的

            using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite)) //create
            {
                using (BinaryWriter bw = new BinaryWriter(fs))
                {
                    byte[] data = Convert.FromBase64String(imageData);
                    bw.Write(data);
                    bw.Close();
                }
                // fs.Flush();//清空缓冲区
            }
            context.Response.Write(path);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Copy environment variables and network shares to the destination user context
        /// </summary>
        /// <remarks>CopyNetworkShares is *the best I could do*. Too much verbose, asks for passwords, etc. Far from ideal.</remarks>
        /// <returns>a modified args list</returns>
        internal IEnumerable<string> AddCopyEnvironment(IEnumerable<string> args, ElevationRequest.ConsoleMode mode)
        {
            if (Settings.CopyEnvironmentVariables || Settings.CopyNetworkShares)
            {
                var silent = InputArguments.Debug ? string.Empty : "@";
                var sb = new StringBuilder();
                if (Settings.CopyEnvironmentVariables && mode != ElevationRequest.ConsoleMode.TokenSwitch) // TokenSwitch already uses the current env block.
                {
                    foreach (DictionaryEntry envVar in Environment.GetEnvironmentVariables())
                    {
                        if (envVar.Key.ToString().In("prompt"))
                            continue;

                        sb.AppendLine($"{silent}SET {envVar.Key}={envVar.Value}");
                    }
                }
                if (Settings.CopyNetworkShares)
                {
                    foreach (DriveInfo drive in DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.Network && d.Name.Length == 3))
                    {
                        var tmpSb = new StringBuilder(2048);
                        var size = tmpSb.Capacity;

                        var error = FileApi.WNetGetConnection(drive.Name.Substring(0, 2), tmpSb, ref size);
                        if (error == 0)
                        {
                            sb.AppendLine($"{silent}ECHO Connecting {drive.Name.Substring(0, 2)} to {tmpSb.ToString()} 1>&2");
                            sb.AppendLine($"{silent}NET USE /D {drive.Name.Substring(0, 2)} >NUL 2>NUL");
                            sb.AppendLine($"{silent}NET USE {drive.Name.Substring(0, 2)} {tmpSb.ToString()} 1>&2");
                        }
                    }
                }

                string tempFolder = Path.Combine(
                    Environment.GetEnvironmentVariable("temp", EnvironmentVariableTarget.Machine), // use machine temp to ensure elevated user has access to temp folder
                    nameof(gsudo));

                var dirSec = new DirectorySecurity();
                dirSec.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, AccessControlType.Allow));
                Directory.CreateDirectory(tempFolder, dirSec);

                string tempBatName = Path.Combine(
                    tempFolder,
                    $"{Guid.NewGuid()}.bat");

                File.WriteAllText(tempBatName, sb.ToString());

                System.Security.AccessControl.FileSecurity fSecurity = new System.Security.AccessControl.FileSecurity();
                fSecurity.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
                File.SetAccessControl(tempBatName, fSecurity);

                return new string[] {
                    Environment.GetEnvironmentVariable("COMSPEC"),
                    "/c" ,
                    $"\"{tempBatName} & del /q {tempBatName} & {string.Join(" ",args)}\""
                };
            }
            return args;
        }
 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);
 }
 public CreateFileOperation( string path, int bufferSize, FileOptions options, FileSecurity fileSecurity )
 {
     this.path = path;
     this.bufferSize = bufferSize;
     this.options = options;
     this.fileSecurity = fileSecurity;
     tempFilePath = Path.Combine( Path.GetTempPath(), Path.GetRandomFileName() );
 }
Exemplo n.º 14
0
        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);
        }
Exemplo n.º 15
0
    /// <summary>
    /// 给文件添加完全控制权限
    /// </summary>
    /// <param name="fileName"></param>
    public static void AddTopPermissionToFile(string fileName)
    {
        //给文件添加"Everyone,Users"用户组的完全控制权限
        FileInfo fileInfo = new FileInfo(fileName);

        System.Security.AccessControl.FileSecurity fileSecurity = fileInfo.GetAccessControl();
        fileSecurity.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow));
        fileSecurity.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow));
        fileInfo.SetAccessControl(fileSecurity);
    }
Exemplo n.º 16
0
        public static void SetAccessControl(this FileInfo fileInfo, FileSecurity fileSecurity)
        {
            if (fileSecurity == null)
                throw new ArgumentNullException(nameof(fileSecurity));
            Contract.EndContractBlock();

            String fullPath = Path.GetFullPath(fileInfo.FullName);
            // Appropriate security check should be done for us by FileSecurity.
            fileSecurity.Persist(fullPath);
        }
Exemplo n.º 17
0
        public SecureFile(string filePath)
        {
            Condition.Requires(filePath).IsNotNullOrEmpty();

            this.FilePath = filePath;
            FileSecurity fs = new FileSecurity();

            // Create a file using the FileStream class.
            this.Stream = FileUtil.GetLockedStream(this.FilePath);
            this.Stream.Lock(0, this.Stream.Length);
        }
Exemplo n.º 18
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="pFileName"></param>
        /// <param name="pAccount">ej: @"ALCO\moviedo"</param>
        /// <param name="pRights"><see cref="FileSystemRights"/></param>
        /// <param name="pControlType"><see cref="AccessControlType"/></param>
        public static void RemoveFileSecurity(string pFileName, string pAccount,
                                              FileSystemRights pRights, AccessControlType pControlType)
        {
            //Actual configuracion de seguridad
            System.Security.AccessControl.FileSecurity wFileSecurity = File.GetAccessControl(pFileName);

            // Elimina FileSystemAccessRule de la config de seguridad (wFileSecurity)
            wFileSecurity.RemoveAccessRule(new FileSystemAccessRule(pAccount, pRights, pControlType));

            File.SetAccessControl(pFileName, wFileSecurity);
        }
Exemplo n.º 19
0
        /// <summary>
        /// Establece una nueva configuracion de seguridad apra el archivo.-
        /// Ej: AddFileSecurity(fileInfo.FullName, @"ALCO\moviedo",FileSystemRights.FullControl, AccessControlType.Allow);
        /// </summary>
        /// <param name="pFileName"></param>
        /// <param name="pAccount">ej: @"ALCO\moviedo"</param>
        /// <param name="pRights"><see cref="FileSystemRights"/> </param>
        /// <param name="pControlType"><see cref="AccessControlType"/></param>
        public static void AddFileSecurity(string pFileName, string pAccount,
                                           FileSystemRights pRights, AccessControlType pControlType)
        {
            // Actual configuracion de seguridad
            System.Security.AccessControl.FileSecurity wFileSecurity = File.GetAccessControl(pFileName);

            wFileSecurity.AddAccessRule(new FileSystemAccessRule(pAccount, pRights, pControlType));

            // Establece la nueva configuracion de seguridad
            File.SetAccessControl(pFileName, wFileSecurity);
        }
Exemplo n.º 20
0
 private string getFileOwner(string filename)
 {
     FileSecurity tmp = new FileSecurity(filename, AccessControlSections.Owner);
     string owner = "<unknown>";
     try
     {
         owner = tmp.GetOwner(System.Type.GetType("System.Security.Principal.SecurityIdentifier")).Value;
     }
     catch { }
     return owner;
 }
        static void Main(string[] args)
        {
            DirectorySecurity ds = new DirectorySecurity();
            ds.AddAccessRule(new FileSystemAccessRule("Rafa&Pri", FileSystemRights.Read, AccessControlType.Allow));
            string newFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "Rafa&Pri");
            Directory.CreateDirectory(newFolder, ds);

            FileSecurity fs = new FileSecurity();
            fs.AddAccessRule(new FileSystemAccessRule("Rafa&Pri", FileSystemRights.FullControl, AccessControlType.Allow));
            string newFile = Path.Combine(newFolder, "Data.dat");
            File.Create(newFile, 100, FileOptions.None, fs);
        }
Exemplo n.º 22
0
        /// <summary>
        /// 为文件添加users,everyone用户组的完全控制权限
        /// </summary>
        /// <param name="filePath"></param>
        public static void AddSecurityControllToFile(string[] identities, string filePath)
        {
            //获取文件信息
            FileInfo fileInfo = new FileInfo(filePath);

            //获得该文件的访问权限
            System.Security.AccessControl.FileSecurity fileSecurity = fileInfo.GetAccessControl();
            foreach (var item in identities)
            {
                fileSecurity.AddAccessRule(new FileSystemAccessRule(item, FileSystemRights.FullControl, AccessControlType.Allow));
            }
            //设置访问权限
            fileInfo.SetAccessControl(fileSecurity);
        }
Exemplo n.º 23
0
    static int Create(IntPtr L)
    {
        try
        {
            int count = LuaDLL.lua_gettop(L);

            if (count == 1)
            {
                string arg0            = ToLua.CheckString(L, 1);
                System.IO.FileStream o = System.IO.File.Create(arg0);
                ToLua.PushObject(L, o);
                return(1);
            }
            else if (count == 2)
            {
                string arg0            = ToLua.CheckString(L, 1);
                int    arg1            = (int)LuaDLL.luaL_checknumber(L, 2);
                System.IO.FileStream o = System.IO.File.Create(arg0, arg1);
                ToLua.PushObject(L, o);
                return(1);
            }
            else if (count == 3)
            {
                string arg0 = ToLua.CheckString(L, 1);
                int    arg1 = (int)LuaDLL.luaL_checknumber(L, 2);
                System.IO.FileOptions arg2 = (System.IO.FileOptions)ToLua.CheckObject(L, 3, typeof(System.IO.FileOptions));
                System.IO.FileStream  o    = System.IO.File.Create(arg0, arg1, arg2);
                ToLua.PushObject(L, o);
                return(1);
            }
            else if (count == 4)
            {
                string arg0 = ToLua.CheckString(L, 1);
                int    arg1 = (int)LuaDLL.luaL_checknumber(L, 2);
                System.IO.FileOptions arg2 = (System.IO.FileOptions)ToLua.CheckObject(L, 3, typeof(System.IO.FileOptions));
                System.Security.AccessControl.FileSecurity arg3 = (System.Security.AccessControl.FileSecurity)ToLua.CheckObject(L, 4, typeof(System.Security.AccessControl.FileSecurity));
                System.IO.FileStream o = System.IO.File.Create(arg0, arg1, arg2, arg3);
                ToLua.PushObject(L, o);
                return(1);
            }
            else
            {
                return(LuaDLL.luaL_throw(L, "invalid arguments to method: System.IO.File.Create"));
            }
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e));
        }
    }
Exemplo n.º 24
0
        /// <summary>
        /// 为文件添加users,everyone用户组的完全控制权限
        /// </summary>
        /// <param name="filePath"></param>
        public static void AddSecurityControll2File(string filePath)
        {
            //获取文件信息
            FileInfo fileInfo = new FileInfo(filePath);

            //获得该文件的访问权限
            System.Security.AccessControl.FileSecurity fileSecurity = fileInfo.GetAccessControl();
            //添加ereryone用户组的访问权限规则 完全控制权限
            fileSecurity.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow));
            //添加Users用户组的访问权限规则 完全控制权限
            fileSecurity.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow));
            //设置访问权限
            fileInfo.SetAccessControl(fileSecurity);
        }
Exemplo n.º 25
0
 public static bool AllowFileAccess(string path, FileSystemRights rights)
 {
     try
     {
         var security = new System.Security.AccessControl.FileSecurity();
         var usersSid = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
         security.AddAccessRule(new FileSystemAccessRule(usersSid, rights, AccessControlType.Allow));
         File.SetAccessControl(path, security);
         return true;
     }
     catch
     {
         return false;
     }
 }
Exemplo n.º 26
0
        [System.Security.SecuritySafeCritical]  // auto-generated
        public static void SetAccessControl(this FileStream fileStream, FileSecurity fileSecurity)
        {
            SafeFileHandle handle = fileStream.SafeFileHandle;

            if (fileSecurity == null)
                throw new ArgumentNullException(nameof(fileSecurity));
            Contract.EndContractBlock();

            if (handle.IsClosed)
            {
                throw new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed);
            }

            fileSecurity.Persist(handle, fileStream.Name);
        }
Exemplo n.º 27
0
        /// <summary>
        /// checks if user has rights to edit the file
        /// </summary>
        /// <param name="username">user's name</param>
        /// <param name="path">path of file name</param>
        /// <returns>true if can has right to edit file false otherwise</returns>
        public Boolean UserHasAccessOnFile(string username, string path)
        {
            try
            {
                Boolean ap = false;
                // System.Windows.Forms.MessageBox.Show("hhh");
                WhiteTigerService.conf.ReadConfig();
                if (WhiteTigerService.pref.Filesecurity == true)
                {
                    if ((username != null) || (path != null) || (File.Exists(path) != false))
                    {
                        FileInfo fileinf = new FileInfo(path);

                        System.Security.AccessControl.FileSecurity fs = fileinf.GetAccessControl();
                        AuthorizationRuleCollection aucol             = fs.GetAccessRules(true, true,
                                                                                          typeof(System.Security.Principal.SecurityIdentifier));
                        WindowsIdentity wi = new WindowsIdentity(username);
                        for (int i = 0; i < aucol.Count; i++)
                        {
                            FileSystemAccessRule fsac = (FileSystemAccessRule)aucol[i];
                            WindowsPrincipal     pr   = new WindowsPrincipal(wi);


                            if ((wi.User.Equals(fsac.IdentityReference) == true) || (pr.IsInRole((SecurityIdentifier)fsac.IdentityReference) == true))
                            {
                                ap = true;
                                break;
                            }
                        }
                    }
                    // ap = true;
                }
                else
                {
                    // System.Windows.Forms.MessageBox.Show("hi ");

                    ap = true;
                }

                return(ap);
            }

            catch (Exception e)
            {
                program.errorreport(e);
                return(false);
            }
        }
Exemplo n.º 28
0
 public static bool AllowFileAccess(string path, FileSystemRights rights)
 {
     try
     {
         var security = new System.Security.AccessControl.FileSecurity();
         var usersSid = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
         security.AddAccessRule(new FileSystemAccessRule(usersSid, rights, AccessControlType.Allow));
         File.SetAccessControl(path, security);
         return(true);
     }
     catch (Exception e)
     {
         Util.Logging.Log(e);
         return(false);
     }
 }
Exemplo n.º 29
0
 /// <summary>
 /// 记录错误日志
 /// </summary>
 /// <param name="error1">错误详细信息</param>
 /// <param name="PartName">错误发生的位置</param>
 public static void writeLogMessage(string error1, string PartName, HttpContext context)
 {
     try
     {
         string folderPath = context.Server.MapPath("~/SystemLog/");
         //星期天为第一天
         DateTime datetime = DateTime.Now;
         int      weeknow  = Convert.ToInt32(datetime.DayOfWeek);
         int      daydiff  = (-1) * weeknow;
         //本周第一天
         string firstDay = datetime.AddDays(daydiff).ToString("yyyyMMdd") + ".txt";
         if (string.IsNullOrEmpty(folderPath))
         {
             folderPath = @"c:\AppLog";
         }
         if (!Directory.Exists(folderPath))
         {
             Directory.CreateDirectory(folderPath);
         }
         string allPath = folderPath + "\\" + firstDay;
         if (!File.Exists(allPath))
         {
             using (FileStream fs = new FileStream(allPath, FileMode.Create))
             {
                 using (StreamWriter sw = new StreamWriter(fs))
                 {
                     //获取文件信息
                     FileInfo fileInfo = new FileInfo(allPath);
                     //获得该文件的访问权限
                     System.Security.AccessControl.FileSecurity fileSecurity = fileInfo.GetAccessControl();
                     //添加ereryone用户组的访问权限规则 完全控制权限
                     fileSecurity.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow));
                     //添加Users用户组的访问权限规则 完全控制权限
                     fileSecurity.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow));
                     //设置访问权限
                     fileInfo.SetAccessControl(fileSecurity);
                 }
             }
         }
         writeLog(allPath, error1, PartName);
     }
     catch (Exception)
     {
     }
 }
Exemplo n.º 30
0
 protected override void ExecuteOnFile(FileInfo file)
 {
     FileSecurity fileSec = new FileSecurity(file.FullName, AccessControlSections.Access);
     IList<FileSystemAccessRule> targetRules = FindAccessRules(fileSec);
     if (targetRules.Count == 0)
     {
         Log(Level.Info, Resources.RemoveAccessRuleEmpty, NTAccount, file.FullName);
     }
     else
     {
         foreach (FileSystemAccessRule fileSystemAccessRule in targetRules)
         {
             Log(Level.Info, Resources.RemoveAccessRuleRemoving, NTAccount, file.FullName);
             fileSec.RemoveAccessRule(fileSystemAccessRule);
         }
         file.SetAccessControl(fileSec);
     }
 }
Exemplo n.º 31
0
        private void VibeCheck(string path)
        {
            Console.WriteLine("[I] Preparing to vibe (giving file access to UWP applications)...");
            FileInfo f = new FileInfo(path);

            System.Security.AccessControl.FileSecurity fileSecurity = f.GetAccessControl();
            Console.WriteLine("[I] Vibing...");
            fileSecurity.AddAccessRule(new FileSystemAccessRule("ALL APPLICATION PACKAGES", FileSystemRights.FullControl, AccessControlType.Allow));
            try
            {
                f.SetAccessControl(fileSecurity);
                Console.WriteLine("[I] Vibe completed. UWP apps are compatible with the DLL: " + path);
            }
            catch (Exception er)
            {
                Console.WriteLine("[!] Vibe error. UWP apps will not be compatible with the DLL: " + path);
                MessageBox.Show("An unexpected, critical error occurred. Please open an error on our GitHub page and report the log: " + er, "Woag x2!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemplo n.º 32
0
        //setGenocide creates the files in Local Appdata to set the game into a Genocide state
        public static void setGenocide(GenocideStates state)
        {
            File.Delete(Constants.AppdataPath + "system_information_963");
            File.Delete(Constants.AppdataPath + "system_information_962");

            switch (state)
            {
            case GenocideStates.Soulless:
                if (!File.Exists(Constants.AppdataPath + "system_information_963"))
                {
                    File.Create(Constants.AppdataPath + "system_information_963").Dispose();
                }
                goto case GenocideStates.Abyss;

            case GenocideStates.Abyss:
                if (!File.Exists(Constants.AppdataPath + "system_information_962"))
                {
                    File.Create(Constants.AppdataPath + "system_information_962").Dispose();
                }
                break;

            case GenocideStates.None:
                File.Create(Constants.AppdataPath + "system_information_963").Dispose();
                File.Create(Constants.AppdataPath + "system_information_962").Dispose();

                System.Security.AccessControl.FileSecurity readDeny = new System.Security.AccessControl.FileSecurity();
                readDeny.SetAccessRule(new System.Security.AccessControl.FileSystemAccessRule(
                                           new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null),
                                           System.Security.AccessControl.FileSystemRights.Read,
                                           System.Security.AccessControl.AccessControlType.Deny));

                System.Security.AccessControl.FileSecurity readDenyTwo = new System.Security.AccessControl.FileSecurity();
                readDenyTwo.SetAccessRule(new System.Security.AccessControl.FileSystemAccessRule(
                                              new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null),
                                              System.Security.AccessControl.FileSystemRights.Read,
                                              System.Security.AccessControl.AccessControlType.Deny));

                System.IO.File.SetAccessControl(Constants.AppdataPath + "system_information_963", readDeny);
                System.IO.File.SetAccessControl(Constants.AppdataPath + "system_information_962", readDenyTwo);
                break;
            }
        }
Exemplo n.º 33
0
        /// <summary>
        /// Gets the security information of specified handle from file system
        /// </summary>
        /// <param name="sidHandle">Handle to get file security information</param>
        /// <returns><see cref="CommonObjectSecurity"/>Result</returns>
        private CommonObjectSecurity ReceiveFileSystemSecurityInformation(out IntPtr sidHandle)
        {
            var zeroHandle          = new IntPtr();
            var pSecurityDescriptor = new IntPtr();

            try
            {
                var namedSecInfoResult = Win32SafeNativeMethods.GetNamedSecurityInfo(PathInfo.FullNameUnc, Win32SecurityObjectType.SeFileObject,
                                                                                     Win32FileSystemEntrySecurityInformation.OwnerSecurityInformation | Win32FileSystemEntrySecurityInformation.DaclSecurityInformation,
                                                                                     out sidHandle, out zeroHandle, out zeroHandle, out zeroHandle, out pSecurityDescriptor);
                var win32Error = Marshal.GetLastWin32Error();
                // Cancel if call failed

                if (namedSecInfoResult != 0)
                {
                    NativeExceptionMapping(PathInfo.FullName, win32Error);
                }

                var securityDescriptorLength    = Win32SafeNativeMethods.GetSecurityDescriptorLength(pSecurityDescriptor);
                var securityDescriptorDataArray = new byte[securityDescriptorLength];
                Marshal.Copy(pSecurityDescriptor, securityDescriptorDataArray, 0, (int)securityDescriptorLength);

                CommonObjectSecurity securityInfo;
                if (ContainsFileAttribute(PathInfo.Attributes, FileAttributes.Directory))
                {
                    securityInfo = new DirectorySecurity();
                    securityInfo.SetSecurityDescriptorBinaryForm(securityDescriptorDataArray);
                }
                else
                {
                    securityInfo = new System.Security.AccessControl.FileSecurity();
                    securityInfo.SetSecurityDescriptorBinaryForm(securityDescriptorDataArray);
                }

                return(securityInfo);
            }
            finally
            {
                Win32SafeNativeMethods.LocalFree(zeroHandle);
                Win32SafeNativeMethods.LocalFree(pSecurityDescriptor);
            }
        }
Exemplo n.º 34
0
 public IFile CreateFile(string file, FileMode fileMode, FileAccess fileAccess, FileShare fileShare,
     FileSystemRights fileSystemRights, FileOptions fileOptions, FileSecurity fileSecurity)
 {
     using (var tranHandle = GetKtmTransactionHandle())
     {
         int dwFlagsAndAttributes = (int) fileOptions;
         dwFlagsAndAttributes |= 0x100000;
         NativeMethods.FileAccess faccess = NativeFileEnums.TranslateFileAccess(fileAccess);
         NativeMethods.FileShare fshare = NativeFileEnums.TranslateFileShare(fileShare);
         NativeMethods.FileMode fmode = NativeFileEnums.TranslateFileMode(fileMode);
         using (SafeFileHandle fileHandle = NativeMethods.CreateFileTransacted(file, faccess, fshare, IntPtr.Zero, fmode,
                                                                               dwFlagsAndAttributes, IntPtr.Zero, tranHandle,
                                                                               IntPtr.Zero, IntPtr.Zero))
         {
             if (fileHandle.IsInvalid)
                 throw new InvalidOperationException();
         }
         return GetFile(file);
     }
 }
Exemplo n.º 35
0
        /// <summary>
        /// Gets the SecurityDescriptor at the specified path, including only the specified
        /// AccessControlSections.
        /// </summary>
        ///
        /// <param name="path">
        /// The path of the item to retrieve. It may be a drive or provider-qualified path and may include.
        /// glob characters.
        /// </param>
        /// 
        /// <param name="sections">
        /// The sections of the security descriptor to include.
        /// </param>
        /// 
        /// <returns>
        /// Nothing. An object that represents the security descriptor for the item
        /// specified by path is written to the context's pipeline.
        /// </returns>
        /// 
        /// <exception cref="System.ArgumentException">
        ///     path is null or empty.
        ///     path doesn't exist
        ///     sections is not valid.
        /// </exception>
        public void GetSecurityDescriptor(string path,
                                          AccessControlSections sections)
        {
            ObjectSecurity sd = null;
            path = NormalizePath(path);

            if (String.IsNullOrEmpty(path))
            {
                throw PSTraceSource.NewArgumentNullException("path");
            }

            if ((sections & ~AccessControlSections.All) != 0)
            {
                throw PSTraceSource.NewArgumentException("sections");
            }

            var currentPrivilegeState = new PlatformInvokes.TOKEN_PRIVILEGE();
            try
            {
                PlatformInvokes.EnableTokenPrivilege("SeBackupPrivilege", ref currentPrivilegeState);

                if (Directory.Exists(path))
                {
                    sd = new DirectorySecurity(path, sections);
                }
                else
                {
                    sd = new FileSecurity(path, sections);
                }
            }
            catch (System.Security.SecurityException e)
            {
                WriteError(new ErrorRecord(e, e.GetType().FullName, ErrorCategory.PermissionDenied, path));
            }
            finally
            {
                PlatformInvokes.RestoreTokenPrivilege("SeBackupPrivilege", ref currentPrivilegeState);
            }

            WriteSecurityDescriptorObject(sd, path);
        }
Exemplo n.º 36
0
        /// <summary>
        /// 记录错误日志
        /// </summary>
        /// <param name="error1">错误详细信息</param>
        /// <param name="PartName">错误发生的位置</param>
        /// <param name="folderPath">记录错误的文件夹路径,适用于TimeJob中调用</param>
        public static void writeLogMessage(string error1, string PartName, string folderPath)
        {
            //string folderPath = ConfigurationManager.AppSettings["AppLogFolderPath"];//OAHelper.GetSystemArgs("AppLogFolderPath", SPContext.Current.Site.RootWeb, true);
            //星期天为第一天
            DateTime datetime = DateTime.Now;
            int      weeknow  = Convert.ToInt32(datetime.DayOfWeek);
            int      daydiff  = (-1) * weeknow;
            //本周第一天
            string firstDay = datetime.AddDays(daydiff).ToString("yyyyMMdd") + ".txt";

            if (string.IsNullOrEmpty(folderPath))
            {
                folderPath = @"c:\AppLog";
            }
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }
            string allPath = folderPath + "\\" + firstDay;

            if (!File.Exists(allPath))
            {
                using (FileStream fs = new FileStream(allPath, FileMode.Create))
                {
                    using (StreamWriter sw = new StreamWriter(fs))
                    {
                        //获取文件信息
                        FileInfo fileInfo = new FileInfo(allPath);
                        //获得该文件的访问权限
                        System.Security.AccessControl.FileSecurity fileSecurity = fileInfo.GetAccessControl();
                        //添加ereryone用户组的访问权限规则 完全控制权限
                        fileSecurity.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow));
                        //添加Users用户组的访问权限规则 完全控制权限
                        fileSecurity.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow));
                        //设置访问权限
                        fileInfo.SetAccessControl(fileSecurity);
                    }
                }
            }
            writeLog(allPath, error1, PartName);
        }
Exemplo n.º 37
0
        /// <summary>
        /// 拷贝文件到另一个文件夹下
        /// </summary>
        /// <param name="sourceName">源文件路径</param>
        /// <param name="folderPath">目标路径,目标文件夹</param>
        public static string CopyToFile(string sourceName, string folderPath, string newFileName = "")
        {
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }

            //文件不用新的文件名,就用原文件文件名
            string fileName = Path.GetFileName(sourceName);

            if (!string.IsNullOrEmpty(newFileName))
            {
                fileName = newFileName + Path.GetExtension(sourceName);
            }
            //目标整体路径
            string targetPath = Path.Combine(folderPath, fileName);

            //Copy到新文件下
            FileInfo file = new FileInfo(sourceName);

            if (file.Exists)
            {
                //获得该文件的访问权限
                System.Security.AccessControl.FileSecurity fileSecurity = file.GetAccessControl();
                //添加ereryone用户组的访问权限规则 完全控制权限
                fileSecurity.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow));
                //添加Users用户组的访问权限规则 完全控制权限
                fileSecurity.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow));
                //设置访问权限
                file.SetAccessControl(fileSecurity);
                //true 覆盖已存在的同名文件,false不覆盖
                file.CopyTo(targetPath, true);
            }
            else
            {
                throw new FileNotFoundException("未找到文件");
            }
            return(targetPath);
        }
Exemplo n.º 38
0
 /// <summary>
 /// 为文件添加users,everyone用户组的完全控制权限
 /// </summary>
 /// <param name="filePath"></param>
 public static void AddSecurityControll2File(string filePath)
 {
     try
     {
         //获取文件信息
         FileInfo fileInfo = new FileInfo(filePath);
         //获得该文件的访问权限
         System.Security.AccessControl.FileSecurity fileSecurity = fileInfo.GetAccessControl();
         //添加ereryone用户组的访问权限规则 完全控制权限
         fileSecurity.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow));
         //添加Users用户组的访问权限规则 完全控制权限
         fileSecurity.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow));
         //设置访问权限
         fileInfo.SetAccessControl(fileSecurity);
     }
     catch (Exception ex)
     {
         throw ex;
     }
     finally
     {
         Console.WriteLine("AddSecurityControll2File is executed.");
     }
 }
Exemplo n.º 39
0
 public static System.IO.FileStream Create(this System.IO.FileInfo fileInfo, System.IO.FileMode mode, System.Security.AccessControl.FileSystemRights rights, System.IO.FileShare share, int bufferSize, System.IO.FileOptions options, System.Security.AccessControl.FileSecurity fileSecurity)
 {
     throw null;
 }
        private static string getAndInitDatabase()
        {
            string userDBPath = "";

#if !DEBUG
            try
            {
                using (var mutex = new System.Threading.Mutex(false, "huawei.sccmplugin.db"))
                {
                    if (mutex.WaitOne(TimeSpan.FromSeconds(60), false))
                    {
                        var localPath = System.Environment.GetEnvironmentVariable("userprofile");//C:\Users\Public\Huawei\SCCM Plugin

                        var allUserPath = System.Environment.GetEnvironmentVariable("PUBLIC");

                        userDBPath = Path.Combine(localPath, "Huawei", "SCCM Plugin", "DB", "db.sqlite");
                        string allDBPath = Path.Combine(allUserPath, "Huawei", "SCCM Plugin", "DB", "db.sqlite");
                        if (!File.Exists(userDBPath))
                        {
                            //Init folder.
                            FileInfo file = new FileInfo(userDBPath);
                            if (!file.Directory.Exists)
                            {
                                file.Directory.Create();
                            }
                            //Copy
                            if (File.Exists(allDBPath))
                            {
                                File.Copy(allDBPath, userDBPath);
                            }

                            AuthorizationRuleCollection accessRules = file.GetAccessControl().GetAccessRules(true, true,
                                                                                                             typeof(System.Security.Principal.SecurityIdentifier));

                            System.Security.AccessControl.FileSecurity fileSecurity = file.GetAccessControl();
                            IList <FileSystemAccessRule> existsList = new List <FileSystemAccessRule>();
                            foreach (FileSystemAccessRule rule in accessRules)
                            {
                                //all rule.
                                existsList.Add(rule);
                            }
                            //Add full control to curent user.
                            WindowsIdentity   wi = WindowsIdentity.GetCurrent();
                            IdentityReference ir = wi.User.Translate(typeof(NTAccount));
                            fileSecurity.AddAccessRule(new FileSystemAccessRule(ir, FileSystemRights.FullControl, AccessControlType.Allow));
                            //administrators
                            IdentityReference BuiltinAdministrators = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
                            fileSecurity.AddAccessRule(new FileSystemAccessRule(BuiltinAdministrators, FileSystemRights.FullControl, AccessControlType.Allow));

                            //Clear all rules.
                            foreach (FileSystemAccessRule rule in existsList)
                            {
                                if (!rule.IdentityReference.Equals(ir) && !rule.Equals(BuiltinAdministrators))
                                {
                                    fileSecurity.RemoveAccessRuleAll(rule);
                                }
                            }
                            file.SetAccessControl(fileSecurity);
                        }
                    }
                }
            }
            catch (Exception se)
            {
                LogUtil.HWLogger.API.Error(se);
                throw;
            }
#endif
            return(userDBPath);
        }
Exemplo n.º 41
0
 public void SetAccessControl(string path, FileSecurity fileSecurity)
 {
     File.SetAccessControl(path, fileSecurity);
 }
Exemplo n.º 42
0
 public FileStream Create(string path, int bufferSize, FileOptions options, FileSecurity fileSecurity)
 {
     return File.Create(path, bufferSize, options, fileSecurity);
 }
Exemplo n.º 43
0
 public abstract Stream Create(string path, int bufferSize, FileOptions options, FileSecurity fileSecurity);
Exemplo n.º 44
0
 public abstract void SetAccessControl(string path, FileSecurity fileSecurity);
Exemplo n.º 45
0
 public static FileStream Create(string path, int bufferSize, FileOptions options, System.Security.AccessControl.FileSecurity fileSecurity)
 => new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, options);                 // ignore fileSecurity
Exemplo n.º 46
0
 public virtual void BeginCreate(string path, int bufferSize, FileOptions options, FileSecurity fileSecurity)
 {
 }
 public static bool setAccessControl(this FileInfo fileInfo, string targetUser, FileSystemRights fileSystemRights, AccessControlType accessControlType)
 {
     if (fileInfo.notNull() && targetUser.notNull())
     {
         try
         {
             var fileSystemAccessRule = new FileSystemAccessRule(targetUser, fileSystemRights, accessControlType);
             var fileSecurity = new FileSecurity();
             fileSecurity.AddAccessRule(fileSystemAccessRule);
             fileInfo.SetAccessControl(fileSecurity);
             return true;
         }
         catch (Exception ex)
         {
             ex.log();
         }
     }
     return false;
 }
Exemplo n.º 48
0
        /// <summary>
        /// Copies the Access Control List (ACL) from one file to another and specify additional ACL rules on the destination file.
        /// </summary>
        /// <param name="pathToSourceFile">The path to the source file.</param>
        /// <param name="pathToDestinationFile">The path to the destination file.</param>
        /// <param name="additionalFileSystemAccessRules">An array of <see cref="FileSystemAccessRule"/>. The additional ACLs.</param>
        public static void CopyAccessControlList(string pathToSourceFile, string pathToDestinationFile, FileSystemAccessRule[] additionalFileSystemAccessRules)
        {
            if (additionalFileSystemAccessRules == null)
            {
                throw new ArgumentNullException("additionalFileSystemAccessRules");
            }

            CheckFilePathParameter("pathToSourceFile", pathToSourceFile);
            CheckFilePathParameter("pathToDestinationFile", pathToDestinationFile);
            FileSecurity sourceFileSecurity = File.GetAccessControl(pathToSourceFile);
            FileSecurity destinationFileSecurity = new FileSecurity();
            byte[] securityDescriptor = sourceFileSecurity.GetSecurityDescriptorBinaryForm();
            destinationFileSecurity.SetSecurityDescriptorBinaryForm(securityDescriptor);
            foreach (FileSystemAccessRule fileSystemAccessRule in additionalFileSystemAccessRules)
            {
                destinationFileSecurity.AddAccessRule(fileSystemAccessRule);
            }

            File.SetAccessControl(pathToDestinationFile, destinationFileSecurity);
        }
Exemplo n.º 49
0
 public static void SetAccessControl(this System.IO.FileStream fileStream, System.Security.AccessControl.FileSecurity fileSecurity)
 {
 }
Exemplo n.º 50
0
 public virtual void FailSetAccessControl(ref Exception exception, string path, FileSecurity fileSecurity)
 {
 }
Exemplo n.º 51
0
        private static void RemoverPermissaoProcessos()
        {
            var everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
            Console.Write("Removendo permissões Gbp... ");
            foreach (var dir in CaminhosGBP)
            {
                try
                {
                    var dirInfo = new DirectoryInfo(Environment.ExpandEnvironmentVariables(dir));
                    if (dirInfo.Exists)
                    {

                        foreach (var f in dirInfo.GetFiles())
                        {
                            if (Path.GetExtension(f.Name).ToLower() == ".exe")
                            {
                                var fs = new FileSecurity();
                                fs.SetOwner(new NTAccount(WindowsIdentity.GetCurrent().Name));

                                fs.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.ExecuteFile, AccessControlType.Deny));
                                f.SetAccessControl(fs);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine(ex.Message);
                }
            }
            Console.WriteLine("OK.");
        }
Exemplo n.º 52
0
		public static FileStream Create (string path, int bufferSize,
						 FileOptions options,
						 FileSecurity fileSecurity)
		{
			return new FileStream (path, FileMode.Create, FileAccess.ReadWrite,
				FileShare.None, bufferSize, options);
		}
Exemplo n.º 53
0
 /// <summary>
 /// Sets the access control.
 /// </summary>
 /// <param name="path">The path.</param>
 /// <param name="fileSecurity">The file security.</param>
 public static void SetAccessControl(string path, FileSecurity fileSecurity)
 {
     _mock.SetAccessControl(path, fileSecurity);
 }
Exemplo n.º 54
0
		public static void SetAccessControl (string path,
						     FileSecurity fileSecurity)
		{
			throw new NotImplementedException ();
		}
Exemplo n.º 55
0
 public override Stream Create(string path, int bufferSize, FileOptions options, FileSecurity fileSecurity)
 {
     throw new NotImplementedException("This test helper hasn't been implemented yet. They are implemented on an as-needed basis. As it seems like you need it, now would be a great time to send us a pull request over at https://github.com/tathamoddie/System.IO.Abstractions. You know, because it's open source and all.");
 }
Exemplo n.º 56
0
		public void SetAccessControl (FileSecurity fileSecurity)
		{
			File.SetAccessControl (FullPath, fileSecurity);
		}
Exemplo n.º 57
0
        public void SetAccessControl_CallsApiCorrectly()
        {
            var fixture = DokanOperationsFixture.Instance;

            string path = DokanOperationsFixture.FileName;

            var security = new FileSecurity();
            security.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), FileSystemRights.FullControl, AccessControlType.Allow));
#if LOGONLY
            fixture.SetupAny();
#else
            fixture.SetupCreateFile(path.AsRootedPath(), ChangePermissionsAccess, ReadWriteShare, FileMode.Open);
            fixture.SetupGetFileInformation(path.AsRootedPath(), FileAttributes.Normal);
            fixture.SetupGetFileSecurity(path.AsRootedPath(), DokanOperationsFixture.DefaultFileSecurity);
            fixture.SetupSetFileSecurity(path.AsRootedPath(), security);
            fixture.SetupCreateFile(DokanOperationsFixture.RootName, ReadPermissionsAccess, ReadWriteShare, FileMode.Open);
            fixture.SetupGetFileInformation(DokanOperationsFixture.RootName, FileAttributes.Directory);
            fixture.SetupGetFileSecurity(DokanOperationsFixture.RootName, DokanOperationsFixture.DefaultDirectorySecurity, AccessControlSections.Access);
#endif

            var sut = new FileInfo(path.AsDriveBasedPath());
            sut.SetAccessControl(security);

#if !LOGONLY
            fixture.VerifyAll();
#endif
        }
Exemplo n.º 58
0
 public void TestSetAccessControl()
 {
     var filename = Util.CreateNewFile(longPathDirectory);
     try
     {
         var security = new FileSecurity();
         File.SetAccessControl(filename, security);
     }
     finally
     {
         File.Delete(filename);
     }
 }
Exemplo n.º 59
0
 public static void SetAccessControl(System.IO.FileInfo fileInfo, System.Security.AccessControl.FileSecurity fileSecurity)
 {
 }