OWASP Foundation – Los Angeles Chapter http://www.owaspLA.org Twitter: @owaspla Email: LosAngeles@owasp.org Monthly meetings, 4th Wednesday of each month Tin Zaw, Chapter Leader February 2012 Top Ten Controls v1 Eoin Keary and Jim Manico Page 1 Top 10 Web Security Controls February 2012 Top Ten Controls v1 Eoin Keary and Jim Manico Page 2 (1) Query Parameterization (PHP PDO) $stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)"); $stmt->bindParam(':name', $name); $stmt->bindParam(':value', $value); February 2012 Top Ten Controls v1 Eoin Keary and Jim Manico Page 3 XSS: Why so Serious? Session hijacking Site defacement Network scanning Undermining CSRF defenses Site redirection/phishing Load of remotely hosted scripts Data theft Keystroke logging February 2012 Top Ten Controls v1 Eoin Keary and Jim Manico Page 4 (2) XSS Defense by Data Type and Context Data Type Context Defense Numeric, Type safe language Doesn’t Matter Cast to Numeric String HTML Body HTML Entity Encode String HTML Attribute, quoted Minimal Attribute Encoding String HTML Attribute, unquoted Maximum Attribute Encoding String GET Parameter URL Encoding String Untrusted URL URL Validation, avoid javascript: URL’s, Attribute encoding, safe URL verification String CSS Strict structural validation, CSS Hex encoding, good design HTML HTML Body HTML Validation (JSoup, AntiSamy, HTML Sanitizer) Any DOM DOM XSS Cheat sheet Untrusted JavaScript Any Sandboxing JSON Client parse time JSON.parse() or json2.js February 2012 Top Ten Controls v1 Eoin Keary and Jim Manico Page 5 Danger: Multiple Contexts Browsers have multiple contexts that must be considered! HTML Body HTML Attributes <STYLE> Context February 2012 Top Ten Controls v1 <SCRIPT> Context Eoin Keary and Jim Manico URL Context Page 6 CSS Pwnage Test Case <div style="width: <%=temp3%>;"> Mouse over </div> temp3 = ESAPI.encoder().encodeForCSS("expression(alert( String.fromCharCode (88,88,88)))"); <div style="width: expression\28 alert\28 String\2e fromCharCode\20 \28 88\2c 88\2c 88\29 \29 \29 ;"> Mouse over </div> Pops in at least IE6 and IE7. lists.owasp.org/pipermail/owasp-esapi/2009February/000405.html February 2012 Top Ten Controls v1 Eoin Keary and Jim Manico Page 7 Simplified DOM Based XSS Defense 1. Initial loaded page should only be static content. 2. Load JSON data via AJAX. 3. Only use the following methods to populate the DOM Node.textContent document.createTextNode Element.setAttribute References: http://www.educatedguesswork.org/2011/08/ guest_post_adam_barth_on_three.html and Abe Kang February 2012 Top Ten Controls v1 Eoin Keary and Jim Manico Page 8 Dom XSS Oversimplification Danger Element.setAttribute is one of the most dangerous JS methods If the first element to setAttribute is any of the JavaScript event handlers or a URL context based attribute ("src", "href", "backgroundImage", "backgound", etc.) then pop. References: http://www.educatedguesswork.org/2011/08/ guest_post_adam_barth_on_three.html and Abe Kang February 2012 Top Ten Controls v1 Eoin Keary and Jim Manico Page 9 Best Practice: DOM Based XSS Defense I Untrusted data should only be treated as displayable text JavaScript encode and delimit untrusted data as quoted strings Use document.createElement("…"), element.setAttribute("…","value"), element.appendChild(…), etc. to build dynamic interfaces Avoid use of HTML rendering methods Understand the dataflow of untrusted data through your JavaScript code. If you do have to use the methods above remember to HTML and then JavaScript encode the untrusted data Make sure that any untrusted data passed to eval() methods is delimited with string delimiters and enclosed within a closure or JavaScript encoded to N-levels based on usage and wrapped in a custom function February 2012 Top Ten Controls v1 Eoin Keary and Jim Manico Page 10 Best Practice: DOM Based XSS Defense II Limit the usage of dynamic untrusted data to right side operations. And be aware of data which may be passed to the application which look like code (eg. location, eval()). When URL encoding in DOM be aware of character set issues as the character set in JavaScript DOM is not clearly defined Limit access to properties objects when using object[x] access functions Don’t eval() JSON to convert it to native JavaScript objects. Instead use JSON.toJSON() and JSON.parse() Run untrusted script in a sandbox (ECMAScript canopy, HTML 5 frame sandbox, etc) February 2012 Top Ten Controls v1 Eoin Keary and Jim Manico Page 11 Attacks on Access Control Vertical Access Control Attacks A standard user accessing administration functionality “Privilege Escalation” Horizontal Access Control attacks Same role, but accessing another user's private data Business Logic Access Control Attacks Abuse of workflow February 2012 Top Ten Controls v1 Eoin Keary and Jim Manico Page 12 Attacking Access Control Impact Elevation of privileges Disclosure of confidential data Compromising admin-level accounts often results in access to user’s confidential data Data tampering Privilege levels do not distinguish users who can only view data and users permitted to modify data February 2012 Top Ten Controls v1 Eoin Keary and Jim Manico Page 13 Access Control Anti-Patterns Hard-coded role checks in application code Lack of centralized access control logic Untrusted data driving access control decisions Access control that is “open by default” Lack of addressing horizontal access control in a standardized way (if at all) Access control logic that needs to be manually added to every endpoint in code February 2012 Top Ten Controls v1 Eoin Keary and Jim Manico Page 14 (3) Access Control Positive Patterns Code to the activity, not the role Centralize access control logic Design access control as a filter Deny by default, fail securely Build centralized access control mechanism Apply same core logic to presentation and server-side access control decisions Server-side trusted data should drive access control February 2012 Top Ten Controls v1 Eoin Keary and Jim Manico Page 15 Best Practice: Code to the Activity if (AC.hasAccess(ARTICLE_EDIT)) { //execute activity } Code it once, never needs to change again Implies policy is persisted/centralized in some way Requires more design/work up front to get right February 2012 Top Ten Controls v1 Eoin Keary and Jim Manico Page 16 Best Practice: Use a Centralized Access Controller In Presentation Layer if (isAuthorized(VIEW_LOG_PANEL)) { <h2>Here are the logs</h2> <%=getLogs();%/> } In Controller try (assertAuthorized(DELETE_USER)) { deleteUser(); } February 2012 Top Ten Controls v1 Eoin Keary and Jim Manico Page 17 Danger: Hard Coded Roles if (user.isManager() || user.isAdministrator() || user.isEditor() || user.isUser()) { // execute action } February 2012 Top Ten Controls v1 Eoin Keary and Jim Manico Page 18 Danger: Hard Coded Roles Makes “proving” the policy of an application difficult for audit or Q/A purposes. Any time access control policy needs to change, new code need to be pushed. Fragile, easy to make mistakes Compliance audits often fail applications specfiically for this issue February 2012 Top Ten Controls v1 Eoin Keary and Jim Manico Page 19 Danger: Order Specific Operations Imagine the following parameters http://example.com/buy?action=chooseDataPackage http://example.com/buy?action=customizePackage http://example.com/buy?action=makePayment http://example.com/buy?action=downloadData Can an attacker control the sequence? What step would an attacker like to skip? Can an attacker abuse this with concurrency? February 2012 Top Ten Controls v1 Eoin Keary and Jim Manico Page 20 Danger: Never Depend on Untrusted Data for Access Control Decisions Never trust user data for access control decisions Never make access control decisions in JavaScript Never make authorization decisions based solely on anything from the request Never depend on the order of values sent from the client February 2012 Top Ten Controls v1 Eoin Keary and Jim Manico Page 21 Danger: Access Control Administration Issues Many administrative interfaces require only a password for authentication Shared accounts combined with a lack of auditing and logging make it extremely difficult to differentiate between malicious and honest administrators Administrative interfaces are often not designed as “secure” as user-level interfaces given the assumption that administrators are trusted users February 2012 Top Ten Controls v1 Eoin Keary and Jim Manico Page 22 Best Practice: Other Access Control Considerations Log all failed access authorization requests to a secure location for review by administrators Avoid assigning permissions on a per-user basis Perform consistent authorization checking routines on all application pages (Filter?) February 2012 Top Ten Controls v1 Eoin Keary and Jim Manico Page 23 Cross Site Request Forgery (CSRF) February 2012 Top Ten Controls v1 Eoin Keary and Jim Manico Page 24 Attacking Sensitive Transactions Once authenticated, users are trusted throughout the lifetime of their session Applications do not require users to reauthenticate when executing sensitive transactions Cross-Site Request Forgery (XSRF/CSRF) Attacks the trust a web application has for authenticated users Browser instances share cookies Users typically browse multiple sites simultaneously Attackers can abuse the shared cookie jar to send requests as the authenticated user February 2012 Top Ten Controls v1 Eoin Keary and Jim Manico Page 25 Anatomy of an CSRF Attack Consider a consumer banking application that contains the following form <form action=“https://bank.com/Transfer.asp” method=“POST” id=“form1”> <p>Account Num: <input type=“text” name=“acct” value=“13243”/></p> <p>Transfer Amt: <input type=“text” name=“amount” value=“1000” /></p> </form> This form will generate requests that resemble the following GET http://www.example.com/Transfer.asp?acct=##&amount=## February 2012 Top Ten Controls v1 Eoin Keary and Jim Manico Page 26 (4) Cross Site Request Forgery Defenses Cryptographic Tokens Primary and most powerful defense. Randomness is your friend. Request that cause side effects should use (and require) the POST method Alone, this is not sufficient Require users to re-authenticate Amazon.com does this *really* well Double-cookie submit Decent defense, but no based on randomness, based on SOP I tend to not recommend this February 2012 Top Ten Controls v1 Eoin Keary and Jim Manico Page 27 Authentication Dangers Weak password Login Brute Force Username Harvesting Session Fixation Weak or Predictable Session Plaintext or poor password storage Weak "Forgot Password” feature Weak "Change Password” feature Credential or session exposure in transit via network sniffing Session Hijacking via XSS February 2012 Top Ten Controls v1 Eoin Keary and Jim Manico Page 28 Login Functionality Attacks Username enumeration which allows an attacker to enumerate valid usernames for use with further attacks Password guessing which is most successful when users are allowed to choose weak passwords Brute-Force Attacks which succeeds when there is no account lockout or monitoring of login attempts Credential Theft which succeeds when there is no encryption protecting credentials stored or in transit February 2012 Top Ten Controls v1 Eoin Keary and Jim Manico Page 29 (5) Authentication Defenses Develop generic failed login messages that do not indicate whether the user-id or password was incorrect Enforce account lockout after a pre-determined number of failed login attempts Account lockout should trigger a notification sent to application administrators and should require manual reset (via helpdesk) Implement server-side enforcement of password syntax and strength (i.e. length, character requirements, etc) February 2012 Top Ten Controls v1 Eoin Keary and Jim Manico Page 30 (6) Forgot Password Secure Design Require identity and security questions Last name, account number, email, DOB Enforce lockout policy Ask one or more good security questions http://www.goodsecurityquestions.com/ Send the user a randomly generated token via out-of-band method email, SMS or token Verify code in same web session Enforce lockout policy Change password Enforce password policy February 2012 Top Ten Controls v1 Eoin Keary and Jim Manico Page 31 Attacking A Session Identifier If session identifiers are issued in a predictable fashion, an attacker can use a recently issued Session ID to guess other valid values If the possible range of values used for Session ID’s is small, an attacker can brute force valid values Session ID’s are also susceptible to disclosure via network sniffing attacks Once obtained, a session ID typically allows impersonation of the user Susceptible to replay No need to steal user credentials February 2012 Top Ten Controls v1 Eoin Keary and Jim Manico Page 32 (7) Core Session Defenses Ensure secure session ID’s 20+ bytes, cryptographically random Stored in HTTP Cookies Cookies: Secure, HTTP Only, limited path Generate new session ID at login time To avoid session fixation Session Timeout Idle Timeout Absolute Timeout Logout Functionality February 2012 Top Ten Controls v1 Eoin Keary and Jim Manico Page 33 (8) Session Cookie Defenses Path The path under which all requests should receive the cookie. “/” would indicate all paths on the server Domain The domain for which servers should receive the cookie (tail match). For example, my.com would match all hosts within that domain (www.my.com, test.my.com, demo.my.com, etc.) Secure Indicates that the cookie should only be sent over HTTPS connections HTTPOnly Helps ensure Javascript can not manipulate the cookie. Good defense against XSS. February 2012 Top Ten Controls v1 Eoin Keary and Jim Manico Page 34 (9a) Secure Password Storage public String hash(String plaintext, String salt, int iterations) throws EncryptionException { byte[] bytes = null; try { MessageDigest digest = MessageDigest.getInstance(hashAlgorithm); digest.reset(); digest.update(ESAPI.securityConfiguration().getMasterSalt()); digest.update(salt.getBytes(encoding)); digest.update(plaintext.getBytes(encoding)); // rehash a number of times to help strengthen weak passwords bytes = digest.digest(); for (int i = 0; i < iterations; i++) { digest.reset(); bytes = digest.digest(bytes); } String encoded = ESAPI.encoder().encodeForBase64(bytes,false); return encoded; } catch (Exception ex) { throw new EncryptionException("Internal error", "Error"); }} February 2012 Top Ten Controls v1 Eoin Keary and Jim Manico Page 35 (9b) Discourage Browser Password Storage Disable Browser Autocomplete <form AUTOCOMPLETE="off”> <input AUTOCOMPLETE="off”> Only send passwords over HTTPS POST Do not display passwords in browser Input type=password Do not display passwords in HTML document February 2012 Top Ten Controls v1 Eoin Keary and Jim Manico Page 36 (10) Encryption in Transit (TLS) Authentication credentials and session identifiers must me be encrypted in transit via HTTPS/SSL Starting when the login form is rendered Until logout is complete All other sensitive data should be protected via HTTPS! https://www.ssllabs.com free online assessment of public facing server HTTPS configuration https://www.owasp.org/index.php/Transport_Layer_Protec tion_Cheat_Sheet for HTTPS best practices February 2012 Top Ten Controls v1 Eoin Keary and Jim Manico Page 37