37
Understanding .NET Understanding .NET Framework Security Framework Security David LeBlanc David LeBlanc Microsoft Office Microsoft Office

Framework Security David LeBlanc Microsoft Office

Embed Size (px)

DESCRIPTION

Why Is This Important? Understanding managed code security will help you make better decisions about when to use managed vs. unmanaged code Framework security can cause bugs Framework security can cause bugs Code running locally isn’t the same as code running from a share Code running locally isn’t the same as code running from a share

Citation preview

Page 1: Framework Security David LeBlanc Microsoft Office

Understanding .NET Understanding .NET Framework SecurityFramework Security

David LeBlancDavid LeBlancMicrosoft OfficeMicrosoft Office

Page 2: Framework Security David LeBlanc Microsoft Office

AgendaAgenda• .NET Framework Security Fundamentals.NET Framework Security Fundamentals

• EvidenceEvidence• PermissionsPermissions• PolicyPolicy

• .NET Framework security administration.NET Framework security administration• Needed for setupNeeded for setup

• When to use .NET Framework vs. core When to use .NET Framework vs. core OS securityOS security

Page 3: Framework Security David LeBlanc Microsoft Office

Why Is This Important?Why Is This Important?Understanding managed code security Understanding managed code security

will help you make better decisions will help you make better decisions about when to use managed vs. about when to use managed vs. unmanaged codeunmanaged code

• Framework security can cause bugsFramework security can cause bugs• Code running locally isn’t the same as Code running locally isn’t the same as

code running from a sharecode running from a share

Page 4: Framework Security David LeBlanc Microsoft Office

What .NET Is and Isn’tWhat .NET Is and Isn’t• .NET .NET ISIS a great new toolset a great new toolset• Can be used to solve previously Can be used to solve previously

unmanageable security problemsunmanageable security problems• Largely eliminates buffer overrunsLargely eliminates buffer overruns• Allows a system or host application to Allows a system or host application to

restrict the capabilities of managed restrict the capabilities of managed codecode

Page 5: Framework Security David LeBlanc Microsoft Office

.NET .NET IS NOTIS NOT a Silver a Silver BulletBullet• A majority of security mistakes are A majority of security mistakes are language-independentlanguage-independent

• Bad design is still bad designBad design is still bad design• New capabilities provided by .NET can New capabilities provided by .NET can

be misusedbe misused• New, improved ways to make security New, improved ways to make security

mistakes!mistakes!• Code running as fully trusted is just as Code running as fully trusted is just as

dangerous as a native binary!dangerous as a native binary!

Page 6: Framework Security David LeBlanc Microsoft Office

User and Code Identity User and Code Identity SecuritySecurity• Classic OS security is based on limiting Classic OS security is based on limiting the capabilities of a user or groupthe capabilities of a user or group• Still an effective mechanismStill an effective mechanism• Does not help when code is either untrusted Does not help when code is either untrusted

or semi-trustedor semi-trusted• Code Identity SecurityCode Identity Security

• Allows a user or admin to define the level of Allows a user or admin to define the level of trust granted based on things we know about trust granted based on things we know about the codethe code

• To be most effective, use both To be most effective, use both approaches togetherapproaches together

Page 7: Framework Security David LeBlanc Microsoft Office

How Permissions Are How Permissions Are ResolvedResolved

Assembly

HostingApp Domain

Policy

Evidence

Permissions

Page 8: Framework Security David LeBlanc Microsoft Office

How Permissions Are UsedHow Permissions Are Used

Assembly

Invokes a method

RequiredPermissions

PermissionsGranted

Exception! Allowed!

Page 9: Framework Security David LeBlanc Microsoft Office

Quick .NET Framework Quick .NET Framework RefreshRefresh• AssembliesAssemblies

• LogicalLogical collection of one or more EXE or collection of one or more EXE or DLL files containing code & resources DLL files containing code & resources

