Home > Articles > Security > Network Security

  • Print
  • + Share This
This chapter is from the book

Adding Restricted Code Sections

The set of permissions an application has is determined by the permissions its application manifest says it requires to run and the permissions that would be granted to it based on the zone it is launching from. However, if you need to elevate permissions for certain parts of your application, you may not want to leave your entire application vulnerable because of those elevated permissions. For example, you may have a very limited scope to perform on-demand updates from your application. As discussed in Chapter 4, on-demand updates require full trust. As a result, you will need to configure your application for full-trust permissions as far as ClickOnce deployment is concerned. However, there may be other portions of your code where you are doing things such as calling out to third-party components, and you want to make sure that they cannot perform any operations or access any resources other than what they are supposed to based on their design purpose.

For example, say for a limited scope you were going to call out to a component that is supposed to perform certain kinds of computation for you, and perhaps it may also present a user interface in doing so or to present error messages to users. However, by design, the component should never do anything other than execute and present user interfaces.

You can use the capabilities of Code Access Security to lock down the security context for a given scope of code. Listing 6.1 shows a section of code where a component is going to be used for a limited scope of code, and you want to ensure that the only thing that component does is to present a user interface to users. To do this, you can use a stack walk modifier, based on the IStackWalk interface, to turn on only a particular permission type.

Listing 6.1. Restricting Permissions for a Code Scope

private void OnCallUntrustedCode(object sender, EventArgs e)
   IStackWalk stackWalk =
      new UIPermission(PermissionState.Unrestricted);
   UIOnlyComponent uoc = new UIOnlyComponent();

With the PermitOnly stack walk modifier in place, any code that is called out to in that scope will be restricted based on the specifications that the stack walk modifier puts in place. You can use stack walk modifiers to permit only a specific permission or set of permissions as shown in Listing 6.1, deny a specific permission or set of permissions, or prevent checking for specific permissions beyond the local scope of code. The latter capability is called a security assertion and requires elevated permissions to be performed.4

  • + Share This
  • 🔖 Save To Your Account