You are on page 1of 207

Secure Architecture and Coding

Application Security Verification Standard 1.0 (beta)


ESAPI 1.4

Andrew van der Stock


vanderaj@owasp.org

OWASP

Copyright 2009 © The OWASP Foundation


Permission is granted to copy, distribute and/or modify this document
under the terms of the OWASP License.

http://www.owasp.org
Introductions
Andrew
• Lead, OWASP Guide
van der Stock
• WebAppSec Moderator

• Set SANS GSSP (Java)


exam

• SANS Top 20 (web apps)

• Executive Director (2005-


7)

• Lead, OWASP Top 10


2007
You?

• Name

• Company

• Objectives

• Favorite lolcat?
Build Secure Applications

• Required by PCI (credit cards)

• Required by law in some countries

• Required by standards in many industries


BUILDING != PEN TESTING

• It takes one or two days


and two blokes with one
bull dozer to destroy a
house

• It takes a team of
professionals and several
months to build a house
The role of security

• Security enables secure


business

• Without security, no
business is possible
Application Security
Verification Standard

• Level 1 Automated
verification

• Level 2 Manual verification

• Level 3 Design verification

• Level 4 Internal verification


Level 1
Automated Verification

• Minimum required to claim compliance with ASVS

• Level 1A - Automated Dynamic Test

• Level 1B - Automated Static Code Analysis


Level 2
Manual Verification

• Level 2

• Optionally, a superset of Level 1

• Level 2A - Manual Penetration Test

• Level 2B - Manual Static Code Review


Level 3
Design Verification
• For apps that deal with legally
protected data

• Design is suitable for asset


value

• Any security controls are


Positive and Centralized

• Perform a Level 2 Manual


Verification
Level 4
Internal Verification
• Security Architecture

• All controls are Positive,


Centralized, Exist, Used
and Enforced

• No malicious software

• Documentation Exists
Reporting Standard

• ASVS has a report


format

• Introduction

• Describe Target

• Architecture

• Verification Results
Enterprise Security API

• Solves about 80% of all


security issues for you

• J2EE, .NET and PHP


ports

• Almost as easy as linking


with ESAPI
ESAPI Features

• Automated request rate regulator (Thresholds)

• Automated intrusion detection

• Safe values from the request

• 10 encoders, canonicalizers, and decoders

• Encrypted properties

• Structured Exception Handling


ESAPI Interfaces

• Authenticator
• User
• AccessController
• AccessReferenceMap
• Validator
• HTTPUtilities
• Executor
• Encoder
• SafeRequest, SafeResponse
Risk management
Humans suck at RISK

• Very few understand basic risk management

• Few know the likelihood of any particular event

• Even less understand the real impact of an event

• The Business just wants to do stuff - whatever the


consequences!
More likely to die?

• Riding to the airport

• Driving to the airport

• Flying from the airport


Best odds?

• Poker machines

• Two up

• Roulette

• Blackjack
Which is more likely?

• Winning Lotto

• Being struck by lightning


Which is more likely?

• Drowning

• Being eaten by a shark


Which is Safer?

• You have 35 meters to


stop from 100 km/h to
avoid hitting a concrete
wall

• Which car will be safer?

• Mini

• Hummer H2?
Risk is simple

• Risk = likelihood x impact

• Web app factors are different to normal apps

• OWASP Risk Management Process


Risk Applies to assets
not threats
• Think about your assets

• You don’t insure for flood,


you insure the house and
contents

• You don’t insure for an


accident, you insure the
replacement value of the
car

• You don’t insure for cancer,


you insure your health
OWASP RIsk Management

• Designed for web apps

• 8 Likelihood Factors

• 8 Impact Factors

• See worksheet
Architecture
V1 - Security Architecture Verification Requirements

1A 1B 2A 2B 3 4
Architecture

• A well designed application has a security architecture

• Security architecture supports the business goals

• A secure application may not have many security


features
Controls

• Not just a complete set of check boxes

• Selected Controls must be:

• Present

• Functional

• Used properly
Functional Requirements

• Security features that require definition in every single


app:

• Identity and access control

• Accountability

• Secure communications and storage


Non-functional requirements

• Something an application has, or the qualities of a


system

• Typical examples include: Usability, Performance,


Scalability, Testability, Maintainability, Compatibility

• Not optional - Security is the only non-functional


requirement of all applications
Structure

• Web MVC n-tier is now well established as best


practice

• Separate user, admin, CSR applications


Identity

• Who can enrol in your app? Why? Regulations? Laws?

• What roles exist within the application? Which users


have those privileges? How are those managed?

• Separation of duties - required by law


1.1 Components

• Don’t get bogged down by detail

• Identify major components

• Functions

• Connections

1A 1B 2A 2B 3 4
1.2 Architecture

• ASVS: Create or verify the architecture

• Identity

• Accountability

• Data Protection

2A 2B 3 4
1.3 Connections
• ASVS: Define or verify connections between all
components

• Authenticated

• Access Controlled

• Input validation / canonicalization / encoded

• Accountable

• Protected
34
1.4 Documentation

• ASVS: Create or Find Architecture Documentation

• Architecture

• Components

• Connections

• High level design

34
1.5 Code Integrity

• ASVS: Ensure architecture artifacts and code has high


quality integrity controls

• Document Control

• Hashes of code

• Digital signing of code

4
Identity and Authentication
V2 Authentication Verification Requirements

1A 1B 2A 2B 3 4
Authentication

• Associating a person (identity) with a user principal

• Accountability

• Controls to prevent identity theft and fraud


Evidence of identity

• Determined by regulation or your asset value

• 100 point check (Austrac)

• Credential recovery MUST equal this strength


“Secret” Questions and
Answers ... suck
• Use the Internet to discover:

• The city where I was born

• My high school mascot

• My pets’ names

• For bonus points, my mother’s maiden name

• You have until the end of the module!


Two factor authentication

• Something you know

• Something you have

• Something you are (No!)

• Cannot create the “Something you are” remotely

• Authenticators must be robust in the face of determined


attack
Single factor authentication

• Something you know (typically)

• Passwords

• PINS

• Too weak for all but brochureware web sites


2.1 Complete Mediation

• ASVS: Requires all secured resources and secured


functions to be authenticated

• Except public resources and functions (login, help,


etc)

1A 1B 2A 2B 3 4
2.2 Central Control

• ASVS: Requires a single authentication mechanism

• Tip: Try to minimize use of any additional authenticators

• Tip2: Disable unused authenticators

2B 3 4
2.3 Server side Decisions
• ASVS: Requires authentication server side decisions

• Authentication business logic and data must be server


side

• Authentication tokens should be random

• BAD http://www.example.com/some/feature?auth=y

• Good - use the session cookie

• Ajax and RIA logins still possible, but not 100% client-
side 2A 2B 3 4
2.4 Malicious Code

• ASVS: Requires
authentication controls
have no malicious code

• Callers

• Centralized routines

4
2.5 Fail securely

• ASVS: Requires authentication code to fail securely

• Failure modes should not result in successful


authentication

• Log all failures

2A 2B 3 4
2.6 Logged

• ASVS: Requires all authentication decisions to be


logged

• Most other standards, too

• Success and Failure!

• Make all security events easily found and analyzed


2B 3 4
2.7 Credential strength
• ASVS: Requires credentials to resist likely brute force
attacks

• Horizontal brute forcing (dynamic username, static


password)

• Vertical brute forcing (static username, dynamic


password)

• Use Two Factor Authentication!

• Still vulnerable to brute force attacks

• Not likely to succeed 2A 2B 3 4


2.8 Password Hashes

• ASVS: Requires passwords to be salted and one way


hashed

• Salt: Use a random nonce per user and store it

• Hash: Use SHA-256 or better

• Salting prevents rainbow tables

• Hashing prevents password disclosure


2B 3 4
2.9 Failure Counts

• ASVS: Requires account to be locked out if too many


attempts

• Soft lockout!

• Choose a reasonable limit 3 - 5 attempts

1A 2A 2B 3 4
Last Login Time

• This is a basic intrusion detection mechanism

• Required by many Info Sec standards

• Lets users work out if someone is doing the wrong


thing

• Make it easy to report suspicious activity - link!


Failed Login
• Tell the user about

• Failed Logins

• Failed Credential Recovery Attempts

• Limit the number of logins and recovery attempts

• Per user: to no more than a few times per hour

• Per app: to no more than a hundred or so per hour


2.10 Account Management

• ASVS: Requires account management functions to be


robust

• Do not use secret questions and answers

• Not needed for tokens - sync issues instead

• E-mail the user with a time limited activation code

• Limit account capabilities for 24+ hours


2A 2B 3 4
2.11 Password Controls

• ASVS: Do not echo passwords or credentials

• Use the “Password” type - bullets appear

• Do not include credentials in hidden fields, headers,


cookies

• Do not include credentials in dynamic JavaScript

• Do not include credentials in HTML comments


1A 1B 2A 2B 3 4
2.12 Change credentials

• ASVS: Requires users to be able to change their


password

• Think about changing username and other elements,


too

• Tip: Most Privacy Laws require “Delete means delete!”

2A 2B 3 4
2.13 SECURE Credentials

• ASVS: Requires credentials to be:

• Stored securely in a centralized location

• Encrypted (preferably salted and hashed)

• Not in source code

2B 3 4
2.14 Re-authentication

• ASVS: Requires re-authentication for “value”


transactions

• Prevents unauthorized use of an application

• Awesome Tip: Use transaction signing, SMS


authentication!

2A 2B 3 4
DEMO

• WebGoat

• Fail open authentication


Session and State
Management
V3 Session Management Verification Requirements

1A 1B 2A 2B 3 4
Session management

• Secure session managers are vital for security

• All major frameworks have one - use it!


3.1 Default Session Manager

• ASVS: Requires the application to use the framework


session manager

• Store authentication, authorization tokens in session


object

• WAFTAM Alert! Do not develop your own session


manager!
1A 2A 2B 3 4
3.2 Malicious Code

• ASVS: Requires inspection of session manager code


for malicious code

• Hint: I’ve never done this, and I’ve been doing it for 10
years.

4
3.3 Invalidate Sessions

• ASVS: Requires session to be completely invalidated


when user clicks logout

• Destroy all objects held by the session object

• Destroy the session object

• Regenerate a new session ID and redirect the user


1A 2A 2B 3 4
3.4 Timeouts

• ASVS: Requires applications to have a reasonable idle


time out

• 5 minutes for high value apps

• 20 minutes for most apps

• 8 hours (max) for low value apps


1A 2A 2B 3 4
3.5 Absolute timeout

• ASVS: Requires applications have an absolute time out

• Suggest 8 hours or a configurable “open window” panel

• Few apps actually need this control

34
3.6 Session regeneration
• ASVS: Requires session token to be regenerated upon:

• Login

• Re-authentication

• Logout

• Also suggested: Change from HTTP to HTTPS


2A 2B 3 4
3.7 Secure Session Tokens

• ASVS: Requires frameworks to issue “secure” session


IDs

• Do not use URL re-writing (c:url in particular)

• Look for “secure” in the HTTP header

• Most frameworks do not do this today

• Log a defect with your framework vendor


1B 2B 3 4
3.8 Logout on every page

• ASVS: Requires the application to have a logout link or


button on every page

• Rationale:

• Allows users to safely logout in a hurry (say at an


airport)

1A 2A 2B 3 4
3.9 Session integrity
• ASVS: Requires applications to only honor issued
tokens

• PHP for example, doesn’t.

• You can send in PHPSESSIONID=abc and PHP will


use that.

• This allows session fixation attacks


2A 2B 3 4
Demo

• WebGoat

• Fail Open
Authentication

• Secondary
Session
Management
Access Control
V4 Access Control Verification Requirements

1A 1B 2A 2B 3 4
Access Control

• Access control maps


users to roles

• Roles define what a user


can do

• Without access control,


any user can do anything
to any resource or
function
4.1 Secured URLs

• ASVS: Requires users only to have access to URLs


they have permission to use

• Deny all by default

• Always make a decision - even for public URLs

1A 2A 2B 3 4
4.2 Secured Files

• ASVS: Requires users only to have access to files they


have permission to use

• Deny all by default

• Always make a decision - even for public files

• Use access reference maps (later in this module)


1A 2A 2B 3 4
4.3 Directory Browsing
• ASVS: Requires directory browsing to be disabled...
unless you need it to be on

• Protects against search engine attacks

• Configuration change required for nearly every


framework!

• Can also hide using index.html tricks


1A 2A 3 4
4.4 Secured Functions

• ASVS: Requires users only to have access to functions


they have permission to use

• Deny all by default

• Always make a decision - even for public functions

• This is doubly true for Ajax / RIA / JS libraries


1A 1B 2A 2B 3 4
4.5 Secured Services

• ASVS: Requires users only to have access to services


they have permission to use