• Can be a single file (EXE or DLL)Can be a single file (EXE or DLL)• Can be a logical (not physcial) collection of Can be a logical (not physcial) collection of

more than one file residing in the same more than one file residing in the same directorydirectory

• Stored in either the Global Assembly Stored in either the Global Assembly Cache, or the local app directoryCache, or the local app directory

Page 10: Framework Security David LeBlanc Microsoft Office

Identifying Assemblies – Identifying Assemblies – Stong NamesStong Names

• An assembly contains a An assembly contains a manifestmanifest• Describes global attributes and layoutDescribes global attributes and layout• Publisher, assembly name, version, …Publisher, assembly name, version, …• Contains the public key of the signerContains the public key of the signer

• A strong named assembly is signedA strong named assembly is signed• Signatures don’t use a third partySignatures don’t use a third party• No automatic means to associate signature key No automatic means to associate signature key

with the publisherwith the publisher• No revocation mechanismNo revocation mechanism

Page 11: Framework Security David LeBlanc Microsoft Office

Uses of Strong NamesUses of Strong Names• Only strong named assemblies can be Only strong named assemblies can be

loaded into the global catalogueloaded into the global catalogue• Strong names allow multiple versions of an Strong names allow multiple versions of an

assembly to co-existassembly to co-exist• No “DLL Hell”No “DLL Hell”

• Protects against tamperingProtects against tampering• Permissions can be assigned to strong Permissions can be assigned to strong

namesnames• Useful for interface and inheritance restrictionsUseful for interface and inheritance restrictions

• Required to allow partially trusted callersRequired to allow partially trusted callers

Page 12: Framework Security David LeBlanc Microsoft Office

Application DomainsApplication Domains

Operating System

Job Object

Process

Native Execution

.NET Framework

App Domain

Assembly

Assembly

Managed Code

Page 13: Framework Security David LeBlanc Microsoft Office

Application DomainsApplication Domains• App domains contain one or more assembliesApp domains contain one or more assemblies

• App domain created by a hostApp domain created by a host• If a specific app domain isn’t created, If a specific app domain isn’t created,

assemblies get loaded into the default domainassemblies get loaded into the default domain• Useful when you want to provide fewer rights Useful when you want to provide fewer rights

than provided by default policythan provided by default policy• Browser HostBrowser Host• Custom Host Custom Host • Server Host (ASP.NET)Server Host (ASP.NET)

• Also used when loading an assembly you’d Also used when loading an assembly you’d like to unload laterlike to unload later

Page 14: Framework Security David LeBlanc Microsoft Office

EvidenceEvidence• Evidence applies to the code, not the Evidence applies to the code, not the

user running the codeuser running the code• Applied to an assembly or app domainApplied to an assembly or app domain• Two types of evidenceTwo types of evidence

• Host-provided evidenceHost-provided evidence• Assembly-provided evidenceAssembly-provided evidence

• Evidence changes when code is run Evidence changes when code is run from different places!from different places!

Page 15: Framework Security David LeBlanc Microsoft Office

Host-Provided EvidenceHost-Provided Evidence• Application DirectoryApplication Directory

• Directory the code is running fromDirectory the code is running from• HashHash

• Typically a SHA1 or MD5 hash of the assemblyTypically a SHA1 or MD5 hash of the assembly• PermissionRequestEvidencePermissionRequestEvidence

• Permissions requested by the assemblyPermissions requested by the assembly• Only visible during policy resolutionOnly visible during policy resolution

• PublisherPublisher• Authenticode signatureAuthenticode signature

Page 16: Framework Security David LeBlanc Microsoft Office

Host-Provided Evidence Host-Provided Evidence (2)(2)• SiteSite

• Web site of originWeb site of origin• StrongNameStrongName

• A cryptographically strong binding of a name, A cryptographically strong binding of a name, version and cultureversion and culture

• URLURL• URl of originURl of origin

