views:

36

answers:

1

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.

+1  A: 

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?

Dan Puzey
Edited my question to include registry access code, thanks :)
Fiona Holder
Which line does it crash on? The `OpenSubKey` or the `GetValue`?
Dan Puzey
OpenSubKey. Hmm, maybe it also needs explicit permissions for Registry.LocalMachine
Fiona Holder
That was it. I had to add [RegistryPermission(SecurityAction.PermitOnly, Read = @"HKEY_LOCAL_MACHINE")] as well. Thanks for your help.
Fiona Holder