Defining Security with the .NET Framework


As we have covered in many areas throughout this book, InfoPath is only one part of the solution within an SOA design pattern. The .NET Framework provides a variety of techniques and security namespaces that you can use to build and deploy secure Web- and client-based applications. Applications or assemblies written to use the .NET Framework are considered managed applications. Assemblies are the building blocks of .NET Framework applications. They form the fundamental unit of deployment, version control, reuse, activation, scoping, and security permissions. An assembly is actually a collection of types and resources that are built to work together. These form a logical unit of functionality. Assemblies provide the CLR with the information needed to determine the specific type implementation needed during runtime. Within the runtime environment of .NET, a type doesn t exist outside of the context of an assembly.

Defining Assemblies

You can create a single file or multi-file assembly using Visual Studio.NET. The simplest type of assembly is a single file that has a simple name and is loaded into a single application. This assembly can t be referenced by other assemblies outside of the application directory and doesn t undergo any type of version checking. If this type of assembly needs to be removed, then simply delete the directory. Multi-file assemblies from several code modules and resource file can be shared by multiple applications. A shared assembly must have a strong name and can be deployed in the Global Assembly Cache (GAC).

Note  

A strong name consists of the assembly s identity, public key, and a digital signature. The strong name is then generated from the assembly file using a private key algorithm. The assembly file actually contains the assembly manifest that names and hashes all of the files defined in the assembly.

The GAC is a machine-wide code cache that is installed on any machine that has the CLR. This assembly cache stores assemblies that are designated to be shared by several applications on the computer. As a general rule, you should always try to keep assembly dependencies private, and locate assemblies in the application directory unless sharing the assembly is required.

Note  

It is not required to install assemblies in the GAC in order to make them accessible to either COM interoperability or unmanaged code.

When developing a multi-file assembly and grouping code modules into assemblies, you should always keep the following design considerations in mind:

Versioning: Group modules that have the same version information.

Deployment: Group code modules and resources that support the deployment model.

Reuse: Group modules if they can be logically used together for the same purpose. For example, an assembly that consists of a specific business function should be grouped into an assembly, and that assembly should be signed with a strong name.

Security: Group modules that contain types that require the same security permissions.

Scoping: Group modules that contain the types with the same level of visibility within the same assembly.

Physically, an assembly can be a DLL or an EXE. When built using managed code, the result is a Microsoft Intermediate Language (MSIL) instruction that is contained in a standard Windows Portable Executable (PE). When an assembly is loaded by a method call, the MSIL is compiled by a Just in Time (JIT) compiler into native machine instructions. The compiled method is executed, while others that are never called are not JIT compiled. The Framework s use of the intermediate language coupled with the runtime environment provided by the CLR offers assemblies the following advantages:

File Format and Metadata Validation: The CLR verifies that the PE file format is valid and that memory addresses do not point outside of the PE file. This helps provide assembly isolation. The CLR also validates the integrity of the metadata that is contained in the assembly.

Code Verification: The MIL code is verified for type safety at JIT compile time. This is a major advantage from a security perspective because this verification process can prevent bad pointer manipulation, validate type conversions, and check array bounds. This virtually eliminates buffer overflow vulnerabilities in managed code, although you still need to carefully inspect any code that calls unmanaged application programming interfaces (APIs) for the possibility of a buffer overflow.

Integrity Checking: The integrity of strong-named assemblies is verified using a digital signature to ensure that the assembly has not been altered in any way since it was built and signed. This means that attackers can t alter your code by manipulating the MIL instructions.

Code Access Security: The virtual execution environment provided by the CLR performs additional security checks at runtime. These allow various runtime security decisions based on the identity of the calling code.

Assemblies in Web Services

