简体   繁体   English

.NET 3.5中方法的声明性安全性-如何锁定方法的权限?

[英]Declarative security on methods in .NET 3.5 - how do I lock down a method's permissions?

I'm using .NET 3.5. 我正在使用.NET 3.5。 Say I have a method that accesses a specific file, and a specific registry key. 假设我有一种访问特定文件和特定注册表项的方法。 I want to add declarative security definitions that restrict the method so that it can only access the file and the registry key specified, and nothing else. 我想添加限制该方法的声明性安全性定义,以便它只能访问指定的文件和注册表项,而不能访问其他任何内容。

When I try: 当我尝试:

    [RegistryPermission(SecurityAction.PermitOnly, Read = "registry key path"]
    [FileIOPermission(SecurityAction.PermitOnly, Read = "file path")]

... it lets me read the file path, but not the registry key - I get a security exception. ...它使我可以读取文件路径,但不能读取注册表项-我遇到了安全异常。

If I use: 如果我使用:

    [RegistryPermission(SecurityAction.Demand, Read = "registry key path"]
    [FileIOPermission(SecurityAction.Demand, Read = "file path")]

... it lets me read the file and the registry key, but also lets me access other files. ...它使我可以读取文件和注册表项,还可以访问其他文件。

Am I missing something about how these methods should be used to acheive this effect? 我是否想知道应该如何使用这些方法来达到这种效果?

Edit: 编辑:

The code I am using to access the registry key is: 我用来访问注册表项的代码是:

    RegistryKey rk = Registry.LocalMachine;
    rk = rk.OpenSubKey("MyKey");
    string registryVal = rk.GetValue("Test").ToString();

and therefore the permission declaration is: 因此,权限声明为:

[RegistryPermission(SecurityAction.PermitOnly, Read = @"HKEY_LOCAL_MACHINE\MyKey")]

Thanks. 谢谢。

I think that what SecurityAction.Demand does is throw a security exception if your current call-chain doesn't already have the specified access. 我认为,如果您当前的调用链还没有指定的访问权限,那么SecurityAction.Demand所做的事情将引发安全异常。 It doesn't change the access that you have (so it wouldn't restrict which other files you can write to), but you should see a security exception if you don't have access to your specified path. 它不会更改您的访问权限(因此不会限制您可以写入的其他文件),但是如果您无权访问指定的路径,则应该看到安全异常。

From what you specify, PermitOnly would be the correct value to use (it restricts access to only the item you specify), and so I wonder whether your registry key code is where the problem is. 从您指定的内容来看, PermitOnly将是要使用的正确值(它仅限制对您指定的项目的访问),因此我想知道您的注册表项代码是否是问题所在。 One typical example is that the .NET registry classes can be used to open a key as either "read only" or "read-write" - and if you try to open read-write, you'll get a security exception even if you never try to change the value. 一个典型的示例是.NET注册表类可用于以“只读”或“读写”方式打开密钥-如果尝试打开读写,即使您遇到了这种情况,也会出现安全异常。永远不要尝试更改值。

Can you post the code to your registry access? 您可以将代码发布到您的注册表访问权限吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM