1 / 53

Code Access Security

Code Access Security. CS 795 Chapters 5-9 (O’Reilly Book) Chapter 13 (Barry Dorrans). References. Videos: http://www.youtube.com/watch?v=qNnOi5xi9KM http://www.codeproject.com/Articles/120911/CAS-Code-access-security-NET-Security-model-FA http://www.youtube.com/watch?v=RitDp3pDYK8

remy
Download Presentation

Code Access Security

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Code Access Security CS 795 Chapters 5-9 (O’Reilly Book) Chapter 13 (Barry Dorrans)

  2. References Videos: • http://www.youtube.com/watch?v=qNnOi5xi9KM • http://www.codeproject.com/Articles/120911/CAS-Code-access-security-NET-Security-model-FA • http://www.youtube.com/watch?v=RitDp3pDYK8 • Slides: • http://slideplayer.us/slide/276700/#.U814cEbkFdM.gmail • Explanation: • http://msdn.microsoft.com/en-us/library/ff648663.aspx

  3. Terminology-SPC • Software Publisher Certificate (SPC): Provide identity of the assembly publisher • Signcode scheme---using this a digital signature is created using the private key components of the certificate and is embedded into the assembly along with the public key component of the SPC • Makecert –sv MyPrivateKey.pvk TestCert.cercreates a certificate with a public key and stores it in TestCert.cer; corresponding private key is stored in MyPrivateKey.pvk • Cert2spc TestCert.cer TestSPC.spc • Signcode –spc TestSPC.spc –v MyPrivateKey.pvk SingleFileAssembly.dll

  4. Terminology-GAC • GAC: Global Assembly Cache • If an assembly is shared by several applications, it can be installed into the GAC. • It is a machine-wide store of shared assemblies • Why place it in GAC? • .Net framework automatically looks for an assembly in GAC; so no need to configure to find it • File security---tamper proof • Simplify administration • Multiple versions may exist • gacutil /i SingleFileAssembly.dll ---install a file into GAC • gacutil /l – lists contents of GAC • gacutil /l SingleFileAssembly ---lists the attributes of this file • gacutil /u SingleFileAssembly ---to uninstall

  5. App Domain 1 Assembly1 Assembly2 Terminology—Application Domain • Logical containers within CLR that provide an isolation boundary for an application • Similar to protection provided by processes in a Unix environment---no sharing of address space, etc. • It is possible for a single process to run multiple applications without any boundary violations • Assemblies within an application may be isolated from each other Process CLR App Domain 2 Assembly3

  6. More on Application Domains and Security • Assembly evidence and identity—when an assembly is loaded into an app domain, we can specify additional evidence to apply to the assembly---evidence determines the permissions granted by CLR to the assembly • Application domain evidence and identity--when an application domain is created, it can be assigned some evidence; CLR grants permissions to an app domain based on the evidence; an action by an assembly is controlled both by assembly permission set and app domain permission set. • App domains and security policy---while the enterprise level, machine level, and user level security policy levels are fixed, app domain security policy may be defined programmatically • App domains and role-based security: By default, the app domain through which a thread runs, defines the principal on whose behalf the thread acts. • App domain and isolated storage: This is based on the identity of the assembly and the app domain in which the assembly is loaded. http://ondotnet.com/pub/a/dotnet/2003/04/21/isolatedstorage.html

  7. Code Access Security (CAS) • A means to assign identity or evidence to .Net assemblies • User identities are not in this picture; only assembly identities • Code that is running may be denied access to a resource • Suitable for environments where partially trusted code runs

  8. CAS (cont.) • .Net Framework uses CAS to provide an optional sandbox for managed code. • It is used to limit access that programs have to protected resources and operations---regardless of the user running the program. • For example, with a non-CASA program such as Notepad, an Admin could write a textfile to C:\Window because his/her account has permission to do so. No restrictions are placed on the Notepad program. • A CAS-enabled editor, however, could have restrictions set up on it---for example, it may not be allowed to write to C:\Windows. So even though Admin has a right to write on C:\Windows, his/her attempt to write using the editor would fail to write here.

  9. CAS (cont.) • Authentication: Deals with assembly evidence (and not Windows principals) • Authorization: Not related to OS-level objects; instead they concern with standard application tasks such as accessing a database via an OLEDB provider or a resource on the Internet via a URL • CAS permissions are directly attached to assemblies at load time

  10. Application Trust Levels • Full Trust: No restrictions imposed by code access security. • High Trust: • No unmanaged code. • Can access Microsoft SQL Server and other OLE DB data sources. • Can send e-mail by using SMTP servers. • Very limited reflection permissions. No ability to invoke code by using reflection. • A broad set of other framework features are available. Applications have full access to the file system and to sockets. • Medium Trust: • Permissions are limited to what the application can access within the directory structure of the application • No file access is permitted outside of the application's virtual directory hierarchy. • Can access SQL Server. • Can send e-mail by using SMTP servers. • Limited rights to certain common environment variables. • No reflection permissions whatsoever. • No sockets permission. • To access Web resources, you must explicitly add endpoint URLs —either in the originUrl attribute of the <trust> element or inside the policy file.

  11. Application Trust Levels (cont.) • Low Trust: • Intended to model the concept of a read-only application with no network connectivity. • Read only access for file I/O within the application's virtual directory structure. • Minimal Trust: • Execute only. • No ability to change the IPrincipal on a thread or on the HttpContext. If an application calls unmanaged code, it must run with Full trust. Even the least restrictive partial trust level, High, does not permit calls to unmanaged code.

  12. Application Trust Levels (cont.) • To choose an appropriate trust level (http://msdn.microsoft.com/en-us/library/ff649312.aspx) • Examine each trust level, beginning with High trust. • Look inside the High trust policy file, web_HighTrust.config. • If your application requires fewer code access security permissions than those provided by the High trust level, move on to consider Medium trust. • Repeat the process, moving from Medium to Low to Minimal, and keep evaluating the partial trust levels until you reach an exact match to your application's requirements or until your application's required permissions slightly exceed a partial trust level. • This process will help you to identify a trust level that matches your application's code access security permission requirements as closely as possible but does not grant permissions that your application does not need.

  13. Application Trust Levels (cont.) Configuring Your ASP.NET Application The following example shows how to configure your application for Medium trust. ... <system.web> ... <trust level="Medium" originUrl="" /> ... </system.web> ...

  14. CAS Evidences for an Assembly • Assembly inner (fixed) properties (e.g., assembly Strong Name or Publisher) and assembly origin (variable) information (e.g., URL, Site, Zone) • .Net Built-in evidences (automatically evaluated and attached to the assembly by the CLR loader when referenced the 1st time): Application Directory Assembly origin Hash (Cryptographic hash) Within assembly Publisher (Authenticode signature) Within assembly Site (Site of origin: http://www..) Assembly origin Strong name (cryptographically strong) Within assembly URL (URL of origin) Assembly origin Zone (Zone of origin such as internet zone) Assembly origin

  15. Application Domain and Assembly Evidence • CLR exposes methods to enable users to create application domains or load assemblies explicitly. At this time it allows us to modify the evidence set (add new evidence or override evidence provided by CLR) • Nothing can be done when it is loaded automatically by the CLR • BCL – base class library • Creating a new evidence set object: Evidence ev = AppDomain.CurrentDomain.Evidence; Zone z = new Zone(SecurityZone.Internet); ev.AddHost(z); AppDomain myappdomain = AppDomain.CreateDomain(“myappdomain”, ev); For an assembly, CLR provides evidence but we can override it: Zone z = new Zone(SecurityZone.Internet); ev.AddHost(z); Myappdomain.ExecuteAssembly(http://localhost/cas/ConsoleApplication1.exe, ev);

  16. CAS Permissions • .Net BCL comes with a list of built-in permission classes, one for each resource or service it provides access to: • System.DirectoryServices.DirectoryServicesPermission • System.NET.DnsPermissions • System.EnvironmentPermission • System.Diagnostics.EventLogPermission • System.Security.SecurityPermissions • System.Data.OledbPermission • Many more • SystemPermissions class is used to allow permission to different disparate actions such as assembly evidences, creating application domains, and calling into unmanaged code

  17. CAS Permissions (cont.)

  18. CAS Permissions (cont.)

  19. CAS Policies • Assembly binding behavior can be configured at different levels based on three XML files: • Application configuration file. • Publisher policy file. • Machine configuration file. • It is also possible to define an application-specific policy and inject it into a newly created application domain • Final permissions are granted by the CAS to an assembly will be those granted in the intersection of the permissions

  20. CAS Policies (cont.) http://www.icodeguru.com/dotnet/core.c.sharp.and.dot.net/0131472275/ch15lev1sec3.html

  21. Permission Sets and Code Groups • Permission Set: named set of permissions registered in a specific security policy. • Membership condition: A specific value of an evidence type; e.g., Zone=Internet; URL=http://….. • Code Groups: Building blocks of security policies. It is an association between a membership condition and a permission set. • When an assembly evidence contains an evidence entry matching the code group membership condition, that assembly is a member of the code group, and thus permission set assigned to the code group is granted to the assembly • Example classes: UnionCodeGroup, NetCodeGroup, FileCodeGroup • Example: Suppose a Code Group B has the membership condition: Zone=Intranet and Permission Set = Everything. Suppose an assembly A has the following evidence set: Zone = X, Hash = Y, Strong Name = Z. So if X = Intranet, then Assembly A will be granted the Permission set of Everything. • Built-in Permission Sets: FullTrust, SkipVerification, Execution, Nothing, LocalIntranet, Internet, Everything • By Default, FullTrust and Everthing or identical permission sets. However, FullTrust may have additional custom permissions, if defined.

  22. Policy Structure Object: Model • Enables us to: • Navigate along the code group structure, and modify it • Get and Set a group’s membership conditions and permission set • Resolve membership conditions against an assembly evidence, and • So on • RootCodeGroup property of a PolicyLevel object provides access to the root code group object of the policy. From that, we can get an enumerator to access its child group using Children property, and so on. Ex: IEnumerator policyenumerator = SecurityManager.PolicyHierarchy(); While (policyenumerator.MoveNext()) { PolicyLevel aPolicyLevel = (PolicyLevel) Policyenumerator.Current; CodeGroup rootcodegroup = aPolicyLevel.RootCodeGroup; Debug.WriteLine(rootcodegroup.name) }

  23. Policy Evaluation • Complex due to the hierarchical nature of code groups in a CAS policy • The order of execution: Enterprise, Machine, and User, and app domain. • Result is permissions granted to an assembly by intersecting permissions granted by each policy

  24. CAS and ASP.Net Applications • In the most common scenario: ASP.Net applications are deployed in IIS virtual directory; thus according to CAS, Zone=MyComputer evidence value. Thus, FullTrust permission set is granted to ASP.Net assemblies (as a default) • Exception 1: Within an ASP.Net page, an assembly is downloaded from a URL ; CAS assigns limited permissions; developers will have to modify security policy config to provide additional permissions if needed. • Exception 2: IIS Virtual directory is mapped to a UNC (Universal naming convention like \\Potato\Chips or //servername/path) path. Here, ASP.Net assemblies are loaded with intranet permission set; they may not be sufficient to run an assembly

  25. CAS Limitations • CAS can perform access control only on managed code • For security reasons, do not allow calls to unmanaged assemblies • Do not load .Net applications that we do not trust from Zone=MyComputer • As long as Windows allows unmanaged code to run, nothing will prevent a virus from modifying security policies (XML files) --- To set a permission set from Nothing to FullTrust. • For CAS to be secure, a robust ACL permission policy is essential.

  26. Security Requests • This takes place during the last stage of the assembly load time phase • By placing security requests on assembly metadata, we can notify CAS about some permissions that we wish to associate with the assembly: • Request minimum (if these are not there), don’t load; • Optional needs (needed but don’t abort loading if they are absent); • Refuse permissions—don’t give these • By default, optional permissions are all permissions. Thus, by specifying optional, we are reducing the scope. • By placing the requirements in metadata, they can be viewed with the permission tool (Permview.exe) and can adjust security policies

  27. Security Requests (cont.) [assembly: FileIOPermission(SecurityAction.RequestMinimum, All=“c:\temp”)] [assembly: SqlClientPermission(SecurityAction.RequestMinimum, Unrestricted=true)] Result: Granted permissions = (policies granted permissions) intersect (requested minimum union requested optional)-(refused permission) Alternately, built-in types: [assembly: PermissionSet(SecurityAction.RequestMinimum, Name=“FullTrust”); (or Internet, LocalIntranet, SkipVerification)

  28. Run-time Security Demands • Demand, Assert, Deny, PermitOnly • Declaratively (via attributes) or imperatively by programmatic settings. • Demand---Request CLR to perform the stack walk process [FileIOPermission(SecurityAction.Demand, Read=“c:\\”] Public class Class1 { public void dowork() { SocketPermission sockperm = new SocketPermission(NetworkAccess.Connect,TransportType.Tcp,www.cs.odu.edu); sockperm.Addpermission (SocketPermission(NetworkAccess.Connect,TransportType.Tcp,www.cs.virginia.edu); sockperm.Demand(); } }

  29. More on Demand() • If an assembly demands a permission it has not been granted, no exception is thrown!! • When a declarative demand fails, an exception is thrown to the direct caller • When an imperative demand fails, an exception is thrown within the method call demanding the permission • When a Demand call is encountered at run time, CLR picks up the demanded permission object and performs a stack walk along the assembly call chain.

  30. Stack Walk • To determine whether code is authorized to access a resource or perform an operation, the runtime's security system walks the call stack, comparing the granted permissions of each caller to the permission being demanded. If any caller in the call stack does not have the demanded permission, a security exception is thrown and access is refused. The stack walk is designed to help prevent luring attacks, in which less-trusted code calls highly trusted code and uses it to perform unauthorized actions. Demanding permissions of all callers at run time affects performance, but it is essential to help protect code from luring attacks by less-trusted code. To optimize performance, you can have your code perform fewer stack walks; however, you must be sure that you do not expose a security weakness whenever you do this. • The following illustration shows the stack walk that results when a method in Assembly A4 demands that its callers have permission P.

  31. Assert • RevertAssert • Deny • RevertDeny • PermitOnly • RevertPermitOnly

  32. Modify stack walk--Assert() • To stop stack walking and force a positive outcome of the Demand call. • It is a method that can be called on code access permission classes and on the PermissionSet class. • It enables your code (and downstream callers) to perform actions that your code has permission to do but its callers might not have permission to do. A security assertion changes the normal process that the runtime performs during a security check. When you assert a permission, it tells the security system not to check the callers of your code for the asserted permission. • Ex: An assembly accesses the windows registry via Microsoft.Win32.Registry class, which raises security demands at runtime. The assembly may not require all callers to have this ability. Declaratively: [PermissionSet (SecurityAction.Assert, Name= “FullTrust”)] Imperatively: Public void dowork() { FileIOPermission x = new FileIOPermission (FileIOPermissionAccess.Read, “c:\\”); x.Assert(); }

  33. Examplehttp://msdn.microsoft.com/en-us/library/vstudio/91wteedy(v=vs.100).aspxExamplehttp://msdn.microsoft.com/en-us/library/vstudio/91wteedy(v=vs.100).aspx • P1A represents the right to read .txt files on the C drive. • P1 represents the right to read all files on the C drive. • P1A and P1 are both FileIOPermissiontypes, and P1A is a subset of P1. • Assemblies E and F have been granted P1A permission. • Assembly C has been granted P1 permission. • Assemblies A and B have been granted neither P1 nor P1A permissions. • Method A is contained in assembly A, method B is contained in assembly B, and so on.

  34. Example (cont.) • Here, method A calls B, B calls C, C calls E, and E calls F. • C asserts permission to read files on the C drive (permission P1) • Method E demands permission to read .txt files on the C drive (permission P1A). • When the demand in F is encountered at run time, a stack walk is performed to check the permissions of all callers of F, starting with E. E has been granted P1A permission, so the stack walk proceeds to examine the permissions of C, where C's assertion is discovered. • Because the demanded permission (P1A) is a subset of the asserted permission (P1), the stack walk stops and the security check automatically succeeds. It does not matter that assemblies A and B have not been granted permission P1A. By asserting P1, method C ensures that its callers can access the resource protected by P1, even if the callers have not been granted permission to access that resource.

  35. Modify Stack Walk – Deny() • Deny has the opposite effect of Assert • http://msdn.microsoft.com/en-us/library/hk3b9142.aspx • It is used in situations where we want to prematurely stop a stack walk, and force a negative outcome. • Of course, the assembly calling Demand must be granted the demanded permission being checked by the stack walk. • Example (at class level): Denying permission to call an unmanaged code [SecurityPermission(SecurityAction.Deny, UnmanagedCode=false)] Public class Form1: …

  36. Example ((http://diranieh.com/NETSecurity/Writing%20Secure%20Class%20Libraries.htm •P1 represents the right to read all files on the C drive. •All five assemblies have been granted permission P1. •Method F in assembly F demands permission P1. •Method C in assembly C calls Deny on Permission P1:

  37. Modify Stack--PermitOnly • It is similar to Deny in the sense both cause stack walks to fail when they would otherwise succeed. • http://msdn.microsoft.com/en-us/library/system.security.codeaccesspermission.permitonly(VS.80).aspx • It is different from Deny --- Deny specifies permissions that will cause the stack walk to fail, but PermitOnly specifies the only permissions that do not cause the stack walk to fail. • Here, we have to specify what permissions will not determine a negative outcome (or continue stack walk unaffected). public MethodB() { try{ FileIOPermission p = new FileIOPermission(PermissionState.Unrestricted); P.PermitOnly(); } catch (SecurityException se) { // Handle exception} } Here, MethodB will cause a stack walk to terminate if methods further down the call stack demand any permissions other than a FileIOPermission. PermitOnly is ignored for a permission not granted because a demand for that permission will not succeed. However, if code lower on the call stack later calls Demand for that permission, a SecurityException is thrown when the stack walk reaches the code that tried to call PermitOnly. This is because the code that called PermitOnly has not been granted the permission, even though it called PermitOnly for that permission. The call stack is typically represented as growing down, so that methods higher in the call stack call methods lower in the call stack.

  38. References • http://www.codeproject.com/dotnet/UB_CAS_NET.asp • http://www.codeguru.com/columns/DotNet/article.php/c9253/ • http://www.codeguru.com/columns/dotnet/article.php/c9393/ • http://www.developer.com/security/article.php/3483866 • http://msdn2.microsoft.com/en-us/library/87x8e4d1.aspx • http://www.code-magazine.com/Article.aspx?quickid=0405031 • www.theserverside.net/articles/ content/PracticalDotNet2/PracticalDotNet2Ch6.pdf • geekswithblogs.net/claeyskurt/Rss.aspx

  39. What about .Net 4? • With all the changes in the security system of .NET 4, the question frequently arises “so, is CAS dead now?”. • One of the reasons that this question comes up so frequently, is that the term CAS in the .NET 1 security model was overloaded to refer to many different aspects of the security system: • CAS policy – policy levels, code groups, and of course our old friend caspol.exe • CAS enforcement – primarily the act of demanding and asserting permissions • CAS permissions – granted by CAS policy or a host to set the level of operations that an application can perform

  40. Problems with CAS There are many problems with CAS policy. • There are versioning problems. • The host doesn’t have control over the policy applied to the code it is hosting. • Enterprise administrators don’t have a good way to deploy CAS policy updates. • CAS policy caused managed applications to run differently from native applications, often in confusing and undesirable ways. • And of course, there’s the general complexity and difficulty of use.

  41. Remedy • For these reasons, in v4 of the CLR, CAS policy has been deprecated and policy decisions are instead left entirely up to the host of an application. • However, the other security mechanisms that fell under the name CAS, which allow hosts to configure AppDomains to host sandboxed code and allow library authors to write a safe library exposing services to partial trust absolutely still exist and are supported. • For instance, when a host sets up a sandboxed AppDomain to run code in, it does this by figuring out what grant set should be given to an application and supplying that grant as a set of permissions – the exact same permissions that have been used since v1 of the .NET Framework. Custom permissions can still be created by hosts or library authors to protect their libraries, and assemblies and AppDomains still receive permission objects in their grant sets. • Similarly, permissions demands are still alive and well, and are one of the most common ways that safe critical APIs in will check to ensure that the sandbox they are running in supports a given operation. For example, opening a file is a security safe critical operation which demands FileIOPermission to ensure that the host has setup the current sandbox with permission to access the requested file.

  42. Even though we’ve moved away from CAS policy, the CLR still provides mechanisms for partially trusted code to be setup and run. • A lot of our work with security transparency was to make it safer for library authors to expose their code to partial trust. • The new SecAnnotate tool was designed exactly to help ensure that more libraries could be safely exposed in a partial trust sandbox.

  43. Security Transparent Code • Security policy was a key element in previous versions of the .NET Framework. Starting with the .NET Framework 4, security policy is obsolete. The elimination of security policy is separate from security transparency. • Transparency is an enforcement mechanism that separates code that runs as part of the application from code that runs as part of the infrastructure. • Transparency draws a barrier between code that can do privileged things (critical code), such as calling native code, and code that cannot (transparent code). Transparent code can execute commands within the bounds of the permission set it is operating in, but cannot execute, derive from, or contain critical code. • The primary goal of transparency enforcement is to provide a simple, effective mechanism for isolating different groups of code based on privilege. Within the context of the sandboxing model, these privilege groups are either fully trusted (that is, not restricted) or partially trusted (that is, restricted to the permission set granted to the sandbox). • Transparency is enforced by the just-in-time compiler and remains in effect regardless of the grant set for an assembly, including full trust. • Transparency was introduced in the .NET Framework version 2.0 to simplify the security model, and to make it easier to write and deploy secure libraries and applications.

  44. Security Transparent Code (cont.) • Specifying the Transparency level: The assembly-level SecurityRulesAttribute attribute explicitly selects the SecurityRuleSet rules that the assembly will follow. The rules are organized under a numeric level system, where higher levels mean tighter enforcement of security rules. • The levels are as follows: • Level 2 (Level2) – the .NET Framework 4 transparency rules. • Level 1 (Level1) – the .NET Framework 2.0 transparency rules. • The primary difference between the two transparency levels is that level 1 does not enforce transparency rules for calls from outside the assembly and is intended only for compatibility.

  45. Level 2 Transparency • Level 2 transparency was introduced in the .NET Framework 4. The three tenets of this model are transparent code, security-safe-critical code, and security-critical code. • Transparent code, regardless of the permissions it is granted (including full trust), can call only other transparent code or security-safe-critical code. If the code is partially trusted, it can only perform actions that are allowed by the domain’s permission set. Transparent code cannot do the following: • Perform an Assert operation or elevation of privilege. • Contain unsafe or unverifiable code. • Directly call critical code. • Call native code or code that has the SuppressUnmanagedCodeSecurityAttribute attribute. • Call a member that is protected by a LinkDemand. • Inherit from critical types. • In addition, transparent methods cannot override critical virtual methods or implement critical interface methods. • Security-safe-critical code is fully trusted but is callable by transparent code. It exposes a limited surface area of full-trust code. Correctness and security verifications happen in safe-critical code. • Security-critical code can call any code and is fully trusted, but it cannot be called by transparent code.

  46. Level 1 Transparency • The level 1 transparency model was introduced in the .NET Framework version 2.0 to enable developers to reduce the amount of code that is subject to a security audit. Code that is identified as transparent does not require a high degree of security auditing. • Level 1 transparency states that the transparency enforcement is limited to within the assembly. In other words, any public types or members that are identified as security-critical are security-critical only within the assembly. If you want to enforce security for those types and members when they are called from outside the assembly, you must use link demands for full trust. If you do not, publicly visible security-critical types and members are treated as security-safe-critical and can be called by partially trusted code outside the assembly. • The level 1 transparency model has the following limitations: • Security-critical types and members that are public are accessible from security-transparent code. • The transparency annotations are enforced only within an assembly. • Security-critical types and members must use link demands to enforce security for calls from outside the assembly. • Inheritance rules are not enforced. • The potential exists for transparent code to do harmful things when run in full trust.

More Related