28
Code Access Security CS 795

Code Access Security

  • Upload
    calais

  • View
    47

  • Download
    1

Embed Size (px)

DESCRIPTION

Code Access Security. CS 795. Terminology--CLR. Common Language Runtime: The .NET Framework provides a runtime environment which runs the code and provides services that make the development process easier. The CLR sits at the very heart of managed code. - PowerPoint PPT Presentation

Citation preview

Page 1: Code Access Security

Code Access Security

CS 795

Page 2: Code Access Security

Terminology--CLR• Common Language Runtime:

– The .NET Framework provides a runtime environment which runs the code and provides services that make the development process easier.

– The CLR sits at the very heart of managed code. – It is the generalized multi-language, reflective execution engine on

which code originally written in various languages runs. – At a higher level, CLR is simply an engine that takes in Intermediate

Language (IL) instructions, translates them into machine instructions, and executes them.

– Although the common language runtime provides many standard runtime services, managed code is never interpreted.

– A feature called just-in-time (JIT) compiling enables all managed code to run in the native machine language of the system on which it is executing. The CLR shares much in common with a traditional operating system.

Page 3: Code Access Security

Terminology---Managed/Unmanaged Code

• Managed code is code that has its execution managed by the .NET Framework Common Language Runtime.

• The necessary information is encoded in an Intermediate Language (IL) and associated metadata, or symbolic information that describes all of the entry points and the constructs exposed in the IL (e.g., methods, properties) and their characteristics.

• There are many languages to choose from, since there are nearly 20 different languages provided by third parties – everything from COBOL to Camel – in addition to C#, J#, VB .Net, Jscript .Net, and C++ from Microsoft.

• Before the code is run, the IL is compiled into native executable code. And, since this compilation happens by the managed execution environment (or, more correctly, by a runtime-aware compiler that knows how to target the managed execution environment), the managed execution environment can make guarantees about what the code is going to do. It can insert traps and appropriate garbage collection hooks, exception handling, type safety, array bounds and index checking, and so forth.

• Unmanaged executable files are basically a binary image, x86 code, loaded into memory. The program counter gets put there and that’s the last the OS knows. There are protections in place around memory management and port I/O and so forth, but the system doesn’t actually know what the application is doing. Therefore, it can’t make any guarantees about what happens when the application runs.

Page 4: Code Access Security

Terminology--Assembly

• Assembly---Code that the common language runtime (CLR) executes.– Library assembly (contains classes others can

use); cannot be executed– Executable assembly– Windows executable assembly---specific to

GUI applications

Page 5: Code Access Security

Terminology---Strong Names• Strong name: Assemblies (especially the shared ones)

may have a strong name. Strong name consists of assembly’s:– name, version, culture metadata (Information on the culture or

language the assembly supports),– Cryptographic public key---cryptographic key pairs are randomly

created; the private key is used to generate the digital signature and the public key is used to later verify it

– Digital signature---based on hash code generated on the contents of the assembly

• Considered as a unique identification for an assembly.• Creating and verifying strong names: see pages 23-24,

26 (O’Reilly)

Page 6: 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 7: 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 8: 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 9: 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 10: Code Access Security

Terminology—Runtime Hosts• While CLR provides an execution environment for

managed code, we need software to first RUN CLR• Unmanaged code that loads and bootstraps CLR is

called a Runtime host• .Net Framework comes with three built-in runtime hosts:

– ASP.Net uses a single CLR to run all ASP.Net web applications; each web application is loaded into a separate application domain

– Internet Explorer uses a single CLR that executes all downloaded controls; one application domain for each web site from which controls are downloaded

– Windows shell also can run CLR. It creates a single application domain that the executable assembly and all referenced assemblies are loaded to.

Page 11: Code Access Security

What is 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 12: Code Access Security

More on CAS

• 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 13: 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 14: 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 15: 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 16: Code Access Security

CAS Policies• Three levels of security policies: Enterprise, Machine,

User (Fixed)• It is also possible to define an application-specific policy

and inject it into a newly created application domain• Final permissions granted by the CAS to an assembly

will be those granted in the intersection of the permissions

• The three policy configurations are stored in XML files<WinDir>\Microsoft.NET\Framework\<version>\config\enterprisesec.config <WinDir>\Microsoft.NET\Framework\<version>\config\security.config (for M/C)<Documents and Settings Path>\<Username>\Application dataMicrosoft\CLRSecurity

Config\<version>\security.config

Page 17: 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 18: 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 acces sto the

root code group object of the policy. From that, we can get an enumerator to access its child group uisng 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 19: 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 20: 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 (or UNC); 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 21: 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 22: 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

[assembly: FileIOPermission(SecurityAction.RequestMinimum, All=“c:\temp”)][assembly: SqlClientPermission(SecurityAction.RequestMinimum, Unrestricted=true)] 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 23: 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 24: 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 25: Code Access Security

Modify stack walk--Assert()• To stop stack walking and force a positive outcome of the Demand

call.• 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 26: 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 27: 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 28: 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