Microsoft KB Archive/317869

= BUG: The CodeAccessPermission.Deny method does not always work as expected =

Article ID: 317869

Article Last Modified on 1/25/2006

-

APPLIES TO


 * Microsoft Visual Studio .NET 2003 Professional Edition
 * Microsoft Visual Studio .NET 2002 Professional Edition

-



This article was previously published under Q317869



SYMPTOMS
When you use the CodeAccessPermission.Deny method to deny permission to a resource, the method does not always work as expected. A user can work around CodeAccessPermission.Deny to obtain access to the resource, even after the method is called.



RESOLUTION
Do not use CodeAccessPermission.Deny to deny access to a resource. Use the CodeAccessPermission.PermitOnly method. This method allows only the specified permissions and successfully denies everything else, as in the following sample code: [C#] [RegistryPermissionAttribute(SecurityAction.PermitOnly, Read=&quot;HKEY_XXX&quot;)] This sample code grants Read permissions to the registry key only. No other access is allowed.



STATUS
Microsoft has confirmed that this is a bug in the Microsoft products that are listed at the beginning of this article.



MORE INFORMATION
The Help documentation for CodeAccessPermission.Deny that is included in the .NET Framework Developers Guide incorrectly implies that when you use CodeAccessPermission.Deny, there is no way for a user to access the resource.

The following registry example, which is provided in the documentation, allows access as described in the &quot;Steps to Reproduce Behavior&quot; section of this article: [C#] using System; using System.Security.Permissions;

[RegistryPermissionAttribute(SecurityAction.Deny, Write =&quot;HKEY_XXX&quot;)] public class MyClass {  public MyClass {      }

public void ReadRegistry {     //Access the registry. } }

Steps to Reproduce Behavior
To work around a denial of Read access to the registry key, follow these steps:   Create the following string value in the registry: Name=&quot;HKEY_CURRENT_USER\Security&quot;, Value =&quot;SecurityKey&quot;   This key is replicated in the registry as follows: HKEY_USERS\S-1-5-21-XXXXXXXXXX-XXXXXXXXXX-XXXXXXXXXX-XXXXXX\Security For the writer, the key appeared as the following: HKEY_USERS\S-1-5-21-124525095-708259637-1543119021-173552\Security   Insert the following code in the previous ReadRegistry method (any changes are reflected in both keys): [C#] using System; using System.Security.Permissions; using Microsoft.Win32;

[RegistryPermission(SecurityAction.Deny, Read = &quot;HKEY_CURRENT_USER&quot;)] public class MyClass {   private static void ReadRegistry {       RegistryKey key = Registry.Users; RegistryKey subkey = key.OpenSubKey(@&quot;S-1-5-21-124525095-708259637-1543119021-173552&quot;); string s = subkey.GetValue(&quot;security&quot;) as string; Console.WriteLine(s); }

}                   