A Web Service is defined by an .asmx file that serves as the endpoint of calls. Calls made to the .asmx file are intercepted and processed by the ASP.NET runtime. The actual implementation of a Web Service is encapsulated within a class. Class definition can either appear inline within the .asmx file or can be contained in a separate DLL. The Web Service page needs to contain the information that the runtime can use to locate the class.

 CD-ROM    Each .asmx page contains a directive at the top of the page that specifies where and in what form the implementation of the Web Service can be found. The directive is used by the ASP.NET runtime to bind the Web Service to a class that contains the actual implementation. Here is an example from the Interview Feedback Web Service that we used in Chapter 4 (this example is available on the companion CD-ROM in \Code\Chapter 9\ResourceRequest\ResourceRequest.exe):

 <%@ WebService Language="vb" Codebehind="Feedback.asmx.vb"  Class="InterviewFeedback.Feedback" %> 

The Class attribute contains the fully qualified name of the class that implements the Web Service. If the code resides within the .asmx file, you must set the Language attribute to specify what the code was developed in.

The first time that a Web Service is accessed, the ASP.NET runtime will use the languages attribute to compile the code. Even if the code implementing the Web Service is contained within the .asmx file, it will always be executed as compiled machine code.

By default, ASP.NET is configured to dynamically compile code using the base languages of the CLR. You can configure additional languages within the Web. config file or the machine.config file. The compiler section of the machine.config file found in the C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\CONFIG\ directory, shown in Figure 9.7, shows these base languages.

click to expand
Figure 9.7: Configuration file that determines .NET-available languages.
Note  

The default language defined in the machine.config file is VB. If you are using any other language, you need to make sure that you set the Language attribute.

The compilation section includes a list of assemblies that are globally referenced by code within the .asmx file. Any Web Service that needs to reference entities from an assembly other than those listed above would add a new machine reference to the machine.config , an application reference in a web.config file, or a form-level variable reference using the following statement:

 Imports System.Configuration 

The last add element specifies a wildcard (*) character for the assembly name. This forces the ASP.NET runtime to search for any assembly that is not directly listed. It is also possible that the class implementing the Web Service can reside in a compiled assembly. If this is the case, then by design the assembly is placed in the Web application s bin directory, because this directory is always included in the runtime search path .

User vs. Code Security

The .NET Framework contains two types of security models. The first is code-based security ”or more commonly called Code Access Security (CAS) ”which is used to determine if the actual code has both a proper set of permissions and verifiable origins to run in the requested application domain. The second is a set of role-based permissions focused on users making the request and then determining if they have proper permissions to access the requested resources.

Code-Based Security

Code-based security involves authorizing the application s access to the required system-level resources. These can include file systems, registry services, and even database access. Within CAS, it doesn t matter what user is making the request or even which account the code is running under; rather, it does matter what permissions have been assigned to the code.

Note  

Security focused on the user is called role-based security and security focused on the actual code is called CAS.

Role-Based Security

Role-based security allows a Web application to make security decisions based on the identity or role membership of the user interacting with the application. If an application uses Windows authentication, then a role directly translates to a Windows group. Other forms of authentication usually store the role details in SQL Server or even Active Directory, as shown in Figure 9.8. The identity of the authenticated user and his associated role membership is made available to Web applications through Principal objects, which are attached to the user Web requests .

click to expand
Figure 9.8: Basics of role-based security.

Role-based security is implemented using Principal and Identity objects. The identity and role membership of an authenticated call is exposed through a Principal object that contains a reference to an Identity object. You can retrieve the object by using the HTTPConnect.Current.User property. If the called application is not required to authenticate the Principal object, as in the case of an intranet-based application, NT Based Authentication is used to represent the anonymous Internet user.

The Identity object contains information about the user or entity being validated . The IIdentity interface defines a set of properties for accessing the user name and authentication type. Within that interface, the HTTPContextUser property provides programmatic access to the properties and methods of the IPrincipal interface. By default, an ASP.NET page contains a default reference to the System.Web namespace that contains the HTTPContext class, which can be used to reference the current members of the HTTPContext within a Web page. This enables the use of the User.Identity.Name to retrieve the named user of the current request. For example, the following Web Service returns the current user identity:

 <WebMethod()> Public Function ReturnSecurityInfo() As String   Return User.Identity.Name End Function 

