SecurityCode Access Security with Microsoft .NET Framework

Code Access Security with Microsoft .NET Framework

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Evidence-Based Security

This installment of .NET Nuts & Bolts is part one of a two-part series exploring code access security and how it is controlled by the Microsoft .NET Framework. The Microsoft .NET Framework includes a number of security features that assist you in developing secure applications. The security system, which is a fundamental part of the common language runtime (CLR), controls execution of .NET code. It includes handy features such as the following:

  • Type safety enforcement, which eliminates the potential for buffer overruns
  • Arithmetic error trapping, which detects the potential for underflows and overflows

In addition, the .NET Framework provides the concept of evidence-based security. Evidence-based security works on top of the security provided by the operating system. For example, it works on top of Win32 security but is not a replacement for Win32 security. While Win32 is based on the user, the evidence-based security is based on the assembly. It gathers and presents information (or evidence) about the assembly to the security system, which then determines whether or not to allow the code to execute. For example, if code tries to read a file during execution, the security system verifies that the assembly has the required permissions and either grants access or throws a SecurityException.

Evidence about an assembly can be controlled and influenced through things like strongly named assemblies, Authenticode signatures, or other custom information. Evidence is mapped to permissions through security policies, which rely on permission sets, code groups, and policy levels (enterprise, machine, and user settings) to achieve the mapping. Policies can be deployed throughout your organization through the Active Directory, but this discussion doesn’t get into the specifics of that.

Code Group Example

Rather than explaining all of the concepts up front, this tutorial just dives right into an example and explains the concepts along the way. The example is a sample Windows Forms application that demonstrates the use of permission sets and code groups. The example code will try to read the contents of a file and display a message indicating success or failure. A strong name for the assembly will serve as the evidence to assign permissions.

Step 1: Create the Strong Name

  1. Create a new Windows Form project.
  2. Open a Visual Studio command prompt.
  3. Change to a directory near the location of your Windows Form project.
  4. Issue the command “sn.exe -k codeaccesskey.snk” to create a strong naming key.
  5. Edit the AssemblyInfo file in your project.
    1. Change the line [assembly: AssemblyKeyFile(“”)] to [assembly: AssemblyKeyFile(@”….codeaccesskey.snk”)], where the “….” is the relative path from where the code compiles compared with the location of the key file generated in Step 4.
    2. Change the line [assembly: AssemblyVersion(“1.0.*”)] to [assembly: AssemblyVersion(“1.0.0.0”)].
  6. Compile the Windows Forms project to create the assembly. Now, you have a strong-named assembly you can use in later examples.

Step 2: Create a Permission Set

  1. Open the .NET Configuration 1.1 (Control Panel -> Administrative Tools -> Microsoft .NET Framework 1.1 Configuration).
  2. Expand the Runtime Security Policy, Machine, Permission Sets node in the tree display.
  3. Right-click on Permission Sets and select the New… button.
  4. Select the Create a new permission set option and fill in the Name and Description and click Next (as shown in Figure 1).

    Figure 1. Create a New Permission Set

  5. Under the Available Permissions list, select the Security list item and press the Add >> button.
  6. Fill in the permission settings (similar to the dialog below in Figure 2) or just grant all permissions and press the OK button.

    Figure 2. Available Security Permissions

  7. Under the Available Permissions list, select the User Interface list item and press the Add >> button.
  8. Fill in the permission settings (similar to the dialog below in Figure 3) or just grant all permissions and press the OK button.

    Figure 3. Available User Interface Permissions

  9. Click the Finish button. Now, you’ve created a new permission set that will allow a Windows application to run, but not much else.

