Saturday, 26 January 2013

Deploying a Web Part with Code Access Security in Visual Studio 2010


Installing Web Parts in the GAC can cause serious security implications - web parts installed in the GAC are run with full trust.

Installing Web Parts in the respective Web Application's bin folder is another option. Web parts installed in the bin folder run with partial trust and access to the system resources is limited.If the Web Part needs additional level of permissions, a best practice recommendation is to create a custom CAS policy for the specific permissions required.

The intent of the CAS  custom policy we're about to make is to allow your code and only your code to run in full trust regardless of where it is (doesn't have to be in the GAC).
All other code in the application will be running as WSS_Minimal which means it will have a reduced set of privileges . For example, codes running in WSS_Minimal can't access the SharePoint object model. Your code however will be running in full trust and will be able to do whatever it wants.
This is often desirable since we have no idea what web parts information workers or administrators will lob into our SharePoint application. It's a little presumptuous to assume that they're all safe and won't do anything malicious. Granting them full trust allows them to do things like write to sensitive areas of the disk, access the registry, etc... Users with high privileges (ie. administrators) get duped in to running malicious code all the time, that's one of the reasons Code Access Security exists in the first place. If you're curious about what the difference between code running in full trust and code running in WSS_Minimal is, refer to the table in the link above. Onward.


Code Access Security (CAS) is a resource-constraints policy that limits the access that an assembly has to protected system resources and operations. SharePoint Foundation has built-in security policies built on top of the built-in security policies of ASP.NET. By default, SharePoint Foundation uses a minimal set of permissions in order to protect the server and underlying infrastructure from malicious code.
If your Web Part needs greater access than what is provided in the minimal settings, there are a number of ways to increase the permissions of your Web Part, but only one is recommended. You can create a custom CAS policy for your Web Part, or increase the overall trust level of the server farm in the web.configfile. This is a security risk and is not recommended.

SharePoint Foundation is a partial trust application by default. SharePoint Foundation can use the ASP.NET built-in trust levels but defines trust levels of its own:
  • WSS_UserCode
  • WSS_Minimal
  • WSS_Medium
These trust levels extend the ASP.NET trust levels for use with SharePoint Foundation. Trust levels are defined in policy files that can be found on the file system of each Web server.
Important   By default, the built-in SharePoint Foundation policy files in SharePoint Foundation, named wss_usercode.configwss_minimaltrust.config, and wss_mediumtrust.config, are found in %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\CONFIG directory.
By default, SharePoint Foundation applies the WSS_Minimal trust level for the virtual server. This trust level grants all of the permissions in the ASP.NETMinimal trust as well as Web Part connections. The WSS_Minimal policy restricts the Web Part from accessing many resources for advanced operations, including the object model and file operations.
The WSS_Medium trust level grants greater access to the environment. Also, WSS_Medium allows access to the SharePoint Foundation object model and file operations including read, write, append, and path discovery. This trust level also allows access to environment variables.
The following table outlines the specific permissions granted with the WSS_MediumWSS_Minimal and WSS_UserCode policy files in the ASP.NET 2.0 environment.
Permission
WSS_Medium
Trust Level
WSS_Minimal
Trust Level
WSS_UserCode (SandBoxed Solutions)
Trust Level
Medium
Minimal
Minimal
Unrestricted=”True”
None
None
Read=”TEMP; TMP;USERNAME;OS;COMPUTERNAME”
None
None
Read, Write, Append, PathDiscovery, Application Directory
None
None
AssemblyIsolationByUser, Unrestricted UserQuota
None
None
Default printing
None
None
Assertion, Execution, ControlThread, ControlPrincipal, RemotingConfiguration
Execution
Execution
ObjectModel=”True”
None
ObjectModel=”True”, UnsafeSaveOnGet=”True”
Access=”Connect”
None
None
Unrestricted=”true”
None
None
Connections=”True”
Connections=”True”
None
Connect to origin host (if configured)
None
None
NoteNote
For more information about Code Access Security, see Using Code Access Security with ASP.NET and also Security Guidelines for .NET Framework 2.0.

