c# - 无法复制文件,即使在 C# 中授予了 FileIOPermission

标签 c# .net security windows-7 file-permissions

我在 .NET 3.5 的 Windows 7 中试用 FileIOPermission。我曾经是 Windows XP 用户并被授予此权限,因为我是管理员

我写了下面的代码,测试能不能写到C:\Program Files\Outlook……

static void Main(string[] args)
{
    Console.WriteLine("Am I an administrator? " + new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);

    //  Try and open a file in C:\Program Files\Microsoft Office\Office14\BCSLaunch.dll
    string path = @"C:\Program Files\Microsoft Office\Office14\BCSLaunch.dll";

    try
    {
        FileIOPermission ioPerm = new FileIOPermission(FileIOPermissionAccess.Read, path);
        ioPerm.Demand();

        string backupPath = Path.ChangeExtension(path, ".bak");
        FileIOPermission writeAccess = new FileIOPermission(FileIOPermissionAccess.AllAccess, backupPath);
        writeAccess.Demand();

        Console.WriteLine("Read access is permitted: {0} => {1}",path,SecurityManager.IsGranted(ioPerm));
        Console.WriteLine("Write backup file is permitted: {0} => {1}", backupPath, SecurityManager.IsGranted(writeAccess));

        File.Copy(path, backupPath);

        Console.WriteLine("File copied! {0}",backupPath);
        Console.WriteLine("Deleting file.....");
        File.Delete(path);
    }
    catch (UnauthorizedAccessException uae)
    {
        Console.WriteLine(uae.ToString());
    }

    Console.ReadLine();
}

所以程序导致 UnauthorizedAccessException(这是我预料的),但我不明白的是 Demand() 允许权限,SecurityManager 确认已授予权限,但是在执行 File.Copy() 时我确实遇到了异常。

虽然我很高兴看到 .NET 正在阻止我,但为什么当我调用 Demand() 时它没有更早地通知我?

我得到以下输出:

Am I an administrator? False
Read access is permitted: C:\Program Files\Microsoft Office\Office14\BCSLaunch.dll => True
Write backup file is permitted: C:\Program Files\Microsoft Office\Office14\BCSLaunch.bak => True
System.UnauthorizedAccessException: Access to the path 'C:\Program Files\Microsoft Office\Office14\BCSLaunch.bak' is denied.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.File.InternalCopy(String sourceFileName, String destFileName, Boolean overwrite)
   at System.IO.File.Copy(String sourceFileName, String destFileName)
   at TryAndGetUACPrompt.Program.Main(String[] args) in C:\Users\..............

Please can someone help me understand why I am getting conflicting information?

--

Update - 19:30 GMT

I have looked through the ACLs of the source file using the following code:

Console.WriteLine("ACL Permissions for Source....");
FileSecurity fileSecurityForOriginalPath = new FileSecurity(path, AccessControlSections.Access);

foreach (FileSystemAccessRule rule in fileSecurityForOriginalPath.GetAccessRules(true,true,typeof(NTAccount)))
{
   Console.WriteLine("{0} => {1}", rule.FileSystemRights, rule.AccessControlType);
}

输出如下:

ACL Permissions for Source....
FullControl => Allow
FullControl => Allow
ReadAndExecute, Synchronize => Allow

Therefore, I do have access to read it. However, I tried to use this code to view the permissions of the backup path and obviously, I get an exception as my backup (destination) file doesn't physically exist, so I can't check permissions on it.

I will next try another suggestion to move this check into another method.

Update - 19:45 GMT

I have refactored the Read/Write demands into another method:

private static FileIOPermission CheckWriteAccess(string backupPath)
{
    FileIOPermission writeAccess = new FileIOPermission(FileIOPermissionAccess.AllAccess, backupPath);
    writeAccess.Demand();
    return writeAccess;
}

private static FileIOPermission CheckReadAccess(string path)
{
    FileIOPermission ioPerm = new FileIOPermission(FileIOPermissionAccess.Read, path);
    ioPerm.Demand();
    return ioPerm;
}

这些都返回正常,无一异常(exception)。

因此,如果 .NET Security 增强了 DACL,我想知道为什么它认为它会成功,如果实际上不是。

--

格林威治标准时间 19:57 更新

好的,我检查了目录的权限,而不是 backupFile(目标文件)并将其作为输出(在 .GetAccessRules() 的 AuthorizationRuleCollection 上使用 foreach)

Checking write access in this directory....
FullControl => Allow
268435456 => Allow
FullControl => Allow
268435456 => Allow
FullControl => Allow
268435456 => Allow
ReadAndExecute, Synchronize => Allow
-1610612736 => Allow
268435456 => Allow

I used an Enum.Format(typeof(FileSystemAccessRights),rule,"G") to get the formatting, effectively doing the ToString(), but I just wasn't sure these numbers were correct.

Code to output the above:

private static DirectorySecurity CheckWriteAccess(string backupPath)
{
    DirectorySecurity writeAccess = new DirectorySecurity( Path.GetDirectoryName(backupPath),AccessControlSections.Access);

    Console.WriteLine("Checking write access in this directory....");
    foreach (FileSystemAccessRule rule in writeAccess.GetAccessRules(true, true, typeof(NTAccount)))
    {
        Console.WriteLine("{0} => {1}", Enum.Format(typeof(FileSystemRights),rule.FileSystemRights,"G"), rule.AccessControlType);
    }

    return writeAccess;
}

最佳答案

读/写的 CAS IOPermisson 只授予您读或写的能力。它不注意文件系统级权限 (ACL)。仔细检查文件夹上的 ACL :)

-奥伊辛

关于c# - 无法复制文件,即使在 C# 中授予了 FileIOPermission,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2149619/

相关文章:

c# - 2 在 c# 中启用可编辑 DataGridViewComboBox(非数据绑定(bind))的问题

c# - 私有(private) TeamCity Nuget 不添加程序集引用

.net - 构建 xunit.xml 文件后,我应该使用 xUnitPublisher 还是 xUnitBuilder?

c# - 白标 ASP.NET webapp

c# - 通过Dictionary KeyCollection保持访问速度

c# - 在没有超时的情况下在 AspNetCore 应用程序上运行进程

.net - 为什么F#无法打开静态类?

.net - 何时解决托管堆碎片问题

security - 如何管理项目的 Sitecore 安全访问权限设置(配置)?

java - 寻找一种网站在客户端监控文件的方法