• ZoneZone• IE security zone for the assemblyIE security zone for the assembly

Page 17: Framework Security David LeBlanc Microsoft Office

Evidence ExampleEvidence ExampleHost Evidence:<Url>file://C:/projects/CSharpCruft/bin/Release/CSharpCruft.exe</Url>

<Zone>MyComputer</Zone>

Host Evidence:<Url>file://BYTEME/C$/projects/CSharpCruft/bin/Release/CSharpCruft.exe

<Zone>Intranet</Zone>

Local:

From a share:

Page 18: Framework Security David LeBlanc Microsoft Office

Assembly-Provided Assembly-Provided EvidenceEvidence• Allows an assembly to provide custom evidenceAllows an assembly to provide custom evidence

• Cannot override any default host-provided Cannot override any default host-provided evidenceevidence• If host evidence is included in an assembly it is ignored If host evidence is included in an assembly it is ignored

by the .NET runtimeby the .NET runtime• Can be any type of data, from a simple integer to Can be any type of data, from a simple integer to

a signed XML statementa signed XML statement

Page 19: Framework Security David LeBlanc Microsoft Office

Assigning PrivilegesAssigning Privileges• Security Policy maps code identity to Security Policy maps code identity to privilegesprivileges

• Evidence defines identityEvidence defines identity• Membership ConditionsMembership Conditions

• Represented by extensible objectsRepresented by extensible objects• Determines membership given evidence as inputDetermines membership given evidence as input

• Code GroupsCode Groups• Hierarchal mapping between policy and Hierarchal mapping between policy and membership conditionsmembership conditions

• Policy LevelsPolicy Levels• Contains a permission set, code group and “full Contains a permission set, code group and “full trust” assembly listtrust” assembly list

Page 20: Framework Security David LeBlanc Microsoft Office

Policy – Membership Policy – Membership ConditionsConditions

• Determines whether an assembly is a Determines whether an assembly is a member of a group based on evidencemember of a group based on evidence

• Implements IMembershipCondition Implements IMembershipCondition • Can be customized – useful with custom Can be customized – useful with custom

evidence classesevidence classes• Default membership condition classesDefault membership condition classes

• HashMembershipConditionHashMembershipCondition• SiteMembershipConditionSiteMembershipCondition• ZoneMembershipConditionZoneMembershipCondition• Etc, etc.Etc, etc.

Page 21: Framework Security David LeBlanc Microsoft Office

Policy – Code GroupsPolicy – Code Groups• Constructed from a membership condition and Constructed from a membership condition and

a PolicyStatementa PolicyStatement• PolicyStatement contains:PolicyStatement contains:

• PermissionSetPermissionSet• AttributesAttributes

• Exclusive – any assembly matching membership Exclusive – any assembly matching membership condition receives permissions only from this code condition receives permissions only from this code groupgroup

• LevelFinal – No lower level groups are evaluatedLevelFinal – No lower level groups are evaluated• All – Exclusive and LevelFinalAll – Exclusive and LevelFinal• Nothing – not Exclusive or LevelFinalNothing – not Exclusive or LevelFinal

Page 22: Framework Security David LeBlanc Microsoft Office

Policy – Policy LevelsPolicy – Policy Levels• Four Policy Levels exist:Four Policy Levels exist:

• EnterpriseEnterprise• MachineMachine• UserUser• App DomainApp Domain

• Resulting permissions are Resulting permissions are the intersection of the the intersection of the permissions from all permissions from all policiespolicies

• Allows lower levels to set Allows lower levels to set policies more restrictive policies more restrictive than upper levelsthan upper levels• Unless LevelFinal attribute Unless LevelFinal attribute

encounteredencountered

Page 23: Framework Security David LeBlanc Microsoft Office

Resolving PermissionsResolving Permissions• For each Policy LevelFor each Policy Level

