Skip to main content
OWASP Top 10 Web Security Vulnerabilities Carol McDonald Sun Microsystems
About the Speaker Carol  cDonald:  Java Architect at Sun Microsystems Before Sun, worked on software development of:  Application to  manage car Loans  for  Toyota  (>10 million loans)  Pharmaceutical  Intranet apps  ( Roche  Switzerland)  Telecom  Network Mgmt  ( Digital  France)  X.400  Email Server  ( IBM  Germany)
OWASP Top 10 Open Web Application Security Project promotes the development of secure web applications developers guide, test guide, top 10, ESAPI... http://www.OWASP.org OWASP TOP 10 The Ten Most Critical Issues Aimed to educate about the most common web application security vulnerabilities Living document: 2007 Top 10 different from 2004 Top 10
WebGoat and WebScarab from OWASP
Enterprise Security API http://www.owasp.org/index.php/Category:OWASP_Enterprise_Security_API
Frameworks and ESAPI ESAPI is  NOT  a framework collection of security building blocks, not “lock in” Designed to help retrofit existing applications Wrap your  existing  libraries and services Extend and customize
Enterprise Security API
Enterprise Security API
A1:  Cross Site Scripting XSS Reflected XSS: HTML page  reflects user input data  back to the browser,  without   sanitizing  the response out.writeln (“You searched for:  “+request.getParameter(“ query ”); Stored XSS: Attacker’s  script  is stored on the  server  (e.g. blog) and  later displayed  in HTML pages, without proper filtering out.writeln (&quot;<tr><td>&quot; +  guest.name  + &quot;<td>&quot; +  guest.comment );  DOM XSS:  input data or data from the server  written to dynamic HTML (DOM) elements , without filtering
A1 Cross Site Scripting Example Allows hacker to execute script in victim's browser Script executes with victim's trust of the affected site Site reflects the script back to user  where it executes and sends the session cookie to the hacker. Hacker tricks user into sending  request containing script in  search parameter. <script>alert(document.cookie)</script>
Never Trust Input HttpServletRequest.getParameter() HttpServletRequest.getCookies() HttpServletRequest.getHeader() Etc… Bad patterns Input unchecked -> Output  ==  XSS
A1 Cross Site Scripting Protection Defense Input Validation do use  White List  (what is allowed), reject if invalid do  Not  filter with  black-list  (what is not allowed) Output Encoding Set character Encoding for HTML pages: <%@ page contentType=&quot;text/html;charset=ISO-8859-1&quot; language=&quot;java&quot; %> user supplied data should be HTML or XML entity encoded before rendering means  <  becomes  &lt;  < script >  in markup represented by  &lt; script &gt;
Validating Input with Java String regex = &quot;[\\s\\w-,]*&quot;; Pattern pattern = Pattern.compile(regex); validate(stringToValidate, pattern); Validating Input with JSF 2.0 <h:inputText id=&quot;creditCard&quot; value=&quot;#{booking.creditCardNumber}&quot;/> A1 Cross Site Scripting Protection
Validating Input with JSF 2.0 @ManagedBean public class Booking {  @NotNull (message = &quot;Credit card number is required&quot;)  @Size (min = 16, max = 16,  message = &quot;Credit card number must 16 digits long&quot;)  @Pattern (regexp = &quot;^\\d*$&quot;,  message = &quot;Credit card number must be numeric&quot;)  public String getCreditCardNumber() {  return creditCardNumber;  }  } A1 Cross Site Scripting Protection
Validation, Encoding, and Injection http://owasp-esapi-java.googlecode.com/files/OWASP%20ESAPI.ppt Any  Encoding Any  Interpreter Set Character Set Encode For HTML Global Validate Canonicalize Specific Validate Sanitize Canonicalize Validate
Handling Validation, and Encoding http://owasp-esapi-java.googlecode.com/files/OWASP%20ESAPI.ppt encodeForURL encodeForJavaScript encodeForVBScript encodeForDN encodeForHTML encodeForHTMLAttribute encodeForLDAP encodeForSQL encodeForXML encodeForXMLAttribute encodeForXPath isValidDirectoryPath isValidCreditCard isValidDataFromBrowser isValidListItem isValidFileContent isValidFileName isValidHTTPRequest isValidRedirectLocation isValidSafeHTML isValidPrintable safeReadLine Canonicalization Double Encoding Protection Normalization Sanitization
Validating Input with ESAPI  ESAPI.validator().getValidInput(String context,String input,String type,int maxLength, boolean allowNull,ValidationErrorList errorList) A1 Cross Site Scripting Protection
Output Encoding  with Struts <bean:write… > Output Encoding  with JSP  <c:out escapeXML=&quot;true&quot;… >  Output Encoding  with JSF  <h:outputText value=&quot;#{param.name}&quot;/>  escapes dangerous characters as XHTML entities.  A1 Cross Site Scripting Protection
Output Encoding with ESAPI  <p>Hello, <%=ESAPI.encoder().encodeForHTML(name)%></p>  A1 Cross Site Scripting Protection
attacker's data modifies a query or command sent to a database, LDAP server, operating system or other Interpreter  A2:  Injection Flaws Hacker sends SQL commands into a form field. Site executes modified SQL query and returns results to hacker. 101’ or ‘1’=‘1
Example &quot;select * from MYTABLE where name=&quot; + parameter user supplies &quot;name' OR 'a'='a' &quot; as the parameter &quot;select * from MYTABLE where name= 'name' OR 'a'='a'; equivalent to &quot;select * from MYTABLE;  A2:  SQL Injection
Example &quot;select * from MYTABLE where name=&quot; + parameter user supplies &quot;name' OR 'a'='a' ; delete from MYTABLE&quot;  &quot;select * from MYTABLE where name= 'name' OR 'a'='a'; delete from MYTABLE; equivalent to &quot;select * from MYTABLE; delete from MYTABLE;  A2:  SQL Injection
Never Trust Input HttpServletRequest.getParameter() HttpServletRequest.getCookies() HttpServletRequest.getHeader() Etc… Bad patterns Input -> Output  == Cross-Site Scripting (XSS) Input -> Query ==  SQL Injection Input -> System ==  Command Injection
Don't  with JDBC  String  empId = req.getParameter(&quot;empId&quot;) // input parameter String query = &quot;SELECT * FROM Employee WHERE  id = '&quot; +  empId  +&quot;'&quot;;  Do  with JDBC String selectStatement = &quot;SELECT * FROM Employee WHERE id = ? &quot;; PreparedStatement pStmt = con.prepareStatement(selectStatement); pStmt.setString(1,  empId ); A2:  SQL Injection  Protection dangerous characters -  escaped by the JDBC driver.
Don't  with JPA  q = entityManager.createQuery(“select e from Employee e WHERE ”+ “e.id = '” +  empId  + “'”); Do  with JPA q = entityManager.createQuery(“select e from Employee e WHERE ” + “e.id = ':id'”); q.setParameter(“id”,  empId ); A2:  SQL Injection  Protection dangerous characters -  escaped by the JDBC driver.
Do  with JPA Criteria API QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Employee> q = qb.createQuery(Employee.class); Root<Employee> e = q.from(Employee.class); ParameterExpression<Long>  id  =cb.parameter(Long .class ); TypedQuery<Employee> query = em.createQuery( q.select(e).where(cb.equal(e.get(Employee_.id),  id ) ); query.setParameter( id ,  empId ); A2:  SQL Injection  Protection compiler checks for correctness dangerous characters -  escaped by the JDBC driver.
attacker's file is executed or processed by the web server. Example: file or filename is accepted from the user without validating content  // get file path on the server's filesystem  String dir = servlet.getServletContext().getRealPath(&quot;/ebanking&quot;) // get input file name String file = request.getParameter(“ file ”);  // Create a new File instance from pathname string  File f = new File((dir + &quot;\\&quot; +  file ).replaceAll(&quot;\\\\&quot;, &quot;/&quot;));   A3:  Malicious File Execution
A3: Malicious File Execution Threat Malicious files  (e.g. script) can be  executed  on the application server modifying paths  to gain  access to directories  on the web server
A3: Malicious File Execution Protection Strongly validate user input do  not  allow user input in the path name for server resources  Java EE Security Manager should be  configured  not allow access to files  outside the web root Upload files to a destination outside of the web application directory.
Handling Validation, and Encoding http://owasp-esapi-java.googlecode.com/files/OWASP%20ESAPI.ppt encodeForURL encodeForJavaScript encodeForVBScript encodeForDN encodeForHTML encodeForHTMLAttribute encodeForLDAP encodeForSQL encodeForXML encodeForXMLAttribute encodeForXPath isValidDirectoryPath isValidCreditCard isValidDataFromBrowser isValidListItem isValidFileContent isValidFileName isValidHTTPRequest isValidRedirectLocation isValidSafeHTML isValidPrintable safeReadLine Canonicalization Double Encoding Protection Normalization Sanitization
ESAPI HTTPUtilities interface getSafeFileUploads   uses the Apache Commons FileUploader to parse the multipart HTTP request and extract any files therein  public class  HTTPUtilities   public void  getSafeFileUploads (java.io.File tempDir,  java.io.File finalDir) throws ValidationException A3: Malicious File Execution Protection
A4:  Insecure Direct Object Reference Direct Object Reference: reference to a file, URL, directory, key to a database record  Insecure Direct Object Reference: reference  is  exposed  so that  attacker  can  manipulate  and access files, database records... Threat An attacker can access objects without authorization, unless an access control check is in place.
Real Attack on Australian Tax office attacker changed the  tax id in the url , got info on 17,000 companies
<select name=&quot;language&quot;> <option value=&quot;fr&quot;>Français</option> </select>  Public static String language = request.getParameter(language);  String language = request.getParameter( language );  RequestDispatcher rd =getServletContext(). getRequestDispatcher( language +”help.jsp”);  rd.include(request, response); A4:  Insecure Direct Object Reference - Example code can be attacked using a string like  &quot;/../../../etc/passwd%00&quot; (null byte injection)
int accountID = Integer.parseInt( request.getParameter( &quot; accountID &quot; ) );  String query = &quot;SELECT * FROM account WHERE accountID=&quot; +  accountID ;   A4:  Insecure Direct Object Reference - Example  reference to database key attacker can  search on another key.
A4:  Insecure Direct Object Reference  Protection Avoid  exposing  direct  object references to users use an  index , indirect reference  map , or other indirect method that is easy to validate.  Validate  any object references with an &quot;accept known good&quot; approach Make sure that input does not contain patterns like   ../ or  %00   Verify  authorization  to all referenced objects
Handling Direct Object References http://app?file=7d3J93   Report123.xls Web Service Database Mainframe File System User Etc… Access Reference Map Indirect Reference Direct Reference Indirect Reference Direct Reference
ESAPI Access Reference Map Key Methods getDirectReference(indirectReference) getIndirectReference(directReference)  update(directReferences) Example http://www.ibank.com?file=report123.xls http://www.ibank.com?file=a3nr38
Set fileSet = new HashSet();  fileSet.addAll(...); //add references (e.g. ids, Files )  AccessReferenceMap map = new  AccessReferenceMap ( fileSet );  // add indirect references to the map String indref = request.getParameter( &quot;file&quot; );  File file = (File)map. getDirectReference ( indref );  // if getDirectReference throws an AccessControlException  // you should handle as appropriate   ESAPI: Handling Direct Object References
try {  ESAPI.accessController(). assertAuthorizedForFile (filepath);  } catch (AccessControlException ace) {  .. attack in progress  } try {  ESAPI.accessController(). assertAuthorizedForData (key);  } catch (AccessControlException ace) {  .. attack in progress  } ESAPI: Controlling Access to Files, Data
A5:  Cross Site Request Forgery Also called  Session Riding exploit of a website whereby  Attacker's commands  are transmitted by  logged in   user's browser Real World Example  google gmail 2007: logon navigate to javascript get users gmail contacts users cookie, session
A5:  Cross Site Request Forgery Real World Example  Netflix 2006: remember me navigate to add movies to users queue users cookie, session http://news.cnet.com/Netflix-fixes-Web-2.0-bugs/2100-1002_3-6126438.html?part=rss&tag=6126438&subj=news <img src=&quot; http://www.netflix.com/AddToQueue?movieid=70011204 &quot; />
A5:  Cross Site Request Forgery <img src=&quot;http://bank.de/withdraw?account=bob&amount=10000&for=mallory&quot;> logon read email, click image  transfer funds  users cookie, session
A5:Cross Site Request Forgery Hostile Web App examples: <img src=&quot;http://bank.de/withdraw?account=bob&amount=10000&for=mallory&quot;> IMG SRC <img src=&quot;http://host/?command&quot;> SCRIPT SRC <script src=&quot;http://host/?command&quot;> IFRAME SRC <iframe src=&quot;http://host/?command&quot;>
A5:Cross Site Request Forgery Hostile Web App examples: 'Image' Object <script> var foo = new Image(); foo.src = &quot;http://host/?command&quot;; </script> <script> var post_data = 'name=value'; var xmlhttp=new XMLHttpRequest(); xmlhttp.open(&quot;POST&quot;, 'http://url/path/file.ext', true); xmlhttp.send(post_data); </script>
A5:Cross Site Request Forgery Make sure there are no XSS vulnerabilities in your application (see A1 – XSS)  Insert custom random  tokens  into every form and URL: send unique token with response, valid for  one  request verify token is correct for user when form submitted  <form action=&quot;/transfer.do&quot; method=&quot;post&quot;>  <input type=&quot;hidden&quot;  token =&quot;8438927730&quot; >  …  </form> For sensitive transactions, re-authenticate notify the user of the request by email
Handling Authentication and Identity http://owasp-esapi-java.googlecode.com/files/OWASP%20ESAPI.ppt Strong Passwords Random Tokens CSRF Tokens Lockout Remember Me Screen Name Roles Timeout Users
A5:Cross Site Request Forgery   Java  Protection Struts  use   org.apache.struts2.components. Token  HTTP data integrity framework  ( http://www.hdiv.org/ ) adds   random parameter   to every form Use the ESAPI  CRSF token: try {  HTTPUtilities.getInstance(). verifyCSRFToken ( request );  } catch( IntrusionException e ) {  response.getWriter().write( &quot;Invalid&quot; );  }  String validURL = HTTPUtilities.getInstance(). addCSRFToken (&quot;/ESAPITest/test?param=test&quot;);
A6:  Information Leakage and  Improper Error Handling Providing too much information  to the user  when an error occurs Examples: SQL errors:  Microsoft  OLE DB  Provider for  SQL Server  error '80040e14' Column ' newsTBL . NEWS_ID ' is invalid in the select list because it is not contained in an aggregate function and there is no GROUP BY clause.  G:\WEBSITE\WWW.SAMPLECOMPANY.COM /internal / dbSys.inc , line 241 Exposing database, field, and table names stack traces:  can reveal names of functions, objects, parameters...  Verification of the existence of a file Information about infrastructure
A6: Information Leakage and  Improper Error Handling   Protection Write detailed  error information  to a secure  Log  ( not  to the  user ) standard error-handling  framework to handle exceptions: return  sanitised error  message for  users  for all  error paths   errors from all layers (SQL, web server..) should be checked, configured so as not to go to the user Always give error message “The username/password is not correct” instead of “The password is not correct” for failed logins.
A7:Broken Authentication/Session Management Failure  to  protect credentials  and  session  tokens weaknesses  in : logout,  password management , timeout, remember me, secret question, and account update  resulting in: compromise of user or admin access session hijacking Defeating authorization controls lack of accountability Privacy violations
A7:Broken Authentication/Session Management Protection: All  restricted  URLs should  use SSL login  page should use  SSL Regenerate  a new  session  upon successful  login Audit  logging: who, when, from where, what data use inbuilt session management --HttpSession don't write  your  own use  well proven SSO  solutions  don't code your own “remember me” reject  new, preset or  invalid  session ids  (session fixation attack)
A7:Broken Authentication/Session Management Protection: encourage  logout  , with link on every page invalidate session upon logout configure  timeout period  to logout inactive sessions require  strong passwords , with locking when guessing be careful with password reset and Q/A clues do  not  put  session id in URL
Add a security constraint in web.xml for every URL that requires HTTPS: <security-constraint>  <web-resource-collection>  <web-resource-name>urls require HTTPS</web-resource-name>  <url-pattern>/profile</url-pattern>  <url-pattern>/register</url-pattern>  <url-pattern>/login</url-pattern>  </web-resource-collection>  <user-data-constraint>  <transport-guarantee>CONFIDENTIAL</transport-guarantee>   </user-data-constraint>  </security-constraint> A7:Broken Authentication/Session Management Protection:
ESAPI Handling Authentication and Identity http://owasp-esapi-java.googlecode.com/files/OWASP%20ESAPI.ppt Strong Passwords Random Tokens CSRF Tokens Lockout Remember Me Screen Name Roles Timeout Users
ESAPI Authenticator Interface  set of Methods for handling credentials and session createUser(accountName, pass1, pass2) generateStrongPassword() getCurrentUser()  gets authenticated user from thread local login(request, response) sets authenticated user from thread local logout() verifyAccountNameStrength(acctName) verifyPasswordStrength(newPass, oldPass)
ESAPI User Interface  set of Methods for handling credentials and session changePassword(old, new1, new2)  disable() enable()  getAccountName() getScreenName()  getCSRFToken() getLastFailedLoginTime () getLastLoginTime() getRoles() isInRole(role)  isEnabled() isExpired() isLocked() loginWithPassword(password, request, response)  resetCSRFToken() resetPassword() verifyCSRFToken(token)
A8: Insecure Cryptographic Storage Failure  to  encrypt sensitive data  or poorly  designed  cryptography Examples: not encrypting home grown algorithms insecure use of algorithms weak algorithms
Use  approved algorithms  (e.g. AES, RSA, SHA-256 instead of Blowfish, RC4, SHA1, MD5) and recommended key strength (128 bit for symmetric and 1048 for public) Encrypt  authentication  credentials  in storage and transit Protect customer sensitive data in storage and transit as appropriate Do not store credit card data (CVV2, magnetic strip information) see PCI compliance Store  keys  in  secure  repositories  Use HSM and  secure key storage such as CryptoAPI or Java Key Store A8: Insecure Cryptographic Storage Protection
Handling Sensitive Information http://owasp-esapi-java.googlecode.com/files/OWASP%20ESAPI.ppt Encryption Digital Signatures Integrity Seals Strong GUID Random Tokens Timestamp Salted Hash Safe Config Details
ESAPI Encryptor set of methods for performing common encryption, random number, and hashing operations. decrypt(ciphertext)  encrypt(plaintext) hash(plaintext, salt)  loadCertificateFromFile(file) Simple master key in configuration Minimal certificate support
A9: Insecure Communication Failure to encrypt network traffic  for sensitive communication Encryption should be used for authenticated connections , with user and backend sensitive data – like credit card Failure Risks: sniffing, loss of credentials -- Identity theft , loss of  sensitive information--  financial fraud
Use  SSL   For all  connections  that are  authenticated   When  transmitting credentials , credit card details, health and other  private information Use  transport layer security  or Protocol level encryption Between  web servers and application servers and  back end systems  and repositories For PCI compliance protect credit card holder data in transit  A9: Insecure Communication Protection
Add a security constraint in web.xml for every URL that requires HTTPS: <security-constraint>  <web-resource-collection>  <web-resource-name>urls require HTTPS</web-resource-name>  <url-pattern>/profile</url-pattern>  <url-pattern>/register</url-pattern>  <url-pattern>/login</url-pattern>   </web-resource-collection>  <user-data-constraint>  <transport-guarantee>CONFIDENTIAL</transport-guarantee>  </user-data-constraint>  </security-constraint> A9: Insecure Communication Protection
A10: Failure to Restrict URL Access Failure  to  restrict access  to  URLs  with  sensitive functions  or  data Examples: “ hidden” URLs  rendered only to admins /admin/adduser.do attacker  forced browsing  can  find unprotected  URLs  test pages deployed in production “ hidden” files , such as system reports out of date access control  privileges checked on the client but not on server
A10: Failure to Restrict URL Access Real World Example: MacWorld 2007 registration Platinum passes worth $1700  approved  with JavaScript  on Client not checked on server http://grutztopia.jingojango.net/2007/01/your-free-macworld-expo-platinum-pass_11.html
A10: Failure to Restrict URL Access Protection don't   assume  users will  not find  “hidden” URLs access control matrix  should be part of architecture/ design  of application all URLs and business functions should have effective  Access Control configure role & authorization constraints in web.xml or use Acegi (Spring) Security, a security framework for authentication and authorization or use ESAPI Access Controller
security constraints and auth-contstraints in web.xml  <security-constraint>  <web-resource-collection>  <web-resource-name>  protected Admin pages </web-resource-name>  <description> Require users to authenticate </description>  <url-pattern>/admin/*</url-pattern>  </web-resource-collection>  <auth-constraint>  <description>  Manager role can access Admin pages </description>  <role-name>Manager</role-name>  </auth-constraint>  </security-constraint>  <security-role>   <description>Managers</description>  <role-name>Manager</role-name>  </security-role>   A10: Protection
ACEGI Spring Security
ESAPI Handling Access Control isAuthorizedForURL isAuthorizedForFunction isAuthorizedForFunction isAuthorizedForService isAuthorizedForData isAuthorizedForFile
ESAPI AccessController Access Controller Interface key methods isAuthorizedForData(key) isAuthorizedForFile(filepath) isAuthorizedForFunction(functionName) isAuthorizedForService(serviceName) isAuthorizedForURL(url)
ESAPI IntrusionDetector Key Methods addException(exception)  addEvent(event)  Model EnterpriseSecurityExceptions  automatically  added Specify a threshold for each event type org.owasp.esapi.ValidationException.count=3 org.owasp.esapi.ValidationException.interval=3 (seconds) org.owasp.esapi.ValidationException.action=logout Actions are log message, disable account
Secure Principles INput Validation white list validation OUTput Validation HTML encoding before rendering Error Handling put details in log, don't send to user Authentication, Authorization, Access controls Enforce Least Privilege Secure  communications, storage,  Session Management,  Encryption Trace and Log User Actions And Security Events
References and More Information:  Open Web Application Security Project (OWASP) http://www.owasp.org/ Top 10 most critical web application security vulnerabilities http://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project OWASP Enterprise Security API http://www.owasp.org/index.php/Category:OWASP_Enterprise_Security_API Aspect Security http://www.aspectsecurity.com/