This then returns the name of the user on whose behalf the request is running, as shown in Figure 9.9.

click to expand
Figure 9.9: The XML returned showing the current user identity.
Note  

If you wanted to use the member of the IPrincipal from an ASP.NET code behind module, you must include the reference to the System.Web namespace in the module as well as provide a fully qualified reference to the currently active request/response context and the class in the System.Web you want to use.

There are many types of Principal objects; the type used depends on the authentication mechanism used by the application. However, all Principal objects implement the System.Security.Principal.IPrincipal interfaces and maintain a list of roles of which the user is a member.

Principal objects also contain an Identity object that includes the user s name. These are combined with parameters regarding whether the user has been authenticated and the available authentication types. This enables the Web request to distinguish between authenticated and anonymous users. There are different types of Identity objects (depending on the authentication type), and each implements the common System.Security.Principal.IIdentity interface. Table 9.3 shows the possible types of authentication objects that an ASP.NET Web application can use, depending on the type of authentication defined within the web.config.

Table 9.3: Authentication objects an ASP.NET application can use.

Authentication Type

Principal and Identity Type

Additional Comments

Windows

WindowsPrincipal+ WindowIdentity

Verified credentials use the Security Accounts Manager (SAM) or Active Directory. Windows groups are used for roles.

Forms

GenericPrincipal+ FormsIdentity

You must add code to verify credentials and retrieve role membership from a security store.

Passport

GenericPrincipal+ PassportIdentity

Relies on the Microsoft Passport SDK.

The PrincipalPermission object defines the identity and role that the current principal must have in order to execute the code. These objects can be used within code either declaratively or imperatively.

Declarative Security

The .NET Framework enables developers to determine which users should be allowed to access a specific class or method by adding a PrincipalPermissionAttribute to the class or method definition. This is a class-level attribute that applies to all class members unless it is overridden by the specific member-level attribute. The PrincipalPermissionAttribute type is defined in the System.Security.Permissions namespace.

Note  

The PrincipalPermissionAttribute can also come in handy when you are trying to restrict access to properties and delegates.

Listing 9.3 shows how to restrict access to a function in the Catalog example to a member of the Sales group. This example assumes that Windows authentication is enabled. For other types of authentication, the form of the role name becomes application specific and will depend on stored credentials.

Listing 9.3: Web Service with restricted permissions.
start example
 <PrincipalPermissionAttribute(SecurityAction.Demand,Role=@"DOMAINNAME\S ales")> <WebMethod()> Public Function InfoPathGetNewCatalog() As  System.Xml.XmlDataDocument   Dim ds As DataSet   ds = GetNewCatalog()   ds.Namespace = "Http://localhost/Catalog"   Dim Info As System.Xml.XmlDataDocument = New  System.Xml.XmlDataDocument(ds)   Return Info End Function 
end example
 

Listing 9.4 shows how to restrict access to the same method class to a member of the local Sales group who is identified by the BUILTIN\Sales identifier.

Listing 9.4: Web Service restricted only to the BUILTIN\Sales group.
start example
 <PrincipalPermissionAttribute(SecurityAction.Demand,  Role=@"BUILTIN\Sales")> <WebMethod()> Public Function InfoPathGetNewCatalog() As  System.Xml.XmlDataDocument   Dim ds As DataSet   ds = GetNewCatalog()   ds.Namespace = "Http://localhost/Catalog"   Dim Info As System.Xml.XmlDataDocument = New  System.Xml.XmlDataDocument(ds)   Return Info End Function 
end example
 

Imperative Security

Imperative security checks allow developers to protect specific blocks of code by demanding the appropriate permissions. You use the Permission object to add imperative security checks within a code block. The Permission object is an instance of a specialized class that represents a particular type of permission. For example, the FileIOPermission class defines the right to read, append, or write files or directories. The following code creates the necessary Permission object:

 Dim MyPermission as New _   Security.Permissions.FileIOPermission(PermissionState.Unrestricted) 

