4. The Threats
Xss SQL Injection
Session management
Buffer Overflows
Flaws
Insecure
Information Disclosure
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!
5. Target audience
Developers Code Auditors /Security Team
This talk is all about
bringing the love between
these two back
9. 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
10. 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>
11. 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(" " "));
12. 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/perl
use 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);
13. 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.
14.
15. 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……
17. 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
18. 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:
19. 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
}
}
}
22. AUTHENTICATION AND AUTHORIZATION
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
23. 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.
24. 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.
25. 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
28. 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.
29. 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.*
30. 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);
31.
32. 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.*
33. 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);}
34.
35. 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
36. SECURE RESOURCE ACCESS
Preventing 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 tree
case "contact":
include('contact.php'); open_basedir = /web/app/
break;
case "news":
include('news.php');}?>
37.
38. 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.
39. 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.
40. SECURE STORAGE
• Last thing we need to take into account is:
Do not use hardcoded passwords in your code.
43. 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
balgan@ptcoresec.eu
44. 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
*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.