Ravi Mukkamala Department of Computer Science Old Dominion University Norfolk, Virginia, USA...
-
Upload
amelia-rose -
Category
Documents
-
view
216 -
download
1
Transcript of Ravi Mukkamala Department of Computer Science Old Dominion University Norfolk, Virginia, USA...
Ravi MukkamalaDepartment of Computer Science
Old Dominion UniversityNorfolk, Virginia, USA
04/20/23 1
Introduction◦ Security◦ .NET Framework
.NET Framework Security Features Identities , Principals & Impersonation ASP.NET Security with IIS Authentication Authorization Summary Resources
04/20/23 2
Consider the following when designing an application:
ImpersonationDelegationOperating system securitySecuring physical accessCode access security
Security goalsSecurity risksAuthenticationAuthorizationSecuring Data Transmission
04/20/23 3
MessageMessageQueuingQueuing
Trans-Trans-actionsactions
ActiveActiveDirectoryDirectory IISIIS Manage-Manage-
mentment ……
Common Language Runtime
Common Language Runtime
Executes code, maintains security, handles component “plumbing” and dependencies
Windows Forms
Secure, easily deployable rich client classes
Win
do
ws
Fo
rms
ASP.NET
Classes and engine for building, deploying, and running Web applications and services
AS
P.N
ET
ADO.NET
Classes for loosely-coupled data access
AD
O.N
ET
Enterprise ServicesA complete set of features enabling transactions, message queuing, etc.
En
terp
rise
S
ervi
ces
XM
L
…
VB C++ C# Perl Java …
04/20/23 4
Provide a robust security system for partially-trusted, mobile code
Make it easy to:◦Express fine- grained authorizations◦Extend & customize the system◦Perform security checks in user code
No end-user UI! ◦Never ask a user to make a security decision “on the
fly”
04/20/23 5
OS security is based on user rights CLR security, added on top of OS security, gives
rights to code
Trusted userTrusted userTrusted codeTrusted code
Untrusted userUntrusted userUntrusted codeUntrusted code
Trusted userTrusted userUntrusted codeUntrusted code
Untrusted userUntrusted userTrusted codeTrusted code
!!!!
04/20/23 6
The .NET Framework security features ◦Assist you in developing secure applications◦Include many components, including: Type Checker Exception Manager Security Engine
◦Complement Windows Security
04/20/23 7
JIT CompilerJIT Compiler& Verification& Verification
ApplicationApplicationDirectoryDirectory
ApplicationApplicationDirectoryDirectory
SetupSetupCopyCopy
BrowserBrowser
Download Download CacheCache
Download Download CacheCache
GlobalGlobalAssemblyAssembly
Cache (GAC)Cache (GAC)
GlobalGlobalAssemblyAssembly
Cache (GAC)Cache (GAC)
AssemblyAssemblyon Target on Target MachineMachine
AssemblyAssemblyon Target on Target MachineMachineAssemblyAssemblyAssemblyAssembly
DEVELOPMENTDEVELOPMENT DEPLOYMENTDEPLOYMENT
InstallInstall
EXECUTIONEXECUTION
AssemblyAssemblyLoaderLoader
PolicyPolicyManagerManager
Class Class LoaderLoader
NativeNativecode code NativeNativecode code
Policy<?xml version="1.0" encoding="utf-8" ?><configuration> <mscorlib> <security> <policy> <PolicyLevel version="1"> <CodeGroup class="UnionCodeGroup" version="1" PermissionSetName="Nothing" Name="All_Code" Description="Code group grants no permissions and forms the root of the code group tree."> <IMembershipCondition class="AllMembershipCondition" version="1"/> <CodeGroup class="UnionCodeGroup" version="1" PermissionSetName="FullTrust"
04/20/23 8
Type-safe code:◦ Prevents buffer overruns◦ Restricts access to authorized memory locations◦ Allows multiple assemblies to run in the same process
App Domains provide:◦ Increased performance◦ Increased code security
04/20/23 9
04/20/23 10
Strong names are◦ Unique identifiers (containing a public key)◦ Used to digitally sign assemblies
Strong-named assemblies◦ Prevent tampering◦ Confirm the identity of the assembly’s
publisher◦ Allow side-by-side components
sn –k MyFullKey.snk
Provides a virtual file system Allows quotas Implements file system isolation based on:
◦ Application identity◦ User identity
04/20/23 11
IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForAssembly();
.NET Framework Security features
Role-based
Code-based
Evidence-based
Cryptography
04/20/23 12
Role-based Security Applications use role-based security to enforce business
rule constraints Individuals are grouped into roles with varying levels of
access .NET role-based security works by making user and role
information available to the current thread Unified model for Authentication & Authorization
04/20/23 13
Role-based Security (Contd..) Authentication :
Examining user credentials Authorization :
Analyzing user roles – what rights and operations allowed to perform
.NET Framework provides support for common authentication protocols KERBEROS SSL/TLS etc.
04/20/23 14
Unified programming model for all forms of authentication:◦ Basic◦ Digest◦ NTLM◦ Kerberos◦ Microsoft Passport◦ Forms/Custom◦ Client Certificates
04/20/23 15
Maximum flexibility again◦Access Control Lists◦Active Directory◦URL Authorization via Configuration Files◦Custom
04/20/23 16
Allows partially trusted code to run with reduced rights
Evidence-based security model No more “all-or-none” or “sandbox” Granular permissions Flexible, extensible
04/20/23 17
Prior to .NET, we lived almost exclusively in a world of tokens and access control lists
Security model implied a world based exclusively on trust◦ “Please buy my component. Don’t worry; I won’t
trash your machine.” Component reuse took some “convincing” from
vendors
04/20/23 18
We (AKA, system administrators) lived at the mercy of third-party components◦ Component-based software is vulnerable to attack
Moreover, we had no way of controlling what code could or could not do◦ “I Love You” exploit
We want to “glean the intention” of the programmer out of the program
04/20/23 19
“We need leverage the existing model…” “We need make components more trustworthy…” “We need give sysadmins more control over what code
and cannot do…” Question: Can we can have our cake and eat it too?
04/20/23 20
A Tale of Two Securities:◦ Code Access Security◦ Evidence Based Security
These two models allow us (as component vendors and sysadmins) to live safely and sanely in this new .NET world
Component reuse is now a reality Control over code is now a reality The security infrastructure of the CLR provides
evidence, policy, permissions, and enforcement services
04/20/23 21
CAS is a mechanism that controls the access that code has to protected resources and operations
CAS allows code to be trusted to varying degrees, depending on where the code originates and on other aspects of the code's identity
CAS also enforces the varying levels of trust on code, which minimizes the amount of code that must be fully trusted in order to run
04/20/23 22
Using CAS can reduce the likelihood that your code can be misused by malicious or error-filled code
It can reduce your liability because you can specify the set of operations your code should be allowed to perform as well as the operations your code should never be allowed to perform
Code access security can also help minimize the damage that can result from security vulnerabilities in your code
04/20/23 23
We take security very, very seriously by hoisting a secure infrastructure directly into the common language runtime (CLR)
CLR is the Mother of All Control This is a good thing; we need much more security than
what Windows alone is able to provide
04/20/23 24
Represent access to a protected resource or the ability to perform a protected operation
They are a fundamental part of the common language runtime's mechanism for enforcing security restrictions on managed code
04/20/23 25
Directory Services DNS Environment Event Log File Dialog File I/O Isolated Storage Message Queue
OLE DB Printing Reflection Security SCM Socket UI Web
04/20/23 26
Note: These permissions are extensible! Every permission inherits from CodeAccessPermission Secure your resources/types with your own
permissions – very cool
04/20/23 27
Code access permissions may be applied either explicitly or declaratively
Code access permissions support a number of operations that control what code can or cannot do
04/20/23 28
All code access permissions derive from CodeAccessPermission
CodeAccessPermission defines the underlying structure of all code access permissions
Code access permissions use a stack walk to ensure that all callers of the code have been granted a permission
04/20/23 29
SecurityException forms the basis of all security violations committed by code running in the CLR
If the system denies a request, it does so by throwing an exception of type SecurityException
SecurityExceptions represent a virtual slap-on-the-wrist; “Don’t do that…”
04/20/23 30
Code access permissions support the following methods:◦ Assert◦ Demand◦ Deny◦ PermitOnly◦ RevertAll◦ RevertAssert◦ RevertDeny◦ RevertPermitOnly
04/20/23 31
Calling Assert prevents a stack walk originating lower in the call stack from proceeding up the call stack beyond the code that calls this method
Disables the stack walk for the frame ALWAYS VERIFY YOUR ASSERTS!
04/20/23 32
Forces a SecurityException at run time if all callers higher in the call stack have not been granted the permission specified by the current instance
A good way to test for available permissions
04/20/23 33
Prevents callers higher in the call stack from accessing a resource specified by the current instance◦ Pseudo-sandboxing
04/20/23 34
Prevents callers higher in the call stack from using the code that calls this method to access all resources except for the resource specified by the current instance
Similar to Deny in that both cause stack walks to fail when they would otherwise succeed◦ However, PermitOnly specifies permissions that do
not cause the stack walk to fail
04/20/23 35
Causes all previous overrides for the current frame to be removed and no longer in effect
Rolls back all overrides made for the current frame
04/20/23 36
Each of these methods causes any previous Assert/Deny/PermitOnly for the current frame to be removed and no longer in effect
04/20/23 37
Clearly, the ability to assert permissions can be abused
Unfortunately, the issue regards assertions is a bit cloudy◦ Unmanaged code requires assertions◦ “Gatekeeper” classes
Rule: Demand before Assert Rule: Always code review your assertions!
04/20/23 38
04/20/23 39
Evidence◦Is assessed when an assembly is loaded ◦Is used to determine the permissions for
the assembly◦Can include the assembly’s: Strong name information URL Zone Authenticode signature
Evidence◦Inputs to policy about code◦Strong name, site, zone, Authenticode signature
Permissions ◦Specific authorizations◦Define a level of access to a resource
Policy◦Determines what code can do◦Grants permissions to an assembly
04/20/23 40
The CLR examines evidence about code to determine which permissions to grant
Evidence is presented by an assembly at load time:◦ From what site was this assembly obtained?◦ From what URL was this assembly obtained?◦ From what Zone was this assembly obtained?◦ What’s the strong name of this assembly?◦ Who signed this assembly?
04/20/23 41
Example: Info about a code assembly◦ Strong names◦ Publisher identity◦ Hash◦ Location of origin (URL, IE zone, site)
Evidence is completely extensible◦ Any object can be a piece of evidence
Time of day, 3rd party certification, etc.◦ Only impacts grants if there is a code group
membership condition that tests for it◦ Assemblies may contain untrusted evidence
cryptographicallycomputed/validated}
04/20/23 42
Policy is the process of determining the set of permissions to grant to code based on evidence known about that code
This is a classic trust management problem◦ Requiring end users to write programs to express
policies was simply out of the question...◦ This is why Microsoft has given us a declarative,
administrative model!
04/20/23 43
Condition:Condition:
Publisher=DodgyBrothersPublisher=DodgyBrothers
Permission Set:Permission Set:
VeryLowTrustVeryLowTrust VeryLowTrustVeryLowTrust
Security Permission: Security Permission: ExecuteExecute
EnvironmentPermission: EnvironmentPermission: Read “OS”Read “OS”
04/20/23 44
A code group may have only one membership condition It is comprised of an attribute that matches evidence
presented by an assembly◦ Zone of originating assembly◦ URL of originating assembly◦ Digital signature of assembly publisher◦ Web site of the originating assembly
04/20/23 45
Comprised of many code groups that map to different assembly types◦ Local, intranet, internet assemblies
Installed as part of the .NET Framework Can be modified by an administrator
04/20/23 46
Four levels of policy in .NET◦ Enterprise◦ Machine◦ User◦ Application Domain
Each level contains code groups that map assemblies to permissions
Policy evaluation is from Enterprise down to Application Domain
04/20/23 47
The .Net Framework configuration tool can be used to modify and manage security policy
Also, there’s a command-line tool caspol.exe
Tools update XML files
04/20/23 48
Enterprise Policy LevelEnterprise Policy Level
•Evaluated firstEvaluated first
•Allows definition of Allows definition of enterprise-wide policyenterprise-wide policy
•Enterprise admin can Enterprise admin can restrict rights granted or restrict rights granted or restricted in lower policy restricted in lower policy levelslevels
04/20/23 49
Machine Policy LevelMachine Policy Level
•Evaluated after Evaluated after Enterprise policyEnterprise policy
•Defined at local machine Defined at local machine level by machine adminlevel by machine admin
•Default .NET policy Default .NET policy expressed hereexpressed here
04/20/23 50
User Policy LevelUser Policy Level
•Evaluated lastEvaluated last
•In default .NET policy, In default .NET policy, allows all permissionsallows all permissions
•User can configure to User can configure to further restrict certain further restrict certain permissionspermissions
04/20/23 51
Each policy level has a set of code groups◦ Code groups are related hierarchically◦ There must be at least one code group for each policy
level◦ Once the CLR determines that a code group does not
map to an assembly, no dependent code groups are examined
04/20/23 52
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 madeevidence match is made
•Five code groups in Five code groups in default .NET Machine default .NET Machine PolicyPolicy
04/20/23 53
A code group may have only one permission set◦ A permission set may be comprised of a variety of
different permissions Full trust to all protected system resources Read/Write access to a local file Read access to a specified environment variable
04/20/23 54
Permission setsPermission sets
•Sets of permissions Sets of permissions referred to by the code referred to by the code groupsgroups
04/20/23 55
More than one code group within a policy level may map to the evidence of an assembly
A policy level has the combination (union) of all code group permissions that map to an assembly
04/20/23 56
Zone:Zone:
MyComputerMyComputer
ps:foops:foo
Zone:Zone:
InternetInternet
ps:barps:bar
Pub:Pub:
DodgySoftDodgySoft
ps:Nothingps:Nothing
URL:URL:
woof.com.auwoof.com.au
ps:bazps:baz
Pub:Pub:
ACMEACME
ps:gimpps:gimp
Pub:Pub:
ACMEACME
ps:bazps:baz
All CodeAll Code
ps:Nothingps:Nothing
04/20/23 57
Zone:Zone:
MyComputerMyComputer
ps:foops:foo
Zone:Zone:
InternetInternet
ps:barps:bar
Pub:Pub:
DodgySoftDodgySoft
ps:Nothingps:Nothing
URL:URL:
woof.com.auwoof.com.au
ps:woofps:woof
Pub:Pub:
ACMEACME
ps:gimpps:gimp
Pub:Pub:
ACMEACME
ps:bazps:baz
All CodeAll Code
ps:nothingps:nothing
nothingnothing
barbar
bazbaz
Resulting Resulting permission Setspermission Sets
Code downloaded from the Code downloaded from the internet AND signed by ACMEinternet AND signed by ACME
Zone:Zone:
InternetInternet
ps:barps:bar
Pub:Pub:
ACMEACME
ps:bazps:baz
All CodeAll Code
ps:Nothingps:Nothing
04/20/23 58
Zone:Zone:
MyComputerMyComputer
ps:foops:foo
Zone:Zone:
InternetInternet
ps:barps:bar
Pub:Pub:
DodgySoftDodgySoft
ps:Nothingps:Nothing
URL:URL:
woof.com.auwoof.com.au
ps:woofps:woof
Pub:Pub:
ACMEACME
ps:gimpps:gimp
Pub:Pub:
ACMEACME
ps:bazps:baz
All CodeAll Code
ps:nothingps:nothing
Code downloaded from the Code downloaded from the internet site woof.com.au AND internet site woof.com.au AND
signed by ACMEsigned by ACME
Zone:Zone:
InternetInternet
ps:barps:bar
Pub:Pub:
ACMEACME
ps:bazps:baz
All CodeAll Code
ps:Nothingps:Nothing
URL:URL:
woof.com.auwoof.com.au
ps:woofps:woof
nothingnothing
barbar
bazbaz
woofwoof
Resulting Resulting permission Setspermission Sets
04/20/23 59
Zone:Zone:
MyComputerMyComputer
ps:foops:foo
Zone:Zone:
InternetInternet
ps:barps:bar
Pub:Pub:
DodgySoftDodgySoft
ps:Nothingps:Nothing
URL:URL:
woof.com.auwoof.com.au
ps:woofps:woof
Pub:Pub:
ACMEACME
ps:gimpps:gimp
Pub:Pub:
ACMEACME
ps:bazps:baz
All CodeAll Code
ps:nothingps:nothing
nothingnothing
foofoo
gimpgimp
Resulting Resulting permission Setspermission Sets
Code installed on local machine Code installed on local machine AND signed by ACMEAND signed by ACME
Zone:Zone:
InternetInternet
ps:barps:bar
Pub:Pub:
ACMEACME
ps:bazps:baz
All CodeAll Code
ps:Nothingps:Nothing
04/20/23 60
Each policy level is evaluated by the CLR to determine an assemblies permissions or level of trust
Resulting permissions granted is the intersection of permissions from each level◦ The least amount of trust from the three policy levels
is granted
04/20/23 61
EnterpriseEnterprise MachineMachine
UserUser
Allowed permissionsAllowed permissions
04/20/23 62
Evidence◦ Inputs to policy about code◦ Strong name, site, zone, Authenticode signature,
hash value, app directory, etc. Permissions
◦ Specific authorizations for code (not users)◦ Define a level of access to a resource or operation
Policy◦ Matches permissions to evidence via “code
groups”◦ Grants permissions to an assembly
04/20/23 63
FullTrust PermissionSet
Full access to all machine capabilities
But: App must be installed on machine by machine’s admin
04/20/23 64
Unlimited UI Same protocol access to site & DNS File read access to origin Open/Save File Dialog Default printer Unlimited Isolated Storage Write to Event Log Env for USERNAME, TEMP, TMP
04/20/23 65
APIs to access code access security system◦Refuse unnecessary permissions◦Refuse to run if not granted necessary permissions◦Check to see if granted a permission and tweak app
behavior based on response
04/20/23 66
Used by developers to state required permissions Implemented by attributes Prevents an assembly from loading when minimum
permissions are not available
//I will only run if I can call unmanaged code[assembly:SecurityPermission (SecurityAction.RequestMinimum, UnmanagedCode=true)]
04/20/23 67
04/20/23 68
Security Entity Description
PolicyPolicy
Is set by administratorsIs enforced at runtimeSimplifies administrationContains permissionsContains code groups
Code GroupCode GroupAssociates similar componentsIs evidence basedIs linked to permission set(s)
Permission SetPermission Set Is a set of granted permissions
04/20/23 68
Imperative security checks◦Create Permission objects◦Call Permission methods
Declarative security checks◦Use Permission attributes◦Apply to methods or classes
Overriding security checks◦Use the Assert method◦Prevent the stack walk
04/20/23 69
Call Stack
Security System
YourAssemblyYourAssembly
SomeAssemblySomeAssembly
.NET Framework Assembly.NET Framework Assembly
Call to ReadFile
Call to ReadFile
Grant: Execute
1. An assembly requests access to a method in your assembly
2. Your assembly passes the request to a .NET Framework assembly
3. The security system ensures that all callers in the stack have the required permissions
4. The security system grants access or throws an exception
Grant: ReadFileGrant: ReadFile
Grant: ReadFile
Permission Demand
Security exception Access deniedSecurity exception Access deniedGrant access?Grant access?
04/20/23 70
Cryptography Term
Description
Symmetric Symmetric EncryptionEncryption
Encrypting and decrypting data with a secret key
Asymmetric Asymmetric EncryptionEncryption
Encrypting and decrypting data with a public/private key pair
HashingHashing Mapping a long string of data to a short, fixed-size string of data
Digital SigningDigital Signing Hashing data and encrypting the hash value with a private key
The .NET Framework provides classes that implement these operations
04/20/23 71
Choose an algorithm◦ TripleDESCryptoServiceProvider◦ RijndaelManaged
Generate a secret key Use the same secret key to encrypt and decrypt data:
◦ FileStream◦ MemoryStream◦ NetworkStream
04/20/23 72
Choose an algorithm◦RSACryptoServiceProvider◦DSACryptoServiceProvider
Generate a private and public key pair Encrypt or decrypt data
04/20/23 73
Action Steps
Signing DataSigning DataHash the dataEncrypt the hash value with a private key
Verifying SignaturesVerifying Signatures
Decrypt the signature by using sender’s public keyHash the dataCompare the decrypted signature to the hash value
04/20/23 74
An identity contains information about a user, such as the user’s logon name
A principal contains role information about a user or computer
The .NET Framework provides: WindowsIdentity and WindowsPrincipal objects GenericIdentity and GenericPrincipal objects
04/20/23 75
An identity represents a certain user Identity is established through authentication by an
authority Processes run code under an identity Access to some resources is granted based on a proven
identity◦NTFS file system◦SQL Server and other server products working with
Windows Integrated security◦Registry
04/20/23 76
Usually identities are of type:◦Windows user◦ASP.NET Forms authenticated user◦Passport account◦Custom application account
04/20/23 77
A principal represents an identity AND its roles Allows you to make security decisions
◦Role Based Security (RBS): Role membership is tested on a principal Role is group of users with similar rights
◦Identity
04/20/23 78
Dedicated namespace is System.Security.Principal .NET Framework provides two interfaces: IIdentity
and IPrincipalpublic interface IPrincipalpublic interface IPrincipal{{ IIdentity Identity { get; }IIdentity Identity { get; } bool IsInRole(string role);bool IsInRole(string role);}}public interface IIdentitypublic interface IIdentity{{ bool IsAuthenticated { get; }bool IsAuthenticated { get; } string AuthenticationType { get; }string AuthenticationType { get; } string Name { get; }string Name { get; }}}
04/20/23 79
Use FCL classes or create custom implementation
Custom implementations should implement Identity and IPrincipal
Identity class Principal class
WindowsIdentity WindowsPrincipal
GenericIdentity GenericPrincipal
PassportIdentity
FormsIdentity
04/20/23 80
Principal objects can be acquired in two ways◦WindowsIdentity.GetCurrent() method, then create
WindowsPrincipal◦Thread.CurrentPrincipal property◦ASP.NET only: HttpContext.Current.User
Once acquired evaluate identities properties and/or check for role membership
04/20/23 81
Identity of Win32 thread leading for resource access Roles of Windows principal are Windows security
groups Control how CLR assigns principal to CLR thread by
setting AppDomain's PrincipalPolicyNoPrincipalNoPrincipal Returns null (Nothing)Returns null (Nothing)
UnauthenticatedPrincipalUnauthenticatedPrincipal Unauthenticated GenericPrincipal Unauthenticated GenericPrincipal with zero roleswith zero roles
WindowsPrincipalWindowsPrincipal WindowsPrincipal equal to current WindowsPrincipal equal to current Win32Win32
04/20/23 82
WindowsIdentity of Win32 thread determined by user token of process
Different ways of setting◦Win32 executables: Console Windows Forms Windows (NT) Services
◦ASP.NET◦COM+ application (Enterprise Services)
04/20/23 83
Setting a new identity onto executing Win32 thread, e.g. when:◦Identity of calling user has to be assumed◦Resource must be accessed through privileged
account WindowsIdentity class has Impersonate method
◦Takes a token of user to impersonate◦Returns a WindowsImpersonationContext◦Identity assumed until Undo is called
04/20/23 84
O/S Thread
ISAPI Extension Control BlockISAPI Extension Control Block
Identity fromIdentity fromApplication Application Pool ConfigPool Config
Impersonation Token comes Impersonation Token comes from “Authenticationfrom “AuthenticationMethods” tabMethods” tab
04/20/23 85
Impersonation TokenImpersonation Token
O/S ThreadO/S ThreadASP.NET ISAPIExtension
ASP.NET Managed Code App-DomainASP.NET Managed Code App-Domain
HTTP Module
HTTP Module
HTTP Module
HTTP Module
HTTP Module
HTTP Module
HTTP Context
UserProperty
SetSetIPrincipalIPrincipal
04/20/23 86
Impersonation TokenImpersonation Token
O/S ThreadO/S ThreadSet Thread Token
ASP.NET App-DomainASP.NET App-Domain
HTTP Module
HTTP Module
HTTP Module
HTTP Module
HTTP Module
HTTP Module
Enter Pipeline withEnter Pipeline withNew Client ImpersonationNew Client Impersonation
04/20/23 87
Impersonation TokenImpersonation Token
O/S ThreadO/S Thread
Logon User
ASP.NET App-DomainASP.NET App-Domain
HTTP Module
HTTP Module
HTTP Module
HTTP Module
HTTP Module
HTTP Module
<identity<identityuser=user=password=password=
Web.ConfigWeb.Config
04/20/23 88
Getting token not supported by managed code◦Some calls to Win32 API are necessary◦Mainly LogonUser
Alternative offered by Enterprise Services (previously COM+)
ASP.NET has built-in facilities for impersonation of calling user
04/20/23 89
Create your own principals◦ WindowsPrincipals are only created explicitly to
evaluate Windows groups◦ Generic principals for ASP.NET and custom
authentication Set or replace principal of current thread
◦ By default new threads take principal from spawning thread
◦ Set principal for new threads using current AppDomain's SetThreadPrincipal method
◦ Code needs to have ControlPrincipal rights04/20/23 90
GenericIdentity and GenericPrincipal◦ For custom authentication◦ Used by ASP.NET Forms Authentication
Complete freedom on choice of identity names and corresponding roles◦ Probably based upon application specific scenario
or requirements
04/20/23 91
Common scenario◦Retrieve names and roles from database◦If credentials are stored in database, securely store
password Create GenericIdentity first
◦Constructor accepts string for username Principal is created by supplying:
◦Previously created (Generic)Identity◦String array containing names of roles
04/20/23 92
// Data is normally retrieved from a database// Data is normally retrieved from a databasestring userName = "Alex";string userName = "Alex";string[] roles = string[] roles = new string[] { "Programmer", "Teacher" };new string[] { "Programmer", "Teacher" };GenericIdentity identity;GenericIdentity identity;GenericPrincipal principal;GenericPrincipal principal;
// Create identity and principal// Create identity and principalidentity = new GenericIdentity(userName, identity = new GenericIdentity(userName, "CustomAuthentication"); "CustomAuthentication");principal = new GenericPrincipal(identity, roles);principal = new GenericPrincipal(identity, roles);
// Set principal to thread// Set principal to thread// You need ControlPrincipal rights to do this// You need ControlPrincipal rights to do thisThread.CurrentPrincipal = principal;Thread.CurrentPrincipal = principal;
04/20/23 93
94
ASP.NET
IIS
Web clients
Launch ASP.NET application
Access denied
ASP.NET applicationassumes client identity
Access granted
IP address and domain permitted?
User authenticated?
No
Yes
YesNo
Yes
ASP.NET impersonation enabled?
NoAccess check OK?
(e.g. NTFS)
No
ASP.NET applicationruns with local
machine identity
Yes
04/20/23 94
95
ASP.NET supports three authentication providers:◦Forms Authentication – Relies on a logon form and
cookies◦Passport Authentication – Centralized authentication
service provided by Microsoft◦Windows Authentication – IIS handles authentication
Provider is specified in the Web.config file<!-- web.config file --><authentication
mode = "[Windows|Forms|Passport|None]"> </authentication>
<!-- web.config file --><authentication
mode = "[Windows|Forms|Passport|None]"> </authentication>
04/20/23 95
96
IIS Authentication Method
ASP.NET Authentication Providers
Forms
Windows
Passport
None (Custom)
Basic
Integrated
Digest
Certificate Mapping
Anonymous
04/20/23 96
97
Authenticate users with Windows user accounts by combining IIS authentication and the Windows authentication provider for ASP.NET
No authentication-specific code needs to be written with this approach
ASP.NET constructs and attaches a WindowsPrincipal object to the application context
04/20/23 97
ASP.NET is an ISAPI extension◦ Only receives requests for mapped content
Windows Authentication (via IIS)◦ Basic, Digest, NTLM, Kerberos, Certificate Support◦ Leverages platform authentication
Forms-based (Cookie) Authentication◦ Application credential verification
Supports Microsoft® Passport Authentication Custom Authentication
04/20/23 98
Configure IIS for Anonymous authentication and use one of the following .NET authentication modules:
None – custom or no authentication Forms – provide a logon page Passport – use the Passport service
04/20/23 99
ASP.NET impersonation
IIS is using Anonymous
IIS is not using Anonymous
Application resides on UNC
share
Disabled Process account Process account IIS UNC token
Enabled IUSR_SERVER Authenticated user IIS UNC token
Enabled with a specified user
"Jeff"
"Jeff" "Jeff" "Jeff"
04/20/23 100
ASP.NET application worker process (aspnet_wp.exe) executes under ASPNET account
ASPNET account has minimal privileges Configure account name in <processModel> element
of machine.config file◦"SYSTEM" (System account) ◦"MACHINE" (ASPNET) ◦Custom user account
<system.web> <processModel
enable="true" username="domain\user" password="pwd">
</processModel> </system.web>
<system.web> <processModel
enable="true" username="domain\user" password="pwd">
</processModel> </system.web>
04/20/23 101
Anonymous Authentication Basic Authentication Digest Authentication Integrated Windows Authentication Certificate Authentication Passport Authentication Forms Authentication Using Cookies
04/20/23 102
Server and client operating systems Client browser type Number of users, location and type of user name and password
database Deployment considerations (Internet vs. intranet and firewalls) Application type (interactive Web site or non-interactive Web
service) Sensitivity of data being protected Performance and scalability factors Application authorization requirements (all users, or restricted
areas)
04/20/23 103
Anonymous and cookiesAnonymous and passport
No
Yes
AnonymousNo
Yes
Yes
(Continued next slide)
No
Yes
No
Certificates
No
Yes
Forms over SSLCertificates
YesNoForms
PassportUsers in
Passport?
Users log on?
Users inWindows accounts?
Personalizationrequired?
Interactiveuser logon?
Secure logon?
04/20/23 104
No
Yes
No BasicFormsDigest
Basic/SSLDigest/SSLForms/SSLCertificates
Yes
No
No
BasicNTLM
Certificates
Yes
Custom Credential MappingBasic
Kerberos
Yes
BasicDigestNTLM
KerberosCertificates
App runs on Internet?
Secure logon?
Delegation required?
Servers and clients
Win2K?
Yes, users are inWindows accounts
04/20/23 105
No authentication occurs in either IIS or ASP.NET Good choice for publicly available Web site not requiring the
identity of the caller No browser restrictions
04/20/23 106
Consider Anonymous authentication when: ◦ Caller name and/or password is not required for logon or
business logic components◦ The information you are protecting is considered "public"
Do not use Anonymous authentication when: ◦ You require a logon name and password
Typical usage scenarios
04/20/23 107
Good choice for sites containing personalized content only◦ For example, a news site only interested in user's zip code
Impersonation cannot be used◦ Appropriate permissions need configuring for anonymous
user account Gives highest performance, but lowest security
Other considerations
04/20/23 108
Configure IIS for Anonymous authentication Configure the appropriate anonymous user account in IIS Configure the ASP.NET Web.config file
Implementation
<!-- web.config file --><system.web>
<authentication mode="None" /> </system.web>
<!-- web.config file --><system.web>
<authentication mode="None" /> </system.web>
04/20/23 109
IIS instructs the browser to send the user's credentials over HTTP◦ Browser prompts the user with a dialog box◦ User names and passwords are sent using Base64 encoding,
which is NOT secure Most browsers support Basic authentication
04/20/23 110
Consider Basic authentication when you require: ◦ Users to have Windows NT Domain or Active Directory
accounts ◦ Support for multiple browsers◦ Support for authentication over the Internet◦ Access to the clear text password in your application code◦ Delegation
Do not use Basic authentication when you require: ◦ Secure logon while not using a secure channel, such as Secure
Sockets Layer (SSL) ◦ Storage of information in a custom database◦ A customized form presented to the user as a logon page
Typical usage scenarios
04/20/23 111
Delegation is possible using Basic authentication
Combine Basic authentication with SSL to prevent passwords from being deciphered
Other considerations
04/20/23 112
Configure IIS for Basic authentication Configure user accounts to have "log on locally" enabled on
Web server Configure the ASP.NET Web.config file
Implementation
<!-- web.config file --><system.web>
<authentication mode="Windows" /> </system.web>
<!-- web.config file --><system.web>
<authentication mode="Windows" /> </system.web>
04/20/23 113
New to Windows 2000 and IIS 5.0 Encrypts the user's password using MD5 Dependent on browser and server capabilities Cannot perform delegation
04/20/23 114
Consider Digest authentication when: ◦ The Web server is running Windows 2000 and users have Windows
accounts stored in Active Directory◦ All clients use either the .NET platform or Internet Explorer 5.0 or later ◦ Password encryption above that of Basic authentication is required◦ Support of authentication over the Internet is required
Do not use Digest authentication when: ◦ Some clients use platforms other than .NET or Internet Explorer 5.0 or
later◦ Users do not have Windows accounts stored in Active Directory◦ Delegation is required
Typical usage scenarios
04/20/23 115
Security◦ Digest authentication is more secure than Basic authentication
alone◦ Less secure than Basic authentication with SSL◦ Can also be combined with SSL
Platform requirements for Digest authentication◦ Clients – .NET or Internet Explorer 5.0 (or later)◦ Server – running Active Directory with user accounts
configured for Digest authentication
Other considerations
04/20/23 116
Configure IIS for Digest authentication Configure the ASP.NET Web.config file
Implementation
<!-- web.config file --><system.web>
<authentication mode="Windows" /> </system.web>
<!-- web.config file --><system.web>
<authentication mode="Windows" /> </system.web>
04/20/23 117
Uses either NTLM challenge/response or Kerberos to authenticate users with a Windows NT Domain or Active Directory account
No password is sent across the network Best suited to an intranet environment Works with Internet Explorer 3.01 or later
04/20/23 118
Consider Integrated Windows authentication when: ◦ Users have Windows NT Domain or Active Directory accounts◦ Your application runs on an intranet (behind a firewall)◦ All clients are running Internet Explorer 3.01 or later◦ Delegation is required (requires Kerberos)◦ Seamless logon procedure for domain users is required
(e.g. without pop-up logon dialog boxes)
Do not use Integrated Windows authentication when: ◦ User accounts are stored in an external database◦ Authentication over the Internet is required◦ Clients are using non-Microsoft browsers◦ You need the client's clear text password
Typical usage scenarios
04/20/23 119
NTLM and Kerberos are considered highly secure NTLM does not support delegation; Kerberos does Neither NTLM or Kerberos are commonly used over the
Internet Kerberos is faster than NTLM, but neither is as fast as Basic
authentication
Other considerations
04/20/23 120
Clients and servers must be running Windows 2000 in a Windows 2000 domain◦ User and service accounts must be enabled for delegation
Configure IIS for Integrated Windows authentication Configure the ASP.NET Web.config file
Implementation
<!-- web.config file --><system.web>
<authentication mode="Windows" /> </system.web>
<!-- web.config file --><system.web>
<authentication mode="Windows" /> </system.web>
04/20/23 121
A certificate is a digital "key" installed on a computer Certificates can be mapped to user accounts
Web Server
DomainController
Client
Request: Welcome.aspxResponse: Certificate request
Response: Welcome.aspxRequest: Login.aspx + Certificate
Certificate Validation
04/20/23 122
Consider Certificate authentication when: ◦ Data is considered very sensitive and you require a very secure solution◦ Mutual authentication is required◦ Third parties will manage the relationship between the server and the
certificate holder◦ Client interaction must be seamless; for example, automated B2B
exchanges
Do not use Certificate authentication when: ◦ The cost of issuing and managing client certificates outweighs the value of
the added security
Typical usage scenarios
04/20/23 123
Client certificates must be deployed to the client workstations Map certificates to:
◦ Individual user accounts (one-to-one mapping)◦ Any user from a single company (many-to-one mapping)
Other considerations
04/20/23 124
Configure IIS for Certificate authentication Configure the ASP.NET Web.config file
Implementation
<!-- web.config file --><system.web>
<authentication mode="Windows" /> </system.web>
<!-- web.config file --><system.web>
<authentication mode="Windows" /> </system.web>
04/20/23 125
A centralized authentication service provided by Microsoft
Web Server
MicrosoftPassport
ClientRequest: Welcome.aspxResponse: Passport Sign InRequest: Login.aspx + CookieResponse: Welcome.aspx
Passport authenticationCreates authentication cookies
04/20/23 126
Consider Passport authentication when: ◦ Your site will interact with other Passport-enabled sites ◦ Single sign-on capability is required◦ External maintenance of user names and passwords is useful
Do not use Passport authentication when: ◦ You want to use user names and passwords already stored in your own
database or Active Directory◦ Clients are other applications that access the site programmatically
Typical usage scenarios
04/20/23 127
Requires registration with the Passport service and installation of the Passport SDK on the server
Delegation is not possible on Windows 2000 Passport User ID (PUID) is an identity only
◦ Implement code to map PUID to users in Active Directory or custom database
Passport uses encrypted cookies making system secure◦ Combine Passport with SSL to prevent replay attacks for
highest level of security
Other considerations
04/20/23 128
Install Passport SDK on server Register with Passport service Configure IIS for Anonymous authentication Configure the ASP.NET Web.config file
Implementation
<!-- web.config file --><system.web>
<authentication mode="Passport" /> </system.web>
<!-- web.config file --><system.web>
<authentication mode="Passport" /> </system.web>
04/20/23 129
A custom user interface accepts user credentials Authentication is performed against a database using custom
codeWeb ServerClient Request: Welcome.aspx
Response: Login.aspxRequest: Login.aspx + data
Response: Welcome.aspx + Cookie
Authenticateuser
Web.configorUser database
04/20/23 130
Cookie-Based Authentication Architecture
Client requests page
Authorized
ASP.NET Authentication
Not Authenticated Authenticated
Login Page(Users enter their credentials)
Authenticated
Cookie
Authorized
Not Authenticated
Access Denied
RequestedPage
04/20/23 131
Consider Forms authentication when: ◦ User names and passwords are stored somewhere other than Windows
accounts◦ Your application runs over the Internet◦ Support for all browsers and client operating systems is required◦ A custom logon page is needed
Do not use Forms authentication when: ◦ Applications are deployed on a corporate intranet and can take advantage
of Integrated Windows authentication◦ You cannot programmatically verify the user name and password
Typical usage scenarios
04/20/23 132
Use SSL to secure passwords submitted via the logon page Set cookie expiration to avoid cookie theft and misuse SSL degrades performance, so consider separating logon and
content servers Checking for the cookie is automatic in ASP.NET applications Use Forms authentication with Windows accounts as an
alternative to Basic or Digest authentication
Other considerations
04/20/23 133
Create a logon page Create your custom account information lookup code Configure IIS for Anonymous authentication Configure the ASP.NET Web.config file, including the redirect
URL for unauthenticated clients
Implementation
<!-- web.config file --><system.web>
<authentication mode="Forms" <forms loginUrl="login.aspx"/>
/> </system.web>
<!-- web.config file --><system.web>
<authentication mode="Forms" <forms loginUrl="login.aspx"/>
/> </system.web>
04/20/23 134
Process of determining whether a user is allowed to perform a requested action
File-based authorization◦ Performed by FileAuthorizationModule◦ Performs checks against Windows ACLs
Custom – handle AuthorizeRequest event◦ Application level (global.asax)◦ HTTP module (implement IHttpModule)
URL-based authorization◦ Performed by UrlAuthorizationModule
04/20/23 135
If User.IsInRole("BUILTIN\Administrators") then
Response.Write("You are an Admin") Else If User.IsInRole("BUILTIN\Users") then Response.Write("You are a User") Else Response.Write("Invalid user") End if
04/20/23 136
Handle AuthenticateRequest event◦ Create GenericPrinciple◦ Attach roles to Identity◦ Assign new Principle to UserSub Application_AuthenticateRequest(s As Object, e As EventArgs) If Not (User Is Nothing) Then If User.Identity.AuthenticationType = "Forms" Then Dim Roles(1) As String Roles(0) = "Admin" User = new GenericPrinciple(User.Identity,Roles) End If End IfEnd Sub
04/20/23 137
if User.IsInRole("Admin") then
Response.Write ("You are an Administrator") Else Response.Write ("You do not have any role assigned") End if
04/20/23 138
Security is a war! Don’t fight fair. Defense in Layers Make Security part of every aspect of your projectso should be about 12% of effort per project
.NET provides means for the info to travel seamlessly and securely between applications , web sites and devices.
.NET provides all round security in to the new world of distributed computing and WS.
Rich set of cryptography services
04/20/23 139
How ASP Security Works◦ An overview of ASP Security
http://msdn2.microsoft.com/en-us/security/aa336653.aspx How to Security
◦ Learn about security as it applies to .NET. http://msdn2.microsoft.com/en-us/security/aa570406.aspx
TechNet Security Site (IT professionals) http://www.microsoft.com/technet/security/default.mspx
Other Resources◦ http://www.gotdotnet.com/
04/20/23 140
04/20/23 141