SharePoint Foundation has the ability to deploy a CAS policy file with a solution. We recommend that you use the permissions for sandboxed solutions as listed in the wss_usercode.config file, but you can also create custom permissions for your Web Parts and use SharePoint Foundation to handle the deployment.
The following code example shows the basic structure of a CAS policy file in a SharePoint Foundation solution package.
<CodeAccessSecurity>
   <PolicyItem>
     <PermissionSet 
      class="NamedPermissionSet" 
      version="1"
      Description="Permission set for custom test WebParts">

        <IPermission 
          class="AspNetHostingPermission" 
          version="1" 
          Level="Minimal" 
        />

        <IPermission 
          class="SecurityPermission" 
          version="1" 
          Flags="Execution" 
        />

        <IPermission 
          class="Microsoft.SharePoint.Security.SharePointPermission, 
            Microsoft.SharePoint.Security, version=11.0.0.0, 
            Culture=neutral, PublicKeyToken=71e9bce111e9429c" 
          version="1" 
          ObjectModel="True" 
         />

        <IPermission 
          class="System.Net.WebPermission, System, 
            version=1.0.5000.0, Culture=neutral, 
            PublicKeyToken=b77a5c561934e089" version="1">
          <ConnectAccess>
            <URI uri="https?://.*" />
          </ConnectAccess>
        </IPermission>

        <IPermission 
          class="System.Security.Permissions.SecurityPermission, 
            mscorlib, version=1.0.5000.0, Culture=neutral, 
            PublicKeyToken=b77a5c561934e089" 
          version="1" 
          Flags="ControlThread, UnmanagedCode" 
        />

        <IPermission 
          class="System.Security.Permissions.EnvironmentPermission, 
            mscorlib, version=1.0.5000.0, Culture=neutral, 
            PublicKeyToken=b77a5c561934e089" 
          version="1" 
          Read="UserName" 
        />

     </PermissionSet>
     <Assemblies>
       <Assembly PublicKeyBlob=PublicKeyBlob />
     </Assemblies>
   </PolicyItem>
</CodeAccessSecurity>

The list below includes some general guidelines that apply when you use a <CodeAccessSecurity> section in your solution manifest.
  • There can only be one <CodeAccessSecurity> per solution manifest.
  • There can be multiple <PolicyItem> nodes.
  • Every <PolicyItem> node can only contain one <PermissionSet> node.
  • Every <PolicyItem> node can only contain one <Assemblies> node.
  • Each <PermissionSet> node can contain multiple <IPermission> nodes.
  • There can be multiple <Assembly> nodes under the <Assemblies> node.
For more information about the schema of the <CodeAccessSecurity> area, see CodeAccessSecurity Element (Solution).
When you deploy your assembly using a custom CAS policy, you must use the -CASPolicies option with SharePoint Management Shell. The command is as follows:
Install-SPSolution –Identity <insert name> -CASPolicies <true/false>


Let’s start by creating a new SharePoint project in Visual Studio 2010 and creating a new Web Part project item.  In this case we are talking about deploying a Farm Solution, not a Sandboxed Solution.  Note: we are going to talk about a traditional web part today, and not a Visual Web Part.  Visual Web Parts are simply not supposed under partial trust.  More on that later below.  My web part has some simple code which uses ASP.NET and also hits the SharePoint object model to display the title of the site in a label.  Here is what the code looks like.
protected override void CreateChildControls()
{
    Controls.Add(new Label(){Text = "<div>My Cool Web Part!</div>"});
    Controls.Add(new Label() { Text = string.Format("Site         Title:0}",SPContext.Current.Web.Title) });
     base.CreateChildControls();
}
When you create a new project, it deploys to the GAC by default.  We start by changing this on the project properties.
This effectively changes the DeploymentTarget attribute on Assembly element in the Manifest.xml.  At this point, you may be asking.  “Sweet, is that it?  Does it take care of the CAS policy for me?”  The answer to that of course is “No.”  However, it is quite easy to add it.  Let’s see what happens if we try to deploy it as is.  I’ll just hit F5 to start debugging.  I then add my web part to any existing page, and I immediately get hit with the following in Visual Studio.
System.Security.SecurityException: Request for the permission of type 'Microsoft.SharePoint.Security.SharePointPermission, Microsoft.SharePoint.Security, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' failed.