• Deny all by default

• Always make a decision - even for public services

• This is doubly true for Ajax / RIA / JS libraries


2A 2B 3 4
4.6 Secured Data

• ASVS: Requires users only to have access to data they


have permission to use

• Deny all by default

• Always make a decision - even for public data

• Best to implement in the DAO layer


2A 2B 3 4
4.7 Fail securely

• ASVS: Requires access control decisions to fail


securely

• Access is denied if the decision evaluation process


fails 2A 2B 3 4
4.8 Logging

• ASVS: Requires

• All access control decisions can be logged

• All failed access control decisions be logged by


default

2B 3 4
4.9 Same access control
rules

• ASVS: Requires the same access control rules for all


paths

• e.g. Ajax based “Add member” and web app “Add


member” should have the same access control rules
evaluated by the same code

2A 2B 3 4
4.10 Integrity of access
control rules
• ASVS: Requires access control rule repository to be
secure from unauthorized changes

• Code: Reasonably safe

• Database or configuration files:

• Protect from change

• Log all changes


2A 2B 3 4
4.11 Direct object references

• ASVS: Requires applications to protect direct object


references

• Primary keys (example_id), files, reports, etc

• Only give access to records or resources allowed for


that user

1A 2A 2B 3 4
Access Reference Maps

• Solves direct object reference attacks - permanently

• ESAPI is your friend - see AccessReferenceMap


4.12 Single Security Control

• ASVS: Requires access control code to be centralized

• All access control checks use a common code base

• Complete mediation: All entry points are access


controlled

2B 3 4
4.13 Server Side ACCESS
CONTROL
• ASVS: Requires server
side access control

• Client side access control


is trivial to bypass

• Do not rely on “secret”


parameters

• Store roles in session


2A 2B 3 4
4.14 Malicious Code

• ASVS: Requires all


access control code to be
reviewed for malicious
code

• Callers

• Implementation

4
4.15 Business Limits

• ASVS: Requires access control based upon business


limits to be enforced

• e.g. Cinema booking system

• 1-15 Seats == Retail users

• 16+ Seats == Group booking only

2A 2B 3 4
Demo

• WebGoat

• Path Based Access Control


Input validation
V5 Input Validation Verification Requirements

1A 1B 2A 2B 3 4
Strong typing
• Many languages, such as PHP and Perl, are not
strongly typed

• This is a HUGE security mistake

• Force your data into the correct type as quickly as


possible

• XSS is not possible if data is a float or an integer


Ranges

• Integers (-231-1 ... 231-1 or -263-1.. 263-1)

• Unsigned integers ( 0 ... 232-1 or 0 .. 264-1)

• Natural numbers (1... n)

• Currency
Length

• Strings should have a maximum length

• Overlong strings lead to buffer overflows

• Bad math with long strings leads to buffer overflows


5.1 Character Set

• Always set a character set

• ISO 8859-1 or UTF-8

• Let the user select from a valid set of safe character


sets

2A 2B 3 4
5.2 Canonicalization

• ASVS: Requires input to made into the simplest


possible form before any work is performed

• Without ESAPI: UNBELIEVABLY, STUPIDLY, REALLY


HARD™

• With ESAPI: Relatively easy


34
5.3 Positive validation

• ASVS: Requires positive validation over all other


mechanisms

• Positive validation

• Sanitization

• Negative validation

• No validation
1A 2A 2B 3 4
5.4 Single Mechanism
• ASVS: Requires a single input validation mechanism

• All data passing through a trust boundary should be


validated

• All callers to use the centralized input validation


routines

• Hook framework to input validation routines


2B 3 4
5.5 Server Side VALIDATION

• ASVS: Requires server side input validation

• Ajax / JS / RIA input validation is allowed...

• Just have to repeat that on the server!

2A 2B 3 4
5.6 Malicious code

• ASVS: Requires highly


protected input validation
to be free of malicious
code

4
5.7 Reject, not sanitize

• ASVS: Positive input validation routines should reject


bad input

• DO NOT sanitize bad input!

• Assumes you know more than the attacker does

1A 2A 2B 3 4
5.8 Log all failures

• ASVS: Requires access control failures to be logged

• Tip: Allow configurable logging for success and other


events

2B 3 4
5.9 Buffer overflows

• ASVS: Requires applications to have no buffer


overflows

• Good luck with that :-)

• Buffer overflows are at least 37 years old

