Puru - Secure Coding Best Practices
Puru - Secure Coding Best Practices
Agenda
• Goal
• Likelihood of vulnerabilities
• Vulnerability distribution
• OWASP Top 10
• Identify common insecure input validation programming errors that lead to XSS
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.
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
• 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
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 is web accessible and contains URLs you don’t want indexed
by a search engine. This might be the kind of data hackers want
• 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
try {
Statement statement = connection.createStatement( … );
ResultSet results = statement.executeQuery( query );
}
Additional Defenses:
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
• 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>
<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
• 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
• Stored XSS
• Reflected XSS
• DOM-based XSS
XSS Example
• 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") + "'>";
Request:
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:
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:
• 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
• An attacker can manipulate direct object references to access other objects without authorization, unless
an access control check is in place.
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
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.
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 #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
• 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
• 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.
• The authentication mechanism should deny all access by default, and provide
access to specific roles for every function
OWASP TOP 10
Request:
csrf-token=&username=Purushotham&password=xxxxxx&confirm_password=xxxxxx&my_signature=test®ister-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
Generate unique random tokens for each form or URL, which are not automatically
transmitted by the browser.
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).
http://website.com/cgi-bin/redirect.cgi?url=attack.com
http://website.com/login?url=website.com
Example:
http://www.amazon.com/Application-Development-Graph-
Cookbook/dp?url=http://www.phishing.com
Any questions or
clarifications?