Speech Title Here

Download Report

Transcript Speech Title Here

Security for Developers
Web Application Security
Steven Borg & Richard Hundhausen
Accentient, Inc
Agenda
Overview of Web Security
ASP.NET Security Architecture
Web Service Security
Wrap Up
This Is Insecure Code!
<html>
<body>
<form runat="server">
<asp:TextBox ID="Input" runat="server" />
<asp:Button Text="Click Me" OnClick="OnSubmit"
runat="server" />
<asp:Label ID="Output" runat="server" />
</form>
</body>
</html>
<script language="C#" runat="server">
void OnSubmit (Object sender, EventArgs e)
{
Output.Text = "Hello, " + Input.Text;
}
</script>
Why is This Code Insecure?
Input is neither validated nor
constrained; user can type anything!
<html>
<body>
<form runat="server">
<asp:TextBox ID="Input" runat="server" />
<asp:Button Text="Click Me" OnClick="OnSubmit"
runat="server" />
<asp:Label ID="Output" runat="server" />
</form>
</body>
</html>
<script language="C#" runat="server">
void OnSubmit (Object sender, EventArgs e)
{
Output.Text = "Hello, " + Input.Text;
}
</script>
Input is echoed to page
without HTML encoding
Cost of Security Threats
Sabotage
$ 0.9 Million
System penetration
$ 0.9 Million
Web site defacement
$ 1 Million
Misuse of public Web applications
$ 2.7 Million
Telecom fraud
$ 4 Million
Unauthorized access
$ 4.3 Million
Laptop theft
Financial fraud
Abuse of wireless networks
Insider abuse of Net access
Theft of proprietary information
Denial of service
Viruses
$ 6.7 Million
$ 7.7 Million
$ 10.2 Million
$ 10.6 Million
$ 11.5 Million
$ 26.1 Million
$ 55.1 Million
Why Security?
2002 Computer Crime and Security Survey
Percentages of companies who participated in the survey
Reported security breaches
in the last 12 months
90%
Acknowledged financial
losses as a result
80%
Identified Internet connection
as frequent source of attacks
Reported intrusions to
authorities
i
http://www.gocsi.com/press/20020407.html
74%
34%
How Does This Happen?
Common Software Vulnerabilities
Percentages of apps that have "serious design flaws" in the indicated areas
79%
Session management
73%
Parameter manipulation
64%
Access control
61%
Cryptographic algorithms
Handling of sensitive data
Administrative controls
Input validation
41%
36%
32%
Your Dilemma
Principle #1: The defender must defend
all points; the attacker can choose the
weakest point.
Principle #2: The defender can defend
only against known attacks; the
attacker can probe for unknown
vulnerabilities.
Principle #3: The defender must be
constantly vigilant; the attacker can
strike at will.
Principle #4: The defender must play by
the rules; the attacker can play dirty.
Types of Threats
Network
Host
Threats against
the network
Spoofed packets, etc.
Threats against the host
Buffer overflows, illicit paths, etc.
Threats against the application
SQL injection, XSS, input tampering, etc.
Application
Intranet vs. Internet
Scenario #1: Intranet applications
Most accesses occur from behind firewall
Serve populations of users defined by
Windows user accounts
Scenario #2: Internet applications
Most accesses occur from outside firewall
Serve populations of users not defined by
Windows user accounts (such as eBay)
Intranet Applications
SQL permissions
database roles
ACL
authorization
Web server
Bob
Alice
Bill
A
A
Database server
A
IIS
A
A ASP.NET
Trusted
Connection
SQL Server
A
IPSec
Integrated Windows
authentication
Windows
authentication
Windows
authentication
Internet Applications
SQL permissions
Database roles
URL authorization
Web server
Database server
Bob
Bill
Firewall
Alice
IIS
ASP.NET
Trusted
connection
SQL Server
IPSec
Anonymous access
(no authentication)
Forms
authentication
Windows
authentication
Agenda
Overview of Web Security
ASP.NET Security Architecture
Web Service Security
Wrap Up
ASP.NET Security Architecture
IIS Security
ASP.NET Security
Principles and Identities
Trust Levels
ASP.NET Security Architecture
Overview of the ASP.NET Security
Architecture
Authentication
Authorization
Process identity (IIS 5 and IIS6)
Principle of least privilege
Using identity and principles
IIS Security
Protection and Pooling
Authorization
Web Metabase Permissions
Windows Access Controls Lists
Where should the
code execute?
What is the caller
allowed to do?
Authentication
Anonymous
Basic
Digest
X.509 Certificates
Integrated Windows
Passport (IIS 6)
SSL/TLS
IP Restrictions
Who did the request
come from?
Should traffic be
encrypted?
Are calls from this
IP address allowed?
ASP.NET Security
Authorization
ACL authorization
URL authorization
Impersonation
What is the caller
allowed to do?
Use process identity
or caller identity?
Authentication
Windows
Passport
Forms
Who did the
request come
from?
Windows Authentication
Anonymous
access disabled
Authentication
mode="Windows"
ACL
Ammar
IIS
A
IIS creates access
token identifying
Ammar and passes it to
ASP.NET
ASP.NET
A
ASPX
ASP.NET checks ACL
on requested file and
fails request if Ammar
lacks read permission
Forms Authentication
First access - Redirect to login page
ASP.
NET
Ammar
Login
Page
URL
T
ASPX
Authentication ticket
Next access - Authenticated access to ASPX
Ammar
T
ASP.
NET
URL
ASPX
ASP.NET Authorization
ACL authorization
Typically combined with Windows auth
Uses NTFS permissions to control access to
resources based on caller's Windows
identity
Does not require impersonation!
URL authorization
Often combined with forms authentication
Controls access to resources based on
caller's Windows, Passport, or forms identity
Applied in Web.config
ACL Authorization
Anonymous access
not permitted
Authentication
mode="Windows"
ACL
Bob
A
IIS
IIS creates access
token identifying Bob
and passes it to
ASP.NET
A
ASP.NET
A
ASP.NET checks ACL
on requested file and
fails request if Bob
lacks read permission
ASPX
URL Authorization
Web.config
<!-- Deny access to anonymous/unauthenticated users -->
<deny users="?" />
<!-- Grant access to Bob and Alice but no one else -->
<allow users="Bob, Alice" />
<deny users="*" />
<!-- Grant access to everyone EXCEPT Bob and Alice -->
<deny users="John, Alice" />
<allow users="*" />
<!-- Grant access to any manager -->
<allow roles="Manager" />
<deny users="*" />
Process Identity
IIS 6
Configurable per application pool
Credentials managed by IIS
IIS 5
Identity shared by all WPs on Web server
Credentials stored in Machine.config
<processModel userName="MyDomain\MyUserName"
password="..." ... />
Securing Process Credentials
On IIS 5, use Aspnet_setreg
ASP.NET 1.1 only; hotfix for 1.0
Machine.config
<processModel ...
userName="registry:HKLM\SOFTWARE\App\Identity\ASPNET_SETREG,userName"
password="registry:HKLM\SOFTWARE\App\Identity\ASPNET_SETREG,password"
/>
Registry
ASPNET_SetReg
Before We Continue…
Don’t Forget!
IIS 6.0 handles ALL of this for you.
You can still use this method, however
IIS 6.0 Application Pools are much
better.
Best Practice: Use IIS 6.0 Application
Pools and let IIS manage the
credentials.
Security Principals
Windows represents security principals
with access tokens
.NET Framework represents security
principals with security principal
objects
Abstracts the authentication type
Enables you to write (mostly) generic code
to query for user names, do role checks,
etc.
Principal objects expose useful data
about users
Authentication Ticket
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1,
// Version
userInfo.Username,
// Identity
DateTime.Now,
// Time issued
DateTime.Now.AddMinutes(30),
// Expiration date
false,
// Is persistent
userInfo.RolesArray
// User data
FormsAuthentication.FormsCookiePath // Path
);
String encTicket = FormsAuthentication.Encrypt( ticket );
Response.Cookies.Add(
new HttpCookie( FormsAuthentication.FormsCookieName,
encTicket
)
);
Response.Redirect(
FormsAuthentication.GetRedirectUrl(
userInfo.Username,
false
);
AuthenticateRequest Event
Capture the current security principal
object.
Capture the role information from the
authentication ticket.
Create a new principal object with the
roles from the ticket.
Change the current user context to the
new principal object.
Security Principal Objects
Identity object's IIdentity interface exposed as
principal object's IPrincipal.Identity property
GenericPrincipal
WindowsPrincipal
FormsIdentity
WindowsIdentity
PassportIdentity
GenericIdentity
IPrincipal
A
IIdentity
Identity object encapsulates Windows
access token if type is WindowsIdentity
IPrincipal and IIdentity
// Find out whether the caller is authenticated
if (HttpContext.Current.User.Identity.IsAuthenticated) {
// The caller is authenticated
}
// Get an authenticated caller's user name
string name = HttpContext.Current.User.Identity.Name;
// Perform a programmatic role check
if (HttpContext.Current.User.IsInRole ("Managers") {
// The caller is a manager
}
// Get the caller's access token
if (HttpContext.Current.User.Identity is WindowsIdentity) {
IntPtr token = ((WindowsIdentity)
HttpContext.Current.User.Identity).Token;
...
}
AuthenticateRequest Event
if(context.User.Identity.IsAuthenticated){
GenericPrincipal oldPrincipal = HttpContext.Current.User;
FormsIdentity formsIdent =
(FormsIdentity)oldPrincipal.Identity;
FormsAuthenticationTicket ticket =
FormsAuthenticationTicket = formsIdent.Ticket;
GenericPrincipal newPrincipal = new GenericPrincipal(
oldPrincipal.Identity,
ticket.UserData.Split(";")
);
HttpContext.Current.User = newPrincipal;
}
Identity Object
Encapsulates information about the
user or entity being validated.
At their most basic level, identity
objects contain:
The user’s name.
An authentication type (i.e. “Forms”).
Implements the IIdentity interface.
Principal Object
Represents the security context under
which code is running, including:
That user's identity.
Any roles to which the user belongs.
Applications grant rights based on the
role associated with a principal object .
Use the principal object to perform
authorization.
Implements the IPrincipal interface.
Security Principal Instance
Identity object's IIdentity interface is
exposed as principal object's
IPrincipal.Identity property
IsInRole()
Identity
Name
IsAuthenticated
AuthenticationType
IPrincipal
IIdentity
Security Events in Page
Lifecycle
Application.AuthenticateRequest
Occurs after BeginRequest.
HttpContext is available.
Create the identity and principal objects
here.
Application.AuthorizeRequest
Occurs before AquireRequestState.
Handle any custom authorization here.
Session state does not become
accessible until after both of these
events.
Forms Authentication - Roles
Handle AuthenticateRequest event
Create GenericPrinciple
Attach roles to Identity
Assign new Principle to User
Sub 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 If
End Sub
Roles & the Ticket
SQL Server 2000
Authentication Ticket
UserData
Role
Collection
Authentication Ticket
You can include role data in the
authentication ticket.
Authentication ticket is persisted in a
cookie.
Authentication ticket information is
encrypted in the cookie.
You should never use a persistent
cookie.
ASP.NET 2.0
In ASP.NET 2.0, all this is done for you.
Membership Service
Represents users
Provider-based
Role Management Service
Represents Roles
Users map to zero to many roles
Provider-based
Membership Service
Service for managing users and
credentials
Declarative access via Web Site Admin
Tool
Programmatic access via Membership and
MembershipUser classes
Membership class provides base
services
MembershipUser class represents
users and provides additional services
Provider-based for flexible data storage
Membership Schema
Controls
Login
LoginStatus
Other Login
Controls
LoginView
Membership API
Membership
MembershipUser
Membership Providers
AccessMembershipProvider
SqlMembershipProvider
Membership
Data
Access
SQL Server
Other Membership
Providers
Other
Data Stores
The Membership Class
Provides static methods for performing
key membership tasks
Creating and deleting users
Retrieving information about users
Generating random passwords
Validating logins
Also includes read-only static
properties for acquiring data about
provider settings
The MembershipUser Class
Represents individual users registered
in the membership data store
Includes numerous properties for
getting and setting user info
Includes methods for retrieving,
changing, and resetting passwords
Returned by Membership methods such
as GetUser and CreateUser
Membership Providers
Membership is provider-based
Provider provides interface between
membership service and physical data
store
Beta 1 ships with two providers
AccessMembershipProvider (Access)*
SqlMembershipProvider (SQL Server)
Use custom providers for other data
stores
* Has been replaced by SQL Express provider in beta 2
Role Management Service
Role-based security in a box
Declarative access via Web Site Admin Tool
Programmatic access via Roles class
Roles class contains static methods for
creating roles, adding users to roles, etc.
Maps users to roles on each request
Replaces Application_AuthenticateRequest
Provider-based for flexible data storage
Role Management Schema
Controls
Login
Roles API
LoginStatus
LoginView
Other Login
Controls
Roles
Role Providers
AccessRoleProvider
SqlRoleProvider
Other Role Providers
Roles Data
Access
SQL Server
Other
Data Stores
The Roles Class
Gateway to the Role Management API
Provides static methods for performing
key role management tasks
Creating and deleting roles
Adding users to roles
Removing users from roles and more
Also includes read-only static
properties for acquiring data about
provider settings
Role Caching
Role manager offers option for caching
role data in cookies
Fewer accesses to data store
Better performance
Controlled via <roleManager> attributes
and programmatically exposed thru
Roles class
Should roles be cached in cookies?
Should role cookies be encrypted?
How long are role cookies valid?
Role Management Providers
Role management is provider-based
Beta 1 ships with four providers
AccessRoleProvider (Access)*
AuthorizationStoreRoleProvider
(AuthMan)
SqlRoleProvider (SQL Server)
WindowsTokenRoleProvider (Windows)
Use custom providers for other data
* stores
Will be replaced by SQL Express provider in beta 2
ASP.NET Trust Levels
Trust Level
Full
High
CAS Restrictions (Cumulative)
None
Can't access Windows event log
Can't access OLE DB data sources
Can't call unmanaged code
Medium
Limited access to environment variables
File I/O limited to own directory hive
Can't access registry
Can't perform reflection
Can't call remote servers
Can only call local Web services
Low
Can't access environment variables
File I/O limited to reading from own directory hive
Can't access SQL Server databases
Can't call Web services
Minimal
Can't do much of anything
Full Trust
SQL Server
Unmanaged
Code
OLE DB
SqlClientPermission
Registry
SecurityPermission.UnmanagedCode
OleDbClientPermission
File System
RegistryPermission
FileIOPermission
DNS
Application
DnsPermission
EnvironmentPermission
Environment
Variables
EventLogPermission
SocketsPermission
Windows
Event Log
WebPermission
Web Services
Remote Servers
High Trust
SQL Server
Unmanaged
Code
OLE DB
SqlClientPermission
Registry
File System
RegistryPermission
FileIOPermission
DNS
Application
DnsPermission
EnvironmentPermission
Environment
Variables
EventLogPermission
SocketsPermission
Windows
Event Log
WebPermission
Web Services
Remote Servers
Medium Trust
SQL Server
Unmanaged
Code
OLE DB
SqlClientPermission
Registry
File System
FileIOPermission
Application
DnsPermission
DNS
Restricted
EnvironmentPermission
Environment
Variables
Windows
Event Log
WebPermission
Restricted
Web Services
Restricted
Remote Servers
Low Trust
SQL Server
Unmanaged
Code
OLE DB
Registry
File System
FileIOPermission
Application
DNS
Environment
Variables
Heavily Restricted
Windows
Event Log
Web Services
Remote Servers
Agenda
Overview of Web Security
ASP.NET Security Architecture
Microsoft Reference Application for
OpenHack
Web Service Security
Wrap Up
What is OpenHack?
Regular contest sponsored by eWEEK
Who can build most hack-resistant Web
app?
Participants build app to eWEEK specs
eWEEK invites all comers to hack it
2002 participants: Microsoft and Oracle
i
http://www.eweek.com/article2/0,3959,741388,00.asp
Microsoft Reference
Application for OpenHack
Microsoft's entry in the 2002
competition
Withstood 80,000+ attacks without a
single breach of security
Written by Vertigo Software and
Microsoft
Code updated since the competition
You get the latest version!
Great example of how to do security
right
Application Architecture
Anonymous
access
Forms authentication
URL authorization
Trusted
SQL
connection permissions
Validation
Layer
Private
Data Access
Layer
IIS
Public
ASP.NET
Protection
Layer
DPAPI
Registry
Connection
strings etc.
Awards
Database
Decryption
keys
Windows
authentication
Forms Authentication
Two-tiered directory structure
Root contains "public" pages (including
the login page)
"Secure" subdirectory contains pages that
require logins
Forms authentication cookie
Always temporary, never persistent
30-minute time-out
Cookie path set to app directory
Input Validation
User input constrained by validation
controls
Input and output sanitized by validation
layer
Sanitize
User Input
Validation
Controls
All Input
Pages
CleanString
HTMLEncode
Other Input
Output
Awards Database Security
Users
One account: webuser (Windows
principal)
Maps to ASP.NET worker process identity
Stored Procedures
30 stored procedures
Used for all interaction with database
Permissions
webuser permitted to call stored procs
"public" granted no permissions
anywhere
Data Access
Multitiered data access layer
All accesses via stored procedures
All accesses performed by webuser
Windows authentication to SQL Server
Connection string DPAPI-encrypted and
stored in ACLed registry key
Data Protection
Registry secrets
HKLM\Software\Microsoft\OpenHack4
DPAPI-encrypted connection string
DPAPI-encrypted crypto decryption key
DPAPI-encrypted crypto initialization vector (IV)
DPAPI entropy value
ACL grants full control to admins and
SYSTEM, read access to ASP.NET worker
process
Database secrets
Encrypted passwords
Encrypted credit card numbers
Error Handling and Logging
Default error page
defaultRedirect points to Error.aspx
Provides generic response to errors
Application_Error
Logs unhandled exceptions in Windows
event log
Includes stack trace and other rich error
info
Failed logins
Logged separately in Windows event log
Aid in forensic analysis and intrusion
detection
Summary
MS Reference Application for OpenHack
MRAO scrubs and validates input
MRAO accesses data securely
MRAO encrypts sensitive data
MRAO uses forms authentication and
URL authorization
MRAO handles errors securely and logs
them as appropriate
MRAO is a secure application!
Agenda
Overview of Web Security
ASP.NET Security Architecture
Microsoft Reference Application for
OpenHack
Wrap Up
Rant
Do not store passwords either in clear
text or with reversible encryption!
Makes me angry.
Storing Login Passwords
Don't store passwords in login databases
Store password hashes for added
security
Salt hashes to impede dictionary attacks
Format
Comments
Plaintext passwords
Exposes entire application if database is
compromised
Encrypted passwords
Better than plaintext, but still vulnerable if
decryption key is compromised
1-way password
hashes
Better than encrypted passwords, but still
vulnerable to dictionary attacks
Salted password
hashes
Less vulnerable to dictionary attacks
Resources
Steve’s Blog: http://blog.accentient.com
Rich’s Blog: http://blog.hundhausen.com
MS Security:
http://www.microsoft.com/security
Your Feedback
is Important!
Please Fill Out a Survey for
This 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.