• Morris Worm recently celebrated 20th birthday


1A 1B 2A 2B 3 4
Demo

• WebGoat
Output Encoding
V6 Output Encoding / Escaping Verification
Requirements

1A 1B 2A 2B 3 4
Last Chance Workout

• Output encoding is often considered the “fix” for XSS

• NO! It’s the last chance before you’re hosed

• Consider it defense in depth if input validation fails


Do not store pre-encoded

• Tip: Just in time output encode for only the output


mechanism (i.e. SMTP, RSS, SOAP, etc)

• It may be tempting but:

• Do not store encoded or escaped data!

• HTML Encoded data is not safe for XML or LDAP or


...
6.1 Choose the right encoder

• ASVS: Requires the selection of the correct encoder for


the mechanism

• LDAP encoding does not mean anything to a browser

• HTML encoding is NOT safe for CSS elements

• ESAPI has 10 encoders so far

2B 3 4
6.2 Single Mechanism

• ASVS: Requires a single, centralized output escaping


and encoding mechanism

• Code should be re-factored to use the single


mechanism

34
6.3 Server Side

• ASVS: Requires output encoding mechanism to be


enforced server side

• Not much point in encoding on the client - can be


trivially bypassed

2A 2B 3 4
6.4 Malicious Code

• ASVS: Requires
encoding
mechanism to be
free of malicious
code

4
6.5 HTML Escaping
• Character references: decimal, hex, character entities
(&)

• HTML Escaping done badly - pick one or two of < > “


‘ &

• ESAPI

• Encodes all non-printable characters

• Base64, CSS, JavaScript, HTML, Percent, VBScript


and XML 1B 2A 2B 3 4
6.6 SQL ESCAPING

• ASVS: If you use dynamic queries*, you must encode


untrusted data for your RDBMS

• PHP addslashes() does this. Badly.

• ESAPI provides MS SQL, Oracle and MySQL encoders

• * Hint: Don’t use dynamic queries


2B 3 4
6.7 XML ESCAPING

• ASVS: Requires untrusted data to be parameterized or


encoded

• XML Parsers should do this... but they may not do it


well

• ESAPI provides a robust XML entity encoder

2B 3 4
6.8 LDAP ESCAPING

• LDAP Special Characters: < > # + , “ \

• Three escaping mechanisms character (\,) hex (\2C)


and quoting “foo bar, company \\ more”

• NB: ESAPI does not have an LDAP encoder (yet)

2B 3 4
6.9 Command Escaping

• ASVS: Requires untrusted data sent to the OS to be


escaped or parameterized

• Java has a parameterized array version of


Runtime.exec()

• ESAPI has Unix and Windows command shell codecs

2B 3 4
6.10 Interpreters

• ASVS: If you have any other interpreters, they should


also be safe

• e.g. using HQL (Hibernate), or similar

2B 3 4
Demo
Cryptography
V7 Cryptography Verification Requirements

1A 1B 2A 2B 3 4
7.1 Validated Crypto

• Only use approved crypto API

• FIPS 140-2

• DO NOT CREATE YOUR OWN CRYPTO!

2B 3 4
7.2 Approved Mode

• Make sure your cipher suite is useful - and approved!

• MD5 == broken

• SHA1 == basically broken

• Should use SHA 256, AES 128, RSA 2048 or better

2A 2B 3 4
7.3 Master Secrets

• Protected - not in the web root!

• Unauthorized access should be prohibited

• Audited for local access

• It’s used by the computer - should be long and random

2B 3 4
7.4 Password Hashes

• Passwords (if any) should be:

• Salted

• Hashed using SHA 256 or better

2B 3 4
7.5 Server Side operation

• Client side crypto is dangerous!

• Crypto must be performed on the server

2A 2B 3 4
7.6 Malicious Code

• Find crypto code

• Inspect code for malicious items:

• Stealing data, secrets or credentials

• Modifying transactions (salami attacks)

4
7.7 Fail securely

• When a crypto call fails, don’t continue in the clear

• Alert administrators

• Log the issue

• Try to restart crypto operation (if possible)

2B 3 4
7.8 Logging

• All failures should be logged

• Detail any data that may be relevant (but not sensitive


stuff)

• Mark as a security item (so it can be found)

2B 3 4
7.9 Random Numbers

• Keep up to date with patches - older PRNGs are weak

• Use approved cryptographic methods to generate


