Date post: | 17-May-2015 |
Category: |
Technology |
Upload: | tiago-henriques |
View: | 5,145 times |
Download: | 0 times |
Who Am I ?
• Tiago Henriques• @balgan• 24• BSc• MSc• CEH• CHFI
• CISSP• MCSA• CISA• CISM• CPT• CCNA
file:///C:/Users/balgan/Downloads/11545_192585389754_513599754_3020198_333349_n.jpg
Team Leader of these guise
Currently employed by these guise
What we are going to (try) to cover today
The ThreatsXss SQL Injection
Buffer Overflows Session management Flaws
Information Disclosure Insecure Communication/storage
We have been on this same shit in security since 2007, we’re worrying about A.P.T. When we can’t even get the basics right!
PEOPLE ! WAKE THE F***UP!
Target audienceDevelopers Code Auditors /Security Team
This talk is all about bringing the love between these two back
Part 1 – Principles of Secure Development
The principles A.K.A. The Bible
Input and Output
ValidationError Handling
Authentication and
Authorization
Session Management
Secure Communications
Secure Resource Access
Secure Storage
Input and Output
Validation
INPUT/OUTPUT VALIDATION
• This principle is all about making sure that data enters, is processed and leaves our application correctly, formatted and validated in the proper way.
Identify the data our application
will receive
Create RegEX to validate the
data
•Its important to validate both content and size (Yes, Size matters!)
Use one of two processes to
validate the data
INPUT/OUTPUT VALIDATION – WHITELISTING VS BLACKLISTING
• White listing:• You define a set of “correct data” for a specific input point in the application • As an example you can say that a certain textfield can only take numbers and
only a limited size of characters.• Easier to use and generally known as more secure.
<td> <input type=text runat=server id=userID> <asp:RegularExpressionValidator runat=server ControlToValidate= “telephonenumb" ErrorMessage=“Phone must be 8-12 numbers." ValidationExpression="[0-9]{8,12}" /> </td>
• Black listing:• You define a set of “malicious inputs” and attempt to remove or replace them. • As an example you can search for certain specific characters that are commonly
used to attempt an SQL Injection attack and replace them.
s.replaceAll(Pattern.quote(" ' "),Matcher.quoteReplacement(" " "));
INPUT/OUTPUT VALIDATION – WHITELISTING VS BLACKLISTING
INPUT/OUTPUT VALIDATION
Input Validation Best Practices:
• Use some kind of filtering method (whitelisting / blacklisting).• Normalise all inputs received.• Check content size and syntax of all input received.
Output Validation:
• You should follow same practices as for input validation• Also correctly encode the output data
#!/usr/bin/perluse CGI;my $cgi = CGI->new();my $name = $cgi->param('username');print $cgi->header();print 'You entered $name';
#!/usr/bin/perluse CGI;use HTML::Entities;my $cgi = CGI->new();my $name = $cgi->param('username');print $cgi->header();print "You entered ", HTML::Entities::encode($name);
VS
INPUT/OUTPUT VALIDATION
This principle protects you against:
Injection attacks, Cross Site Scripting, Security Misconfiguration, Unvalidated Redirects and Forwards, Content Spoofing, Unrestricted Upload of File with Dangerous Type, Failure to Preserve SQL Query Structure, Failure to Preserver Web Page Structure, Failure to Preserve OS Command Structure, URL Redirection to Untrusted Site, Buffer Copy without Checking Size on Input, Improper Limitation of a Pathname to a Restricted Directory, Improper Control of Filename for Include or Require Statement in PHP Program, Buffer Access with Incorrect Length Value, Improper Validation of Array Index, Integer Overflow or Wraparound, Incorrect Calculation of Buffer Size.
Error Handling
ERROR HANDLING
When a developer first starts coding an application everything is beautiful. It works flawlessly and it will never fail.
Your application will fail sooner or later and its important that you deal with errors gracefully and in a proper way.
Unlike you know……
ERROR HANDLING
Our government
ERROR HANDLING
Every application will eventually fail, and have to deal with na exception. These should be handled carefully and securely.
If an attacker manages to force na exception to occur he might be able to obtain certain information that can help him attack our application/Infrastructure.
This is a common example of an error message that could definetely help na attacker:
Microsoft OLE DB Provider for ODBC Drivers (0x80040E14)[Microsoft][ODBC SQL Server Driver][SQL Server]Invalid column name 'users'./samplesite/login.asp, line 6
ERROR HANDLING
We should always try to prevent these messages from reaching the end user.
When developing code make sure you always handle expected and unexpected exceptions. And then when returning errors to the users make sure they are general messages such as:
ERROR HANDLING
This principle will help you protect against:Information Leakage, Information Exposure Through an Error Message, Improper Check for Unusual or Exceptional Conditions
import java.io.IOException;import java.io.InputStream;import java.net.MalformedURLException;import java.net.URL;public class Test {public static void main(String[] args)
{String urlStr = "http://securityninja.co.uk/no_exist.html"; //A URL that we will try to
use
try //Start of a Try/Catch block to return a "sanitised" error should url.openstream fail{
URL url = newURL(urlStr);InputStream is = url.openStream();is.close();
} catch(Exception e) {System.out.println("Error requesting" + e.getMessage()); //Print out exception}
}}
Authentication and
Authorization
AUTHENTICATION AND AUTHORIZATION
You can have a door and locks, but they will be useless if the door structure isn’t good enough
If you don’t have strong and proper built authentication in your application, na attacker could possibily access sensitive content without having the permission to.
There is a plentora of problems that can exist with authentication such as: * Lack of an appropriate timeout * The use of weak password * The use of weak "secret question" system * The use of broken CAPTCHA system * Failure to protect credentials in transit * Failure to implement least privilege access
AUTHENTICATION AND AUTHORIZATION
When implementing a login system on ur application you should analyse what sort of content you are protecting, that way you can define a correct timeout for the sessions on your system.
AUTHENTICATION AND AUTHORIZATION
Important parts of authentication and authorization:• Password Strenght (general rule for a minimum password is lenght of 7 characters) • Maximum age of a password• Prevention of password reuse• Passwords must be protected while stored and on transit• Secret question/answer system to recover access to account must not be vulnerable to
easily guessable choices. (Examples: Favourite color? Favourite Country? )• Another important thing to use on the account creation part and even in authentication is
a CAPTCHA system, which would stop automated systems from creating bogus accounts or trying to bruteforce the existant accounts. CAPTCHA systems have their flaws so when choosing one choose one that isn’t vulnerable to OCR Software attacks.
• The final rule to remember is to implement a system of authorization through least privilege where users only have access to their own functionality and “admin” to their own functionality.
• PS: When making access decisions do not use client side tokens, URL values, or hidden fields, these can be manipulated and give a user elevated privileges.
AUTHENTICATION AND AUTHORIZATION
AUTHENTICATION AND AUTHORIZATION
This principle will help you protect against:
Broken Authentication and Session Management, Security Misconfiguration, Unvalidated Redirects and Forwards, Insufficient Authorisation, Insufficient Authentication, Abuse of Functionality, Use of Hard-coded Credentials, Incorrect Permission Assignment for Critical Resource, Reliance on Untrusted Inputs in a Security Decision, Missing Authentication for Critical Function, Improper Access Control
Session Management
SESSION MANAGEMENT
Normally when a user connects to our application this is what happens:
User
Authentication sucessful
Authentication failed
SESSION MANAGEMENT
Normally an attacker will focus his attacks on trying to obtain a valid session either through exploiting users or taking advantage of flaws in the session management system itself. Using this set of rules, you won’t need to have any knowledge of how the attacker is attempting to exploit ur application:
• The session ID's used to identify individual authenticated users should be of a sufficient length to prevent brute force attacks
• It’s important to stress that session ID length isn't enough to provide protection by itself; you also need to have a high amount of entropy per character in the session ID.
• A session ID should be constructed from a large character set without any obvious patterns in the ID's. *
• We need to ensure that these ID's are secured both on the application server and whilst they are in transit.
SESSION MANAGEMENT
• The storage location for the session ID's should be a secure location and not in world readable locations.
• The next point we need to secure is the transmission of the session ID's and a simple answer exists for this. If the session ID is transmitted via HTTP it can be easily intercepted and re-used by an attacker, by using HTTPS instead you can protect the session ID in transit.
• You should always mandate that session ID's are only accepted if they are generated by your application server and overwrite those values which are present in requests but not provided by your application.
• The final two session protection mechanisms you need to provide are timeouts on sessions and changes of session ID's when users carry out sensitive actions.*
SESSION MANAGEMENT
• In java having a secure session management system is as simple as:
Using HttpServletRequest in Java to generate a unique session ID:
HttpSession session = request.getSession(true);
Using HttpServletRequest to invalidate an existing session ID:
session.invalidate();
Setting a 15 minute timeout for the session ID:
session.setMaxInactiveInterval(900);
Secure Communications
SECURE COMMUNICATION
• This is a simple principle. All you have to do is make sure your applications enforce the use of secure transport mechanisms such as SSL, TLS or SSH. You must also make sure that your application enforces specific secure versions of these mechanisms such as SSL version 3 or SSH version 2.
• Usually the place where we F*** up in this principle is:• When to use this mechanisms • Which version to use
• For the first problem the solution is: Protect your website as soon as the user lands on it. Do not wait for authentication to be made to pass an HTTP page to HTTPS.
• On top of that you should protect the session all the way not just at the submission of credentials. And depending on the sensitivity level of data you need to provide secure transport mechanisms internally for example from an application server to a database server.
• The final thing to address is using a mechanism that is cryptographically secure and does not have a flawed design.*
SECURE COMMUNICATIONS
• There are multiple ways of enforcing secure communications:
PHP code to force SSL
if($_SERVER["HTTPS"] != "on") { $newurl = "https://" .
$_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
header("Location: $newurl"); exit();}
Java code to force SSL
if(!request.isSecure()) { String sNewURL = "https://" +
request.getServerName() + request.getRequestURI();
if (request.getQueryString()!=null) sNewURL += "?"+request.getQueryString();
response.sendRedirect(sNewURL);}
Using Apache mod_rewrite to force SSL
RewriteEngine OnRewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
Force SSHv2 by editing sshd_config
Change the "Protocol" line to:
Protocol 2
Secure Resource Access
SECURE RESOURCE ACCESS
• If a design depends on the principle of security through obscurity it is almost certain to fail. A common approach to securing sensitive locations is to hide them from users by not publishing a link to them. This really fails to provide any level of security because automated tools will discover these locations and allow attackers to access them directly. If the location contains sensitive information (i.e. /backups) or functionality (i.e. /admin) you must provide strong access control mechanisms that ensure users accessing the location are authorised to do so.
• This principle helps you protect against:
Insecure Direct Object Reference, Failure to Restrict URL Access, Security Misconfiguration, Unvalidated Redirects and Forwards, Predictable Resource Location, Improper Limitation of a Pathname to a Restricted Directory, Improper Control of Filename for Include/Require Statement in PHP Program, Allocation of Resource Without Limits or Throttling
SECURE RESOURCE ACCESS
Preventing RFI/LFI in code:
<?php$page = $_GET['page'];switch($page) { default: include('blog.php'); break; case "blog": include('blog.php'); break;case "contact": include('contact.php'); break;case "news": include('news.php');}?>
Preventing Directory Traversal - PHP.ini
Uncomment "open_basedir"
Enter a path to limit the files which can be opened and read by PHP to the specified directory tree
open_basedir = /web/app/
Secure Storage
SECURE STORAGE
• We will now look at secure storage, we have secured our inputs and outputs, implemented sanitised error messages, created strong access control for all of our resources and protected information in transit but we cannot neglect the security of data at rest.
• The requirement to securely store data such as credit card numbers is obvious but we must also secure data such as passwords and session details whilst they are at rest. You not only need to identify what data needs to be protected but also which mechanisms you will use to provide the protection. The selection of the protection mechanism should follow the same guidelines as selecting one for secure communications; never create your own and do not use weak mechanisms such as DES, MD4 and SHA-0.
SECURE STORAGE
• You should ensure that the following bit sizes are used for Symmetric, Asymmetric and Hash mechanisms:
* Symmetric - 256 bits or above * Asymmetric - 2048 bits or above * Hashes - 168 bits or above
You should also provide a secure location for any encryption keys you are using; storing them on the application servers generally would not be a secure location.
SECURE STORAGE
• Last thing we need to take into account is:
Do not use hardcoded passwords in your code.
Part 2 – Getting it right…
AGNITIO
DEMO TIME
CONCLUSIONS
• Always audit your code
• Get your developers to be careful about their code and get them to learn and
follow the principles.
• Integrate code auditing in your SDLC.
• Use Agnitio reporting to see where your developers are failing and train them.
• If you write new agnitio rules, send them to us so we can integrate them directly
in Agnitio #givingback #opensource
• If you have any features you would like in Agnitio email me on
KUDOS
@Securityninja aka David Rook
For: • Developing the principles I taught u today• Starting Agnitio• Teaching me how to audit code and being my mentor
@vdbaan aka Steven van der Baan
For: Helping with the Agnitio development
THE END – HAVE SOME MEMES