简体   繁体   中英

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

I'm using .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. 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. 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.

Can you post the code to your registry access?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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