You create imperative security checks by creating an instance of the appropriate security object, and then calling the object s Demand function. This has the net effect of denying access to all callers except those that can supply the proper credentials. The following example shows how you can implement this within a code block:

 Try   MyPermission.Demand()   ' implement the actions Catch e as Exception   ' Insert code to handle the exception. End Try 
Note  

When a user fails the Demand permissions in a code block, a SecurityException is thrown. It is always important to pre-determine how to handle these types of exceptions.

Comparing Declarative and Imperative Security

When you re developing an application using role-based security, you can choose between using attributes declaratively or imperatively within code. Overall, declarative security offers the most benefits and is the easiest to use and maintain. To help you decide which one to use, take note of these considerations to keep in mind.

The main advantages of declarative security are that:

  • Declarative security allows the administrator to see the exact security permissions that a particular class or method needs.

  • Declarative security offers increased performance. Declarative demands are evaluated only once at load time. Imperative demands inside methods are evaluated each time the method that contains the demand is called.

  • Declarative security attributes ensure that the permission demand is executed before any other code in the method has a chance to run.

  • Declarative security checks occur at the class level.

The main advantages of imperative security are:

  • Imperative security allows dynamic security requests during runtime.

  • Imperative security allows a more granular authorization scheme within the conditional logic placed in code.

CAS

CAS is the security system of the .NET Framework that controls access to resources by controlling the execution of code. This security feature is actually a separate layer on top of the standard operating system security. CAS is actually a resource-constraint model that allows administrators to determine if and how particular code is able to access specified resources and perform other privileged operations. For example, an administrator might decide that code downloaded from the Internet is by default denied access to any local resources. However, Web application code developed by one of their internal developers needs a higher degree of trust and access to the local file system, event log, and Microsoft SQL Server databases.

Traditional principal-based security like the operating system authorizes access to resources based on only user identity. For example, any program launched by a local administrator has complete control of the local machine. The problem is that if the administrator s identity is spoofed and any code is executed, it also has no restrictions. This is where CAS is important because it provides additional restrictions and security based on the code itself, rather than user identity.

CAS works by assigning all code to a zone defined by the CLR. These zones are:

My Computer: Application code is hosted directly on the user s computer.

Local Intranet: Application code runs from a file share on the user s intranet.

Internet: Application code runs from the Internet.

Trusted Sites: Applications run from a site defined as Trusted through IE.

Untrusted Sites: Applications run from sites defined as Restricted through IE.

The default assignment of the first three zones ”My Computer, Local Intranet, and Internet ”is based on where the actual code is located. You can override these assignments by assigning specific sites to the Trusted Sites or Untrusted Sites group in IE. This is similar to the form template-based restrictions used by InfoPath and available through the Tools Options, as shown in Figure 9.10.

click to expand
Figure 9.10: Selecting the Internet Options within InfoPath.

On this dialog box, select the Internet Options button to access the zones setting, as shown in Figure 9.11.

click to expand
Figure 9.11: Accessing IE zones settings.

With the.NET Framework version 1.1, administrators can configure specific policy settings for ASP.NET Web applications services. These may consist of multiple assemblies that are granted code access security permissions; these allow the application to access specific resource types and to perform specific privileged operations.

Note  

Web applications and Web Services built using .NET Framework version 1.0 always run with unrestricted code access permissions.

CAS with Web applications provides application isolation in hosted environments where multiple Web applications run on the same Web server. System administrators that run multiple applications on the same server can use CAS to do the following:

Isolate applications from each other: For example, you can use CAS to ensure that one Web application cannot write to another Web application s directories.

Isolate applications from specific system resources: For example, CAS can restrict access to the file system, registry, event logs, and network resources.




Programming Microsoft Infopath. A Developers Guide
Programming Microsoft Infopath: A Developers Guide
ISBN: 1584504536
EAN: 2147483647
Year: 2006
Pages: 111
Authors: Thom Robbins

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net