Friday, 4 September 2015

Process and Execution Trust Model

In the simplest scenarios, the process model of SharePoint is the same as any other ASP.NET application; but in SharePoint, the distinction between farm solutions and sandboxed solutions entails some more complex scenarios.

Worker Processes, Farm Solutions, and Sandboxed Solutions

When an HTTP request is received by a front-end web server, a special driver, HTTP.SYS, detects the request and routes it to the application pool that is handling requests for the targeted IIS website, and thus, the targeted SharePoint web application. Every application pool has an IIS worker process (w3wp.exe) in which the request pipeline for each request is executed. (For more information about the IIS 7.0 worker processes and application pools, see Introduction to IIS 7 Architecture.) On a SharePoint server, the IIS worker process runs in the application pool account, which gives the process read and write permissions to SharePoint resources. On a multiserver farm, the application pool account is a domain user that is not a machine administrator on any server in the farm, but is a member of the WSS_WPG, WSS_ADMIN_WPG, and IIS_USERS groups on each server. (This should be a different account from the farm administration account. The latter is also not a local machine administrator on any farm server. The farm account is a member of all the same groups as the application pool account and also the WSS_RESTRICTED_WPG_V4 and Performance Monitor User groups. An exception is made for the application pool of the Central Administration web application: its application pool account is the farm account. Also, the SharePoint 2010 Timer Service executes in the context of the farm account.) For more information about the accounts needed in a SharePoint farm, see Plan for administrative and service accounts (Office SharePoint Server).
Figure 4 shows how an IIS worker process that is running on a front-end web server processes an HTTP request.
Figure 4. Request processing model for full-trust farm solution

Process model for full-trust farm solutions However, unlike a standard ASP.NET application, SharePoint makes a distinction between sandboxed solutions and farm solutions. Farm solutions run in the IIS worker process just like any ASP.NET application. Sandboxed solutions run in a specially restricted execution environment. This is necessary because sandboxed solutions are installed on (and scoped to) SharePoint site collections without the intervention of the IT professionals that are managing the SharePoint farm. To prevent rogue or poorly performing code from slowing or crashing the application pool, SharePoint imposes restrictions on what the code in a sandboxed solution can do. As a crucial part of the implementation of this system, sandboxed solutions must run in a special sandboxed worker process (SPUCWorkerProcess.exe).
When a request attempts to access a sandboxed solution, a SharePoint execution manager that runs in the IIS worker process finds a sandbox worker process (or starts one, if none is running) in which the code of the sandboxed solution will run. In principal, this sandboxed worker process can be started on any server in the farm that is running the SharePoint 2010 User Code Host service (SPUCHostService.exe). (In the UI of the Central Administration application, this is known as the Microsoft SharePoint Foundation Sandboxed Code Service.)
The server that is running the SharePoint 2010 User Code Host service can be, but does not have to be, the front-end web server on which the IIS worker process is running. Which server is used is configurable in the Central Administration application: Administrators can choose to have each sandboxed process run in "local mode," which means that each request for a sandboxed solution is processed on the same front-end web server on which the IIS worker process is running; or they can have the execution manager start each sandboxed process in "remote mode," also known as "affinity mode." In affinity mode, the execution manager looks for a server that is running the SharePoint 2010 User Code Host service and which already has created an application domain inside its SPUCWorkerProcess.exe process for the very same sandboxed solution. (This would be the case if that same sandboxed solution was requested before, possibly by another user on another site collection.) If there is a matching application domain, the request is sent to that same application domain for handling. If none of the servers that are running the SharePoint 2010 User Code Host service already has an application domain for the sandboxed solution, the execution manager assigns the request to the least busy of those servers. The server then creates the needed application domain and processes the request for the sandboxed solution. The application domain stays alive after the request is processed and is reused if there is another request for the same sandboxed solution.
By default, all sandboxed solutions that are handled by a given server run in the same sandbox worker process, but this is configurable through the object model. Each sandboxed solution gets its own application domain within the common process, and this, too, is configurable through the object model. The SharePoint 2010 User Code Host service runs in an account that has the same rights as a typical application pool account. It should be a member of the WSS_WPG, WSS_ADMIN_WPG, and IIS_USERS groups on the server on which the service instance is running.
Code Execution and Access Constraints on Sandboxed Solutions
All code that runs in this sandbox worker process is subject to execution and access constraints. There are two systems of constraints: One applies to all and only calls to any assembly, except Microsoft.SharePoint.dll, whether it is a SharePoint assembly or not. The other applies to all and only calls made to the parts of the SharePoint Foundation object model that are in the assembly Microsoft.SharePoint.dll. The calls that this second system applies to are not just calls in custom SharePoint solutions. Calls to Microsoft.SharePoint.dll from other SharePoint assemblies (that have themselves been called by custom code) such as Microsoft.SharePoint.Linq.dll are also subject to this constraint.
The first system of is imposed by two mechanisms:
  1. A highly restrictive code access security (CAS) policy significantly limits what code in the sandboxed worker process can do. This policy is defined in the wss_usercode.config file in %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\CONFIG, and it is referenced in the web.config file in %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\UserCode. Among the restrictions imposed by the CAS policy are the following:
    • Code in the sandbox cannot call unmanaged code.
    • Code in the sandbox cannot call the Microsoft .NET Framework 3.5 reflection APIs.
    • Code in the sandbox can call only the .NET Framework 3.5 assemblies that have the AllowPartiallyTrustedCallersAttribute attribute. This blocks access to about two-thirds of all the .NET Framework 3.5 APIs, including System.Printing, for example.
    Note
    The CAS policy makes an exception for strong-named Microsoft Office assemblies. These are granted full trust.
  2. Secondly, the sandboxed worker process has a low-privileged security token.
    • The token denies the process the right to read from or write to the file system.
    • The token denies the process the right to call to the network. Therefore, only resources available on the server that is running the sandboxed worker process may be accessed. An external database, for example, cannot be accessed.
    • The token denies the process the right to write to the registry.
    • The token denies the right to call to any assembly that is not in the general assembly cache, even if it has the AllowPartiallyTrustedCallersAttribute attribute and would otherwise be eligible to be called from the sandboxed worker process.