pseudo random numbers

• Do not generate too many - your system will run out of


entropy

• There is no such thing as truly random numbers

2B 3 4
7.10 Key management

• Make sure that you can change the:

• Master keys

• Keys for users

• Keys for remote systems

• Without re-encrypting all backups, all transactions and


all data
34
Accountability
V8 Error Handling, Logging, and Auditing

1A 1B 2A 2B 3 4
Accountability

• Logging for logging’s sake is absolutely 100% pointless

• Log just enough to provide accountability!


8.1 Success and Failure

• Log both success and failure

• Log as a security event!

2B 3 4
8.2 Important Elements

• Each log event should include:

• Time stamp

• Severity level

• Security event (or not)

• Identity of user

2B 3 4
8.3 Protect Logs

• Logs should be protected from unauthorized access

• Outside the webroot

• Local access should be audited

• Highly privileged access required to view or query

2B 3 4
8.4 Centralized Logging

• Only one logging mechanism to rule them all!

• Historic APIs ... create a façade!

• Easy to over do - tune for size

2B 3 4
8.5 Trusted Logging

• Client side logging is optional for attackers

• Logging, auditing and exception handling must be


server side

• Unavoidable for developers to use

2A 2B 3 4
8.6 No Malicious Code

• Exception handlers - particularly global exception


handlers - are called all the time

• Ensure no malicious code

• Ensure no ability to wiggle out of logging / auditing

4
8.7 Do not log Sensitive data

• Do not log sensitive information:

• Session IDs

• Passwords, tokens

• CC PANs

• SSN / TFN / Driver’s license numbers, etc

2B 3 4
8.8 Detailed Error Messages

• Detailed error messages are only useful for attackers

• Disable outside of development

• Only send to development logging servers (not the


screen)

• HTML comments are not safe!


1A 1B 2A 2B 3 4
8.9 Log Analysis

• Logging without review is useless!

• Ensure application has a meaningful way to interpret


results

• Baseline

• Unusual activity

• Heuristics
2B 3 4
Exception handling
• Use structured exception handling - always!

• Handle exceptions you can deal with meaningfully

• Log exceptions when security related

• No empty exception blocks

• Do not catch global exceptions


Intrusion Prevention

• Correlate security events

• Too many per minute per user? Slow down user

• Too many per second per user? Log out / Lock user

• Too many per application per minute?

• Clear attack - Suspend operations and notify!


Demo
Data Protection
V9 Data Protection Verification Requirements

1A 1B 2A 2B 3 4
9.1 Identify Sensitive Data

• Not all data needs to be protected to the same extent

• Identify, document and classify all data stores (via


policy)

• Protect appropriately!

• Do not spend $25k to protect $1k of data

• Do spend $10k to protect $1m of data!


2B 3 4
9.2 Cached Data

• Use cache control headers to prevent browser caching

• Ensure server-side caches are protected and purged

• PHP sessions in /tmp

• Reporting engine caches

2B 3 4
9.3 Disable Client Side
Caching
• Use AUTOCOMPLETE=”off” in forms and fields to
prevent caching of:

• Credentials (Usernames, passwords, PINs, tokens)

• SSNs / TFNs

• If you still have them, secret questions and answers

• Value transactions
1A 1B 2A 2B 3 4
9.4 Sensitive Data in body

• URLs are persisted in browser history, cache

• Unsafe at any speed for libraries, etc

• Send credit cards, passwords, SSNs, TFNs, etc as a


POST body

2A 3 4
Minimize data collected
• If you don’t have the data, you can’t lose it

• Some information is useless to collect and keep (CC


PAN)

• Some information illegal to collect (SSN, TFN, Track


2 of credit cards, mother’s maiden name)

• Some information you are allowed to collect, but not


store (CCV)

• Get rid of sensitive information as soon as you’re done


with it
Store outside the web root

• Store the database, configuration and other sensitive


files:

• Outside the webroot (minimum required)

• Audit any local access other than app server

• On a separate, unreachable server (Best)


read only Web root

• Where possible, ensure that:

• Web root is read only

• Local access is audited for non app server access

• Easily reconstructed via automated means


File Download

• Files should be:

• Stored outside the web root

• Access controlled (reference map, fine grained)

• Virus scanned

• Deliver via octet stream


File Upload
• If you can avoid it, do not allow file uploads!

• If you have to, follow these simple rules:

• Enforce file rules (type, size, content, etc)

• Be wary of the user’s filename - input validate,


canonicalize!

• Store outside the web root

• Virus scan
Secure Database
The Missing ASVS Section
Authentication

• Always use a low privilege connection to the database

• Use a separate connection for each app

• Use a long random password

• Consider using connection encryption, particularly in


shared environments
Low privilege connections

• Use connections with just enough table privileges (user,


admin)

• Use a read only connection for guest roles

• Use tight schema privileges to stop data farming


between apps and roles
Prepared Statements

• Prepared Statements are by far the most secure


method of data access

• Eliminates SQL injection

• Still has direct object reference issues


Stored Procedures

• Stored Procedures are reasonably safe

• Do not concatenate strings within the procedure

• Do not use exec to dynamically execute SQL


Active Record
• Active Record (and ORM implementations) are
reasonably safe

• AR used by Ruby on Rails. Hibernate, and Spring are


ORMs

• Be wary of using untrusted data with find record


queries

• Still has direct object reference issues


Demo
Communications Security
V10 Communications Security Verification Requirements

1A 2A 2B 3 4
10.1 Use SSLv3 / TLS

• Use SSLv3 / TLS 1.0 or later between:

• Browser and web server - always

• Web server and app server - always

• App server and all other servers transiting sensitive


information or functions

2B 3 4
10.2 Centralized
Implementation
• Only one crypto library to
rule them all!

• Approved mode of
operation

• Will not fall back to


unsafe ciphers
34
10.3 Fail Safe

• Configure your web server or crypto library such that


negotiation failure does not fall back to:

• Weak ciphers (e.g. SSLv2)

• Weak key strengths (e.g. 40 bit keys)

• No ciphers (clear text or plain HTTP)

• These connections should just fail!


2A 3 4
10.4 Log Failures

• Any failure to communicate securely must be logged

2B 3 4
10.5 Use trusted CA

• No reason to use self signed today!

• Real TLS certificates cost $20 from many trusted CAs

• Extended verification cost $250++

• Provide green address bar

• No additional security

1A 2A 2B 3 4
10.6 Trusted Certificate
PATHs

• Configure your crypto library to:

• Check certificate revocation

• Check certificate validity

• Check certificate trust (e.g. don’t trust any old


Verisign cert)

2B 3 4
10.7 Encodings

• All connections must have a defined character


encoding

• Choose a safe encoding (e.g. UTF-8)

• Do not allow users to select the connection encoding

2A 2B 3 4
10.8 SAFE components

• Ensure ALL connections to helper systems (database,


LDAP, etc):

• Unique account per application

• Lowest possible privilege

• Logged for failures

2B 3 4
HTTP Security
V11 HTTP Security Verification Requirements

1A 1B 2A 2B 3 4
11.1 HttpOnly

• HttpOnly prevents JavaScript from sending the cookie


collection to hostile sites

• Supported by all major browsers (some more than


others)

• Your code should set and use this feature

2A 2B 3 4
11.2 Secure Cookies

• If your system uses SSL / TLS (and it should):

• If you use cookies, set the secure flag

• Session IDs must have the secure flag set

2A 2B 3 4
11.3 CSRF Guard
• All forms, links, etc should have a random token

• Verify the token before doing any value action

• If you rotate token frequently, will break “Back” button

• Works as long as you do not have XSS

• If you have XSS, you must move to two factor


authentication
34
11.4 REsponse Type

• Choose a “safe” character set

• All output should have ISO 8859-1 or UTF-8 set

• Prevents certain types of XSS

• Internationalization is a huge topic

1A 1B 2A 2B 3 4
11.5 Unchecked Redirects

• Redirects should use access reference maps

http://www.example.com/redir?url=6AF87BDE

• Do not place user input into redirects:

http://www.example.com/redir?url=http://evilsite.com

1A 1B 2A 2B 3 4
11.6 Minimal HTTP Methods

• All unused HTTP methods MUST be blocked and


logged

• Non-REST apps should use GET for navigation, POST


for value actions

• REST apps will use GET, POST, PUT, and DELETE

1A 1B 2A 2B 3 4
11.7 Safe HEaders

• RFC requires only ASCII


characters in 32-127 to
appear in headers

• Make it so!

2A 2B 3 4
Configuration
V12 Security Configuration Verification Requirements

2B 3 4
V12.1 Secure Configuration