• Membership conditions are resolvedMembership conditions are resolved• Permission set is intersection of permissions Permission set is intersection of permissions

for code groups for the assemblyfor code groups for the assembly• If LevelFinal is encountered, lower levels If LevelFinal is encountered, lower levels

are not evaluatedare not evaluated• Each lower level can reduce permissionsEach lower level can reduce permissions

• Lower levels cannot increase permissionsLower levels cannot increase permissions

Page 24: Framework Security David LeBlanc Microsoft Office

PermissionsPermissions• Types of Permissions:Types of Permissions:

• Code Access PermissionsCode Access Permissions• Standard permissions derived from Standard permissions derived from

System.Security.CodeAccessPermissionSystem.Security.CodeAccessPermission• Identity PermissionsIdentity Permissions

• Represents evidenceRepresents evidence• Zone evidence creates a Zone evidence creates a

ZoneIdentityPermissionZoneIdentityPermission• Custom PermissionsCustom Permissions

• Could be App Domain specificCould be App Domain specific

Page 25: Framework Security David LeBlanc Microsoft Office

Using PermissionsUsing Permissions• Granted by security policyGranted by security policy

• Policy states that any assembly that provides Policy states that any assembly that provides certain evidence is allowed specific permissionscertain evidence is allowed specific permissions

• Permission demandsPermission demands• Used by trusted code to require permissions of Used by trusted code to require permissions of

semi-trusted callerssemi-trusted callers

Page 26: Framework Security David LeBlanc Microsoft Office

Stating Permission Stating Permission RequirementsRequirements• Declarative Declarative

• Stored in an assembly’s metadataStored in an assembly’s metadata• Available at load timeAvailable at load time• Can be placed at class or method levelCan be placed at class or method level• Easily reviewed by a hostEasily reviewed by a host

• ImperativeImperative• Requires permissions at run-timeRequires permissions at run-time• Allows more complex logicAllows more complex logic

• Permission SetsPermission Sets• Any operation that can be performed on a single Any operation that can be performed on a single privilege can be performed on a setprivilege can be performed on a set• Increases performanceIncreases performance

Page 27: Framework Security David LeBlanc Microsoft Office

Walking the StackWalking the Stack• A Stack Walk is triggered when a A Stack Walk is triggered when a

permission is required to continuepermission is required to continue• Designed to overcome luring attacksDesigned to overcome luring attacks

• Ensures that the original caller has Ensures that the original caller has enough permissions to perform an actionenough permissions to perform an action

Page 28: Framework Security David LeBlanc Microsoft Office

Asserting PermissionsAsserting Permissions• Assert stops the stack walk in your code for Assert stops the stack walk in your code for

the permission assertedthe permission asserted• No effect on other permissionsNo effect on other permissions

• Must be used with careMust be used with care• Claims that you can allow semi-trusted Claims that you can allow semi-trusted

callers to perform higher-level actions safelycallers to perform higher-level actions safely

Page 29: Framework Security David LeBlanc Microsoft Office

Denying PermissionsDenying Permissions• Deny also stops the stack walk immediatelyDeny also stops the stack walk immediately

• Throws a security exception when encounteredThrows a security exception when encountered• Rarely useful in practice, except in testingRarely useful in practice, except in testing

• When creating custom permissions be sure and When creating custom permissions be sure and test negative casetest negative case

• PermitOnlyPermitOnly• Allows request only if the requested set of Allows request only if the requested set of

permissions is a subset of the allowed setpermissions is a subset of the allowed set• Can be useful in hosting applications and testingCan be useful in hosting applications and testing

Page 30: Framework Security David LeBlanc Microsoft Office

Class and Method Class and Method PermissionsPermissions• LinkDemand – used to restrict the LinkDemand – used to restrict the callers of public methodscallers of public methods

• InheritanceDemand – used to restrict InheritanceDemand – used to restrict which code can inherit from your which code can inherit from your assemblyassembly