As noted, a second system of constraints imposes restrictions on what APIs in Microsoft.SharePoint.dll can be directly called by code in the sandboxed worker process, and a call to any forbidden API in the object model results in an exception (which is caught and reported to the user as an error). The implementation of these restrictions is accomplished by a pair of specially restricted versions of the Microsoft.SharePoint.dll assembly, sometimes called shim assemblies, that are located in %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\UserCode\assemblies. One of the two assemblies is loaded by the sandboxed worker process. The other assembly is loaded in a special proxy process (SPUCWorkerProcessProxy.exe) that runs in full trust and that is also managed by the SharePoint 2010 User Code Host. The standard Microsoft.SharePoint.dll assembly is also loaded in this proxy process.
The main job of the two shim assemblies is to filter out forbidden SharePoint classes and members. When the sandboxed solution calls an approved API, the first shim assembly passes it to the second in the proxy process, which in turn passes it to the standard Microsoft.SharePoint.dll. Any returned results are passed back to the original calling code. This cross-process interaction is possible through .NET Framework remoting. A sandboxed worker process and a full-trust proxy process are always started together and paired with one another. If either process crashes, the other is also stopped.
The shim assemblies also have a secondary job. Some SharePoint APIs are available to sandboxed solutions, but only with special restrictions on the parameters that are passed to them. It is the shim assemblies that enforce these input restrictions and ensure that an exception is thrown when there is a violation. The only case of this in SharePoint Foundation 2010 are the SPSite(String) and SPSite(Guid) constructors. These constructors can be called in sandboxed solutions, but only URLs or GUIDs that refer to the site collection in which the sandboxed solution is running can be passed to them.
Note
Because the second shim assembly and the standard Microsoft.SharePoint.dll run in a full-trust process, permitted APIs in the SharePoint object model can do some things that would otherwise be forbidden in a sandboxed solution. For example, the GetLocalizedString method can read .resx files even though sandboxed solutions cannot generally read from the disk. (However, a file cannot be deployed to disk in sandboxed solution, so the .resx file would have to be previously installed as a farm solution.)
The following are some of the restrictions on the SharePoint object model that can be accessed:
  • The SPWebApplication class cannot be accessed. Among other things, this means that a sandboxed solution cannot access anything outside its hosting site collection.
  • Almost all classes in the Microsoft.SharePoint.WebControls namespace cannot be accessed, which means that you are mainly restricted to ASP.NET controls in sandboxed solutions.
