Estratégia de segurança do WPF - Segurança da Plataforma
While Windows Presentation Foundation (WPF) provides a variety of security services, it also leverages the security features of the underlying platform, which includes the operating system, the CLR, and Internet Explorer. These layers combine to provide WPF a strong, defense-in-depth security model that attempts to avoid any single point of failure, as shown in the following figure:
The remainder of this topic discusses the features in each of these layers that pertain to WPF specifically.
Este tópico contém as seguintes seções.
- Operating System Security
- Common Language Runtime Security
- Microsoft Internet Explorer Security
- Tópicos relacionados
Operating System Security
The minimum level of operating system that is required by WPF is Windows XP SP2. O núcleo da Windows XP SP2 fornece vários recursos de segurança que formam a base de segurança para todas as Windows aplicativos, incluindo aquelas construídas com WPF. Windows Vistaincorpora recursos de segurança do WPF e se estende ainda mais. This topic discusses the breadth of these security features that are important to WPF, as well as how WPF integrates with them to provide further defense-in-depth.
Microsoft Windows XP Service Pack 2 (SP2)
In addition to a general review and strengthening of Windows, there are three key features from Windows XP SP2 that we will discuss in this topic:
/GS compilation
Microsoft Windows Update.
/GS Compilation
Windows XP SP2 provides protection by recompiling many core system libraries, including all of the WPF dependencies such as the CLR, to help mitigate buffer overruns. This is achieved by using the /GS parameter with the C/C++ command-line compiler. Although buffer overruns should be explicitly avoided, /GS compilation provides an example of a defense-in-depth against potential vulnerabilities that are inadvertently or maliciously created by them.
Historically, buffer overruns have been the cause of many high-impact security exploits. A buffer overrun occurs when an attacker takes advantage of a code vulnerability that allows the injection of malicious code that writes past the boundaries of a buffer. This then allows an attacker to hijack the process in which the code is executing by overwriting the return address of a function to cause the execution of the attacker's code. The result is malicious code that executes arbitrary code with the same privileges as the hijacked process.
At a high level, the /GS compiler flag protects against some potential buffer overruns by injecting a special security cookie to protect the return address of a function that has local string buffers. After a function returns, the security cookie is compared with its previous value. If the value has changed, a buffer overrun may have occurred and the process is stopped with an error condition. Stopping the process prevents the execution of potentially malicious code. Consulte /GS (Buffer Security Check) para obter mais detalhes.
WPF is compiled with the /GS flag to add yet another layer of defense to WPF applications.
Microsoft Windows Update Enhancements
Microsoft Windows Update was also improved in Windows XP SP2 to simplify the process for downloading and installing updates. These changes significantly enhance security for WPF customers by helping to ensure that their systems are up-to-date, particularly with respect to security updates.
Windows Vista
WPF users on Windows Vista will benefit from the operating system's additional security enhancements, including "Least-Privilege User Access", code integrity checks, and privilege isolation.
User Account Control (UAC)
Today, Windows users tend to run with administrator privileges because many applications require them for either installation or execution, or both. Being able to write default application settings to the Registry is one example.
Running with administrator privileges really means that applications execute from processes that are granted administrator privileges. The security impact of this is that any malicious code that hijacks a process running with administrator privileges will automatically inherit those privileges, including access to critical system resources.
One way to protect against this security threat is to run applications with the least amount of privileges that are required. This is known as the principle of least privilege, and is a core feature of the Windows Vista operating system. This feature is called User Account Control (UAC), and is used by Windows Vista UAC in two key ways:
To run most applications with UAC privileges by default, even if the user is an administrator; only applications that need administrator privileges will run with administrator privileges. To run with administrative privileges, applications must be explicitly marked in either their application manifest or as an entry in security policy.
To provide compatibility solutions like virtualization. For example, many applications try to write to restricted locations like C:\Program Files. For applications executing under UAC, an alternative per-user location exists that does not require administrator privileges to write to. For applications running under UAC, UAC virtualizes C:\Program Files so that applications who think they are writing to it are actually writing to the alternative, per-user location. This kind of compatibility work enables the operating system to run many applications that couldn't previously run in UAC.
Code Integrity Checks
Windows Vista incorporates deeper code integrity checks to help prevent malicious code from being injected into system files or into the kernel at load/run time. This goes beyond system file protection.
Limited Rights Process for Browser-Hosted Applications
Hospedado por navegador WPF a execução de aplicativos em seguro de zona da Internet. WPFintegração com Microsoft Internet Explorer estende essa proteção com suporte adicional.
Internet Explorer 6 Service Pack 2 and Internet Explorer 7 for XP
WPF leverages operating system security by limiting process privileges for XAML browser applications (XBAPs) for further protection. Before a browser-hosted WPF application is launched, the operating system creates a host process that removes unnecessary privileges from the process token. Some examples of privileges that are removed include the ability to shut down the user's machine, load drivers, and read access to all files on the machine.
Internet Explorer 7 for Vista
In Windows Internet Explorer 7, WPF applications run in protected mode. Specifically, XAML browser applications (XBAPs) run with medium-level integrity.
Defense-In-Depth Layer
Since XAML browser applications (XBAPs) are generally sandboxed by the Internet zone permission set, removing these privileges does not harm XAML browser applications (XBAPs) from a compatibility perspective. Instead, an additional defense-in-depth layer is created; if a sandboxed application is able to exploit other layers and hijack the process, the process will still only have limited privileges.
Consulte usando uma conta de usuário com menos privilégios.
Common Language Runtime Security
The common language runtime (CLR) offers a number of key security benefits that include validation and verification, Code Access Security (CAS), and the Security Critical Methodology.
Validation and Verification
Para fornecer isolamento de assembly e a integridade, a CLR usa um processo de validação. CLRa validação garante que os assemblies são isolados, validando seu formato de arquivo executável portátil (PE) para endereços que aponte fora do assembly. CLRvalidação também valida a integridade dos metadados que é incorporado dentro de um assembly.
Para garantir a segurança de tipos, ajudar a evitar problemas comuns de segurança (ex.: saturações de buffer) e habilitar o modo seguro por meio do isolamento de subprocesso, CLR security usa o conceito de verificação.
Managed applications are compiled into Microsoft Intermediate Language (MSIL). When methods in a managed application are executed, its MSIL is compiled into native code through Just-In-Time (JIT) compilation. JIT compilation includes a verification process that applies many safety and robustness rules that ensure code does not:
Violate type contracts
Introduce buffer overruns
Wildly access memory.
Managed code that does not conform to verification rules is not allowed to execute, unless it is considered trusted code.
The advantage of verifiable code is a key reason why WPF builds on the .NET Framework. To the extent that verifiable code is used, the possibility of exploiting possible vulnerabilities is greatly lowered.
Code Access Security
A client machine exposes a wide variety of resources that a managed application can have access to, including the file system, the Registry, printing services, the user interface, reflection, and environment variables. Para um aplicativo gerenciado possa acessar os recursos em uma máquina cliente, ele deve ter .NET Framework Code Access Security (CAS) permissão para fazer o SO. A permission in CAS is a subclass of the CodeAccessPermission; CAS implements one subclass for each resource that managed applications can access.
The set of permissions that a managed application is granted by CAS when it starts executing is known as a permission set and is determined by evidence provided by the application. Para WPF a evidência que é fornecida de aplicativos, é o local ou a zona, a partir do qual os aplicativos são iniciados. CASidentifica as seguintes zonas:
My Computer. Applications launched from the client machine (Fully Trusted).
Local Intranet. Applications launched from the intranet. (Somewhat Trusted).
Internet. Applications launched from the Internet. (Least Trusted).
Trusted Sites. Applications identified by a user as being trusted. (Least Trusted).
Untrusted Sites. Applications identified by a user as being untrusted. (Untrusted).
For each of these zones, CAS provides a predefined permission set that includes the permissions which matches the level of trust associated with each. These include:
FullTrust. For applications launched from the My Computer zone. All possible permissions are granted.
LocalIntranet. For applications launched from the Local Intranet zone. A subset of permissions are granted to provide moderate access to a client machine’s resources, including isolated storage, unrestricted UI access, unrestricted file dialogs, limited reflection, limited access to environment variables. Permissions for critical resources like the Registry are not provided.
Internet. For applications launched from the Internet or Trusted Sites zone. A subset of permissions are granted to provided limited access to a client machine’s resources, including isolated storage, file open only, and limited UI. Essentially, this permission sets isolates applications from the client machine.
Applications identified as being from the Untrusted Sites zone are granted no permissions by CAS at all. Consequently, a predefined permission set does not exist for them.
The following figure illustrates the relationship between zones, permission sets, permissions, and resources.
The restrictions of the Internet zone security sandbox apply equally to any code that a XBAP imports from a system library, including WPF. This ensures that every bit of the code is locked down, even WPF. Unfortunately, to be able to execute, a XBAP needs to execute functionality that requires more permissions than those enabled by the Internet zone security sandbox.
Consider a XBAP application that includes the following page:
Dim fp As New FileIOPermission(PermissionState.Unrestricted)
fp.Assert()
' Perform operation that uses the assert
' Revert the assert when operation is completed
CodeAccessPermission.RevertAssert()
FileIOPermission fp = new FileIOPermission(PermissionState.Unrestricted);
fp.Assert();
// Perform operation that uses the assert
// Revert the assert when operation is completed
CodeAccessPermission.RevertAssert();
To execute this XBAP, the underlying WPF code must execute more functionality than is available to the calling XBAP, including:
Creating a window handle (hWnd) for rendering
Dispatching messages
Loading the Tahoma font
From a security point of view, allowing direct access to any of these operations from the sandboxed application would be catastrophic.
Fortunately, WPF caters to this situation by allowing these operations to execute with elevated privileges on behalf of the sandboxed application. While all WPF operations are checked against the limited Internet zone security permissions of the application domain of the XBAP, WPF (as with other system libraries) is granted a permission set that includes all possible permissions
This requires that WPF receives elevated privileges while preventing those privileges from being governed by the Internet zone permission set of the host application domain.
WPF does this by using the Assert method of a permission. The following code shows how this happens.
Dim fp As New FileIOPermission(PermissionState.Unrestricted)
fp.Assert()
' Perform operation that uses the assert
' Revert the assert when operation is completed
CodeAccessPermission.RevertAssert()
FileIOPermission fp = new FileIOPermission(PermissionState.Unrestricted);
fp.Assert();
// Perform operation that uses the assert
// Revert the assert when operation is completed
CodeAccessPermission.RevertAssert();
The Assert essentially prevents the unlimited permissions required by WPF from being restricted by the Internet zone permissions of the XBAP.
From a platform perspective, WPF is responsible for using Assert correctly; an incorrect use of Assert could enable malicious code to elevate privileges. Consequently, it is important then to only call Assert when needed, and to ensure that sandbox restrictions remain intact. Por exemplo, o código em modo seguro não é permitido para abrir arquivos aleatórios, mas é permitido usar fontes. WPFpermite que os aplicativos em modo seguro usar a funcionalidade de fonte chamando Asserte WPF ler arquivos conhecidos por conter essas fontes em nome do aplicativo no modo seguro.
ClickOnce Deployment
ClickOnceé uma tecnologia de implantação abrangente que está incluída no .NET Frameworke integra Microsoft Visual Studio (consulte Visão geral sobre a implantação de ClickOnce para obter informações detalhadas). Standalone WPF applications can be deployed using ClickOnce, while browser-hosted applications must be deployed with ClickOnce.
Applications deployed using ClickOnce are given an additional security layer over Code Access Security (CAS); essentially, ClickOnce deployed applications request the permissions that they need. They are granted only those permissions if they do not exceed the set of permissions for the zone from which the application is deployed. By reducing the set of permissions to only those that are needed, even if they are less than those provided by the launch zone's permission set, the number of resources that the application has access to is reduce to a bare minimum. Consequently, if the application is hijacked, the potential for damage to the client machine is reduced.
Security-Critical Methodology
The WPF code that uses permissions to enable the Internet zone sandbox for XBAP applications must be held to highest possible degree of security audit and control. To facilitate this requirement, .NET Framework provides new support for managing code that elevates privilege. Specifically, the CLR enables you to identify code that elevates privilege and mark it with the SecurityCriticalAttribute; any code not marked with SecurityCriticalAttribute becomes transparent using this methodology. Conversely, managed code that is not marked with SecurityCriticalAttribute is prevented from elevating privilege.
The Security-Critical Methodology allows the organization of WPF code that elevates privilege into security-critical kernel, with the remainder being transparent. Isolating the security-critical code enables the WPF engineering team focus an additional security analysis and source control on the security-critical kernel above and beyond standard security practices (see Estratégia de segurança do WPF - Engenharia de Segurança).
Note that .NET Framework permits trusted code to extend the XBAP Internet zone sandbox by allowing developers to write managed assemblies that are marked with AllowPartiallyTrustedCallersAttribute (APTCA) and deployed to the user's Global Assembly Cache (GAC). Marking an assembly with APTCA is a highly sensitive security operation as it allows any code to call that assembly, including malicious code from the Internet. Extreme caution and best practices must be used when doing this and users must choose to trust that software in order for it to be installed.
Microsoft Internet Explorer Security
Beyond reducing security issues and simplifying security configuration, Microsoft Internet Explorer 6 (SP2) contains several features that security improvements that enhance security for users of XAML browser applications (XBAPs). The thrust of these features attempts to allow users greater control over their browsing experience.
Prior to IE6 SP2, users could be subject to any of the following:
Random popup windows.
Confusing script redirection.
Numerous security dialogs on some Web sites.
In some cases, untrustworthy Web sites would try to trick users by spoofing installation user interface (UI) or repeatedly showing a Microsoft ActiveX installation dialog box, even though the user may have canceled it. Using these techniques, it is possible that a significant number of users have been tricked into making poor decisions that resulted with the installation of spyware applications.
IE6 SP2inclui vários recursos para atenuar esses tipos de problemas, que giram em torno do conceito de inicialização do usuário. IE6 SP2detecta quando um usuário clicar em um elemento link ou a página antes de uma ação, o que é conhecido como a iniciação de usuárioe trata de forma diferente do que quando uma ação semelhante em vez disso, for disparada pelo script em uma página. As an example, IE6 SP2 incorporates a Pop-Up Blocker that detects when a user clicks a button prior to the page creating a pop-up. This enables IE6 SP2 to allow most innocuous pop-ups while preventing pop-ups that users neither ask for nor want. Blocked pop-ups are trapped under the new Information Bar, which allows the user to manually override the block and view the pop-up.
A mesma lógica de inicialização do usuário também é aplicada a Abrir/Salvar avisos de segurança. ActiveXcaixas de diálogo de instalação são interceptadas sempre sob a barra de informações, a menos que eles representam uma atualização de um controle instalado anteriormente. These measures combine to give users a safer, more controlled user experience since they are protected against sites which harass them to install either unwanted or malicious software.
These features also protect customers who use IE6 SP2 to browse to web sites that allow them to download and install WPF applications. Em particular, isso ocorre porque IE6 SP2 oferece uma melhor experiência de usuário, que reduz as chances de que os usuários instalem aplicativos mal-intencionados ou divergente independentemente de qual tecnologia foi usada para criá-la, incluindo WPF. WPFAdiciona a essas proteções usando ClickOnce para facilitar o download de seus aplicativos pela Internet. Since XAML browser applications (XBAPs) execute within an Internet zone security sandbox, they can be seamlessly launched. On the other hand, standalone WPF applications require full trust to execute. For these applications, ClickOnce will display a security dialog box during the launch process to notify the use of the application's additional security requirements. However, this must be user-initiated, will also be governed by user initiated logic, and can be canceled.
Internet Explorer 7 incorporates and extends the security capabilities of IE6 SP2 as part of an ongoing commitment to security.
Consulte também
Conceitos
Estratégia de segurança do WPF - Engenharia de Segurança
Outros recursos
Noções básicas sobre segurança no Microsoft Internet Explorer 6 no Windows XP SP2
Compreendendo e trabalhando no modo protegido do Internet Explorer