Code Access Security (CAS) and Design Patterns

Embed Size (px)

Citation preview

  • 8/8/2019 Code Access Security (CAS) and Design Patterns

    1/10

    Code Access Security (CAS) and Design Patterns

    IntroductionTo be classified as a good developer is no longer characterized by merely writing manageable and well-documented codebut by todays definition it also includes knowing how to write a secure code. This has priority over all other qualitiesassessed. Last year "Web Services" was the buzz in the technology field, but has since been replaced with "Security".Many job positions have been modified to include Security as a primary responsibility. On many levels of the CorporateEnterprise, changes are made to ensure that production systems are Secure and hackers cannot gain control of criticalapplications inside the businesses. When it comes to "Security", there are so many layers; it is like an onion in whichevery layer that is peeled away, reveals yet another layer and so on. It takes great effort and much invested time in ordto expose the core of the onion and the same is true with Security. In todays installment, I want to peel that initial laye

    from regarding the Security topic. I regret not being familiar with this technology a year ago, but have put forth mucheffort this year to learn, manipulate and implement solutions with this highly demanded skill. The outcome of my personendeavor is my collective thoughts and learnings that you will find below. My main goal was to decipher the complexity Code Access Security (CAS for short) into simple, understandable English supplemented with colorful diagrams toreinforce the knowledge. A picture speaks a thousand words!

    What is Code Access Security?The world has drastically changed in these last few years. This week I was in Washington DC, our capital, and wasshocked with the measures that have been taken through the city to ensure the security of the government and historicamonuments. Even though some of the buildings were surrounded with huge flower pots, beautified barricades, I still felt sense of exclusion as I walked through the streets. This is a perfect example of what security is all about. I looked up thmeaning of the word "Security" and here is what I found: "Freedom from risk or danger". To be honest with you, I did noexpect to see the word "freedom" anywhere in the definition of a word that at its core compromises freedom. Aftercontemplating, it began to make sense after all. Traveling through airports a few years back did not require extensive

    scanning procedures on passengers and their luggage. Also, friends and family members still had the ability to say theirlast good-byes at the boarding gates. This is no longer the case; Security at airports has changed so dramatically. Whatwe see here is countermeasures that have been taken by our government to prevent another 9/11 from happening. Asdevelopers and computer users, weve seen how a harmless computer virus can evolve into detrimental pieces of codetargeted to steal our personal information, destroy systems and take over our computers. Of course, as our governmentand major software companies roll-out countermeasures for computer security, we developers need to be on top of theissue as well and this requires a proactive approach in the Security our own applications. Microsoft has launched thetrustworthy initiative that includes not only developing secure code for their own products, but also a means fordevelopers to write trustworthy code. In order to write secure code though, we need to be educated and the wholeparadigm shift needs to fall into place before developers begin writing secure code. Is Microsoft doing a good job ofeducating us? You can answer this from your own perspective; surely there is much more that can be done. Recently, Iattended the Security Summit where a number of tracks were presented. The reoccurring theme of the seminar was toengage developers to begin thinking about the actions needed to develop secure code. If security is a set of actions thatultimately prevents us from being exposed and vulnerable again and again, then we need to be aware of the techniques

    and tactics of the Hacker. Education is a critical role to make this fortification happen.

    Role-Based security is at the heart of Microsoft Windows 2000/XP operating systems, but it isnt enough to depend on thcode itself and to neglect the skills and awareness of the user. This security model cares about user access secureresources and any code usually runs under the credentials of the logged on user. Here is a common scenario for Windowusers: "John, the accountant, needs to file some information with the partner site, so he typed in the partners URL intothe web browser. Next thing he knows, a message box pops up that reads: "In order to run this application we need toinstall ActiveX control on your machine, do you trust us? For John it means the following: "Do I want to be productivetoday?" Of course, he answers with a "Yes", which successfully installs this piece of the software, but John has no cluewhat secure resources this application has been granted to access it. This all happened just because he agreed to onepop-up message. What is wrong with this approach? Off the top of my head two things are wrong:

    1. Installed ActiveX runs under Johns user security permission set or it can do pretty much anything with the syste

    that John can. (Delete, update files, etc.)2. John has no idea of what the ActiveX does and most likely it doesnt cross his mind, but what matters to John isbeing productive and his computer being secure.

    The recent virus "Sasser" does not require user interaction for the computer to get infected; simply plug an unprotectedmachine to the net and in a matter of minutes it becomes infected. So, Code Access Security picks up where Role-Basedsecurity falls short. It provides it with the mechanism of securing the code based on who wrote it and where it came fromor where it is executed (evidences). These evidences are mapped to the permissions (rights), which can be administered

    by four different policies, which correspond to the role user represents:

    1. Domain Administrator Enterprise Policy2. Machine Administrator Machine Policy3. Actual User of the machine - User Policy4. Developer - Application domain Policy

    1

    http://www.microsoft.com/security/incident/sasser.asphttp://www.microsoft.com/security/incident/sasser.asp
  • 8/8/2019 Code Access Security (CAS) and Design Patterns

    2/10

    Code Access Security (CAS) and Design Patterns

    These policies are configurable after the application is deployed and can be modified at any point in time. One majorconcept was introduced with CAS - Partially trusted code is code that has been granted only access to the resources itneeds to execute successfully and no more. Looking at the big picture, Code Access Security and Role-Based security bosupport the same Patterns, which I call "2AR" as demonstrated in the diagram below.

    Security Identity Pattern "2AR" includes the process of determining the identity and then assigning it to a group, whichcorresponds to the permission set (rights), which can be performed on the secure resource. The key to this pattern is

    Reinforcement of the access to the secure resource. The process of reinforcement will not allow unauthorized access tothe secure resource without going through the process ofAuthentication and Authorization. Common Language Runtime

    (CLR) accomplishes this by means of a Stack- Walk, which can be compared to the following scenario:

    "Teenager Joe (19 years of age) wanted to drink some beer with his friends, but he could not legally go to the store topurchase it himself, so he asked his older friend if he could get it for him. Even though Bill (20 years of age) is older he inot old enough to purchase beer at the store, so he talks his dad into buying it for his friend. Bills dad knows he isbreaking the law, but he still does it. The Store Clerk checks Bills driver license and finds he is over 21, so he sells a pacof beer to him."

    The chain of request from Joe--> Bill --> Bills Dad to the clerk represents the software concept of the Stack-Walk.

    2

  • 8/8/2019 Code Access Security (CAS) and Design Patterns

    3/10

    Code Access Security (CAS) and Design Patterns

    In the real-world, the beer will be sold because there is only one ID check and all of the chain members of the request dnot need to present proper ID to the clerk, just Bills dad. Joe and Bill represent partially trusted code and Bills dadrepresents fully trusted code as far as the system is concerned. That is exactly what is happening when viruses gainaccess to a secure resource by luring it to do its dirty work. In .NET Framework scenario CLR prevents a successful StacWalk from happening, because it requests proper ID on every level of the chain cell; therefore, if somebody in the chaindoes not have proper ID then it consequently rejects the requests on all levels. Thus, if CLR reinforcement rules wereapplied to a real-life scenario than Joe or Bill would never have the beer. The following scenario will fail by the time it

    reaches Bill. Realistically, some of the code that is partially trusted (does not have full access to the system) sometimesneeds to have access to fully trusted resources and that is where modifications of the stack-walk comes into play.

    3

  • 8/8/2019 Code Access Security (CAS) and Design Patterns

    4/10

    Code Access Security (CAS) and Design Patterns

    In the diagram above the Clerk denies (Deny) anybody who does not have proper ID (evidence) to sell beer, but Billsdad permits (PermitOnly) his son and his sons friend to drink beer because he has almost reached the legal age.Outsmarting the system neither makes it right nor legal, only possible. When Bill gets his beer he shares it with his frien(Assert or voucher) and they enjoy beer together on a sunny day. Code Access Security provides us with this flexibility,but we need to be aware that it also introduces greater security risk; therefore, design your systems in advance. Idemonstrated how to use the Deny(), PermitOnly() and Assert() to modify Stack-Walk. This is not a complete list ofmodifiers. Please reference to .NET Framework SDK for more info (Overriding Security Checks). I just wanted to get youfeet wet; the rest of the onion peeling is in your hands!!

    This is as simple as it gets when it comes to Code Access Security and its patterns. Now, the complexity comes withunderstanding CAS terminology and the .NET Framework implementation of it.

    Learning Code Access Security through ASP.NET implementationThis learning process usually starts with discovering how to use Code Access Security for the existing applications andthen later applying it for your own projects. I have read a great deal of resources and nothing clicked for me, until Istarted working with Microsoft SharePoint 2004 that extends ASP.NET architecture and relies on CAS to secure itsresources. Since not everyone is developing with SharePoint server just yet, Microsoft hopes to corner the portal marketsoon with this product. I chose to demonstrate and explain the main concepts of CAS through ASP.NET technology.

    The most common scenario that demonstrates Code Access Security is smart client application. It has been downloadedover the intranet and has certain permissions (rights), but ASP.NET is installed on the machine and runs locally on thecomputer; thus, this scenario does not explain fully the CAS. We determine that code either can be executed by itself

    (smart client scenario) or hosted by Host Assembly or Unmanaged Code (IIS Filter). This is the main difference where thEvidences will come from.

    Therefore, there are two ways an assembly can be loaded:1. User clicks on executable and code executes2. Host assembly loads your assembly by means of Reflection or unmanaged code initialized the CLR.

    Most people do not realize that CLR is not native to Win32; therefore, it is hosted by unmanaged code. In the smart clienscenario assembly executable runs by itself, so default evidence gathering process is invoked as demonstrated below:

    4

    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconOverridingSecurityChecks.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconOverridingSecurityChecks.asp
  • 8/8/2019 Code Access Security (CAS) and Design Patterns

    5/10

    Code Access Security (CAS) and Design PatternsCLR Policy evaluator will gather evidence automatically, and you can not supply your own evidences at this point.Application domain policy is optional. What has been gathered by the Policy Evaluator is a set of Evidences about thecode. Policy Evaluator gathers evidence and grants a set of permission every time your code has been executed by JIT.There are 7 default evidence types, which can be split into two groups:

    1. Assembly Evidence answers the question "Who is the author of the Assembly" For example, all of Microsoft

    CLR classes signed with the same private/public key pair, which allows CLR to determine that Microsoft developewrote the code and grantsfull trust (full control) to the system.

    2. Host Evidence answers the questions "Where did the Assembly come from?" If you started a smart client by

    referencing the URL location and than at a later date you move the executable to a local hard-drive, CLR does notrack the history of its location.

    Of course, like everything else it is possible to write your own Evidence class and provide custom Evidence object for you

    applications.

    ASP.NET unmanaged IIS filter hosts managed ASP.NET process and passes needed information from unmanaged worldinto managed process. This scenario is an exception and most likely if you need to host an Assembly you will usemanaged code and use Reflection to load the assemblies. Rockford Lhotka business object framework has a nice utility(NetRun) for smart clients, which basically modifies machine polices for the hosted Smart Client Applications.

    ASP.NET relies on the Application Domain policy to provide extra flexibility for configuring the applications. That is why Ihave ASP.NET and SharePoint on the slides above.

    What is Policy? It is a configuration file containing information about what the code can do depending on the codeevidence. There are four levels of configurations for the applications, which are based on administration needs. They areas follows:

    1. Enterprise Policy default setting allows all code to have full trust.2. Machine Policy - configured by default to give the assemblies installed in Global Assembly Cache full trust and

    others.3. User Policy if the user wants he can restrict its machine based on these settings.4. Application Domain Policy security configuration for the application.

    5

    http://www.lhotka.net/WeBlog/http://www.lhotka.net/WeBlog/
  • 8/8/2019 Code Access Security (CAS) and Design Patterns

    6/10

    Code Access Security (CAS) and Design PatternsThe process of evaluating permissions (rights) between different polices levels is known as "Intersection".Intersection is a complex algorithm to determine the final or Grant Set of Permissions. There are two things to remembeabout policies:

    1. Policies are based on the hierarchy structure; thus, if the top layer of the policy grants no permissions (rights) tothe code, then the policy below it cannot grant permissions either.

    2. All of the policies have to agree on permission, before that permission can make a final grant permission set.

    To demonstrate simply how Policies work together, I diagramed the following:

    This diagram includes ASP.NET Application Domain policies levels that normal application does not have. There are 5default ASP.NET Application policies:

    1. Full2. High3. Medium4. Low5. Minimal

    All policies correspond to a physical file, with the exception of Full, which has a built in policy (full control). I can createmy own Policy file by simply adding an entry to the Machine.config as follows:

    6

  • 8/8/2019 Code Access Security (CAS) and Design Patterns

    7/10

    Code Access Security (CAS) and Design Patterns

    Did you know that ASP.NET by default runs under Full trust? You can change it by modifying trust level attribute of theMachine.Config file for the server or Web.Config for the virtual directory:

    Here is a very simple scenario for you guys, to try out and learn about CAS.

    1. Create a WebService on a local machine with IIS Server and add a simple method "SayHi" that returns a string"Hello World"

    2. Create an ASP.NET application and Add Web Reference to your WebService3. Add a button, wire the click event to call the WebService method for "SayHi" and display return value into the

    label.4. Build and View in the Browser. It should work with no problem.5. Add trust level attribute and set it to Minimal6. Does it still work?

    If you get a Security Permission Exception then you have done everything right. How can you fix it? The Policy containsinformation about what the code can do based on the evidence. By switching Application Domain Policy for ASP.NET fromFull to Minimal we can change what the code can do and this is where the understanding of Code Groups --> MembershiConditions --> Permission Sets and Permissions begins.

    All right, first things first; Code Groups are containers for Permissions (rights) that the code can have based on theEvidence, which are the XML elements within the policy configuration file. There are 7 defaults evidence types and theyare mapped out on a one-to-one relationship to Membership Condition element of Code Group, plus one MembershipCondition that maps all of the code.

    Code can belong to a Code Group based on the Membership Condition, which reflects the evidence that has been collecteor provided to a policy evaluator while assembly was loading. We know that in ASP.NET applications the code executes ithe virtual directories; therefore we can create the following Code Group to match this condition.

    7

  • 8/8/2019 Code Access Security (CAS) and Design Patterns

    8/10

    Code Access Security (CAS) and Design Patterns

    Code Groups can contain child Code Groups; therefore, it is possible to create permissions across matched groups. Mostcommonly used Code Groups types are Union (AND) and First Match (stop when the match is found). It is also possible tuse PolicyStatementAttribute to provide the mechanism to stop policy evaluator from calculating the remainder of thehierarchy of policies. Options are Exclusive or LevelFinal. Please refer to .NET Framework SDK for more info.

    What is a Permission Set? A Permission Set is a combination of all the permissions (rights) that can be granted to thecode. There are 6 Immutable (pre-built) Permission Sets that we can not modify, meaning we can add or delete themfrom the permissions collection:

    8

    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemsecuritypolicypolicystatementattributeclasstopic.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemsecuritypolicypolicystatementattributeclasstopic.asp
  • 8/8/2019 Code Access Security (CAS) and Design Patterns

    9/10

    Code Access Security (CAS) and Design PatternsIf you noticed "Everything" and "ASP.NET "are Named Permission Sets but they are mutable and I can freely addor delete permissions to it. I also can create my own name for XML PermissionSetelement and combined permissions I want this Permission Set to have it.

    Now, we are back to our earlier scenario with WebService. Do you still want to fix it or have you already given up on theidea?

    Of course, you want to fix it. I know I did. What I found out was that in order for the WebServices calls to work properlywe needed to allow WebHttpRequest/ WebHttpResponse classes to haveWebPermissiongranted. If you look atweb_minimal.config configuration file you will find the following entry for ASP.NET Permission set:

    This Permission Set does not give much rights for my virtual directory code (ASP.NET application).

    Microsoft always likes to gives us many options to do the same thing and works in our favor.

    Our First option will be to find out which ASP.NET Application Domain Policy file contains the WebPermission. You can dit by simply looking through the Policy files. You will find that web_mediumtrust.config has WebPermission as a part oASP.NET Permission Set:

    So all you need to is modify your web.config file to the following

    Now, when you run the application it should work without a hitch. OriginUrl is used to grant permissions to the specificweb server. What if you had references to more then one server?

    Then simply make the following entry in web_mediumtrust.config:

    Our Second option involves creating a custom policy. For example, if I really wanted to lock down my server and onlyallow running under Minimaltrust level, then I need to create a custom Policy based on Minimaltrust level and then apermissions (rights) for WebService execution.

    Here are the steps for creating ASP.NET Application Domain Policy, which has minimal trust level and allows callingWebServices:

    1. Navigate to C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\CONFIG or the location where .NET Framework installed on your machine.

    2. Open Machine.config file and belowdefault ASP.NET trust levels

    3. Create a copy ofweb_minimaltrust.config and name it web_minimal_Web.config or what you desire your

    policy file to be named

    4. Open web_minimal_Web.config and now were ready to make modifications needed to grant WebPermission

    ASP.NET PermissionSet5. Add reference to WebPermission assembly between Element:

    9

    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemNetWebPermissionClassTopic.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemNetWebPermissionClassTopic.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemNetWebPermissionClassTopic.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemNetWebPermissionClassTopic.asp
  • 8/8/2019 Code Access Security (CAS) and Design Patterns

    10/10

    Code Access Security (CAS) and Design Patterns6.

    8. Navigate to ASP.NET Named Permission Set and add9. 10. 11. 12.

    13. Open your Web.Config file within ASP.NET application and add the following

    14. Build and View it in the browser. It should work like a charm

    if you followed all of the steps you were successful in creating a custom policy and running ASP.NET application with aMinimal Trust level (permissions that are requiring running the application and no more).

    Let me summarize the whole process quickly for you. Unmanaged Code loads ASP.NET assembly and provides it with a sof Evidences. There are five ASP.NET Application Domain polices that configured by modifying trust attribute of theMachine.Config or Web.Config files. Policy Evaluator performs "intersection" on four polices (enterprise, machine, user,application domain) and maps Evidence to a membership condition of the Code Group that supply permissions (rights). I

    all the policies agree between different levels then permission set is included in the grant set.

    Declarative vs. Imperative

    The main difference is where the information is stored in an assembly as shown below:

    Manifest stores Metadata information that can be read without running the assembly; therefore if you used Declarativesecurity to enforce security than I can simply run command-line utility (Permview.exe) to view what Permission I needto have to run your code. In comparision, Imperative is more flexible and is stored as MSIL code, which will be compiledin JIT and given a Security Exception at run-time.

    10