Secure coding - Balgan - Tiago Henriques
Upcoming SlideShare
Loading in...5

Secure coding - Balgan - Tiago Henriques






Total Views
Views on SlideShare
Embed Views



5 Embeds 1,963 1722 194 45 1 1



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.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
Post Comment
Edit your comment
  • *A pattern such as character positions 1, 4 and 5 always containing the letter C would be easily identified by automated tools and will reduce the computation time required to brute force genuine ID's.
  • *For example an online bank application would re-authenticate the user prior to transferring funds. This second authentication should also prompt the creation of a second session ID and the destruction of the original ID.
  • * A good example of a protection mechanism that is not secure is SSLv2; several of its vulnerabilities come from weaknesses in its design and not through a cryptographic weakness.
  • The password reset functionality of the T-Mobile website required a user to prove who they are by providing their phone number; the site would send them a unique token to enter into the site before they progressed to a password reset page. The problem with the site design was it assumed users would only ever access the password rest page if they had been authenticated. An attacker called Luckstr4w found that if you browsed directly to the password reset page you could reset the accounts password without providing any evidence of who you were.

Secure coding - Balgan - Tiago Henriques Secure coding - Balgan - Tiago Henriques Presentation Transcript

  • Secure Coding
  • Who Am I ? Team Leader of these guise• Tiago Henriques• @balgan• 24• BSc• MSc• CEH• CHFI file:///C:/Users/balga n/Downloads/11545_• CISSP 192585389754_51359• MCSA 9754_3020198_33334• CISA 9_n.jpg• CISM Currently employed• CPT by these guise• CCNA
  • What we are going to (try) to cover today
  • The Threats Xss SQL Injection Session management Buffer Overflows Flaws Insecure Information Disclosure Communication/storageWe 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!
  • 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/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 • Its important to validate both content validate the data and size (Yes, Size matters!) Use one of two • There are two types: processes to Whitelisting validate the data and Blacklisting
  • 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>
  • INPUT/OUTPUT VALIDATION – WHITELISTING VS BLACKLISTING• 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 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/perl #!/usr/bin/perluse CGI; use CGI;my $cgi = CGI->new(); use HTML::Entities;my $name = $cgi->param(username); VS my $cgi = CGI->new();print $cgi->header(); my $name = $cgi->param(username);print You entered $name; print $cgi->header(); print "You entered ", HTML::Entities::encode($name);
  • INPUT/OUTPUT VALIDATIONThis principle protects you against:Injection attacks, Cross Site Scripting, Security Misconfiguration, UnvalidatedRedirects and Forwards, Content Spoofing, Unrestricted Upload of File withDangerous Type, Failure to Preserve SQL Query Structure, Failure to Preserver WebPage Structure, Failure to Preserve OS Command Structure, URL Redirection toUntrusted Site, Buffer Copy without Checking Size on Input, Improper Limitation ofa Pathname to a Restricted Directory, Improper Control of Filename for Include orRequire Statement in PHP Program, Buffer Access with Incorrect Length Value,Improper Validation of Array Index, Integer Overflow or Wraparound, IncorrectCalculation of Buffer Size.
  • ERROR HANDLINGWhen a developer first starts coding an application everything is beautiful. Itworks flawlessly and it will never fail.Your application will fail sooner or later and its important that you deal with errorsgracefully and in a proper way.Unlike you know……
  • ERROR HANDLINGOur government
  • ERROR HANDLINGEvery application will eventually fail, and have to deal with na exception. Theseshould be handled carefully and securely.If an attacker manages to force na exception to occur he might be able to obtaincertain information that can help him attack our application/Infrastructure.This is a common example of an error message that could definetely help naattacker: 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 HANDLINGWe should always try to prevent these messages from reaching the end user.When developing code make sure you always handle expected and unexpectedexceptions. And then when returning errors to the users make sure they aregeneral 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 Conditionsimport;import;import;import;public class Test{public static void main(String[] args) { String urlStr = ""; //A URL that we will try touse 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 AUTHORIZATIONYou can have a door and locks, but they will be useless if the door structure isn’t good enough
  • AUTHENTICATION AND AUTHORIZATIONIf you don’t have strong and proper built authentication in your application, naattacker 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 AUTHORIZATIONWhen implementing a login system on ur application you should analyse what sortof content you are protecting, that way you can define a correct timeout for thesessions on your system.
  • AUTHENTICATION AND AUTHORIZATIONImportant 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 AUTHORIZATIONThis principle will help you protect against:Broken Authentication and Session Management, Security Misconfiguration,Unvalidated Redirects and Forwards, Insufficient Authorisation, InsufficientAuthentication, Abuse of Functionality, Use of Hard-coded Credentials, IncorrectPermission Assignment for Critical Resource, Reliance on Untrusted Inputs in aSecurity Decision, Missing Authentication for Critical Function, Improper AccessControl
  • SESSION MANAGEMENTNormally when a user connects to our application this is what happens: User
  • SESSION MANAGEMENTNormally an attacker will focus his attacks on trying to obtain a valid session eitherthrough exploiting users or taking advantage of flaws in the session managementsystem itself. Using this set of rules, you won’t need to have any knowledge of howthe attacker is attempting to exploit ur application:• The session IDs 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 isnt 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 IDs. *• We need to ensure that these IDs are secured both on the application server and whilst they are in transit.
  • SESSION MANAGEMENT• The storage location for the session IDs should be a secure location and not in world readable locations.• The next point we need to secure is the transmission of the session IDs 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 IDs 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 IDs 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 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 Using Apache mod_rewrite to force SSL if($_SERVER["HTTPS"] != "on") { RewriteEngine On $newurl = "https://" . RewriteCond %{HTTPS} off $_SERVER["SERVER_NAME"] . RewriteRule (.*) $_SERVER["REQUEST_URI"]; https://%{HTTP_HOST}%{REQUEST_URI} header("Location: $newurl"); exit();} Force SSHv2 by editing sshd_config Java code to force SSL Change the "Protocol" line to: if(!request.isSecure()) { Protocol 2 String sNewURL = "https://" + request.getServerName() + request.getRequestURI(); if (request.getQueryString()!=null)sNewURL += "?"+request.getQueryString(); response.sendRedirect(sNewURL);}
  • 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, SecurityMisconfiguration, Unvalidated Redirects and Forwards, Predictable ResourceLocation, Improper Limitation of a Pathname to a Restricted Directory, ImproperControl of Filename for Include/Require Statement in PHP Program, Allocation ofResource Without Limits or Throttling
  • SECURE RESOURCE ACCESSPreventing RFI/LFI in code: Preventing Directory Traversal - PHP.ini<?php$page = $_GET[page]; Uncomment "open_basedir"switch($page) { default: include(blog.php); Enter a path to limit the files break; case "blog": which can be opened and read include(blog.php); by PHP to the specified break; directory treecase "contact": include(contact.php); open_basedir = /web/app/ break;case "news": include(news.php);}?>
  • 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 aboveYou 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…
  • 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