Presentation is loading. Please wait.

Presentation is loading. Please wait.

Defensive Coding.

Similar presentations


Presentation on theme: "Defensive Coding."— Presentation transcript:

1 Defensive Coding

2 Hackers employ common vulnerabilities to compromise web applications
Prevention 20% effort produces 80% defensive coverage (diminished returns for additional coverage) Impossible to be 100% safe Detection Less than 1% of applications have the ability to detect an intrusion Majority of intrusions go undetected or are discovered by 3rd parties Response Once an intrusion is discovered (often long after the fact), organizations are very slow to correct the issue

3 OWASP – Open Web Application Security Project

4 SQL Injection

5 SQL Injection User-supplied data is sent to an interpreter as part of a command or query Hackers use hostile data to trick the interpreter into executing unintended commands or changing the data In the worst case scenario, can compromise the application and the underlying systems, even bypassing firewalled environments

6 All SQL Injection is due to dynamic SQL queries (concatenated sql strings)
String query = "SELECT * FROM accounts WHERE custID='" + request.getParameter("id") + "'"; Stored Procedures: don’t protect against SQL injection. The programmer can still build the call to the stored proc dynamically CREATE OR REPLACE PROCEDURE SP_ Search(Username IN VARCHAR2) AS sql VARCHAR; code VARCHAR; BEGIN sql := ‘SELECT WHERE’ + ‘ USERNAME=‘’’ || Username || ‘’’’; EXECUTE IMMEDIATE sql INTO code; END; The attacker modifies the ‘id’ and ‘Username’ parameter value in their browser to send: ' or '1'='1. For example: or '1'='1 This changes the meaning of both queries to return all the records from the accounts table. More dangerous attacks could modify or delete data, or even invoke stored procedures LDAP Injection These are rare, but possible if the attacker includes special LDAP characters in the user id parameter. Validate the username to check for invalid characters

7 SQL Injection Prevention
ORM – Object Relational Mapper (Entity Framework EFSQL, Hibernate HQL, JPA JPQL) Improves the chances that your code is free from SQL Injection, but not guaranteed: Unsafe HQL Statement: (don’t concatenate!) Query unsafeHQLQuery = session.createQuery("from Inventory where productID='"+userSuppliedParameter+"'"); Safe version of the same query using named parameters: Query safeHQLQuery = session.createQuery("from Inventory where productID=:productid"); safeHQLQuery.setParameter("productid", userSuppliedParameter); Use positive or whitelist server-side input validation Escape special characters using the specific escape syntax for the interpreter SQL structure (table, column names) cannot be escaped, so user-supplied structure names are dangerous Use LIMIT and other SQL controls within queries to prevent mass disclosure of records Use Prepared Statements and Bind parameters Can still be vulnerable to SQL injection if you are not binding parameters (don’t ever construct SQL statements via string concatenation) Least Privilege: Use less privileged database access. Application’s db login should be restricted as much as possible and should not include any schema privileges.

8 The Unsecure Set Up : No Security Measures
Login Page has a form Set the form action to login (servlet) Username and password text fields and submit button Once user enters data, query the db for the user information.  Set the user id in the session if found and redirect to a “success” page, else redirects to a “fail” page The Result : Hackable Attempt to login (without knowing a user id or password) using SQL Injection x' or 'y'='y' -- x' closes username; 'y'='y' creates the true statement; -- this comments everything else out SELECT * FROM GsUser where username='x' or 'y'='y' -- and password=‘… '; drop table -- '; drop database yourDbName --

9 The Unsecure Set Up : Client Side Validation
Login Page form : once user enters data, query the db for the user information  Sets the user id in the session if found and redirect to a “success” page, else redirects to a “fail” page Includes JavaScript validation for the username and password text fields The Result : Hackable Attempt to login (without knowing a user id or password) using SQL Injection x' or 'y'='y’ – The client side validation regular expression comparison does not allow usernames/passwords that don’t match word characters that are char in length Now Disable Javascript in the browser Try the SQL injection again – no validation is called

