Enterprise Security API (ESAPI) Java Java User Group – San Antonio
Jarret Raim June 3rd, 2010
What is it?
ESAPI (The OWASP Enterprise Security API) is a free, open source, web application security control library that makes it easier for programmers to write lower-risk applications. The ESAPI libraries are designed to make it easier for programmers to retrofit security into existing applications. The ESAPI libraries also serve as a solid foundation for new development.
Who cares?
How Does it Work? Allowing for language-specific differences, all OWASP ESAPI versions have the same basic design: • There is a set of security control interfaces. They define for example types of parameters that are passed to types of security controls. • There is a reference implementation for each security control. The logic is not organization‐specific and the logic is not application‐specific. An example: string‐based input validation. • There are optionally your own implementations for each security control. There may be application logic contained in these classes which may be developed by or for your organization. An example: enterprise authentication.
There are several supported languages • • • • • • • • •
Java EE PHP Classic ASP .NET Coldfusion Python JavaScript Haskell Force.com
And they have a plan. Maybe.
Tyranny of Choice Write Spring Custom Java Jasypt Java Code URL Pattern Commons xml-enc EncoderLog4j Validator Cryptix JAAS Stinger JCE ACEGI Struts BouncyCastle Reform Many Anti-XSS More HDIV Java xml-dsig Logging
Standard Control
Vulnerability Theory
Threat Agent
Vector
Vulnerability
Control
Technical Impact
Business Impact
Vector Business Impact Vector
Vector
Vector
Vulnerability
Vulnerability
Control Asset
Business Impact
Function
Business Impact
Missing Control
Vulnerability Asset
Vector
Vulnerability
Control
Where do Vulnerabilities Come From? • Missing Controls – Lack of encryption – Failure to perform access control
• Broken Controls – Weak hash algorithm – Fail open
• Ignored Controls – Failure to use encryption – Forgot to use output encoding
• ESAPI Solves – Missing – Broken
• Process Solves – Ignored
Existing Enterprise Security Services/Libraries SecurityConfiguration
IntrusionDetector
Logger
Exception Handling
Randomizer
EncryptedProperties
Encryptor
HTTPUtilities
Encoder
Validator
AccessReferenceMap
AccessController
User
Authenticator
Custom Enterprise Web Application Enterprise Security API
Encoder • Typical output in most web frameworks leads to XSS and CSRF vulnerabilities. • The ESAPI encoder allows direct encoding depending on context. • • • • • •
Web (HTML, JavaScript, CSS) Databases (MySQL, Oracle) URL Shells (Unix, Windows) XML LDAP
• Also provides a canonnicalize method to remove any encodings.
<p>Hello, <%=name%></p> <p>Hello, <%=ESAPI.encoder().encodeForHTML(name)%> </p>
User
isValidCreditCard isValidDataFromBrowser isValidDirectoryPath isValidFileContent isValidFileName isValidHTTPRequest isValidListItem isValidRedirectLocation isValidSafeHTML isValidPrintable safeReadLine
Controller
Validator
Business Functions
Data Layer
Encoder
Canonicalization Double Encoding Protection Sanitization Normalization
Backend
encodeForJavaScript encodeForVBScript encodeForURL encodeForHTML encodeForHTMLAttribute encodeForLDAP encodeForDN encodeForSQL encodeForXML encodeForXMLAttribute encodeForXPath
Validator EXAMPLE: <script>alert(document.cookie)</script> ESAPI.validator().getValidInput(String context,String input,String type,int maxLength,boolean allowNull,ValidationErrorList errorList)
assertIsValidHttpRequest() assertIsValidHttpRequestParameterSet() assertIsValidFileUpload() getValidCreditCard() getValidDate() getValidDirectoryPath() getValidDouble() getValidFileContent() getValidFileName() …
• The Validator interface defines a set of methods for canonicalizing and validating untrusted input. – Returns booleans as not all validation problems are security issues.
• Invalid input will generate a descriptive ValidationException which will be stored in the ValidationErrorList • Input that is clearly an attack will generate a descriptive IntrusionException
Validator Example
• ESAPI provides the ValidationRule and Validator interfaces. • Implement your own validators for your data. • Reference Regex codes in the ESAPI properties from generic to specific.
Any Interpreter
Global Validate Canonicalize
Specific Validate Web Service
Sanitize
Any Encoding Controller
Database Mainframe Business Functions
User
Data Layer
Etcâ&#x20AC;Ś
User Interface Set Character Set Encode For HTML
File System Canonicalize Validate
Authenticator • Interface with a simple, file based example implementation • Log In / Log Out • Password Verification • Create User • Password Generation • Change Password • Expirations • Logging • Per User Session • Anonymous User
• • • • • • • • • • •
Locale Roles Disable / Enable Locked / Unlocked CSRF Tokens Last Login Last Invalid Login Password Age Screen Name Failed Log In Count Last Logged in Host
User
Controller
Business Functions
Data Layer
Logging
Access Control
Intrusion Detection
Users
Authentication
ESAPI
Backend
Note that the ESAPI project does not have out of the box support for projects like Spring, but can be made to work.
isAuthorizedForURL
isAuthorizedForData Web Service
isAuthorizedForFunction isAuthorizedForService Controller
Database Mainframe Business Functions
User
Data Layer
Etcâ&#x20AC;Ś
isAuthorizedForFile User Interface File System
isAuthorizedForFunction
Encryption • Encryption failures can lead to violations of the “Big Three” – Confidentiality – Integrity – Availability (maybe)
• Encryption is surprisingly difficult to get right. – You are probably doing it wrong right now.
• The Encryptor interface provides a set of methods for performing common encryption, random number, and hashing operations. encrypted = ESAPI.encryptor().encrypt( decrypted ); decrypted = ESAPI.encryptor().decrypt( encrypted );
User
Integrity Seals
Controller
Business Functions
Encrypted Properties
Data Layer
Encryptor
Strong GUID Safe Config Details
Backend
Encryption Digital Signatures
Random Tokens
Timestamp
Salted Hash
Direct Object Reference • Occurs when a developer exposes a reference to an internal implementation object, such as a file, directory, database record, or key, as a URL or form parameter. • Fix is to generate suitably random garbage, then internally map that to the appropriate IDs. • Doing this is surprisingly annoying, especially if there are no sessions. – Not really scalable friendly.
• ESAPI provides a random access map which also helps protect against CSRF. String directReference = "This is a direct reference."; RandomAccessReferenceMap instance = new RandomAccessReferenceMap(); String ind = instance.addDirectReference((Object)directReference);
Acct:9182374
ref=jfo8we4oji
Web Service Database Mainframe
Access Reference Map
User
Etcâ&#x20AC;Ś
Report123.xls File System
Indirect References
Direct References
Logging & Exceptions • For many applications, logging is only used to detect application errors. • Is usually geared to solving problems in development – Hopefully with an eye to production.
• ESAPI provides a logging implementation that integrates with the security substructure. – Logs security exceptions that are ESAPI generated with identify information – Can be used by normal business code to log security exceptions or just log information with identify
• Integrates an intrusion detection system that can respond to different types of intrusions by disabling accounts or other actions.
User
User Message (no detail)
Controller
Business Functions
Enterprise Security Exceptions
AccessControlException AuthenticationException AvailabilityException EncodingException EncryptionException ExecutorException IntegrityException IntrusionException ValidationException
Data Layer
Logger
Intrusion Detector
Backend
Log Message (w/Identity)
Configurable Thresholds Responses •Log Intrusion •Logout User •Disable Account
Handling HTTP • Many applications make heavy use of HTTP for functionality – Classic ASP uses redirects for flow control, error handing, etc.
• The use of data from the request accounts for most web security defects • ESAPI provides methods to interact with the request – Helper methods for encryption – CSRF tokens – Etc.
• Deals with Characters Sets and Encodings
User
Controller
Business Functions
Data Layer
Add Safe Header No Cache Headers
HTTP Utilities
Backend
sendSafeForward sendSafeRedirect
Set Content Type Add Safe Cookie Kill Cookie
isSecureChannel
Change SessionID
Safe Request Logging Safe File Uploads
CSRF Tokens
Encrypt State in Cookie Hidden Field Encryption Querystring Encryption
OWASP Top Ten 2007
OWASP ESAPI
A1. Cross Site Scripting (XSS)
Validator, Encoder
A2. Injection Flaws
Encoder
A3. Malicious File Execution
HTTPUtilities (Safe Upload)
A4. Insecure Direct Object Reference
AccessReferenceMap, AccessController
A5. Cross Site Request Forgery (CSRF)
User (CSRF Token)
A6. Leakage and Improper Error Handling
EnterpriseSecurityException, HTTPUtils
A7. Broken Authentication and Sessions
Authenticator, User, HTTPUtils
A8. Insecure Cryptographic Storage
Encryptor
A9. Insecure Communications
HTTPUtilities (Secure Cookie, Channel)
A10. Failure to Restrict URL Access
AccessController
Special Thanks
â&#x20AC;˘ Supports OWASP and ESAPI â&#x20AC;˘ Many of the diagrams for in the slides are from a similar presentation by Aspect.