Page 31: Framework Security David LeBlanc Microsoft Office

Design ScenariosDesign Scenarios• Security-neutral codeSecurity-neutral code

• Does nothing with the security subsystemDoes nothing with the security subsystem• Must typically be installed locallyMust typically be installed locally• Few advantages over native codeFew advantages over native code

• Non-reusable applicationNon-reusable application• Should take steps to ensure semi-trusted callers are Should take steps to ensure semi-trusted callers are blockedblocked

• Managed wrapper over native codeManaged wrapper over native code• Needs to be carefully validatedNeeds to be carefully validated• Similar problem to an ActiveX controlSimilar problem to an ActiveX control

• Library code that exposes protected resourcesLibrary code that exposes protected resources• Must take care to demand appropriate permissionsMust take care to demand appropriate permissions• Code and design must be carefully evaluatedCode and design must be carefully evaluated

Page 32: Framework Security David LeBlanc Microsoft Office

Development Development ConsiderationsConsiderations• Principle of Least PrivilegePrinciple of Least Privilege

• Ask for the permissions your assembly requiresAsk for the permissions your assembly requires• Explicitly refuse all other permissionsExplicitly refuse all other permissions• Protects you from coding and design errors by limiting Protects you from coding and design errors by limiting

your assemblyyour assembly• Read The Fine Manual!Read The Fine Manual!

• Read “Secure Coding Guidelines” in .NET Framework Read “Secure Coding Guidelines” in .NET Framework SDKSDK

• User input is just as evil as it was with native User input is just as evil as it was with native code!code!

Page 33: Framework Security David LeBlanc Microsoft Office

Securing MethodsSecuring Methods• If another assembly calls into your object, the If another assembly calls into your object, the

methods it calls must be publicmethods it calls must be public• Not all public methods need to be available to Not all public methods need to be available to

all usersall users• Similar problem to undocumented DLL exportsSimilar problem to undocumented DLL exports

• SolutionsSolutions• Limit scope of methods when possibleLimit scope of methods when possible• Require callers to have a specific identityRequire callers to have a specific identity• Use inheritance demands to limit sub-classesUse inheritance demands to limit sub-classes

• Can be used to restrict which methods can be Can be used to restrict which methods can be overriddenoverridden

Page 34: Framework Security David LeBlanc Microsoft Office

Tricks and TrapsTricks and Traps• LinkDemandLinkDemand

• Only checks the immediate caller during JITOnly checks the immediate caller during JIT• If a LinkDemand is required on a derived If a LinkDemand is required on a derived

method, it must also be required on the method, it must also be required on the base methodbase method

• Assembly.LoadAssembly.Load• Loads an assembly using the evidence of Loads an assembly using the evidence of

the caller, NOT the assembly being loadedthe caller, NOT the assembly being loaded

Page 35: Framework Security David LeBlanc Microsoft Office

ConclusionsConclusions• Managed code is a great toolManaged code is a great tool

• Like all tools, you have to understand how Like all tools, you have to understand how they workthey work

• Managed code is NOT a silver bulletManaged code is NOT a silver bullet• It is possible to create security holes in any It is possible to create security holes in any

languagelanguage• .NET Security adds complexity.NET Security adds complexity

• Differences in execution context can create Differences in execution context can create large differences in how your code runslarge differences in how your code runs

Page 36: Framework Security David LeBlanc Microsoft Office

Additional ResourcesAdditional Resources• .NET Framework Security.NET Framework Security

• LaMacchia, Lange, Lyons, Martin and PriceLaMacchia, Lange, Lyons, Martin and Price• .NET Framework SDK.NET Framework SDK

• Secure Coding GuidelinesSecure Coding Guidelines• Writing Secure Code, 2Writing Secure Code, 2ndnd Edition Edition

Page 37: Framework Security David LeBlanc Microsoft Office

© 2006 Microsoft Corporation. All rights reserved.This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.