Code Access Security

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

description

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 - PowerPoint PPT Presentation

Transcript of Code Access Security

Page 1: Code Access Security

Code Access Security

CS 795

Chapters 5-9 (O’Reilly Book)

Chapter 13 (Barry Dorrans)

Page 2: Code Access Security

References

Videos: – http://www.youtube.com/watch?v=qNnOi5xi9KM– http://www.codeproject.com/Articles/120911/CAS-Code-access-security-NET-Se

curity-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

Page 3: Code Access Security

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.cer creates 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

Page 4: Code Access Security

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

Page 5: Code Access Security

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

Assembly1 Assembly2

App Domain 1

Assembly3

App Domain 2

Page 6: Code Access Security

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

Page 7: Code Access Security

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

Page 8: Code Access Security

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.

Page 9: Code Access Security

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

Page 10: Code Access Security

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.

Page 11: Code Access Security

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.

Page 12: Code Access Security

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.

Page 13: Code Access Security

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>

...

Page 14: Code Access Security

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 originHash (Cryptographic hash) Within assemblyPublisher (Authenticode signature) Within assemblySite (Site of origin: http://www..) Assembly originStrong name (cryptographically strong) Within assemblyURL (URL of origin) Assembly originZone (Zone of origin such as internet zone) Assembly origin

Page 15: Code Access Security

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);

Page 16: Code Access Security

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

Page 17: Code Access Security

CAS Permissions (cont.)Resources Accessed Required Permissions

DNS directory DnsPermission

Environment variables EnvironmentPermission

Event log EventLogPermission

File dialog FileDialogPermission

File system FileIOPermission

Isolated file storage IsolatedStoragePermission

Key containers KeyContainerPermission

Message queues MessageQueuePermission

Network information and traffic statistics

NetworkInformationPermission

OLE DB data sources OleDbPermission

Performance counters PerformanceCounterPermission

Printers PrintingPermission

Page 18: Code Access Security

CAS Permissions (cont.)Resources Accessed Required Permissions

Reflection ReflectionPermission

Registry RegistryPermission

Security SecurityPermission

SMTP servers SmtpPermission

Sockets SocketsPermission

SQL Server notifications SqlNotificationPermission

SQL Server SqlClientPermission

Stores containing X.509 certificates StorePermission

User interfaces and clipboard UIPermission

Web services (and other HTTP Internet resources)

WebPermission

Page 19: Code Access Security

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

Page 20: Code Access Security

CAS Policies (cont.)

http://www.icodeguru.com/dotnet/core.c.sharp.and.dot.net/0131472275/ch15lev1sec3.html

Page 21: Code Access Security

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.

Page 22: Code Access Security
Page 23: Code Access Security
Page 24: Code Access Security

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)}

Page 25: Code Access Security

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

Page 26: Code Access Security

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

Page 27: Code Access Security

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.

Page 28: Code Access Security

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

Page 29: Code Access Security

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)

Page 30: Code Access Security

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();}}

Page 31: Code Access Security

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.

Page 32: Code Access Security

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.

Page 33: Code Access Security
Page 34: Code Access Security
Page 35: Code Access Security

• Assert

• RevertAssert

• Deny

• RevertDeny

• PermitOnly

• RevertPermitOnly

Page 36: Code Access Security

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();

}

Page 37: Code Access Security

Examplehttp://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 FileIOPermission types, 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.

Page 38: Code Access Security

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.

Page 39: Code Access Security

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: …

Page 40: Code Access Security

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:

Page 41: Code Access Security

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.

Page 42: Code Access Security

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

Page 43: Code Access Security

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

Page 44: Code Access Security

Problems with CASThere 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.

Page 45: Code Access Security

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.

Page 46: Code Access Security

• 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.

Page 47: Code Access Security

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.

Page 48: Code Access Security

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.

Page 49: Code Access Security

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.

Page 50: Code Access Security

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.

Page 51: Code Access Security

Enforcing Transparency

• Transparency rules are not enforced until transparency is calculated. At that time, an InvalidOperationException is thrown if a transparency rule is violated.

• The time that transparency is calculated depends on multiple factors and cannot be predicted. It is calculated as late as possible. In the .NET Framework 4, assembly-level transparency calculation occurs sooner than it does in the .NET Framework 2.0.

• The only guarantee is that transparency calculation will occur by the time it is needed. This is similar to how the just-in-time (JIT) compiler can change the point when a method is compiled and any errors in that method are detected.

• Transparency calculation is invisible if your code does not have any transparency errors.

Page 52: Code Access Security

What are the changes in .NET 4.0 security model & What is sandboxing?

• CAS is completely deprecated in .NET 4.0 and there are 2 big changes done in .Net 4.0-

• 1. Granting of permission is dependent on the host and not the CAS Model.• 2. Introduction of Security Transparent Model. In this .NET Code is divided in 3 kinds

of code-– I. Security Critical Code – A full trusted code if known as Security Critical Code

and it has full access to my system. We need to ensure that this code is not called by unsafe code (Security Transparent Code).To create a code as Security Critical we have to put “[assembly: SecurityCritical()]” attribute in

Properties->Assemblyinfo.cs– II. Security Transparent Code – A code which you feel unsafe is known as

Security Transparent Code. To create a code as Security Critical we have to put “[assembly: SecurityTransparent()]” attribute in Properties->Assemblyinfo.cs

– III Security Safe Critical Code- A Bridge between Security Transparent Code and Security Critical Code to access Security Critical Code via Security Transparent Code.

Page 53: Code Access Security

• Security Transparent model is good if the code control is in our hand.

• Sandboxing- If you want to execute an untrusted third party DLL you can create your own “Appdomain” and assign permission set so that your third party DLL runs under a control environment. This process is called sandboxing.

• To implement Sandboxing first we have to create the object of “PermissionSet” and assign Permissions as per our requirement, then we have to create “AppDomain” object with the permissionset object we created and in this “AppDomain” object we will put that class in which we want to implement Sandboxing.

• http://www.codeproject.com/Articles/782803/What-are-the-Changes-in-NET-Security-Model-What-is