Sdílet prostřednictvím


WPF Partial Trust Security

In general, Internet applications should be restricted from having direct access to critical system resources, to prevent malicious damage. By default, HTML and client-side scripting languages are not able to access critical system resources. Because Windows Presentation Foundation (WPF) browser-hosted applications can be launched from the browser, they should conform to a similar set of restrictions. To enforce these restrictions, WPF relies on both Code Access Security (CAS) and ClickOnce (see WPF Security Strategy - Platform Security). By default, browser-hosted applications request the Internet zone CAS set of permissions, irrespective of whether they are launched from the Internet, the local intranet, or the local computer. Applications that run with anything less than the full set of permissions are said to be running with partial trust.

WPF provides a wide variety of support to ensure that as much functionality as possible can be used safely in partial trust, and along with CAS, provides additional support for partial trust programming.

This topic contains the following sections:

  • WPF Feature Partial Trust Support

  • Partial Trust Programming

  • Managing Permissions

WPF Feature Partial Trust Support

The following table lists the high-level features of Windows Presentation Foundation (WPF) that are safe to use within the limits of the Internet zone permission set.

Table 1: WPF Features that are Safe in Partial Trust

Feature Area

Feature

General

Browser Window

Site of Origin Access

IsolatedStorage (512KB Limit)

UIAutomation Providers

Commanding

Input Method Editors (IMEs)

Tablet Stylus and Ink

Simulated Drag/Drop using Mouse Capture and Move Events

OpenFileDialog

XAML Deserialization (via XamlReader.Load)

Web Integration

Browser Download Dialog

Top-Level User-Initiated Navigation

mailto:links

Uniform Resource Identifier Parameters

HTTPWebRequest

WPF Content Hosted in an IFRAME

Hosting of Same-Site HTML Pages using Frame

Hosting of Same Site HTML Pages using WebBrowser

Web Services (ASMX)

Web Services (using Windows Communication Foundation)

Scripting

Document Object Model

Visuals

2D and 3D

Animation

Media (Site Of Origin and Cross-Domain)

Imaging/Audio/Video

Reading

FlowDocuments

XPS Documents

Embedded & System Fonts

CFF & TrueType Fonts

Editing

Spell Checking

RichTextBox

Plaintext and Ink Clipboard Support

User-Initiated Paste

Copying Selected Content

Controls

General Controls

This table covers the WPF features at a high level. For more detailed information, the Windows Software Development Kit (SDK) documents the permissions that are required by each member in WPF. Additionally, the following features have more detailed information regarding partial trust execution, including special considerations.

The following table outlines the WPF features that are not safe to run within the limits of the Internet zone permission set.

Table 2: WPF Features that are Not Safe in Partial Trust

Feature Area

Feature

General

Window (Application Defined Windows and Dialog Boxes)

SaveFileDialog

File System

Registry Access

Drag and Drop

XAML Serialization (via XamlWriter.Save)

UIAutomation Clients

Source Window Access (HwndHost)

Full Speech Support

Windows Forms Interoperability

Visuals

Bitmap Effects

Image Encoding

Editing

Rich Text Format Clipboard

Full XAML support

Partial Trust Programming

For XBAP applications, code that exceeds the default permission set will have different behavior depending on the security zone. In some cases, the user will receive a warning when they attempt to install it. The user can choose to continue or cancel the installation. The following table describes the behavior of the application for each security zone and what you have to do for the application to receive full trust.

Security Zone

Behavior

Getting Full Trust

Local computer

Automatic full trust

No action is needed.

Intranet and trusted sites

Prompt for full trust

Sign the XBAP with a certificate so that the user sees the source in the prompt.

Internet

Fails with "Trust Not Granted"

Sign the XBAP with a certificate.

NoteNote

The behavior described in the previous table is for full trust XBAPs that do not follow the ClickOnce Trusted Deployment model.

In general, code that may exceed the allowed permissions is likely to be common code that is shared between both standalone and browser-hosted applications. CAS and WPF offer several techniques for managing this scenario.

Detecting Permissions Using CAS

In some situations, it is possible for shared code in library assemblies to be used by both standalone applications and XBAPs. In these cases, code may execute functionality that could require more permissions than the application's awarded permission set allows. Your application can detect whether or not it has a certain permission by using Microsoft .NET Framework security. Specifically, it can test whether it has a specific permission by calling the Demand method on the instance of the desired permission. This is shown in the following example, which has code that queries for whether it has the ability to save a file to the local disk:


Imports System.IO ' File, FileStream, StreamWriter
Imports System.IO.IsolatedStorage ' IsolatedStorageFile
Imports System.Security ' CodeAccesPermission, IsolatedStorageFileStream
Imports System.Security.Permissions ' FileIOPermission, FileIOPermissionAccess
Imports System.Windows ' MessageBox

Namespace SDKSample
    Public Class FileHandling
        Public Sub Save()
            If IsPermissionGranted(New FileIOPermission(FileIOPermissionAccess.Write, "c:\newfile.txt")) Then
                ' Write to local disk
                Using stream As FileStream = File.Create("c:\newfile.txt")
                Using writer As New StreamWriter(stream)
                    writer.WriteLine("I can write to local disk.")
                End Using
                End Using
            Else
                MessageBox.Show("I can't write to local disk.")
            End If
        End Sub

        ' Detect whether or not this application has the requested permission
        Private Function IsPermissionGranted(ByVal requestedPermission As CodeAccessPermission) As Boolean
            Try
                ' Try and get this permission
                requestedPermission.Demand()
                Return True
            Catch
                Return False
            End Try
        End Function



...


    End Class
End Namespace
using System.IO; // File, FileStream, StreamWriter
using System.IO.IsolatedStorage; // IsolatedStorageFile
using System.Security; // CodeAccesPermission, IsolatedStorageFileStream
using System.Security.Permissions; // FileIOPermission, FileIOPermissionAccess
using System.Windows; // MessageBox

namespace SDKSample
{
    public class FileHandling
    {
        public void Save()
        {
            if (IsPermissionGranted(new FileIOPermission(FileIOPermissionAccess.Write, @"c:\newfile.txt")))
            {
                // Write to local disk
                using (FileStream stream = File.Create(@"c:\newfile.txt"))
                using (StreamWriter writer = new StreamWriter(stream))
                {
                    writer.WriteLine("I can write to local disk.");
                }
            }
            else
            {
                MessageBox.Show("I can't write to local disk.");
            }
        }

        // Detect whether or not this application has the requested permission
        bool IsPermissionGranted(CodeAccessPermission requestedPermission)
        {
            try
            {
                // Try and get this permission
                requestedPermission.Demand();
                return true;
            }
            catch
            {
                return false;
            }
        }



...


    }
}

If an application does not have the desired permission, the call to Demand will throw a security exception. Otherwise, the permission has been granted. IsPermissionGranted encapsulates this behavior and returns true or false as appropriate.

Graceful Degradation of Functionality

Being able to detect whether code has the permission to do what it needs to do is interesting for code that can be executed from different zones. While detecting the zone is one thing, it is far better to provide an alternative for the user, if possible. For example, a full trust application typically enables users to create files anywhere they want, while a partial trust application can only create files in isolated storage. If the code to create a file exists in an assembly that is shared by both full trust (standalone) applications and partial trust (browser-hosted) applications, and both applications want users to be able to create files, the shared code should detect whether it is running in partial or full trust before creating a file in the appropriate location. The following code demonstrates both.


Imports System.IO ' File, FileStream, StreamWriter
Imports System.IO.IsolatedStorage ' IsolatedStorageFile
Imports System.Security ' CodeAccesPermission
Imports System.Security.Permissions ' FileIOPermission, FileIOPermissionAccess
Imports System.Windows ' MessageBox

Namespace SDKSample
    Public Class FileHandlingGraceful
        Public Sub Save()
            If IsPermissionGranted(New FileIOPermission(FileIOPermissionAccess.Write, "c:\newfile.txt")) Then
                ' Write to local disk
                Using stream As FileStream = File.Create("c:\newfile.txt")
                Using writer As New StreamWriter(stream)
                    writer.WriteLine("I can write to local disk.")
                End Using
                End Using
            Else
                ' Persist application-scope property to 
                ' isolated storage
                Dim storage As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
                Using stream As New IsolatedStorageFileStream("newfile.txt", FileMode.Create, storage)
                Using writer As New StreamWriter(stream)
                    writer.WriteLine("I can write to Isolated Storage")
                End Using
                End Using
            End If
        End Sub

        ' Detect whether or not this application has the requested permission
        Private Function IsPermissionGranted(ByVal requestedPermission As CodeAccessPermission) As Boolean
            Try
                ' Try and get this permission
                requestedPermission.Demand()
                Return True
            Catch
                Return False
            End Try
        End Function