10 The Secure Set Up : Parameterized Queries
Modify your code to use parameterized queries. Retry the attack. The Result : Secure Attempt to login (without knowing a user id or password) using SQL Injection x' or 'y'='y’ – Does not allow you to log in without proper credentials

11

12 Broken Authentication

13 Broken Authentication Vulnerabilities
Failure to protect credentials and session tokens lead to hijacking of user or admin accounts. Allows brute force or other automated attacks. Application allows default, weak, or well-known passwords, such as “Password1” or “admin/admin”. Credential stuffing: using lists of known usernames and passwords against the app to determine if the credentials are valid. Log In Use multi-factor authentication instead of using passwords as a sole factor. Do not rely upon spoofable credentials as the sole form of authentication, such as IP addresses or address range masks. Do not allow the login process to start from an unencrypted page. Ensure pathways are hardened against account enumeration attacks by using the same messages for all outcomes. Username and password are incorrect. Password was incorrect for that username. Could not find username. Limit or increasingly delay failed login attempts. Log all failures and alert administrators when credential stuffing, brute force, or other attacks are detected.

14 Broken Authentication Prevention
Cookies Refuse login if cookies are disabled in the browser, otherwise info will default to store in URL and then history Store data server side instead of using cookies (don’t store state client-side) Limit or rid code of custom cookies for authentication or session management purposes (remember me, or home grown single sign on functionality) Session Do not expose any session identifiers or any portion of valid credentials in URLs or logs Do not accept new, preset, or invalid session identifiers from the URL or in the request Session hijacking – steals the established session between the client and web server after user log in Session fixation attack – fixes an established session on victim’s browser, so the attack starts before the user logs in Could possibly send user session id from a http link at a https page Regenerate Session IDs after successful login/ authentication/ privilege level Use server-side, secure, built-in session management mechanism – do not write or use secondary session handlers Invalidate Session IDs and authentication tokens (particularly single sign-on (SSO) tokens) during logout or a timeout

15 Log Out Application session timeouts - A user uses a public computer to access an application. Instead of selecting “logout” the user simply closes the browser tab and walks away. An attacker uses the same browser an hour later, and the user is still authenticated. When closing browser, delete the session and expire the cookie. Ensure that every page has a logout link – logout should destroy all server side session state and client side cookies Passwords Do not ship or deploy with any default credentials, particularly for admin users. Require password length, complexity and rotation in accordance with National Institute of Standards and Technology (NIST) policies Passwords – strong hashed or encrypted form Password Resets - Be careful of sending secrets to registered addresses as a mechanism for password resets. Use limited-time-only random numbers to reset access Send a follow up as soon as password has been reset. Be careful of allowing self-registered users changing their address – send a message to the previous address before enacting the change. JAAS– security authentication for Java, Spring Security

16

17 Cross Site Scripting (XSS)

18 Cross Site Scripting (XSS)
XSS flaws occur whenever an application takes user supplied data and sends it to a web browser without first validating or encoding that content. XSS allows attackers to execute script in the victim’s browser which can hijack user sessions, deface web sites, possibly introduce worms, etc. Hacker submits <script> as part of an input form, server delivers hacker’s script to others’ browsers Script will make AJAX or similar calls to hacker’s server, delivering cookies, etc Attacker can host JS on own server and add a reference to it The goal is to get <script> tags stored as data in the application’s data storage. Later when that data is presented back to users in the form of a report or other web page, the <script> is executed in the user’s browser. The user trusts the script because it came from a known, trustworthy source. Difficulty in detection – cannot look simply for script tags or a few permutations of symbols Websites offer ability to insert executable code into an entry field (Ebay allows markup)

19 Three forms of XSS, usually targeting users' browsers:
1. Reflected XSS Unvalidated and unescaped user input as part of HTML output. Allows the attacker to execute arbitrary HTML and JavaScript in the victim’s browser. Typically the user will need to interact with some malicious link that points to an attacker- controlled page, such as malicious websites or advertisements 2. Stored XSS Stores unsanitized user input that is viewed at a later time by another user or an administrator. The hostile code is stored in a back end database or file, then delivered to the user at a future time 3. DOM XSS JavaScript frameworks, single-page applications, and APIs that dynamically include attacker- controllable data to a page are vulnerable to DOM XSS. Typical XSS attacks include session stealing, account takeover, DOM node replacement or defacement (such as trojan login panels), attacks against the user's browser such as malicious software downloads and key logging The hostile script manipulates DOM variables rather than html

