Recipe17.11.Verifying That an Assembly Has Been Granted Specific Permissions


Recipe 17.11. Verifying That an Assembly Has Been Granted Specific Permissions

Problem

When your assembly requests optional permissions (such as asking for disk access to enable users to export data to disk as a product feature) using the SecurityAction. RequestOptional flag, it might or might not get those permissions. Regardless, your assembly will still load and execute. You need a way to verify whether your assembly actually obtained those permissions. This can help prevent many security exceptions from being thrown. For example, if you optionally requested read/write permissions on the registry but did not receive them, you could disable the user interface controls that are used to read and store application settings in the registry.

Solution

Check to see if your assembly received the optional permissions using the SecurityManager.IsGranted method like this:

 using System; using System.Text.RegularExpressions; using System.Web; using System.Net; using System.Security; Regex regex = new Regex(@"http://www\.oreilly\.com/.*"); WebPermission webConnectPerm = new WebPermission(NetworkAccess.Connect,regex); if(SecurityManager.IsGranted(webConnectPerm)) {    // Connect to the O'Reilly site. } 

This code sets up a Regex for the O'Reilly web site, then uses it to create a WebPermission for connecting to that site and all sites containing the www.oreilly.com string. You then check the WebPermission by calling SecurityManager.IsGranted to see whether you have permission to do this.

Discussion

The IsGranted method is a lightweight way of determining whether permission is granted for an assembly without incurring the full stackwalk that a Demand gives you. The downside to this approach is that the code is still subject to a luring attack if Assert is misused, so you need to consider where the call to IsGranted is being made in the overall scheme of your security.

Some of the reasons you might design an assembly to have optional permissions is for deployment in different customer scenarios. In some scenarios (like desktop applications), it might be acceptable to have an assembly that can perform more robust actions (talk to a database, create network traffic via HTTP, etc.). In other scenarios, you can defer these actions if the customer does not wish to grant enough permissions for these extra services to function.

See Also

See the "WebPermission Class," "SecurityManager Class," and "IsGranted Method" topics in the MSDN documentation.



C# Cookbook
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2004
Pages: 424

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net