...


    End Class
End Namespace
using System.IO; // File, FileStream, StreamWriter
using System.IO.IsolatedStorage; // IsolatedStorageFile
using System.Security; // CodeAccesPermission
using System.Security.Permissions; // FileIOPermission, FileIOPermissionAccess
using System.Windows; // MessageBox

namespace SDKSample
{
    public class FileHandlingGraceful
    {
        public void Save()
        {
            if (IsPermissionGranted(new FileIOPermission(FileIOPermissionAccess.Write, @"c:\newfile.txt")))
            {
                // Write to local disk
                using (FileStream stream = File.Create(@"c:\newfile.txt"))
                using (StreamWriter writer = new StreamWriter(stream))
                {
                    writer.WriteLine("I can write to local disk.");
                }
            }
            else
            {
                // Persist application-scope property to 
                // isolated storage
                IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
                using (IsolatedStorageFileStream stream = 
                    new IsolatedStorageFileStream("newfile.txt", FileMode.Create, storage))
                using (StreamWriter writer = new StreamWriter(stream))
                {
                    writer.WriteLine("I can write to Isolated Storage");
                }
            }
        }

        // Detect whether or not this application has the requested permission
        bool IsPermissionGranted(CodeAccessPermission requestedPermission)
        {
            try
            {
                // Try and get this permission
                requestedPermission.Demand();
                return true;
            }
            catch
            {
                return false;
            }
        }



...


    }
}

In many cases, you should be able to find a partial trust alternative.

In a controlled environment, such as an intranet, custom managed frameworks can be installed across the client base into the global assembly cache (GAC). These libraries can execute code that requires full trust, and be referenced from applications that are only allowed partial trust by using AllowPartiallyTrustedCallersAttribute (for more information, see Security (WPF) and WPF Security Strategy - Platform Security).

Browser Host Detection

Using CAS to check for permissions is a suitable technique when you need to check on a per-permission basis. Although, this technique depends on catching exceptions as a part of normal processing, which is not recommended in general and can have performance issues. Instead, if your XAML browser application (XBAP) only runs within the Internet zone sandbox, you can use the BrowserInteropHelper.IsBrowserHosted property, which returns true for XAML browser applications (XBAPs).

NoteNote

IsBrowserHosted only distinguishes whether an application is running in a browser, not which set of permissions an application is running with.

Managing Permissions

By default, XBAPs run with partial trust (default Internet zone permission set). However, depending on the requirements of the application, it is possible to change the set of permissions from the default. For example, if an XBAPs is launched from a local intranet, it can take advantage of an increased permission set, which is shown in the following table.

Table 3: LocalIntranet and Internet Permissions

Permission

Attribute

LocalIntranet

Internet

DNS

Access DNS servers

Yes

No

Environment Variables

Read

Yes

No

File Dialogs

Open

Yes

Yes

File Dialogs

Unrestricted

Yes

No

Isolated Storage

Assembly isolation by user

Yes

No

Isolated Storage

Unknown isolation

Yes

Yes

Isolated Storage

Unlimited user quota

Yes

No

Media

Safe audio, video, and images

Yes

Yes

Printing

Default printing

Yes

No

Printing

Safe printing

Yes

Yes

Reflection

Emit

Yes

No

Security

Managed code execution

Yes

Yes

Security

Assert granted permissions

Yes

No

User Interface

Unrestricted

Yes

No

User Interface

Safe top level windows

Yes

Yes

User Interface

Own Clipboard

Yes

Yes

Web Browser

Safe frame navigation to HTML

Yes

Yes

NoteNote

Cut and Paste is only allowed in partial trust when user initiated.

If you need to increase permissions, you need to change the project settings and the ClickOnce application manifest. For more information, see WPF XAML Browser Applications Overview. The following documents may also be helpful.

If your XBAP requires full trust, you can use the same tools to increase the requested permissions. Although an XBAP will only receive full trust if it is installed on and launched from the local computer, the intranet, or from a URL that is listed in the browser's trusted or allowed sites. If the application is installed from the intranet or a trusted site, the user will receive the standard ClickOnce prompt notifying them of the elevated permissions. The user can choose to continue or cancel the installation. 

Alternatively, you can use the ClickOnce Trusted Deployment model for full trust deployment from any security zone. For more information, see Trusted Application Deployment Overview and Security (WPF).

See Also

Concepts

Security (WPF)

WPF Security Strategy - Platform Security

WPF Security Strategy - Security Engineering