20 Cross Site Scripting (XSS) Prevention
Encode/escape the entire input string, specifically search for and replace allowed markup If text box is not encoded, the hacker could add in </textarea> to close tag, then script to do something malicious Encode all output to web pages Validate input data against known good patterns – assume all data is bad. Use Regular Expression validators Anti-Samy : OWASP server side API for validating rich content, ESAPI Library (includes Anti-Samy) – builds DOM tree out of just whitelisted items

21 -Description Input Field
The Set Up – Lacking any security Login Page Display Items Page -Link to edit each item Edit Items Page -Description Input Field -Price Input Field Database (query / save) The Result : Hackable On the Edit page, any javascript entered in the description field will save to the database. When it is next displayed to the browser on the redirect to the Display page, it will execute! <script>alert('haha gotcha');</script>

22 Adding security for cross site scripting Add ESAPI to your project
Call the getValidSafeHtml function in the validator to sanitize the description getValidSafeHTML(java.lang.String context, java.lang.String input, int maxLength, boolean allowNull)  Returns validated "safe" HTML that does not contain unwanted scripts in the body, attributes, CSS, URLs, or anywhere else.

23 Insecure Direct Object References

24 Insecure Direct Object References & Broken Access Control
Developer exposes a reference to an internal implementation object, such as a file, directory, database record, or key, as a URL or form parameter. Attacker manipulates direct object references to access other objects without authorization, unless an access control check is in place. An attacker simply force browses to target URLs. Admin rights are required for access to the admin page. Examples: Application uses unverified data in a SQL call that is accessing account information: pstmt.setString(1, request.getParameter("acct")); ResultSet results = pstmt.executeQuery( ); An attacker simply modifies the 'acct' parameter in the browser to send whatever account number they want. If not properly verified that user is the account holder and authorized to see the account, the attacker can access and change any user's account. Australian Taxation Office website in legit but hostile user changed the ~FEIN present in URL; user farmed 17,000 company details, then ed the companies with details

25 Insecure Direct Object References & Broken Access Control Prevention
With the exception of public resources, deny by default Log access control failures, alert admins when appropriate Business layer objects are responsible for checking the authority of the authenticated user to access the requested data or to perform the requested task.  ESAPI provides utility for: Authorization services - verify that the authenticated user is authorized to reference the requested object Creating randomly generated indirect references to embed on web pages that are mapped to vulnerable direct references server side Provides a class called RandomAccessReferenceMap(java) Store the new map in the session Replace the vulnerable direct reference value with the result of calling addDirectReference(), which returns a random string (the indirect reference) Call getDirectReference() to obtain the simple business key to use in your SQL queries

26 Using Components with Known Vulnerabilities

27 Using Components with Known Vulnerabilities
8 minutes after Oracle patch was released, attackers probed for unpatched systems (reverse engineered patch) Shodan IoT search engine : find devices that still suffer from Heartbleed vulnerability (OpenSSL) that was patched in April 2014 Patch management process: Remove unused dependencies, unnecessary features, components, files, and documentation. Inventory the versions of both client-side and server-side frameworks and libraries and dependencies DependencyCheck National Vulnerability Database Only obtain components from official sources over secure links and prefer signed packages. Unpatched components are sitting ducks Monitor for libraries and components that are unmaintained or do not create security patches for older versions. If patching is not possible, consider deploying a virtual patch to monitor, detect, or protect against the discovered issue. Ensure that there is an ongoing plan for monitoring, triaging, and applying updates or configuration changes for the lifetime of the application.

28 Go now and secure the galaxy!


Download ppt "Defensive Coding."

Similar presentations


Ads by Google