Title: Best Practices for Building Secure Solutions
1Best Practices for Building Secure Solutions
- Peter Willmot
- Peter.Willmot_at_XpertEase.co.za
2A quick refresh on security challenges
3Security requires a holistic approach
Network
Host
Application
Port blocking Filtering Encryption
Updates IIS hardening ACLs CAS Logging Least
privilege Account mgmt.
Validation Hashing Encryption Secrets
mgmt. Cookie mgmt. Session mgmt. Error handling
Defend the network
Spoofed packets, etc.
Buffer overflows, illicit paths, etc.
Defend the host
SQL injection, XSS, input tampering, etc.
Defend the application
4Critical Security Principles
- Minimise the Attack Surface
- Defend in Depth
- Design for Sustainability
- Test rigorously
- In a meaningfully representative environment
- .. and use the OS / Tools if you can
5Dont Advertise / Disclose too much
Well-known Product / Services Signatures
Server and Service Identity Data in URLs / e-mails
Unhandled exception messages
Over-friendly error messages
6Protect your Servers
Apply sound Service Layering practices
Stay current with service packs and updates
Monitor Event Logs and Resources
Use Windows Firewall or Reverse Proxy
Apply the principle of least privilege
Lock-down IP, File System and Registry
Lock-down Services and Configurations
Manage / Monitor the configuration
7Authenticate Rigorously
Strong Authentication is key to non-repudiation
Leverage Active Directory / Kerberos if you can
Browser / Client can not be protected by SSL
Take Identity Management as close to the
source as you can in federated environments
8Validate all Inputs / Parameters
Never trust user input (always validate!)
Dont Echo Input Directly Back to Browser
Secure ASP.NET session state
Store secrets securely (dont use hidden fields)
Anticipate errors and handle them appropriately
9ASP.Net Input Validation Tools
10Error Handling
Anticipate errors and handle them sensibly
Use ltcustomErrorsgt to display custom error pages
Don't reveal too much information in error pages
Beware mode"off" and debug"true"
Log unhandled exceptions
Be aggressive about logging failures
11Log Unhandled Exceptions
Global.asax
void Application_Error (Object sender, EventArgs
e) // Formulate message to write to event
log string msg "Error accessing "
Request.Path "\n" Server.GetLastError
().ToString () // Write the message to
Windows event log EventLog log new EventLog
() log.Source "My ASP.NET Application"
log.WriteEntry (msg, EventLogEntryType.Error)
12.. or e-mail them somewhere
Global.asax
lt_at_ Import Namespace"System.Web.Mail" gt
ltscript language"C" runat"server"gt void
Application_Error (Object sender, EventArgs e)
MailMessage message new MailMessage ()
message.From WebApp_at_XpertEase.co.za"
message.To AppManagement_at_XpertEase.co.za"
message.Subject "Unhandled Exception"
message.Body "Error accessing " Request.Path
"\n" Server.GetLastError ().ToString
() SmtpMail.SmtpServer smtp.xpertease.co.z
a" SmtpMail.Send (message) lt/scriptgt
13Secure SQL Data Access
Use stored procedures or parameterized commands
in lieu of dynamic SQL commands
Never use privileged accounts to access DBs
Store connection strings securely
Do not assume only authorised apps will connect
Partition your schema application identity
to access SPs only
14Securing Connection Strings
15Defending against SQL Injection
- Injection Example
- SqlCommand myCommand new SqlCommand("SELECT
ModelName FROM Products WHERE ProductID "
productID, myConnection) - Basic Stored Procedures are not necessarily a
mitigation - CREATE Procedure GetProductDetails( _at_ProductID
VARCHAR(100) ) - AS
- DECLARE _at_sql AS VARCHAR(4000)
- SET _at_sql 'SELECT ModelName FROM Products WHERE
ProductID ' _at_ProductID - EXECUTE(_at_sql)
16Defending against SQL Injection
- Mitigation using stored procedures
-
- SqlParameter parameterProductID
- new SqlParameter("_at_ProductID", SqlDbType.Int,
4) - myCommand.Parameters.Add(parameterProductID)
- myConnection.Open()
- SqlDataReader result myCommand.ExecuteReader(Co
mmandBehavior.CloseConnection) -
- CREATE Procedure GetProductDetails(_at_ProductID
int) - AS
- SELECT ModelName
- FROM Products
- WHERE ProductID _at_ProductID
17Use Code Access Security (CAS)
- Defines permissions that represent the right to
access resources - Enables administrators to configure security
policy - Enables code to request the permissions it
requires to run - Enables code to Authenticate Callers Identity
- Enables code to demand that its callers have
specific permissions
18Consider AzMan for Application AuthZ
- A Role Based Access Control mechanism which
allows you to - Isolate Authorisation rules from Code
- More long-term flexibility in aligning changing
business rules to Security - Maintenance of Security becomes and IT Admin Role
- Rules consist of
- Operations Low Level granular steps in a
process - Tasks High Level groups of related Operations
- Roles - allowed to access the above
- Auditing to Windows Security Event Log is
supported - These rules can be
- Stored in XML, AD and ADAM
- Shared by multiple Applications
19Visual Studio 2005 EnhancementsManaged Code
20Develop Under Less Privileged Account
- Developing under Least Privileged account is a
good practice - User will not run your application as an
administrator - When developing as admin you may be unaware that
non-admin accounts dont have access to resources
that you may access - Visual Studio 2005 runs much better under non
administrative account than previous versions
21Code Access Security
- Applies security to Assembly Identity
- Allows restriction on the actions an assembly can
perform - Predefined permission sets are available to
sandbox low trust code - Visual Studio 2005 allows the developer to
select a target permission set
22Permissions Calculator
- PermCalc replaces the PermView utility
- Looks into assemblies on which target has
dependencies - Traces through possible code paths to detect
imperative security request - Available as both a command line tool and
integrated into Visual Studio
23Application Domain Security
- Application Domains can be created to sandbox
assemblies - Process for creating a sandbox has been
simplified under the 2.0 framework
24FxCop
- Integrated into Visual Studio
- Identifies Design Issues and supplies information
on how to fix them - Enforces Microsoft .Net Design Guidelines
- Can be used as a part of the code check-in policy
25Visual Studio 2005 EnhancementsUnmanaged Code
26Application Verifier
- Performs Active Monitoring of an applications
resource usage - Analyzes behavior in of application to look for
common problems, e.g. - Incorrect Lock usage in critical sections
- Use of invalid handles
- Heap corruption issues
- Makes suggestions on how to avoid detected
problems
27Code Analysis
- Similar to FxCop, but for Unmanaged code
- Performs static analysis of source code
- Individual checks can be enabled / disabled, but
through code directives rather than the
Properties page - Notifies developer about possible defects in
code, e.g. - Use of uninitialised variables
- Type conversion problems
- Parameters with incorrect sizes / lengths
28Buffer Security Checks
- Buffer Security Checks enabled with /GS
compilation switch - Checks for buffer overflow at the end of each
function - Terminates a program if buffer overflow is
detected - Always enabled in Debug mode
29Safe C Runtime Libraries
- Many functions in the standard C runtime library
can be the target of Buffer Overflow attacks - Unsafe functions have been deprecated
- Replacement functions have error checking and
validation
strcpy( char Destination, char Source )
while ( Destination Source )
30SQL Server Enhancements
31Secure by Default
- If SQL Server 2005 is installed and no options
are changed, it is installed in a secure state - Access to many resources must now be explicitly
granted or enabled before being used
32Password Policy and Authentication
- SQL Server 2005 can inherit the Password Policy
when hosted on Windows 2003 - Can be enabled or disabled on a per login basis
- Logins can be enabled and disabled
- Login protocol uses stronger channel
- Uses SQL Server generated certificate
- No SSL certificate loading is required
33User-Schema Separation
- Objects are associated with a schema instead of a
user - You no longer need to drop owned objects to
removing owner users - Object naming scheme and resolution have been
changed - server.database.schema.object
- You no longer need to use dbo as a catch-all
owner of objects - You dont need to change application code if you
drop the user that created the objects - Users can be assigned a default schema
34Granular Permissions
- Permissions can be applied to three scopes
server, database, and schema - New Permissions
- CONTROL all permissions granted to objects
owner - ALTER provides ability to alter the properties
of an object - IMPERSONATE permits impersonating a user
- VIEW DEFINITION gives access to an objects
metadata - Securable entities
- Tables, views, assemblies, servers, .
- Catalog Security
- System tables are no longer accessed directly
- A Login can no longer find out what other
databases exist - Metadata is access via Views with permissions set
at the row level - A user may only view metadata for an object if an
owner or has permissions to access the object
35Endpoint Security
- An Endpoint is a point of entry into SQL Server
- Endpoint Transports Include
- Shared Memory
- Named Pipes
- TCP
- Virtual Interface Adapter
- HTTP (Windows 2003 Only)
- HTTP Transport is not created by default
- HTTP Endpoints support four authentication types
for web methods - Basic, Windows Integrated, Digest, Kerberos
- Anonymous is not allowed
- IIS does not need to be running on the server to
host HTTP Endpoints - Communications can be secured with SSL
- With auto-generated certificates if required
36Execution Context
- EXECUTE AS CALLER (default)
- EXECUTE AS USER
- EXECUTE AS SELF
- EXECUTE AS OWNER
37Crypto Support
- SQL Server now has built in support for
encryption and decryption - With previous versions, you needed to use
external code - Keys can be secured within or external to SQL
Server - Supports
- Symmetric encryption (EncryptByKey)
- Asymmetric encryption (EncryptByAsymKey)
- Encryption by Phrase (EncryptByPassPhrase)
- Certificates (EncryptByCert)
38Any Questions?
- Peter Willmot
- Peter.Willmot_at_XpertEase.co.za
39(No Transcript)