Step 3: Create a Code Group

  1. Open the .NET Configuration 1.1 (Control Panel -> Administrative Tools -> Microsoft .NET Framework 1.1 Configuration).
  2. Expand the Runtime Security Policy, Machine, Code Groups node in the tree display.
  3. Right-click on the All_Code and select the New… button.
  4. Provide a Name and Description for the code group (as shown in Figure 4) and click Next.

    Figure 4. Create a Code Group

  5. Choose the Strong Name as the condition type.
  6. Press the Import button and navigate to the location of the executable file compiled when you created your strong-named assembly. Double-click on the executable name. This will read the public key associated with the executable and fill in the name and version information (see Figure 5).

    Figure 5. Choose the Strong Name as the Condition Type

  7. Click the Next button.
  8. Choose CodeGuruSamplePermissionSet (or whatever you named the permission set) as the existing permission set.
  9. Click Next and then Finish.
  10. Right-click on the newly formed code group and select Properties.
  11. Check the option This policy level will only have the permissions from the permission set associated with this code group and then click OK (see Figure 6). This will ensure that any other policies that may exist on your machine will not interfere with this example.

    Figure 6. Ensure That Other Policies Won’t Interfere

You have established a code group and the evidence that will result in membership in the code group. Now, demonstrate the use of the code group by adding some code to your project and trying to execute it.

Step 4: Try to Read a File

  1. Add a button onto your Windows Form in your sample project.
  2. Enter the following code to the button’s click event:
  3. try{   Form1.SplitFileByLine(@"c:helloworld.txt");   MessageBox.Show("Able to read", "Read OK");}catch( SecurityException securityEx ){   MessageBox.Show( securityEx.Message, "Security Exception" );}catch( IOException fileException ){   MessageBox.Show( fileException.Message, "IO Exception" );}
  4. Also, add the following additional code to handle the file reading (I’m all about reuse, so I pulled it from one of my prior articles on Parsing Data Files.):
  5. /// <summary>/// Read the contents of the file and return an array of lines/// </summary>/// <param name="FileName">Location of the file.</param>public static string[] SplitFileByLine(string FileName){   StreamReader fileReader = null;   try   {      // Read the contents of the entire file      fileReader = new StreamReader(FileName);      System.Text.StringBuilder fileContents =         new System.Text.StringBuilder();      char[] buffer = new char[32768];      while( fileReader.ReadBlock(buffer, 0,                                  buffer.Length) -> 0 )      {         fileContents.Append(buffer);         buffer = new char[32768];      }      // Separate the contents of the file into lines      fileContents = fileContents.Replace("rn", "n");      return fileContents.ToString().Split('n');   }   finally   {      if( fileReader != null )      {         fileReader.Close();      }   }}
  6. Compile and run the program. You should see a dialog similar to Figure 7, which tells you that your assembly was evaluated and the evidence presented put you into a restricted group. As a result, not everything you try to do will be allowed.

    Figure 7. The Evidence Presented Put You into a Restricted Group

  7. Click the button you added to your form.
  8. You should see a message box that displays information on the SecurityException that was generated (see Figure 8).

    Figure 8. Information on the Generated SecurityException

Step 5: Grant Access to Read a File

  1. Go back to the .NET Configuration 1.1 tool.
  2. Go into the Runtime Security Policy, Machine, Permission Sets, and right-click on the CodeGuruSamplePermission set created earlier. Select the Change Permissions… option.
  3. Under the Available Permissions list, select the File IO list item and press the Add >> button.
  4. Complete the Permission Settings (similar to the dialog below in Figure 9) or just select the unrestricted access option. (I chose the most restrictive option, which is generally a good idea from a security perspective).

    Figure 9. Permission Settings to Grant Access to Read a File

  5. Click the OK button, followed by the Finish button.
  6. If you execute your project again, you should ultimately receive a message box indicating that the program was able to read the file, assuming the file exists and is in a location where you have read permissions. Recall that the evidence-based security works on top of Win32 security, so if the operating system isn’t granting you permissions to read the file, you’re still not going to be able to read the file.

Stay Tuned for Part 2

This lengthy example demonstrated how you could use the security policy to allow or deny actions to assemblies. The second part of this two-part series will explore the System.Security.Permissions namespace. It looks at imperative and declarative security checks and overriding security checks with the Assert() method.

About the Author

Mark Strawmyer, MCSD, MCSE, MCDBA is a Senior Architect of .NET applications for large and mid-size organizations. Mark is a technology leader with Crowe Chizek in Indianapolis, Indiana. He specializes in architecture, design, and development of Microsoft-based solutions. Mark was honored to be named a Microsoft MVP for application development with C# for the second year in a row. You can reach Mark at mstrawmyer@crowechizek.com.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories