secure coding - balgan - tiago henriques

46
Secure Coding 101 [email protected]

Upload: tiago-henriques

Post on 17-May-2015

5.149 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Secure coding - Balgan - Tiago Henriques

Secure Coding 101

[email protected]

Page 2: Secure coding - Balgan - Tiago Henriques

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

Page 3: Secure coding - Balgan - Tiago Henriques

What we are going to (try) to cover today

Page 4: Secure coding - Balgan - Tiago Henriques

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!

Page 5: Secure coding - Balgan - Tiago Henriques

Target audienceDevelopers Code Auditors /Security Team

This talk is all about bringing the love between these two back

Page 6: Secure coding - Balgan - Tiago Henriques

Part 1 – Principles of Secure Development

Page 7: Secure coding - Balgan - Tiago Henriques

The principles A.K.A. The Bible

Input and Output

ValidationError Handling

Authentication and

Authorization

Session Management

Secure Communications

Secure Resource Access

Secure Storage

Page 8: Secure coding - Balgan - Tiago Henriques

Input and Output

Validation

Page 9: Secure coding - Balgan - Tiago Henriques

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

Page 10: Secure coding - Balgan - Tiago Henriques

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>

Page 11: Secure coding - Balgan - Tiago Henriques

• 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

Page 12: Secure coding - Balgan - Tiago Henriques

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

Page 13: Secure coding - Balgan - Tiago Henriques

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.

Page 14: Secure coding - Balgan - Tiago Henriques

Error Handling

Page 15: Secure coding - Balgan - Tiago Henriques

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……

Page 16: Secure coding - Balgan - Tiago Henriques

ERROR HANDLING

Our government

Page 17: Secure coding - Balgan - Tiago Henriques

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

Page 18: Secure coding - Balgan - Tiago Henriques

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:

Page 19: Secure coding - Balgan - Tiago Henriques

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}

}}

Page 20: Secure coding - Balgan - Tiago Henriques

Authentication and

Authorization

Page 21: Secure coding - Balgan - Tiago Henriques

AUTHENTICATION AND AUTHORIZATION

You can have a door and locks, but they will be useless if the door structure isn’t good enough

Page 22: Secure coding - Balgan - Tiago Henriques

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

Page 23: Secure coding - Balgan - Tiago Henriques

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

Page 24: Secure coding - Balgan - Tiago Henriques

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

Page 25: Secure coding - Balgan - Tiago Henriques

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

Page 26: Secure coding - Balgan - Tiago Henriques

Session Management

Page 27: Secure coding - Balgan - Tiago Henriques

SESSION MANAGEMENT

Normally when a user connects to our application this is what happens:

User

Authentication sucessful

Authentication failed

Page 28: Secure coding - Balgan - Tiago Henriques

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.

Page 29: Secure coding - Balgan - Tiago Henriques

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.*

Page 30: Secure coding - Balgan - Tiago Henriques

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);

Page 31: Secure coding - Balgan - Tiago Henriques

Secure Communications

Page 32: Secure coding - Balgan - Tiago Henriques

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.*

Page 33: Secure coding - Balgan - Tiago Henriques

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

Page 34: Secure coding - Balgan - Tiago Henriques

Secure Resource Access

Page 35: Secure coding - Balgan - Tiago Henriques

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

Page 36: Secure coding - Balgan - Tiago Henriques

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/

Page 37: Secure coding - Balgan - Tiago Henriques

Secure Storage

Page 38: Secure coding - Balgan - Tiago Henriques

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.

Page 39: Secure coding - Balgan - Tiago Henriques

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.

Page 40: Secure coding - Balgan - Tiago Henriques

SECURE STORAGE

• Last thing we need to take into account is:

Do not use hardcoded passwords in your code.

Page 41: Secure coding - Balgan - Tiago Henriques

Part 2 – Getting it right…

Page 42: Secure coding - Balgan - Tiago Henriques

AGNITIO

DEMO TIME

Page 43: Secure coding - Balgan - Tiago Henriques

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

[email protected]

Page 44: Secure coding - Balgan - Tiago Henriques

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

Page 45: Secure coding - Balgan - Tiago Henriques

THE END – HAVE SOME MEMES

Page 46: Secure coding - Balgan - Tiago Henriques