• Ensure configuration files are:

• Not in the web root

• Safe from unauthorized modification

• Audited when they change

2B 3 4
Turn off unnecessary features

• Allow the end user to enable more risky items

• End user accepts the risk

• Reduces the impact (and thus likelihood) of a mass


attack

• Makes testing easier

2B 3 4
Encrypting configuration

• Most frameworks have clear text configuration files

• Encrypt credentials (at least)

• HMAC or digitally sign the configuration file

2B 3 4
V12.2 Log all Changes

• Accountability!

• Every time the security configuration changes:

• Log WHEN the change occurred

• Log WHAT changed (Control X changed from Y to Z


state)

• Log WHO did the change


34
V12.3 Fail Closed

• If security configuration is not available or just wrong:

• Disable all services

• Notify admins

• Log

2B 3 4
12.4 Human READable
Configuration

• For audit purposes

• All configuration should be human readable

• Opaque configuration is automatically a high risk


finding

4
Trojans, Backdoors, and
Easter Eggs
V13 Malicious Code Search Verification Requirements

4
V13.1 Time Bombs

• Review code for usage of date, time and ticks API

• Sackable offense

4
V13.2 Back doors

• Inspect controllers, network and URL handler code

• Deeper - look at all controllers / entry points

• Sackable and prosecutable offense

4
V13.3 Easter Eggs
• Used to be a fun way of providing credit or props

• Review code for unexplained ... functionality

• Review checkins - devs cluster around particular areas

• Major reputation issue - c.f. Microsoft Excel 97 Flight


Sim

• Sackable offense
4
V13.4 Salami Attacks

• Attack sends fractional amounts to a surreptitious


account

• Investigate any float or fractional handling of currency

• Sackable and prosecutable offense

4
V13.5 All Others

• Inspect code until the money runs out...

• Look for trojans, malicious code (say delete all files),


etc

• Sometimes hard to infer motive with some code

4
Internal Security Controls
V14 Internal Security Verification Requirements

34
14.1 Secure Meta Data

• Security controls have meta data. It must be protected!

• Identity information (LDAP, AD, database, XML files,


etc)

• Access control lists

• Configured security elements

34
14.2 Simple Security API

• Security controls should be simple

• Ensure that developers use them

• Ensure that developers are using them correctly!

4
14.3 Protect Shared Variables
and Resources

• Protect:

• Singletons

• Multi-threaded access to shared resources / memory

• Distributed access to shared resources / objects

4
Reporting
How to write a great report

1234
Communicating Bad nEws
• Headings should be positive in tone

• Present just the facts - good and bad

• Findings should state if they comply with the positive


heading

• Recommendations should be an opportunity, not a road


bump

• Write to the intended audience!


R1 Report Introduction

• Intended audience: Business owner, Tech / Dev / Test


Leads

• Key strengths and weaknesses of the application

• Key recommendations - opportunity, not criticism

• Overall verdict
R2 Application Description

• Describe the application under test

• Describe the test, test environment and when and


where

• Scope

• Assumptions
R3 Application Security
Architecture

• Create or Insert the application architecture

• Level 1 - Basic diagram will suffice

• Level 4 - Detailed diagram and information about the


application is necessary
R4 Verification Results

• Audience: Technical folks, developers, testers, system


admins

• Pass and fail minimal documentation requirements


Pass

Level 1 Level 2 Level 3 Level 4

Verdict PASS PASS PASS PASS

URL or source URL or source URL and any URL and any
Location
file file components components

Justification Scan output Justification Justification Justification

Description

Risk Rating

Risk
Justification
FAIL

Level 1 Level 2 Level 3 Level 4

Verdict FAIL FAIL FAIL FAIL

URL or source URL or source URL and any URL and any
Location
file file components components

Justification Scan output Justification Justification Justification

Description Description Description Description


Description
Repro steps Repro steps Repro steps Repro steps

Risk Rating OWASP OWASP OWASP OWASP

Risk
Description Description Description Description
Justification
References
OWASP Links

• ASVS

• ESAPI

• Developer Guide 3.0

• Testing Guide 3.0

• Code Review Guide 3.0

• Top 10 2007
Thank you!

• Feel free to contact me about this deck -


vanderaj@owasp.org

• Images from Stock Exchange (http://www.sxc.hu) and I


Can Has Cheeze Burger
(http://icanhascheezburger.com/)

You might also like