For a complete list of APIs in Microsoft.SharePoint.dll that are available to sandboxed solutions, see Microsoft.SharePoint.dll APIs That Are Available from Sandboxed Solutions.
Important
The deployment stage of a sandboxed solution itself runs in a sandboxed worker process and is subject to the same execution constraints. For example, you cannot deploy a file to the disk when you are deploying a sandboxed solution. This is the main reason why a user control (ASCX file) cannot be in a sandboxed solution. See SharePoint Deployment Models for information about the deployment stage.
Resource Usage Restrictions on Sandboxed Solutions
Sandboxed solutions are also subject to three kinds of resource usage restrictions that can be organized based on the kind of entity to which the restriction applies and the kind of entity on which the penalty for exceeding the restriction is imposed.
  • Per Request with the Request Penalized: There is a hard limit to how long a sandboxed solution can take to finish. By default, this is 30 seconds. If a sandboxed solution exceeds the limit, the request (but not the sandboxed worker process) is terminated. (This limit is configurable, but only through custom code against the object model. The relevant parts of the object model cannot be accessed by sandboxed solutions, so no sandboxed solution can change the limit.)
  • Per Request with the Process Penalized: A set of 15 resource limits apply to requests. If a request exceeds one of them, the process (and all the sandboxed solutions that are running in it) is terminated.
  • Per Day/Per Site Collection with the Site Collection Penalized: Each site collection is subject to a configurable maximum of daily resource points. These points accumulate based on an algorithm that takes into account the use of resources in the 15 resource categories by the sandboxed solutions that are installed in the site collection. When a site collection exceeds its maximum allowed points, all sandboxed solutions in the site collection are terminated and no more can run for the rest of the day.
SharePoint provides a solution validator framework that can be used to develop custom solution validators, such as a validator that verifies whether a solution is signed with a specific certificate. The validators in a site collection run when a sandboxed solution is activated (that is, deployed, in the terminology used earlier in this article). The activation of any invalid solution is blocked. If a validator is updated or a new validator is added, each activated solution is rechecked by the validators the next time it is executed. Invalid solutions are deactivated. For an introduction to custom validators, see Developing, Deploying, and Monitoring Sandboxed Solutions in SharePoint 2010.
For more information about the sandbox restrictions, see Sandboxed Solutions in SharePoint 2010 and its child topics and the Microsoft patterns and practices guidelines for Sandboxed Solutions.
Figure 5 shows how an HTTP request is handled when it accesses a sandboxed solution.
Figure 5. Request processing model for sandboxed solutions

Request processing model in sandboxed solutions The SPUCHostService.exe, SPUCWorkerProcess.exe, and SPUCWorkerProcessProxy.exe files are located at %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\UserCode.
Note
A solution that is designed to run in the sandbox can be deployed by a farm administrator as a farm solution. It might perform better if it is, because it would run in the IIS worker process instead of the sandboxed worker process.
Not all SharePoint execution is in an IIS worker process, a sandboxed worker process, or the proxy process. The following are some examples:
  • The SharePoint Timer Service (owstimer.exe) runs on all servers and is used to execute prescheduled timer jobs. It runs under the farm account.
  • The SharePoint Tracing Service (wsstracing.exe) runs under the local service account.
  • The SharePoint Administration Service (wssadmin.exe) runs under the local system account.
Within the category of farm solutions, a further distinction can be made when the requested resource is an .aspx page. If the requested page is what SharePoint calls an application page, the returned page is passed to the regular ASP.NET page parser; but if the requested page is what SharePoint calls a site page, the returned page is routed through a special safe mode parser. The distinction between the two kinds of parsing is best understood in light of the distinction between the two kinds of pages. For more information about both subjects, see Pages, Parsing, and Safe Mode later in this article. (Application pages cannot be included in sandboxed solutions. All pages installed as part of a sandboxed solution use safe mode parsing.)

Assembly Deployment, Execution, and Persistence

