Mar 26, 2015
Security for DevelopersSecurity for DevelopersCode Access SecurityCode Access Security
Steven Borg & Richard HundhausenSteven Borg & Richard HundhausenAccentient, IncAccentient, Inc
OverviewOverview
Overview of Code-Access Overview of Code-Access SecuritySecurity
Code Access Permissions Code Access Permissions
Imperative vs. Declarative Imperative vs. Declarative Security OperationsSecurity Operations
Adding Permission RequestsAdding Permission Requests
Overview of Code-Access SecurityOverview of Code-Access SecurityThe BasicsThe Basics
EvidenceEvidence
Security PolicySecurity Policy
Code GroupsCode Groups
Security Policy LevelsSecurity Policy Levels
How Policy Levels Resolve How Policy Levels Resolve Permission GrantPermission Grant
Why Modify Security Policy?Why Modify Security Policy?
.NET Security Basics.NET Security BasicsEvidenceEvidence
Inputs to policy about codeInputs to policy about code
Strong name, site, zone, Authenticode Strong name, site, zone, Authenticode signaturesignature
PermissionsPermissionsSpecific authorizationsSpecific authorizations
Define a level of access to a resourceDefine a level of access to a resource
PolicyPolicyDetermines what code can doDetermines what code can do
Grants permissions to an assemblyGrants permissions to an assembly
What Is Evidence? What Is Evidence?
Data about an assembly the assembly loader uses to determine whether to load an assembly
Code location (URL) Zone of originSimple name
Authenticode signature Cryptographic hashStrong name
Forms of evidenceForms of evidence
Weaker StrongerRelative strength
EvidenceEvidence
The CLR examines evidence about code The CLR examines evidence about code to determine which permissions to grantto determine which permissions to grant
Evidence is presented by an assembly at Evidence is presented by an assembly at load time:load time:
From what site was this assembly obtained?From what site was this assembly obtained?
From what URL was this assembly obtained?From what URL was this assembly obtained?
From what Zone was this assembly obtained?From what Zone was this assembly obtained?
What’s the strong name of this assembly?What’s the strong name of this assembly?
Who signed this assembly?Who signed this assembly?
Evidence = input to policyEvidence = input to policy
Example: Info about a code assemblyExample: Info about a code assemblyStrong namesStrong namesPublisher identityPublisher identityHashHashLocation of origin (URL, IE zone, site)Location of origin (URL, IE zone, site)
Evidence is completely extensibleEvidence is completely extensibleAny object can be a piece of evidenceAny object can be a piece of evidence
Time of day, 3Time of day, 3rdrd party certification, etc. party certification, etc.
Only impacts grants if there is a code group Only impacts grants if there is a code group membership condition that tests for itmembership condition that tests for itAssemblies may contain untrusted evidenceAssemblies may contain untrusted evidence
cryptographicallycomputed/validated}
Policy Evaluation in the CLRPolicy Evaluation in the CLR
PolicyPolicy is the process of determining is the process of determining the set of the set of permissionspermissions to grant to code to grant to code based on based on evidenceevidence known about that known about that codecodeClassic trust management problemClassic trust management problem
Requiring end users to write programs to Requiring end users to write programs to express policies is not possibleexpress policies is not possibleCAS gives us an extensible model that CAS gives us an extensible model that can be easily administered.can be easily administered.
What Is a Security Policy?What Is a Security Policy?A security policy uses evidence to control A security policy uses evidence to control the permission set that an application the permission set that an application receivesreceives
A security policy matches a specific type A security policy matches a specific type of evidence to a permission setof evidence to a permission set
Permission sets:Permission sets:NothingNothing
ExecutionExecution
InternetInternet
LocalIntranetLocalIntranet
EverythingEverything
FullTrustFullTrust
Custom-definedCustom-defined
Evidence Based SecurityEvidence Based SecurityCode GroupsCode Groups
Assembly evidence is matched against a Assembly evidence is matched against a code group to gain permissionscode group to gain permissions
A code group has 2 attributesA code group has 2 attributesMembership conditionMembership condition
Permission setPermission set
An assembly can match more than one An assembly can match more than one code groupcode group
Evidence Based SecurityEvidence Based SecurityMembership ConditionsMembership Conditions
A code group may have only one A code group may have only one membership conditionmembership condition
It is comprised of an attribute that It is comprised of an attribute that matches evidence presented by an matches evidence presented by an assemblyassembly
Zone of originating assemblyZone of originating assembly
URL of originating assemblyURL of originating assembly
Digital signature of assembly publisherDigital signature of assembly publisher
Web site of the originating assemblyWeb site of the originating assembly
What Is a Code Group?What Is a Code Group?
Code groups
Permission GrantPermission GrantEvidenceEvidence
ContosoApp.dllPublisher = ContosoSNKey = 9F AD…
Read C:\ContosoRead C:\ContosoApp\TempWrite: C:\Contoso
Adatum.exePublisher = AdatumSN Key=25 98…
ExecuteRead:C:\Adatum
Definition: A code group matches evidence to a permission set. Definition: A code group matches evidence to a permission set.
Site = Adatum.comAll Printer AccessSite = Adatum.comAll Printer Access
Publisher=ContosoRead:C:\ContosoPublisher=ContosoRead:C:\Contoso
Zone=InternetInternetZone=InternetInternet
Zone=MyComputerExecuteZone=MyComputerExecute
SN Key=25 98…Read:C:\AdatumSN Key=25 98…Read:C:\Adatum
SN Key = 9F AD…Simple Name = ContosoAppRead:C:\..ContosoApp\Temp
SN Key = 9F AD…Simple Name = ContosoAppRead:C:\..ContosoApp\Temp
SN Key = 1A GG…Simple Name = NorthwindWrite:C:\Northwind
SN Key = 1A GG…Simple Name = NorthwindWrite:C:\Northwind
All CodeNothingAll CodeNothing
Security Policy LevelSecurity Policy Level
Four levels of policy in .NETFour levels of policy in .NETEnterpriseEnterprise
MachineMachine
UserUser
Application DomainApplication Domain
Each level contains code groups that map Each level contains code groups that map assemblies to permissionsassemblies to permissions
Policy evaluation is from Enterprise down Policy evaluation is from Enterprise down to Application Domainto Application Domain
Resolving Permission GrantResolving Permission Grant
Final permission is based on the Final permission is based on the intersection of permission sets intersection of permission sets granted at each policy levelgranted at each policy level
Code Code GroupGroupss
Membership Membership ConditionCondition Permission SetPermission Set
Code group Code group A(root group)A(root group) All codeAll code NothingNothing
Code group BCode group BPublisher is Publisher is Contoso.comContoso.com
Read access to files in C:\Read access to files in C:\ContosoContoso
Code group CCode group C Site is *.contoso.comSite is *.contoso.comRead access to Read access to USERNAME environment USERNAME environment variablevariable
Code group DCode group DStrong-name key is 45 Strong-name key is 45 9A EF9A EF
Read access to files in C:\Read access to files in C:\TEMPTEMP
Publisher is Contoso.comPublisher is Contoso.com
Strong-name key is 45 9A EFStrong-name key is 45 9A EF
Read access to files in Read access to files in C:\ContosoC:\Contoso
Read access to files in Read access to files in C:\TEMP C:\TEMP
Why Modify Security Policy?Why Modify Security Policy?Developers and testers:Developers and testers:
To verify application functionality To verify application functionality under a range of security policy under a range of security policy scenariosscenarios
To test application securityTo test application security
Systems administrators: Systems administrators: To apply security best practicesTo apply security best practices
To facilitate application deploymentTo facilitate application deployment
Administration ToolsAdministration Tools
The .Net Framework configuration tool The .Net Framework configuration tool can be used to modify and manage can be used to modify and manage security policysecurity policy
Mscorcfg.msc - Management Console Mscorcfg.msc - Management Console
The command-line tool caspol.exe can The command-line tool caspol.exe can be used to modify and managed be used to modify and managed security policysecurity policy
Security Policy AdministrationSecurity Policy Administration
The .Net Framework The .Net Framework configuration tool configuration tool can be used to can be used to modify and manage modify and manage security policysecurity policy
Tool update XML Tool update XML filesfiles
Security Policy AdministrationSecurity Policy Administration
Machine Policy Code Machine Policy Code GroupsGroups
•Each group defines a Each group defines a set of permissions set of permissions granted when an granted when an evidence match is evidence match is mademade
•Five code groups in Five code groups in default .NET Machine default .NET Machine PolicyPolicy
Security Policy AdministrationSecurity Policy Administration
Permission setsPermission sets
•Sets of permissions Sets of permissions referred to by the code referred to by the code groupsgroups
Using the Code-Access Using the Code-Access Security Policy ToolSecurity Policy Tool
Open the Visual Studio .NET command promptOpen the Visual Studio .NET command prompt11
Type a command indicating the policy level and what you want to seeType a command indicating the policy level and what you want to see33
Run Caspol.exeRun Caspol.exe22
Caspol policy_level what_to_showCaspol policy_level what_to_show
SwitchSwitch DescriptionDescription
-l-l List the code groups and List the code groups and permission setspermission sets
-lg-lg Display code groupsDisplay code groups
-lp-lp Display the permission setsDisplay the permission sets
SwitchSwitch DescriptionDescription
-a-a All policy levelsAll policy levels
-en-en EnterpriseEnterprise
-m-m MachineMachine
-u-u UserUser
Policy Configuration Policy Configuration ToolsTools
Code Access PermissionsCode Access Permissions
Permissions represent access to a Permissions represent access to a protected resource or the ability to protected resource or the ability to perform a protected operationperform a protected operation
They are fundamental to CLR’s ability to They are fundamental to CLR’s ability to enforce security restrictions on enforce security restrictions on managed codemanaged code
Restricted ResourcesRestricted Resources
Directory ServicesDirectory Services
DNSDNS
EnvironmentEnvironment
Event LogEvent Log
File DialogFile Dialog
File I/OFile I/O
Isolated StorageIsolated Storage
Message QueueMessage Queue
OLE DBOLE DB
PrintingPrinting
ReflectionReflection
SecuritySecurity
SocketSocket
UIUI
WebWeb
CodeAccessPermission ClassCodeAccessPermission Class
All code access permissions derive All code access permissions derive from CodeAccessPermissionfrom CodeAccessPermission
CodeAccessPermission defines the CodeAccessPermission defines the underlying structure of all code access underlying structure of all code access permissionspermissions
Code access permissions use a stack Code access permissions use a stack walk to ensure that all callers of the walk to ensure that all callers of the code have been granted a permissioncode have been granted a permission
SecurityExceptionSecurityException
SecurityException forms the basis of all SecurityException forms the basis of all security violations committed by code security violations committed by code running in the CLRrunning in the CLR
If the system denies a request, it does If the system denies a request, it does so by throwing an exception of type so by throwing an exception of type SecurityExceptionSecurityException
SecurityExceptions represent a virtual SecurityExceptions represent a virtual slap-on-the-wrist; “Don’t do that…”slap-on-the-wrist; “Don’t do that…”
Code Access PermissionsCode Access Permissions
Code access permissions support the Code access permissions support the following methods:following methods:
AssertAssert
DemandDemand
DenyDeny
PermitOnlyPermitOnly
RevertAllRevertAll
RevertAssertRevertAssert
RevertDenyRevertDeny
RevertPermitOnlyRevertPermitOnly
AssertAssert
Calling Assert prevents a stack walk Calling Assert prevents a stack walk originating lower in the call stack from originating lower in the call stack from proceeding up the call stack beyond the proceeding up the call stack beyond the code that calls this methodcode that calls this method
Disables the stack walk for the frameDisables the stack walk for the frame
ALWAYS VERIFY YOUR ASSERTS!ALWAYS VERIFY YOUR ASSERTS!
Security system Grant access?
Call stackCall stack
Call to NUMBER_Of_PROCESSORS
SomeAssemblyGrant: Execute
.NET Framework AssemblyGrant: read the system variable:
NUMBER_OF_PROCESSORS
Call to NUMBER_Of_PROCESSORS
FinanceCalculatorAssert: Read system variable:NUMBER_OF_PROCESSORS
Permission Asserts Permission Asserts The Assert method The Assert method reduces the reach of the reduces the reach of the permission demand permission demand Use it to couple a .NET Use it to couple a .NET Framework application Framework application to unmanaged codeto unmanaged codeCaution: Using an Assert Caution: Using an Assert can create a security can create a security vulnerabilityvulnerability
The Assert method The Assert method reduces the reach of the reduces the reach of the permission demand permission demand Use it to couple a .NET Use it to couple a .NET Framework application Framework application to unmanaged codeto unmanaged codeCaution: Using an Assert Caution: Using an Assert can create a security can create a security vulnerabilityvulnerability
Permission Demand
DemandDemand
Forces a SecurityException at run time Forces a SecurityException at run time if all callers higher in the call stack have if all callers higher in the call stack have not been granted the permission not been granted the permission specified by the current instancespecified by the current instance
Can be used to test for available Can be used to test for available permissionspermissions
Permission DemandsPermission Demands
11 22 33
YourAssembly(Execute + WriteFile)YourAssembly(Execute + WriteFile)
SomeAssembly(Execute only)SomeAssembly(Execute only)
.NET Framework Assembly(Execute + WriteFile)
.NET Framework Assembly(Execute + WriteFile)
WriteFile
WriteFile
1. An assembly requests Write 1. An assembly requests Write access via your assembly access via your assembly
2. Your assembly passes Write 2. Your assembly passes Write request to a .NET Framework request to a .NET Framework assemblyassembly
3. Security system issues a 3. Security system issues a permission demand up the stackpermission demand up the stack
4. Security system either grants 4. Security system either grants access or throws an exception access or throws an exception
1. An assembly requests Write 1. An assembly requests Write access via your assembly access via your assembly
2. Your assembly passes Write 2. Your assembly passes Write request to a .NET Framework request to a .NET Framework assemblyassembly
3. Security system issues a 3. Security system issues a permission demand up the stackpermission demand up the stack
4. Security system either grants 4. Security system either grants access or throws an exception access or throws an exception
Permission demand
Security exception Access denied
Security exception Access deniedGrant access?Grant access?
The Call Stack
Security system
DenyDeny
Prevents callers higher in the call stack Prevents callers higher in the call stack from accessing a resource specified by from accessing a resource specified by the current instancethe current instance
Pseudo-sandboxingPseudo-sandboxing
PermitOnlyPermitOnly
Prevents callers higher in the call stack Prevents callers higher in the call stack from using the code that calls this from using the code that calls this method to access all resources except method to access all resources except for the resource specified by the current for the resource specified by the current instanceinstance
Similar to Deny in that both cause stack Similar to Deny in that both cause stack walks to fail when they would otherwise walks to fail when they would otherwise succeedsucceed
However, However, PermitOnly specifies permissions PermitOnly specifies permissions that do not cause the stack walk to failthat do not cause the stack walk to fail
RevertAllRevertAll
Causes all previous overrides for the Causes all previous overrides for the current frame to be removed and no current frame to be removed and no longer in effectlonger in effect
Rolls back all overrides made for the Rolls back all overrides made for the current framecurrent frame
RevertAssert, RevertDeny, and RevertAssert, RevertDeny, and RevertPermitOnlyRevertPermitOnly
Each of these methods causes any Each of these methods causes any previous Assert/Deny/PermitOnly for the previous Assert/Deny/PermitOnly for the current frame to be removed and no current frame to be removed and no longer in effectlonger in effect
Other Security Checks Other Security Checks
To perform this operation:To perform this operation: Use this method:Use this method:Compare two permissions of Compare two permissions of the same classthe same class IsSubsetOfIsSubsetOf
Combine and intersect Combine and intersect permissionspermissions
UnionUnion
IntersectIntersect
Imperative vs. Declarative Imperative vs. Declarative DemandsDemands
ImperativeImperativeFileIOPermission p = new FileIOPermission(FileIOPermission p = new FileIOPermission(
FileIOPermissionAccess.Write, f);FileIOPermissionAccess.Write, f);
p.Demand();p.Demand();
DeclarativeDeclarative[FileIOPermission(SecurityAction.Demand, [FileIOPermission(SecurityAction.Demand,
Read = ”c:\\temp”)]Read = ”c:\\temp”)]
public void foo() {public void foo() {
// class does something with c:\temp// class does something with c:\temp
}}
Imperative DemandsImperative Demands
Allows security checks to vary by control Allows security checks to vary by control flow or method stateflow or method state
Initiated with call to Initiated with call to Demand()Demand()
public File(String fileName) { //Fully qualify the path for the security check String fullPath =
Directory.GetFullPathInternal(fileName); new FileIOPermission(FileIOPermissionAccess.Read,
fullPath).Demand(); //The above call will either pass or throw a //SecurityException //[…rest of function…]}
Declarative DemandsDeclarative Demands
Specified using Custom AttributesSpecified using Custom AttributesStored in the assembly’s metadataStored in the assembly’s metadata
Permission State must be known at Permission State must be known at compile timecompile time
Can be viewed with PermView SDK ToolCan be viewed with PermView SDK Tool
[FileIOPermission(SecurityAction.Demand, Write = "c:\\temp")]
public void foo() { // class does something with c:\temp}
Demanding a Permission Demanding a Permission ImperativelyImperatively
To demand a permission imperatively:To demand a permission imperatively:
Create a new instance of a permission objectCreate a new instance of a permission object11
Call the object’s Demand method in a try blockCall the object’s Demand method in a try block33
Set the properties on the permission objectSet the properties on the permission object22
Asserting a Permission Asserting a Permission ImperativelyImperatively
To assert a permission imperatively:To assert a permission imperatively:
Create an instance of a permission objectCreate an instance of a permission object11
Call the Assert method on itCall the Assert method on it22
Using Declarative PermissionsUsing Declarative Permissions
Use attributes to set permissions Use attributes to set permissions declaratively:declaratively:
AssertAssert
DemandDemand
DenyDeny
PermitPermit
Identity PermissionsIdentity Permissions
Identity permissions are Identity permissions are associated with the evidence for associated with the evidence for the assemblythe assembly
Identity permissions allow Identity permissions allow checking of:checking of:
PublisherPublisher
Strong nameStrong name
SiteSite
URLURL
ZoneZone
Link DemandsLink DemandsA link demandA link demand specifies the set of specifies the set of permissions that direct callers must permissions that direct callers must have to call your codehave to call your code
A link demand is checked during JIT A link demand is checked during JIT compilation of the callercompilation of the caller
A security exception results if the A security exception results if the caller lacks sufficient permissioncaller lacks sufficient permission
Especially useful is a link demand Especially useful is a link demand that requires identity permissionsthat requires identity permissions
Allows you to create a private assembly Allows you to create a private assembly that can only be called by assemblies that can only be called by assemblies with the same publisher with the same publisher
Inheritance DemandsInheritance Demands
An inheritance demand may be An inheritance demand may be placed on a class or a methodplaced on a class or a method
LevelLevelAn inheritance demand requires An inheritance demand requires
that code have a specified that code have a specified permission topermission to
ClassClass Inherit from the classInherit from the class
MethodMethod Override the methodOverride the method
Permission RequestsPermission RequestsA permission request specifies those A permission request specifies those permissions an assembly requires to run, permissions an assembly requires to run, can run, and should not runcan run, and should not run
Minimum permissions (RequestMinimum)Minimum permissions (RequestMinimum)
The minimum set of permissions that the The minimum set of permissions that the code needs code needs to runto run
Optional permissions (RequestOptional)Optional permissions (RequestOptional)
Permissions that code can use but can run Permissions that code can use but can run effectively withouteffectively without
Refused permissions (RequestRefused)Refused permissions (RequestRefused)
Permissions that code should never be Permissions that code should never be grantedgranted
The .NET Framework processes assembly The .NET Framework processes assembly permission requests at load timepermission requests at load time
Adding a Permission RequestAdding a Permission Request
To request multiple permissions on To request multiple permissions on the same assemblythe same assembly
To request a named permission setTo request a named permission set[assembly:PermissionSet(SecurityAction.RequestMinimum,Name = "FullTrust")][assembly:PermissionSet(SecurityAction.RequestMinimum,Name = "FullTrust")]
[assembly:SecurityPermission(SecurityAction.RequestMinimum,UnmanagedCode = True)][assembly:SecurityPermission(SecurityAction.RequestMinimum,UnmanagedCode = True)]
Best PracticesBest Practices““Sandboxing” codeSandboxing” code
Rely on Security PoliciesRely on Security Policies
Assert appropriatelyAssert appropriately
Strong Name your assembliesStrong Name your assemblies
Sandboxing CodeSandboxing CodeDo not use “Deny” to sandbox code Do not use “Deny” to sandbox code securitysecurity
Because the hacker can use “Assert” to Because the hacker can use “Assert” to bypass your limitationbypass your limitation
Rely on security policiesRely on security policiesEnterprise, machine-level and user Enterprise, machine-level and user policiespolicies
Dynamically with AppDomainsDynamically with AppDomainsAppDomain.CreateDomainAppDomain.CreateDomainmyDomain.SetAppDomainPolicymyDomain.SetAppDomainPolicymyDomain.Load(<assembly>)myDomain.Load(<assembly>)myDomain.CreateInstanceAndUnwrapmyDomain.CreateInstanceAndUnwrap
Potentially Dangerous PermissionsPotentially Dangerous PermissionsSecurityPermission SecurityPermission
UnmanagedCode – allows managed code to call UnmanagedCode – allows managed code to call into unmanagedinto unmanagedSkipVerification – without verification, code can SkipVerification – without verification, code can do anything. do anything. ControlEvidence – allows security policy to be ControlEvidence – allows security policy to be fooled. fooled. ControlPolicy – can disable security or change ControlPolicy – can disable security or change policypolicyControlAppDomain – can change probing paths, ControlAppDomain – can change probing paths, load anythingload anythingSerializationFormatter –can circumvent SerializationFormatter –can circumvent accessibilityaccessibilityControlPrincipal –can trick role-based security. ControlPrincipal –can trick role-based security. ControlThread –security state associated with ControlThread –security state associated with threads.threads.
Potentially Dangerous PermissionsPotentially Dangerous Permissions
ReflectionPermission ReflectionPermission MemberAccess – defeats accessibility MemberAccess – defeats accessibility mechanisms (can use private members). mechanisms (can use private members).
FileIOPermissionFileIOPermission
RegistryPermissionRegistryPermission
When to Assert?When to Assert?
Clearly, the ability to assert permissions Clearly, the ability to assert permissions can be abusedcan be abused
Unfortunately, the issue regards Unfortunately, the issue regards assertions is a bit cloudyassertions is a bit cloudy
Unmanaged code requires assertionsUnmanaged code requires assertions
““Gatekeeper” classesGatekeeper” classes
Rule: Demand before AssertRule: Demand before Assert
Rule: Always code review your Rule: Always code review your assertions!assertions!
ResourcesResources
Steve’s Blog: http://blog.accentient.com
Rich’s Blog: http://blog.hundhausen.com
Security Book / Wiki: http://www.winsecguide.net
Your FeedbackYour Feedbackis Important!is Important!
Please Fill Out a Survey forPlease Fill Out a Survey forThis Session on CommNetThis Session on CommNet
© 2005 Microsoft Corporation. All rights reserved.This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.