Luckily we know how to fix this.  Hopefully, this will also help new developers when they get this error in the future and aren’t sure what to do.  We need to grant permissions to this assembly to use the object model as well as a few other things.  We’ll start by using a standard set of IPermission elements that I have used in past posts.  This gives me basic ASP.NET, SharePoint object model, and Security permissions.
<CodeAccessSecurity>
  <PolicyItem>
    <PermissionSet class="NamedPermissionSet" version="1" Description="Permission set for VisualWebPartProject1.">
      <IPermission class="AspNetHostingPermission" version="1" Level="Minimal" />
      <IPermission class="SecurityPermission" version="1"Flags="Execution,ControlPrincipal,ControlAppDomain,ControlDomainPolicy,ControlEvidence,ControlThread"/>
      <IPermission class="Microsoft.SharePoint.Security.SharePointPermission, Microsoft.SharePoint.Security, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"
                   version="1" ObjectModel="True"  />
      <IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1"Read="UserName" />
      <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1"Read="$AppDir$" Write="$AppDir$" Append="$AppDir$" PathDiscovery="$AppDir$" />
    </PermissionSet>
    <Assemblies>
      <Assembly Name="VisualWebPartProject1"  />
    </Assemblies>
  </PolicyItem>
</CodeAccessSecurity>
You can use this in your code almost exactly but two small changes are required.  First, you need to change your assembly name to whatever you have called yours.  Secondly, if you look at that SharePointPermission, you’ll notice it says version 12.0.0.0.  We need to change this to 14.0.0.0 since we are working with SharePoint 2010 now.  Adding this to your package is quite easy.  In the Solution Explorer, locate Package and then Package.package and open it.  This will bring open the package designer.  Click on the Manifest tab at the bottom and then expand Edit Options.  The way this works is that you can paste any additional elements here and it will merge your items with the ones it automatically generates.  Here is what I would paste in.
<?xml version="1.0" encoding="utf-8"?>
<Solution xmlns="http://schemas.microsoft.com/sharepoint/">
  <CodeAccessSecurity>
    <PolicyItem>
      <PermissionSet class="NamedPermissionSet" version="1" Description="Permission set for VisualWebPartProject1.">
        <IPermission class="AspNetHostingPermission" version="1" Level="Minimal" />
        <IPermission class="SecurityPermission" version="1"Flags="Execution,ControlPrincipal,ControlAppDomain,ControlDomainPolicy,ControlEvidence,ControlThread"/>
        <IPermission class="Microsoft.SharePoint.Security.SharePointPermission, Microsoft.SharePoint.Security, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"
                     version="1" ObjectModel="True"  />
        <IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1"Read="UserName" />
        <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1"Read="$AppDir$;C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\CONTROLTEMPLATES\VisualWebPartProject1" Write="$AppDir$"Append="$AppDir$" PathDiscovery="$AppDir$" />
      </PermissionSet>
      <Assemblies>
        <Assembly Name="VisualWebPartProject1"  />
      </Assemblies>
    </PolicyItem>
  </CodeAccessSecurity>
</Solution>

Here is what it would look like on the screen.

If everything is correct, you will see the merged result up top.  If there is an error in your XML, you will also see it there.  Now let’s deploy the solution and see if we can add the web part to an existing page. 

Unfortunately, this is the error we get and it actually gives us good information.  We simply forgot to add the APTCA attribute (or AllowPartiallyTrustedCallers).  Just open your AssmeblyInfo.cs file and add the following line.
[assemblyAllowPartiallyTrustedCallers()]
Redeploy your solution and try to add your web part again.  If all goes well, you will have a lovely web part on the screen that looks like this.

With the above set of CAS policies, you can probably get most of the code you want to do to work.  I mentioned Visual Web Parts above.  Here is the issue I am currently seeing.  If you remember my post on the Visual Web Part, you will know that this is just a web part with a Page.LoadControl() method calling a User Control (.ascx).  Page.LoadControl requires a ton of permissions and I haven’t been able to figure them out.  This means, it simply will not work.  I posted something to the forums about it.  Paul Andrew was nice enough to respond to my post and state that Page.LoadControl simply will not function under partial trust.  It has a check in it to verify that it is not running under partial trust.  He also goes on to explain this is why you can’t use Visual Web Parts in sandboxed solutions.
This may seem like a lot of steps, but really I just posted a lot of pictures.  Trust me it’s a lot fewer steps than it was before in MOSS 2007.  Just look at my old post if you don’t believe me.  Now, you might ask why would I do this instead of a Sandboxed solution?  Sandboxed solutions are severely limited on what they can do with the SharePoint object model.  By default, the CAS policy that defines them can’t even connect to a database.  I can specify at a per assembly level here what each one can do.  That is a big advantage.

No comments:

Post a Comment