Farm solutions divide into two types depending on where their assemblies are deployed and the trust level of the assemblies' execution:
  • GAC/Full Trust: The assemblies are deployed to the global assembly cache (GAC) of every front-end web server in the farm and run with full trust. They are callable from any SharePoint web application on the farm.
  • Bin/CAS: The assemblies are deployed to the \bin folder (on every front-end web server) of a specific SharePoint web application and their trust level is determined by a CAS policy referenced in the web application's web.config file. They have to be separately deployed to every SharePoint web application that needs to call them.
    Tip
    We recommend that you use the Bin/CAS model only when neither full-trust farm solutions nor sandboxed solutions (nor the hybrid solutions described in Hybrid Solution Techniques) are possible for your solution.
Noncompiled files for both kinds of farm solutions—including, for example, images, user controls, and string resources—are deployed to subfolders of %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\.
Sandboxed solutions are deployed inside a SharePoint solution package (.wsp file) to the Solution Gallery of a specific site collection. Thus, they are deployed and persisted in the site collection's content database. As noted earlier, they do not run in full trust: Instead, they run within a highly restricted CAS policy and can only call a restricted subset of the SharePoint object model. A sandboxed solution can be accessed only in site collections to which it is deployed.
When a sandboxed solution is accessed for the first time, such as when a user navigates to a page that contains a Web Part from a sandboxed solution, any assemblies in the solution are unpacked from the solution package and copied to the file system of the server that is handling the sandbox request. The default location is C:\ProgramData\Microsoft\SharePoint\UCCache, but this is configurable on each server that is running the User Code Host Service. (Recall that the server that handles the sandbox request is not necessarily the front-end web server that is handling the initial HTTP request. The User Code Host Service can be run on back-end application servers in the farm instead.) Because the sandboxed worker process cannot copy anything to the file system, the copying is done by the User Code Host Service.
The assemblies do not stay in the file cache perpetually. When the user session that accessed the assemblies finishes, the assemblies stay in the cache for only a short time, and they may be reloaded from there if another user session accesses them. Eventually, if they are not accessed, they are removed according to a proprietary algorithm that takes into account how busy the server is and how much time has gone by since the assemblies were last accessed. If the sandboxed solution is used after that time, the assemblies are unpacked again and copied to the UCCache.
Caution
Administrators, developers, and third-party code should not add, remove, or load anything from the UCCache. It should be accessed only by the SharePoint infrastructure.

Hybrid Solution Techniques

The SharePoint solutions architecture includes a technique by which a sandboxed solution can call custom operations that run in full trust. The technique requires that a farm solution be developed that includes one or more classes that derive from SPProxyOperation. Each of these defines an operation that will run in full trust and can be called from sandboxed solutions by using the ExecuteRegisteredProxyOperation method. Specifically, these full-trust proxy operations execute in the same proxy process (SPUCWorkerProcessProxy.exe) that was described earlier in Worker Processes, Farm Solutions, and Sandboxed Solutions. The proxy operations can return data to the sandboxed solution.
Like all farm solutions, the assembly with the proxy operations can be deployed only if it is from a trusted source.
Figure 6 shows how a request that accesses a sandboxed solution is processed when the sandboxed solution makes a call to a full-trust proxy.
Figure 6. Request processing model when a sandboxed solutions calls a full-trust proxy

Sandbox and full-trust proxy process model The preceding description might give the impression that, with the hybrid technique, a farm solution and a sandboxed solution are always developed together by the same development team. In fact, the farm solution may be developed specifically to provide certain operations to any and all sandboxed solutions that need those services, including sandboxed solutions that are developed by other teams. For example, because a sandboxed solution cannot write to the SharePoint Unified Logging Service (ULS) logs, a farm solution that opened proxy logging operations to sandboxed solutions would be very useful.
Another hybrid technique uses client-side code to access the resources that cannot be accessed from a sandboxed solution. For example, a sandboxed solution could include a custom site page with JavaScript that makes calls to the SharePoint JavaScript client object model. Also, a sandboxed solution could include a Web Part that hosts a Silverlight application. The latter application can make calls to the SharePoint Silverlight client object model. For more information about the client-side code in SharePoint, see Client Object Models in SharePoint later in this article.
For more information about hybrid solution techniques, see Hybrid Approaches.

0 comments:

Post a Comment