Constraining code and building least privileged code is analogous to using the principle of least privilege when you configure user or service accounts. By restricting the code access security permissions available to your code, you minimize scope for the malicious use of your code.
There are two ways to constrain code to restrict which resources it can access and restrict which other privileged operations it can perform:
Using policy permission grants
Using stack walk modifiers
You can configure code access security policy to grant a restricted permission set to a specific assembly. This constrains its ability to access resources or perform other privileged operations. For more information, see "How To: Configure Code Access Security Policy to Constrain an Assembly" in the "How To" section of this guide.
You can use stack walk modifiers to ensure that only specific permissions are available to the code that you call. For example, you can use SecurityAction.PermitOnly to ensure that your method and any methods that are called only have a restricted permission set. The following example applies a very restrictive permission set. The code only has the permission to execute. It cannot access resources or perform other privileged operations.
[SecurityPermissionAttribute(SecurityAction.PermitOnly, Flags=SecurityPermissionFlag.Execution)] public void SomeMethod() { // The current method and downstream can only execute. They cannot access // resources or perform other privileged operations. SomeOtherMethod(); }
The following sections show you how to use code access security to constrain various types of resource access including file I/O, event log, registry, data access, directory services, environment variables , Web services, and sockets.